Merge remote-tracking branch 'origin/master'
Conflicts: pom.xml
This commit is contained in:
commit
45f0774c83
|
@ -0,0 +1 @@
|
|||
target/
|
|
@ -8,18 +8,42 @@
|
|||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<properties>
|
||||
<cxf.version>3.1.6</cxf.version>
|
||||
<spring.version>4.3.1.RELEASE</spring.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxws</artifactId>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http-jetty</artifactId>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.6</version>
|
||||
<configuration>
|
||||
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
@ -33,6 +57,7 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
|
@ -50,7 +75,7 @@
|
|||
<configuration>
|
||||
<properties>
|
||||
<cargo.hostname>localhost</cargo.hostname>
|
||||
<cargo.servlet.port>8080</cargo.servlet.port>
|
||||
<cargo.servlet.port>8081</cargo.servlet.port>
|
||||
</properties>
|
||||
</configuration>
|
||||
</configuration>
|
||||
|
@ -71,6 +96,7 @@
|
|||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire.version}</version>
|
||||
|
@ -91,27 +117,13 @@
|
|||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
</profiles>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxws</artifactId>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http-jetty</artifactId>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.6</cxf.version>
|
||||
<spring.version>4.3.1.RELEASE</spring.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.cxf.spring;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
import org.apache.cxf.transport.servlet.CXFServlet;
|
||||
import org.springframework.web.WebApplicationInitializer;
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
|
||||
public class AppInitializer implements WebApplicationInitializer {
|
||||
@Override
|
||||
public void onStartup(ServletContext container) {
|
||||
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
|
||||
context.register(ServiceConfiguration.class);
|
||||
container.addListener(new ContextLoaderListener(context));
|
||||
|
||||
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new CXFServlet());
|
||||
dispatcher.addMapping("/services");
|
||||
}
|
||||
}
|
|
@ -5,5 +5,6 @@ import javax.jws.WebService;
|
|||
@WebService
|
||||
public interface Baeldung {
|
||||
String hello(String name);
|
||||
|
||||
String register(Student student);
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.cxf.spring;
|
||||
|
||||
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class ClientConfiguration {
|
||||
@Bean(name = "client")
|
||||
public Object generateProxy() {
|
||||
return proxyFactoryBean().create();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JaxWsProxyFactoryBean proxyFactoryBean() {
|
||||
JaxWsProxyFactoryBean proxyFactory = new JaxWsProxyFactoryBean();
|
||||
proxyFactory.setServiceClass(Baeldung.class);
|
||||
proxyFactory.setAddress("http://localhost:8081/services/baeldung");
|
||||
return proxyFactory;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.cxf.spring;
|
||||
|
||||
import javax.xml.ws.Endpoint;
|
||||
|
||||
import org.apache.cxf.Bus;
|
||||
import org.apache.cxf.bus.spring.SpringBus;
|
||||
import org.apache.cxf.jaxws.EndpointImpl;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class ServiceConfiguration {
|
||||
@Bean(name = Bus.DEFAULT_BUS_ID)
|
||||
public SpringBus springBus() {
|
||||
return new SpringBus();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Endpoint endpoint() {
|
||||
EndpointImpl endpoint = new EndpointImpl(springBus(), new BaeldungImpl());
|
||||
endpoint.publish("http://localhost:8081/services/baeldung");
|
||||
return endpoint;
|
||||
}
|
||||
}
|
|
@ -1,10 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
|
||||
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schema/jaxws.xsd">
|
||||
<bean id="client" factory-bean="clientFactory" factory-method="create" />
|
||||
<bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
|
||||
<property name="serviceClass" value="com.baeldung.cxf.spring.Baeldung" />
|
||||
<property name="address" value="http://localhost:8080/services/baeldung" />
|
||||
</bean>
|
||||
</beans>
|
|
@ -1,7 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
|
||||
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
|
||||
<jaxws:endpoint id="baeldung"
|
||||
implementor="com.baeldung.cxf.spring.BaeldungImpl" address="http://localhost:8080/services/baeldung" />
|
||||
</beans>
|
|
@ -1,14 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
version="3.0"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
|
||||
<servlet>
|
||||
<servlet-name>cxf</servlet-name>
|
||||
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>cxf</servlet-name>
|
||||
<url-pattern>/services/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
</web-app>
|
|
@ -3,15 +3,12 @@ package com.baeldung.cxf.spring;
|
|||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
|
||||
public class StudentTest {
|
||||
private ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "client-beans.xml" });
|
||||
private Baeldung baeldungProxy;
|
||||
|
||||
{
|
||||
baeldungProxy = (Baeldung) context.getBean("client");
|
||||
}
|
||||
private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class);
|
||||
private Baeldung baeldungProxy = (Baeldung) context.getBean("client");
|
||||
|
||||
@Test
|
||||
public void whenUsingHelloMethod_thenCorrect() {
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
@ -9,7 +8,7 @@
|
|||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<name>Resource vs Inject vs Autowired</name>
|
||||
<name>dependency-injection</name>
|
||||
<description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely
|
||||
Resource, Inject, and Autowired
|
||||
</description>
|
||||
|
@ -54,6 +53,7 @@
|
|||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
|
@ -71,13 +71,29 @@
|
|||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>java.net</id>
|
||||
<url>https://maven.java.net/content/repositories/releases/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -7,9 +7,19 @@ import java.util.List;
|
|||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
|
||||
|
||||
public class CustomListDeserializer extends JsonDeserializer<List<ItemWithSerializer>> {
|
||||
public class CustomListDeserializer extends StdDeserializer<List<ItemWithSerializer>> {
|
||||
|
||||
private static final long serialVersionUID = 1095767961632979804L;
|
||||
|
||||
public CustomListDeserializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomListDeserializer(final Class<?> vc) {
|
||||
super(vc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ItemWithSerializer> deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {
|
||||
|
|
|
@ -6,11 +6,20 @@ import java.util.List;
|
|||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class CustomListSerializer extends JsonSerializer<List<ItemWithSerializer>> {
|
||||
public class CustomListSerializer extends StdSerializer<List<ItemWithSerializer>> {
|
||||
|
||||
private static final long serialVersionUID = 3698763098000900856L;
|
||||
|
||||
public CustomListSerializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomListSerializer(final Class<List<ItemWithSerializer>> t) {
|
||||
super(t);
|
||||
}
|
||||
@Override
|
||||
public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
final List<Integer> ids = new ArrayList<Integer>();
|
||||
|
|
|
@ -8,12 +8,21 @@ import java.util.Date;
|
|||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
|
||||
|
||||
public class CustomDateDeserializer extends JsonDeserializer<Date> {
|
||||
public class CustomDateDeserializer extends StdDeserializer<Date> {
|
||||
|
||||
private static final long serialVersionUID = -5451717385630622729L;
|
||||
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
|
||||
public CustomDateDeserializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomDateDeserializer(final Class<?> vc) {
|
||||
super(vc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {
|
||||
final String date = jsonparser.getText();
|
||||
|
|
|
@ -6,13 +6,22 @@ import java.util.Date;
|
|||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class CustomDateSerializer extends JsonSerializer<Date> {
|
||||
public class CustomDateSerializer extends StdSerializer<Date> {
|
||||
|
||||
private static final long serialVersionUID = -2894356342227378312L;
|
||||
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
|
||||
public CustomDateSerializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomDateSerializer(final Class<Date> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
|
||||
gen.writeString(formatter.format(value));
|
||||
|
|
|
@ -8,10 +8,20 @@ import org.joda.time.format.DateTimeFormatter;
|
|||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class CustomDateTimeSerializer extends JsonSerializer<DateTime> {
|
||||
public class CustomDateTimeSerializer extends StdSerializer<DateTime> {
|
||||
|
||||
private static final long serialVersionUID = -3927232057990121460L;
|
||||
|
||||
public CustomDateTimeSerializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomDateTimeSerializer(final Class<DateTime> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
private static DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
|
||||
|
||||
|
|
|
@ -6,13 +6,23 @@ import java.time.format.DateTimeFormatter;
|
|||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
|
||||
public class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
|
||||
|
||||
|
||||
private static final long serialVersionUID = -7449444168934819290L;
|
||||
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
||||
|
||||
public CustomLocalDateTimeSerializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomLocalDateTimeSerializer(final Class<LocalDateTime> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final LocalDateTime value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
|
||||
gen.writeString(formatter.format(value));
|
||||
|
|
|
@ -2,17 +2,26 @@ package com.baeldung.jackson.deserialization;
|
|||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.dtos.User;
|
||||
import com.baeldung.jackson.dtos.Item;
|
||||
|
||||
import com.baeldung.jackson.dtos.User;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
|
||||
import com.fasterxml.jackson.databind.node.IntNode;
|
||||
|
||||
public class ItemDeserializer extends JsonDeserializer<Item> {
|
||||
public class ItemDeserializer extends StdDeserializer<Item> {
|
||||
|
||||
private static final long serialVersionUID = 1883547683050039861L;
|
||||
|
||||
public ItemDeserializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public ItemDeserializer(final Class<?> vc) {
|
||||
super(vc);
|
||||
}
|
||||
|
||||
/**
|
||||
* {"id":1,"itemNr":"theItem","owner":2}
|
||||
|
|
|
@ -4,15 +4,24 @@ import java.io.IOException;
|
|||
|
||||
import com.baeldung.jackson.dtos.ItemWithSerializer;
|
||||
import com.baeldung.jackson.dtos.User;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
|
||||
import com.fasterxml.jackson.databind.node.IntNode;
|
||||
|
||||
public class ItemDeserializerOnClass extends JsonDeserializer<ItemWithSerializer> {
|
||||
public class ItemDeserializerOnClass extends StdDeserializer<ItemWithSerializer> {
|
||||
|
||||
private static final long serialVersionUID = 5579141241817332594L;
|
||||
|
||||
public ItemDeserializerOnClass() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public ItemDeserializerOnClass(final Class<?> vc) {
|
||||
super(vc);
|
||||
}
|
||||
|
||||
/**
|
||||
* {"id":1,"itemNr":"theItem","owner":2}
|
||||
|
|
|
@ -4,10 +4,20 @@ import java.io.IOException;
|
|||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class TypeSerializer extends JsonSerializer<TypeEnumWithCustomSerializer> {
|
||||
public class TypeSerializer extends StdSerializer<TypeEnumWithCustomSerializer> {
|
||||
|
||||
private static final long serialVersionUID = -7650668914169390772L;
|
||||
|
||||
public TypeSerializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public TypeSerializer(final Class<TypeEnumWithCustomSerializer> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final TypeEnumWithCustomSerializer value, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
|
|
|
@ -3,13 +3,22 @@ package com.baeldung.jackson.serialization;
|
|||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.dtos.Item;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class ItemSerializer extends JsonSerializer<Item> {
|
||||
public class ItemSerializer extends StdSerializer<Item> {
|
||||
|
||||
private static final long serialVersionUID = 6739170890621978901L;
|
||||
|
||||
public ItemSerializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public ItemSerializer(final Class<Item> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void serialize(final Item value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
|
|
|
@ -3,13 +3,22 @@ package com.baeldung.jackson.serialization;
|
|||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.dtos.ItemWithSerializer;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class ItemSerializerOnClass extends JsonSerializer<ItemWithSerializer> {
|
||||
public class ItemSerializerOnClass extends StdSerializer<ItemWithSerializer> {
|
||||
|
||||
private static final long serialVersionUID = -1760959597313610409L;
|
||||
|
||||
public ItemSerializerOnClass() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public ItemSerializerOnClass(final Class<ItemWithSerializer> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void serialize(final ItemWithSerializer value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
|
|
|
@ -4,10 +4,20 @@ import java.io.IOException;
|
|||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class MyDtoNullKeySerializer extends JsonSerializer<Object> {
|
||||
public class MyDtoNullKeySerializer extends StdSerializer<Object> {
|
||||
|
||||
private static final long serialVersionUID = -4478531309177369056L;
|
||||
|
||||
public MyDtoNullKeySerializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public MyDtoNullKeySerializer(final Class<Object> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
|
|
|
@ -6,10 +6,19 @@ import com.fasterxml.jackson.core.JsonParser;
|
|||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.ObjectCodec;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
|
||||
|
||||
public class RestLoaderRequestDeserializer extends JsonDeserializer<RestLoaderRequest<IEntity>> {
|
||||
public class RestLoaderRequestDeserializer extends StdDeserializer<RestLoaderRequest<IEntity>> {
|
||||
private static final long serialVersionUID = -4245207329377196889L;
|
||||
|
||||
public RestLoaderRequestDeserializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public RestLoaderRequestDeserializer(final Class<?> vc) {
|
||||
super(vc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RestLoaderRequest<IEntity> deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
||||
|
|
|
@ -5,3 +5,4 @@
|
|||
|
||||
### Relevant Articles:
|
||||
- [JMockit 101](http://www.baeldung.com/jmockit-101)
|
||||
- [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations)
|
||||
|
|
|
@ -1,9 +1,11 @@
|
|||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
public class Collaborator {
|
||||
|
||||
public boolean collaborate(String string){
|
||||
return false;
|
||||
}
|
||||
|
||||
public void receive(boolean bool){
|
||||
//NOOP
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
public class Model {
|
||||
public String getInfo(){
|
||||
return "info";
|
||||
public String getInfo() {
|
||||
return "info";
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,21 +1,20 @@
|
|||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.hamcrest.BaseMatcher;
|
||||
import org.hamcrest.Description;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import mockit.Delegate;
|
||||
import mockit.Expectations;
|
||||
import mockit.Mocked;
|
||||
import mockit.StrictExpectations;
|
||||
import mockit.Verifications;
|
||||
import mockit.integration.junit4.JMockit;
|
||||
import org.hamcrest.BaseMatcher;
|
||||
import org.hamcrest.Description;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(JMockit.class)
|
||||
@SuppressWarnings("unchecked")
|
||||
|
@ -23,71 +22,56 @@ public class ExpectationsTest {
|
|||
|
||||
@Test
|
||||
public void testForAny(@Mocked ExpectationsCollaborator mock) throws Exception {
|
||||
new Expectations() {
|
||||
{
|
||||
mock.methodForAny1(anyString, anyInt, anyBoolean);
|
||||
result = "any";
|
||||
}
|
||||
};
|
||||
new Expectations() {{
|
||||
mock.methodForAny1(anyString, anyInt, anyBoolean);
|
||||
result = "any";
|
||||
}};
|
||||
|
||||
assertEquals("any", mock.methodForAny1("barfooxyz", 0, Boolean.FALSE));
|
||||
mock.methodForAny2(2L, new ArrayList<>());
|
||||
|
||||
new Verifications() {
|
||||
{
|
||||
mock.methodForAny2(anyLong, (List<String>) any);
|
||||
}
|
||||
};
|
||||
new Verifications() {{
|
||||
mock.methodForAny2(anyLong, (List<String>) any);
|
||||
}};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForWith(@Mocked ExpectationsCollaborator mock) throws Exception {
|
||||
new Expectations() {
|
||||
{
|
||||
mock.methodForWith1(withSubstring("foo"), withNotEqual(1));
|
||||
result = "with";
|
||||
}
|
||||
};
|
||||
new Expectations() {{
|
||||
mock.methodForWith1(withSubstring("foo"), withNotEqual(1));
|
||||
result = "with";
|
||||
}};
|
||||
|
||||
assertEquals("with", mock.methodForWith1("barfooxyz", 2));
|
||||
mock.methodForWith2(Boolean.TRUE, new ArrayList<>());
|
||||
|
||||
new Verifications() {
|
||||
{
|
||||
mock.methodForWith2(withNotNull(), withInstanceOf(List.class));
|
||||
}
|
||||
};
|
||||
new Verifications() {{
|
||||
mock.methodForWith2(withNotNull(), withInstanceOf(List.class));
|
||||
}};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithNulls(@Mocked ExpectationsCollaborator mock) {
|
||||
new Expectations() {
|
||||
{
|
||||
mock.methodForNulls1(anyString, null);
|
||||
result = "null";
|
||||
}
|
||||
};
|
||||
new Expectations() {{
|
||||
mock.methodForNulls1(anyString, null);
|
||||
result = "null";
|
||||
}};
|
||||
|
||||
assertEquals("null", mock.methodForNulls1("blablabla", new ArrayList<String>()));
|
||||
mock.methodForNulls2("blablabla", null);
|
||||
|
||||
new Verifications() {
|
||||
{
|
||||
mock.methodForNulls2(anyString, (List<String>) withNull());
|
||||
}
|
||||
};
|
||||
new Verifications() {{
|
||||
mock.methodForNulls2(anyString, (List<String>) withNull());
|
||||
}};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithTimes(@Mocked ExpectationsCollaborator mock) {
|
||||
new Expectations() {
|
||||
{
|
||||
// exactly 2 invocations are expected
|
||||
mock.methodForTimes1();
|
||||
times = 2;
|
||||
mock.methodForTimes2(); // "minTimes = 1" is implied
|
||||
}
|
||||
};
|
||||
new Expectations() {{
|
||||
mock.methodForTimes1();
|
||||
times = 2;
|
||||
mock.methodForTimes2();
|
||||
}};
|
||||
|
||||
mock.methodForTimes1();
|
||||
mock.methodForTimes1();
|
||||
|
@ -96,56 +80,44 @@ public class ExpectationsTest {
|
|||
mock.methodForTimes3();
|
||||
mock.methodForTimes3();
|
||||
|
||||
new Verifications() {
|
||||
{
|
||||
// we expect from 1 to 3 invocations
|
||||
mock.methodForTimes3();
|
||||
minTimes = 1;
|
||||
maxTimes = 3;
|
||||
}
|
||||
};
|
||||
new Verifications() {{
|
||||
mock.methodForTimes3();
|
||||
minTimes = 1;
|
||||
maxTimes = 3;
|
||||
}};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomArgumentMatching(@Mocked ExpectationsCollaborator mock) {
|
||||
new Expectations() {
|
||||
{
|
||||
mock.methodForArgThat(withArgThat(new BaseMatcher<Object>() {
|
||||
@Override
|
||||
public boolean matches(Object item) {
|
||||
return item instanceof Model && "info".equals(((Model) item).getInfo());
|
||||
}
|
||||
new Expectations() {{
|
||||
mock.methodForArgThat(withArgThat(new BaseMatcher<Object>() {
|
||||
@Override
|
||||
public boolean matches(Object item) {
|
||||
return item instanceof Model && "info".equals(((Model) item).getInfo());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
// NOOP
|
||||
}
|
||||
}));
|
||||
}
|
||||
};
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
}
|
||||
}));
|
||||
}};
|
||||
mock.methodForArgThat(new Model());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResultAndReturns(@Mocked ExpectationsCollaborator mock) {
|
||||
new StrictExpectations() {
|
||||
{
|
||||
// return "foo", an exception and lastly "bar"
|
||||
mock.methodReturnsString();
|
||||
result = "foo";
|
||||
result = new Exception();
|
||||
result = "bar";
|
||||
// return 1, 2, 3
|
||||
mock.methodReturnsInt();
|
||||
result = new int[] { 1, 2, 3 };
|
||||
// return "foo" and "bar"
|
||||
mock.methodReturnsString();
|
||||
returns("foo", "bar");
|
||||
// return only 1
|
||||
mock.methodReturnsInt();
|
||||
result = 1;
|
||||
}
|
||||
};
|
||||
new StrictExpectations() {{
|
||||
mock.methodReturnsString();
|
||||
result = "foo";
|
||||
result = new Exception();
|
||||
result = "bar";
|
||||
mock.methodReturnsInt();
|
||||
result = new int[]{1, 2, 3};
|
||||
mock.methodReturnsString();
|
||||
returns("foo", "bar");
|
||||
mock.methodReturnsInt();
|
||||
result = 1;
|
||||
}};
|
||||
|
||||
assertEquals("Should return foo", "foo", mock.methodReturnsString());
|
||||
try {
|
||||
|
@ -164,27 +136,23 @@ public class ExpectationsTest {
|
|||
|
||||
@Test
|
||||
public void testDelegate(@Mocked ExpectationsCollaborator mock) {
|
||||
new StrictExpectations() {
|
||||
{
|
||||
// return "foo", an exception and lastly "bar"
|
||||
mock.methodForDelegate(anyInt);
|
||||
times = 2;
|
||||
result = new Delegate() {
|
||||
public int delegate(int i) throws Exception {
|
||||
if (i < 3) {
|
||||
return 5;
|
||||
} else {
|
||||
throw new Exception();
|
||||
}
|
||||
new Expectations() {{
|
||||
mock.methodForDelegate(anyInt);
|
||||
result = new Delegate() {
|
||||
public int delegate(int i) throws Exception {
|
||||
if (i < 3) {
|
||||
return 5;
|
||||
} else {
|
||||
throw new Exception();
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
}};
|
||||
|
||||
assertEquals("Should return 5", 5, mock.methodForDelegate(1));
|
||||
try {
|
||||
mock.methodForDelegate(3);
|
||||
} catch (Exception e) {
|
||||
// NOOP
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -21,7 +21,9 @@ public class PerformerTest {
|
|||
model.getInfo();result = "bar";
|
||||
collaborator.collaborate("bar"); result = true;
|
||||
}};
|
||||
|
||||
performer.perform(model);
|
||||
|
||||
new Verifications() {{
|
||||
collaborator.receive(true);
|
||||
}};
|
||||
|
|
24
pom.xml
24
pom.xml
|
@ -15,10 +15,17 @@
|
|||
<modules>
|
||||
<module>assertj</module>
|
||||
<module>apache-cxf</module>
|
||||
<module>apache-fop</module>
|
||||
<module>core-java</module>
|
||||
<module>core-java-8</module>
|
||||
<module>couchbase-sdk-intro</module>
|
||||
<module>couchbase-sdk-spring-service</module>
|
||||
|
||||
<module>dependency-injection</module>
|
||||
<module>gatling</module>
|
||||
|
||||
<module>gson</module>
|
||||
<!-- <module>gson-jackson-performance</module> -->
|
||||
<module>gson-jackson-performance</module>
|
||||
<module>guava</module>
|
||||
<module>guava18</module>
|
||||
<module>guava19</module>
|
||||
|
@ -28,27 +35,35 @@
|
|||
<module>javaxval</module>
|
||||
<module>jjwt</module>
|
||||
<module>jooq-spring</module>
|
||||
<module>json-path</module>
|
||||
<module>jpa-storedprocedure</module>
|
||||
<module>json</module>
|
||||
<module>json-path</module>
|
||||
<module>junit5</module>
|
||||
<module>mockito</module>
|
||||
<module>mocks</module>
|
||||
<module>jee7schedule</module>
|
||||
<!-- <module>jpa-storedprocedure</module> -->
|
||||
<module>querydsl</module>
|
||||
<!-- <module>raml</module> -->
|
||||
<module>rest-assured</module>
|
||||
<module>rest-testing</module>
|
||||
<module>resteasy</module>
|
||||
<module>log4j</module>
|
||||
|
||||
<module>spring-all</module>
|
||||
<module>spring-apache-camel</module>
|
||||
<module>spring-autowire</module>
|
||||
<module>spring-batch</module>
|
||||
<module>spring-boot</module>
|
||||
<module>spring-controller</module>
|
||||
<module>spring-data-cassandra</module>
|
||||
<module>spring-data-couchbase-2</module>
|
||||
<module>spring-data-couchbase-2b</module>
|
||||
<module>spring-data-elasticsearch</module>
|
||||
<module>spring-data-neo4j</module>
|
||||
<module>spring-data-mongodb</module>
|
||||
<module>spring-data-redis</module>
|
||||
<module>spring-data-rest</module>
|
||||
<module>spring-exceptions</module>
|
||||
<module>spring-freemarker</module>
|
||||
<module>spring-hibernate3</module>
|
||||
|
@ -62,9 +77,12 @@
|
|||
<module>spring-openid</module>
|
||||
<module>spring-protobuf</module>
|
||||
<module>spring-quartz</module>
|
||||
<module>spring-spel</module>
|
||||
<module>spring-rest</module>
|
||||
<module>spring-rest-docs</module>
|
||||
|
||||
<module>spring-security-basic-auth</module>
|
||||
<module>spring-security-custom-permission</module>
|
||||
<module>spring-security-mvc-custom</module>
|
||||
<module>spring-security-mvc-digest-auth</module>
|
||||
<module>spring-security-mvc-ldap</module>
|
||||
|
@ -82,9 +100,11 @@
|
|||
<module>xml</module>
|
||||
<module>lombok</module>
|
||||
<module>redis</module>
|
||||
<module>webjars</module>
|
||||
|
||||
<module>mutation-testing</module>
|
||||
<module>spring-mvc-velocity</module>
|
||||
<module>xstream</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
|
||||
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
|
||||
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
|
||||
</launchConfiguration>
|
|
@ -1,7 +0,0 @@
|
|||
=========
|
||||
|
||||
## A Guide To REST-Assured
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
|
||||
<name>rest-assured</name>
|
||||
|
||||
<properties>
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<wiremock.version>2.1.7</wiremock.version>
|
||||
<hamcrest-all.version>1.3</hamcrest-all.version>
|
||||
<json-schema-core.version>1.2.5</json-schema-core.version>
|
||||
<json-schema-validator.version>2.2.6</json-schema-validator.version>
|
||||
<rest-assured.version>3.0.0</rest-assured.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- logging -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>json-schema-validator</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.fge</groupId>
|
||||
<artifactId>json-schema-validator</artifactId>
|
||||
<version>${json-schema-validator.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.fge</groupId>
|
||||
<artifactId>json-schema-core</artifactId>
|
||||
<version>${json-schema-core.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.tomakehurst</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
<version>${wiremock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<version>${hamcrest-all.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>rest-assured</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
|
@ -1,206 +0,0 @@
|
|||
package com.baeldung.restassured;
|
||||
|
||||
import com.github.fge.jsonschema.SchemaVersion;
|
||||
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
|
||||
import com.github.fge.jsonschema.main.JsonSchemaFactory;
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
import com.github.tomakehurst.wiremock.client.WireMock;
|
||||
import io.restassured.module.jsv.JsonSchemaValidator;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.*;
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static io.restassured.RestAssured.post;
|
||||
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
|
||||
import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.xml.HasXPath.hasXPath;
|
||||
|
||||
|
||||
public class RestAssuredTest {
|
||||
|
||||
@Test
|
||||
public void givenJsonResponse_whenKeyValuePairMatches_thenCorrect() {
|
||||
JsonSchemaFactory factory = JsonSchemaFactory
|
||||
.newBuilder()
|
||||
.setValidationConfiguration(
|
||||
ValidationConfiguration.newBuilder()
|
||||
.setDefaultVersion(SchemaVersion.DRAFTV3)
|
||||
.freeze()).freeze();
|
||||
JsonSchemaValidator.settings = settings().with()
|
||||
.jsonSchemaFactory(factory).and().with()
|
||||
.checkedValidation(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJsonArrayOfSimilarObjects_whenHasGivenValuesForGivenKey_thenCorrect() {
|
||||
|
||||
}
|
||||
|
||||
private WireMockServer wireMockServer = new WireMockServer();
|
||||
private static final String EVENTS_PATH = "/events?id=390";
|
||||
private static final String APPLICATION_JSON = "application/json";
|
||||
|
||||
private static final String GAME_ODDS = "" +
|
||||
"{" +
|
||||
" \"id\": 390," +
|
||||
" \"data\": {" +
|
||||
" \"countryId\": 35," +
|
||||
" \"countryName\": \"Norway\"," +
|
||||
" \"leagueName\": \"Norway 3\"," +
|
||||
" \"status\": 0," +
|
||||
" \"sportName\": \"Soccer\"," +
|
||||
" \"time\": \"2016-06-12T12:00:00Z\"" +
|
||||
" }," +
|
||||
" \"odds\": [" +
|
||||
" {" +
|
||||
" \"price\": \"1.30\"," +
|
||||
" \"status\": 0," +
|
||||
" \"ck\": \"1\"," +
|
||||
" \"name\": \"1\"" +
|
||||
" }," +
|
||||
" {" +
|
||||
" \"price\": \"5.25\"," +
|
||||
" \"status\": 0," +
|
||||
" \"ck\": \"X\"," +
|
||||
" \"name\": \"X\"" +
|
||||
" }" +
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenSuccessOnGetsResponse_andJsonHasRequiredKV_thenCorrect() {
|
||||
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", 8080);
|
||||
|
||||
stubFor(WireMock.get(urlEqualTo(EVENTS_PATH)).willReturn(aResponse()
|
||||
.withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_JSON)
|
||||
.withBody(GAME_ODDS)));
|
||||
|
||||
get("/events?id=390").then().statusCode(200).assertThat()
|
||||
.body("id", equalTo(390));
|
||||
|
||||
wireMockServer.stop();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() {
|
||||
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", 8080);
|
||||
|
||||
stubFor(WireMock.get(urlEqualTo(EVENTS_PATH)).willReturn(aResponse()
|
||||
.withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_JSON)
|
||||
.withBody(GAME_ODDS)));
|
||||
|
||||
get("/events?id=390").then().assertThat()
|
||||
.body("odds.price", hasItems("1.30", "5.25"));
|
||||
|
||||
wireMockServer.stop();
|
||||
}
|
||||
|
||||
|
||||
@Test @Ignore
|
||||
public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() {
|
||||
get("/events?id=390").then().assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json"));
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() {
|
||||
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory
|
||||
.newBuilder()
|
||||
.setValidationConfiguration(
|
||||
ValidationConfiguration.newBuilder()
|
||||
.setDefaultVersion(SchemaVersion.DRAFTV4)
|
||||
.freeze()).freeze();
|
||||
|
||||
get("/events?id=390")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json").using(
|
||||
jsonSchemaFactory));
|
||||
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() {
|
||||
|
||||
get("/events?id=390")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json").using(
|
||||
settings().with().checkedValidation(false)));
|
||||
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() {
|
||||
get("/odd").then().assertThat().body("odd.ck", equalTo(12.2f));
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() {
|
||||
post("/employees").then().assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"));
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() {
|
||||
post("/employees").then().assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"))
|
||||
.body("employees.employee.last-name", equalTo("Daisy"))
|
||||
.body("employees.employee.sex", equalTo("f"));
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"),
|
||||
"employees.employee.last-name", equalTo("Daisy"),
|
||||
"employees.employee.sex", equalTo("f"));
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(hasXPath("/employees/employee/first-name",
|
||||
containsString("Ja")));
|
||||
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(hasXPath("/employees/employee/first-name[text()='Jane']"));
|
||||
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() {
|
||||
get("/teachers")
|
||||
.then()
|
||||
.body("teachers.teacher.find { it.@department == 'science' }.subject",
|
||||
hasItems("math", "physics"));
|
||||
}
|
||||
|
||||
@Test @Ignore
|
||||
public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() {
|
||||
get("/odds").then().body("odds.findAll { it.status > 0 }.price",
|
||||
hasItems(1.30f, 1.20f));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -1,22 +0,0 @@
|
|||
<employees>
|
||||
<employee category="skilled">
|
||||
<first-name>Jane</first-name>
|
||||
<last-name>Daisy</last-name>
|
||||
<sex>f</sex>
|
||||
</employee>
|
||||
<employee category="unskilled">
|
||||
<first-name>John</first-name>
|
||||
<last-name>Doe</last-name>
|
||||
<sex>m</sex>
|
||||
</employee>
|
||||
<employee category="skilled">
|
||||
<first-name>Billy</first-name>
|
||||
<last-name>Getty</last-name>
|
||||
<sex>m</sex>
|
||||
</employee>
|
||||
<employee category="skilled">
|
||||
<first-name>Hill</first-name>
|
||||
<last-name>Clinton</last-name>
|
||||
<sex>f</sex>
|
||||
</employee>
|
||||
</employees>
|
|
@ -0,0 +1,257 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>rest-assured</name>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<source>8</source>
|
||||
<target>8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.1-b06</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>servlet-api</artifactId>
|
||||
<version>2.5</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-security -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-security</artifactId>
|
||||
<version>9.2.0.M1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-servlet -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-servlet</artifactId>
|
||||
<version>9.2.0.M1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-servlets -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-servlets</artifactId>
|
||||
<version>9.2.0.M1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-io -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-io</artifactId>
|
||||
<version>9.2.0.M1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-http -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-http</artifactId>
|
||||
<version>9.2.0.M1</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-server -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-server</artifactId>
|
||||
<version>9.2.0.M1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-util -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-util</artifactId>
|
||||
<version>9.2.0.M1</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.21</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-log4j12</artifactId>
|
||||
<version>1.7.21</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/com.jayway.restassured/rest-assured-common -->
|
||||
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
|
||||
<dependency>
|
||||
<groupId>commons-logging</groupId>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<version>1.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpcore</artifactId>
|
||||
<version>4.4.5</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.4</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/com.github.fge/uri-template -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.fge</groupId>
|
||||
<artifactId>uri-template</artifactId>
|
||||
<version>0.9</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/com.googlecode.libphonenumber/libphonenumber -->
|
||||
<dependency>
|
||||
<groupId>com.googlecode.libphonenumber</groupId>
|
||||
<artifactId>libphonenumber</artifactId>
|
||||
<version>7.4.5</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.mail</groupId>
|
||||
<artifactId>mail</artifactId>
|
||||
<version>1.4.7</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>2.9.4</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
<version>2.8.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.8.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
<version>2.8.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.fge</groupId>
|
||||
<artifactId>msg-simple</artifactId>
|
||||
<version>1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.fge</groupId>
|
||||
<artifactId>jackson-coreutils</artifactId>
|
||||
<version>1.8</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>18.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.fge</groupId>
|
||||
<artifactId>btf</artifactId>
|
||||
<version>1.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>4.5.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>2.4.7</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.tomakehurst</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
<version>2.1.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>json-schema-validator</artifactId>
|
||||
<version>3.0.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.fge</groupId>
|
||||
<artifactId>json-schema-validator</artifactId>
|
||||
<version>2.2.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.fge</groupId>
|
||||
<artifactId>json-schema-core</artifactId>
|
||||
<version>1.2.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<version>1.3</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
|
||||
<dependency>
|
||||
<groupId>commons-collections</groupId>
|
||||
<artifactId>commons-collections</artifactId>
|
||||
<version>3.2.2</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,55 @@
|
|||
package com.baeldung.restassured;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static io.restassured.RestAssured.get;
|
||||
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
|
||||
public class RestAssured2Test {
|
||||
private WireMockServer wireMockServer = new WireMockServer();
|
||||
|
||||
private static final String EVENTS_PATH = "/odds";
|
||||
private static final String APPLICATION_JSON = "application/json";
|
||||
private static final String ODDS = getJson();
|
||||
|
||||
@Before
|
||||
public void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", 8080);
|
||||
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_JSON)
|
||||
.withBody(ODDS)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() {
|
||||
get("/odds").then().body("odds.findAll { it.status > 0 }.price",
|
||||
hasItems(5.25f, 1.2f));
|
||||
}
|
||||
|
||||
private static String getJson() {
|
||||
|
||||
return Util.inputStreamToString(new RestAssured2Test().getClass()
|
||||
.getResourceAsStream("/odds.json"));
|
||||
|
||||
}
|
||||
|
||||
@After
|
||||
public void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,106 @@
|
|||
package com.baeldung.restassured;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
|
||||
import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.github.fge.jsonschema.SchemaVersion;
|
||||
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
|
||||
import com.github.fge.jsonschema.main.JsonSchemaFactory;
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
|
||||
public class RestAssuredTest {
|
||||
|
||||
private WireMockServer wireMockServer = new WireMockServer();
|
||||
private static final String EVENTS_PATH = "/events?id=390";
|
||||
private static final String APPLICATION_JSON = "application/json";
|
||||
private static final String GAME_ODDS = getEventJson();
|
||||
|
||||
@Before
|
||||
public void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", 8080);
|
||||
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_JSON)
|
||||
.withBody(GAME_ODDS)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() {
|
||||
get("/events?id=390").then().assertThat()
|
||||
.body("odd.ck", equalTo(12.2f));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() {
|
||||
|
||||
get("/events?id=390").then().statusCode(200).assertThat()
|
||||
.body("id", equalTo("390"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() {
|
||||
get("/events?id=390").then().assertThat()
|
||||
.body("odds.price", hasItems("1.30", "5.25", "2.70", "1.20"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() {
|
||||
|
||||
get("/events?id=390").then().assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() {
|
||||
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory
|
||||
.newBuilder()
|
||||
.setValidationConfiguration(
|
||||
ValidationConfiguration.newBuilder()
|
||||
.setDefaultVersion(SchemaVersion.DRAFTV4)
|
||||
.freeze()).freeze();
|
||||
|
||||
get("/events?id=390")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json").using(
|
||||
jsonSchemaFactory));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() {
|
||||
|
||||
get("/events?id=390")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json").using(
|
||||
settings().with().checkedValidation(false)));
|
||||
}
|
||||
|
||||
@After
|
||||
public void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
|
||||
private static String getEventJson() {
|
||||
return Util.inputStreamToString(RestAssuredTest.class
|
||||
.getResourceAsStream("/event_0.json"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.restassured;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static io.restassured.RestAssured.get;
|
||||
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
|
||||
public class RestAssuredXML2Test {
|
||||
private WireMockServer wireMockServer = new WireMockServer();
|
||||
|
||||
private static final String EVENTS_PATH = "/teachers";
|
||||
private static final String APPLICATION_XML = "application/xml";
|
||||
private static final String TEACHERS = getXml();
|
||||
|
||||
@Before
|
||||
public void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", 8080);
|
||||
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_XML)
|
||||
.withBody(TEACHERS)));
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() {
|
||||
get("/teachers")
|
||||
.then()
|
||||
.body("teachers.teacher.find { it.@department == 'science' }.subject",
|
||||
hasItems("math", "physics"));
|
||||
}
|
||||
private static String getXml() {
|
||||
|
||||
return Util
|
||||
.inputStreamToString(new RestAssuredXML2Test().getClass().getResourceAsStream("/teachers.xml"));
|
||||
|
||||
}
|
||||
@After
|
||||
public void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,99 @@
|
|||
package com.baeldung.restassured;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static io.restassured.RestAssured.post;
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
|
||||
import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.xml.HasXPath.hasXPath;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.github.fge.jsonschema.SchemaVersion;
|
||||
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
|
||||
import com.github.fge.jsonschema.main.JsonSchemaFactory;
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
public class RestAssuredXMLTest {
|
||||
private WireMockServer wireMockServer = new WireMockServer();
|
||||
private static final String EVENTS_PATH = "/employees";
|
||||
private static final String APPLICATION_XML = "application/xml";
|
||||
private static final String EMPLOYEES = getXml();
|
||||
|
||||
@Before
|
||||
public void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", 8080);
|
||||
stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_XML)
|
||||
.withBody(EMPLOYEES)));
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() {
|
||||
post("/employees").then().assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() {
|
||||
post("/employees").then().assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"))
|
||||
.body("employees.employee.last-name", equalTo("Daisy"))
|
||||
.body("employees.employee.sex", equalTo("f"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"),
|
||||
"employees.employee.last-name", equalTo("Daisy"),
|
||||
"employees.employee.sex", equalTo("f"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(hasXPath("/employees/employee/first-name",
|
||||
containsString("Ja")));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(hasXPath("/employees/employee/first-name[text()='Jane']"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static String getXml() {
|
||||
|
||||
return Util
|
||||
.inputStreamToString(new RestAssuredXMLTest().getClass().getResourceAsStream("/employees.xml"));
|
||||
|
||||
}
|
||||
@After
|
||||
public void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.restassured;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
public class Util {
|
||||
public static String inputStreamToString(InputStream is) {
|
||||
BufferedReader br = null;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
String line;
|
||||
try {
|
||||
|
||||
br = new BufferedReader(new InputStreamReader(is));
|
||||
while ((line = br.readLine()) != null) {
|
||||
sb.append(line);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (br != null) {
|
||||
try {
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
<employees>
|
||||
<employee category="skilled">
|
||||
<first-name>Jane</first-name>
|
||||
<last-name>Daisy</last-name>
|
||||
<sex>f</sex>
|
||||
</employee>
|
||||
</employees>
|
|
@ -1,5 +1,11 @@
|
|||
{
|
||||
"id": "390",
|
||||
"odd": {
|
||||
"price": "1.20",
|
||||
"status": 2,
|
||||
"ck": 12.2,
|
||||
"name": "2"
|
||||
},
|
||||
"data": {
|
||||
"countryId": 35,
|
||||
"countryName": "Norway",
|
||||
|
@ -9,25 +15,25 @@
|
|||
"time": "2016-06-12T12:00:00Z"
|
||||
},
|
||||
"odds": [{
|
||||
"price": 1.30,
|
||||
"price": "1.30",
|
||||
"status": 0,
|
||||
"ck": 12.2,
|
||||
"name": "1"
|
||||
},
|
||||
{
|
||||
"price": 5.25,
|
||||
"price":"5.25",
|
||||
"status": 1,
|
||||
"ck": 13.1,
|
||||
"name": "X"
|
||||
},
|
||||
{
|
||||
"price": 2.70,
|
||||
"price": "2.70",
|
||||
"status": 0,
|
||||
"ck": 12.2,
|
||||
"name": "0"
|
||||
},
|
||||
{
|
||||
"price": 1.20,
|
||||
"price": "1.20",
|
||||
"status": 2,
|
||||
"ck": 13.1,
|
||||
"name": "2"
|
|
@ -0,0 +1,16 @@
|
|||
## Logger configure
|
||||
datestamp=yyyy-MM-dd HH:mm:ss
|
||||
log4j.rootLogger=TRACE, file, console
|
||||
|
||||
log4j.appender.file=org.apache.log4j.RollingFileAppender
|
||||
log4j.appender.file.maxFileSize=1GB
|
||||
log4j.appender.file.maxBackupIndex=5
|
||||
log4j.appender.file.File=log/rest-assured.log
|
||||
log4j.appender.file.threshold=TRACE
|
||||
log4j.appender.file.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.file.layout.ConversionPattern=%d{${datestamp}} %5p: [%c] - %m%n
|
||||
|
||||
log4j.appender.console=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.console.Threshold=INFO
|
||||
log4j.appender.console.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.console.layout.ConversionPattern=%d{${datestamp}} %5p\: [%c] - %m%n
|
|
@ -1,6 +1,6 @@
|
|||
package com.baledung.controller;
|
||||
package com.baeldung.controller;
|
||||
|
||||
import com.baledung.student.Student;
|
||||
import com.baeldung.student.Student;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
|
@ -1,6 +1,6 @@
|
|||
package com.baledung.controller;
|
||||
package com.baeldung.controller;
|
||||
|
||||
import com.baledung.student.Student;
|
||||
import com.baeldung.student.Student;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
@ -2,7 +2,7 @@
|
|||
/**
|
||||
* @author Prashant Dutta
|
||||
*/
|
||||
package com.baledung.controller;
|
||||
package com.baeldung.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baledung.student;
|
||||
package com.baeldung.student;
|
||||
|
||||
public class Student {
|
||||
private String name;
|
|
@ -10,7 +10,7 @@
|
|||
http://www.springframework.org/schema/context/spring-context-4.0.xsd
|
||||
http://www.springframework.org/schema/mvc
|
||||
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
|
||||
<context:component-scan base-package="com.baledung.controller" />
|
||||
<context:component-scan base-package="com.baeldung.controller" />
|
||||
<mvc:annotation-driven />
|
||||
|
||||
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baledung.test;
|
||||
package com.baeldung.test;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
|
@ -14,7 +14,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
|||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import com.baledung.student.Student;
|
||||
import com.baeldung.student.Student;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
|
@ -1,5 +1,5 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
@ -32,6 +32,7 @@
|
|||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>1.3.6.RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
|
|
@ -3,4 +3,5 @@
|
|||
<installed facet="wst.jsdt.web" version="1.0"/>
|
||||
<installed facet="jst.web" version="3.0"/>
|
||||
<installed facet="java" version="1.8"/>
|
||||
<installed facet="jpt.jpa" version="2.1"/>
|
||||
</faceted-project>
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
package com.baeldung.mvc.velocity.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.mvc.velocity.domain.Tutorial;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ITutorialsService {
|
||||
|
||||
public List<Tutorial> listTutorials();
|
||||
List<Tutorial> listTutorials();
|
||||
}
|
||||
|
|
|
@ -1,2 +0,0 @@
|
|||
###The Course
|
||||
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
|
|
@ -1,7 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
|
||||
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
|
||||
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
|
||||
</launchConfiguration>
|
|
@ -1,5 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" path="src/main/webapp"/>
|
||||
<classpathentry kind="output" path=""/>
|
||||
</classpath>
|
|
@ -1,95 +0,0 @@
|
|||
eclipse.preferences.version=1
|
||||
org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
|
||||
org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
|
||||
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
|
||||
org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
|
||||
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
|
||||
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
|
||||
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
|
||||
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
|
||||
org.eclipse.jdt.core.compiler.compliance=1.8
|
||||
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
|
||||
org.eclipse.jdt.core.compiler.debug.localVariable=generate
|
||||
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
|
||||
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
|
||||
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
|
||||
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
|
||||
org.eclipse.jdt.core.compiler.problem.deadCode=warning
|
||||
org.eclipse.jdt.core.compiler.problem.deprecation=warning
|
||||
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
|
||||
org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.fieldHiding=error
|
||||
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
|
||||
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
|
||||
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
|
||||
org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
|
||||
org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.localVariableHiding=error
|
||||
org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
|
||||
org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
|
||||
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
|
||||
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
|
||||
org.eclipse.jdt.core.compiler.problem.nullReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
|
||||
org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
|
||||
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
|
||||
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
|
||||
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
|
||||
org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
|
||||
org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
|
||||
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedImport=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
|
||||
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
|
||||
org.eclipse.jdt.core.compiler.source=1.8
|
|
@ -1,55 +0,0 @@
|
|||
#Sat Jan 21 23:04:06 EET 2012
|
||||
eclipse.preferences.version=1
|
||||
editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
|
||||
sp_cleanup.add_default_serial_version_id=true
|
||||
sp_cleanup.add_generated_serial_version_id=false
|
||||
sp_cleanup.add_missing_annotations=true
|
||||
sp_cleanup.add_missing_deprecated_annotations=true
|
||||
sp_cleanup.add_missing_methods=false
|
||||
sp_cleanup.add_missing_nls_tags=false
|
||||
sp_cleanup.add_missing_override_annotations=true
|
||||
sp_cleanup.add_missing_override_annotations_interface_methods=true
|
||||
sp_cleanup.add_serial_version_id=false
|
||||
sp_cleanup.always_use_blocks=true
|
||||
sp_cleanup.always_use_parentheses_in_expressions=true
|
||||
sp_cleanup.always_use_this_for_non_static_field_access=false
|
||||
sp_cleanup.always_use_this_for_non_static_method_access=false
|
||||
sp_cleanup.convert_to_enhanced_for_loop=true
|
||||
sp_cleanup.correct_indentation=true
|
||||
sp_cleanup.format_source_code=true
|
||||
sp_cleanup.format_source_code_changes_only=true
|
||||
sp_cleanup.make_local_variable_final=true
|
||||
sp_cleanup.make_parameters_final=true
|
||||
sp_cleanup.make_private_fields_final=false
|
||||
sp_cleanup.make_type_abstract_if_missing_method=false
|
||||
sp_cleanup.make_variable_declarations_final=true
|
||||
sp_cleanup.never_use_blocks=false
|
||||
sp_cleanup.never_use_parentheses_in_expressions=false
|
||||
sp_cleanup.on_save_use_additional_actions=true
|
||||
sp_cleanup.organize_imports=true
|
||||
sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
|
||||
sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
|
||||
sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
|
||||
sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
|
||||
sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
|
||||
sp_cleanup.remove_private_constructors=true
|
||||
sp_cleanup.remove_trailing_whitespaces=true
|
||||
sp_cleanup.remove_trailing_whitespaces_all=true
|
||||
sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
|
||||
sp_cleanup.remove_unnecessary_casts=true
|
||||
sp_cleanup.remove_unnecessary_nls_tags=false
|
||||
sp_cleanup.remove_unused_imports=true
|
||||
sp_cleanup.remove_unused_local_variables=false
|
||||
sp_cleanup.remove_unused_private_fields=true
|
||||
sp_cleanup.remove_unused_private_members=false
|
||||
sp_cleanup.remove_unused_private_methods=true
|
||||
sp_cleanup.remove_unused_private_types=true
|
||||
sp_cleanup.sort_members=false
|
||||
sp_cleanup.sort_members_all=false
|
||||
sp_cleanup.use_blocks=false
|
||||
sp_cleanup.use_blocks_only_for_return_and_throw=false
|
||||
sp_cleanup.use_parentheses_in_expressions=false
|
||||
sp_cleanup.use_this_for_non_static_field_access=true
|
||||
sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
|
||||
sp_cleanup.use_this_for_non_static_method_access=true
|
||||
sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
|
|
@ -1,4 +0,0 @@
|
|||
activeProfiles=
|
||||
eclipse.preferences.version=1
|
||||
resolveWorkspaceProjects=true
|
||||
version=1
|
|
@ -1,2 +0,0 @@
|
|||
eclipse.preferences.version=1
|
||||
org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false
|
|
@ -1,10 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
|
||||
<wb-module deploy-name="spring-security-mvc-basic-auth">
|
||||
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
|
||||
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
|
||||
<property name="java-output-path" value="/spring-security-mvc-basic-auth/target/classes"/>
|
||||
<property name="context-root" value="spring-security-mvc-basic-auth"/>
|
||||
</wb-module>
|
||||
</project-modules>
|
|
@ -1,5 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<faceted-project>
|
||||
<installed facet="jst.web" version="3.0"/>
|
||||
<installed facet="java" version="1.8"/>
|
||||
</faceted-project>
|
|
@ -1 +0,0 @@
|
|||
org.eclipse.wst.jsdt.launching.baseBrowserLibrary
|
|
@ -1 +0,0 @@
|
|||
Window
|
|
@ -1,15 +0,0 @@
|
|||
DELEGATES_PREFERENCE=delegateValidatorList
|
||||
USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
|
||||
USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
|
||||
USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.402.v201212031633
|
||||
disabled=06target
|
||||
eclipse.preferences.version=1
|
||||
override=true
|
||||
suspend=false
|
||||
vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01
|
||||
vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01
|
||||
vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01
|
||||
vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01
|
||||
vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01
|
||||
vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02
|
||||
vf.version=3
|
|
@ -1,2 +0,0 @@
|
|||
eclipse.preferences.version=1
|
||||
org.eclipse.wst.ws.service.policy.projectEnabled=false
|
|
@ -44,8 +44,9 @@ public class SecurityWithoutCsrfConfig extends WebSecurityConfigurerAdapter {
|
|||
http
|
||||
.csrf().disable()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN")
|
||||
.anyRequest().authenticated()
|
||||
.antMatchers("/auth/admin/*").hasRole("ADMIN")
|
||||
.antMatchers("/auth/*").hasAnyRole("ADMIN","USER")
|
||||
.antMatchers("/*").permitAll()
|
||||
.and()
|
||||
.httpBasic()
|
||||
.and()
|
||||
|
|
|
@ -14,24 +14,25 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
|||
@EnableWebMvc
|
||||
public class WebConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
public WebConfig() {
|
||||
super();
|
||||
}
|
||||
public WebConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver viewResolver() {
|
||||
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
|
||||
viewResolver.setPrefix("/WEB-INF/view/");
|
||||
viewResolver.setSuffix(".jsp");
|
||||
return viewResolver;
|
||||
}
|
||||
@Bean
|
||||
public ViewResolver viewResolver() {
|
||||
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
|
||||
viewResolver.setPrefix("/WEB-INF/view/");
|
||||
viewResolver.setSuffix(".jsp");
|
||||
return viewResolver;
|
||||
}
|
||||
|
||||
// API
|
||||
@Override
|
||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||
super.addViewControllers(registry);
|
||||
registry.addViewController("/graph.html");
|
||||
registry.addViewController("/csrfHome.html");
|
||||
}
|
||||
// API
|
||||
@Override
|
||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||
super.addViewControllers(registry);
|
||||
registry.addViewController("/graph.html");
|
||||
registry.addViewController("/csrfHome.html");
|
||||
registry.addViewController("/homepage.html");
|
||||
}
|
||||
|
||||
}
|
|
@ -12,21 +12,22 @@ import org.springframework.web.bind.annotation.ResponseStatus;
|
|||
|
||||
// to test csrf
|
||||
@Controller
|
||||
@RequestMapping(value = "/auth/")
|
||||
public class BankController {
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
@RequestMapping(value = "/transfer", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
||||
logger.info("Transfer to {}", accountNo);
|
||||
return amount;
|
||||
}
|
||||
@RequestMapping(value = "/transfer", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
||||
logger.info("Transfer to {}", accountNo);
|
||||
return amount;
|
||||
}
|
||||
|
||||
// write - just for test
|
||||
@RequestMapping(value = "/transfer", method = RequestMethod.POST)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
||||
logger.info("Transfer to {}", accountNo);
|
||||
// write - just for test
|
||||
@RequestMapping(value = "/transfer", method = RequestMethod.POST)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
|
||||
logger.info("Transfer to {}", accountNo);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -29,93 +29,93 @@ import org.springframework.web.util.UriComponentsBuilder;
|
|||
import com.google.common.base.Preconditions;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/foos")
|
||||
@RequestMapping(value = "/auth/foos")
|
||||
public class FooController {
|
||||
|
||||
@Autowired
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
@Autowired
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
|
||||
@Autowired
|
||||
private IFooService service;
|
||||
@Autowired
|
||||
private IFooService service;
|
||||
|
||||
public FooController() {
|
||||
super();
|
||||
}
|
||||
public FooController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
// API
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/count")
|
||||
@ResponseBody
|
||||
@ResponseStatus(value = HttpStatus.OK)
|
||||
public long count() {
|
||||
return 2l;
|
||||
}
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/count")
|
||||
@ResponseBody
|
||||
@ResponseStatus(value = HttpStatus.OK)
|
||||
public long count() {
|
||||
return 2l;
|
||||
}
|
||||
|
||||
// read - one
|
||||
// read - one
|
||||
|
||||
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
|
||||
final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
|
||||
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
|
||||
final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
|
||||
|
||||
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
|
||||
return resourceById;
|
||||
}
|
||||
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
|
||||
return resourceById;
|
||||
}
|
||||
|
||||
// read - all
|
||||
// read - all
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public List<Foo> findAll() {
|
||||
return service.findAll();
|
||||
}
|
||||
@RequestMapping(method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public List<Foo> findAll() {
|
||||
return service.findAll();
|
||||
}
|
||||
|
||||
@RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
|
||||
final Page<Foo> resultPage = service.findPaginated(page, size);
|
||||
if (page > resultPage.getTotalPages()) {
|
||||
throw new MyResourceNotFoundException();
|
||||
}
|
||||
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));
|
||||
@RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
|
||||
final Page<Foo> resultPage = service.findPaginated(page, size);
|
||||
if (page > resultPage.getTotalPages()) {
|
||||
throw new MyResourceNotFoundException();
|
||||
}
|
||||
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));
|
||||
|
||||
return resultPage.getContent();
|
||||
}
|
||||
return resultPage.getContent();
|
||||
}
|
||||
|
||||
// write
|
||||
// write
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST)
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
@ResponseBody
|
||||
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
|
||||
Preconditions.checkNotNull(resource);
|
||||
final Foo foo = service.create(resource);
|
||||
final Long idOfCreatedResource = foo.getId();
|
||||
@RequestMapping(method = RequestMethod.POST)
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
@ResponseBody
|
||||
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
|
||||
Preconditions.checkNotNull(resource);
|
||||
final Foo foo = service.create(resource);
|
||||
final Long idOfCreatedResource = foo.getId();
|
||||
|
||||
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
|
||||
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
|
||||
|
||||
return foo;
|
||||
}
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
|
||||
Preconditions.checkNotNull(resource);
|
||||
RestPreconditions.checkFound(service.findOne(resource.getId()));
|
||||
service.update(resource);
|
||||
}
|
||||
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
|
||||
Preconditions.checkNotNull(resource);
|
||||
RestPreconditions.checkFound(service.findOne(resource.getId()));
|
||||
service.update(resource);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void delete(@PathVariable("id") final Long id) {
|
||||
service.deleteById(id);
|
||||
}
|
||||
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void delete(@PathVariable("id") final Long id) {
|
||||
service.deleteById(id);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.HEAD)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void head(final HttpServletResponse resp) {
|
||||
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
resp.setHeader("bar", "baz");
|
||||
}
|
||||
@RequestMapping(method = RequestMethod.HEAD)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void head(final HttpServletResponse resp) {
|
||||
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
resp.setHeader("bar", "baz");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,14 @@
|
|||
package org.baeldung.web.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/")
|
||||
public class HomeController {
|
||||
|
||||
public String index() {
|
||||
return "homepage";
|
||||
}
|
||||
|
||||
}
|
|
@ -20,65 +20,66 @@ import org.springframework.web.bind.annotation.ResponseStatus;
|
|||
import org.springframework.web.util.UriTemplate;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/auth/")
|
||||
public class RootController {
|
||||
|
||||
@Autowired
|
||||
private IMetricService metricService;
|
||||
@Autowired
|
||||
private IMetricService metricService;
|
||||
|
||||
@Autowired
|
||||
private IActuatorMetricService actMetricService;
|
||||
@Autowired
|
||||
private IActuatorMetricService actMetricService;
|
||||
|
||||
public RootController() {
|
||||
super();
|
||||
}
|
||||
public RootController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
// API
|
||||
|
||||
// discover
|
||||
// discover
|
||||
|
||||
@RequestMapping(value = "admin", method = RequestMethod.GET)
|
||||
@ResponseStatus(value = HttpStatus.NO_CONTENT)
|
||||
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
|
||||
final String rootUri = request.getRequestURL().toString();
|
||||
@RequestMapping(value = "admin", method = RequestMethod.GET)
|
||||
@ResponseStatus(value = HttpStatus.NO_CONTENT)
|
||||
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
|
||||
final String rootUri = request.getRequestURL().toString();
|
||||
|
||||
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
|
||||
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
|
||||
response.addHeader("Link", linkToFoo);
|
||||
}
|
||||
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
|
||||
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
|
||||
response.addHeader("Link", linkToFoo);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/metric", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Map getMetric() {
|
||||
return metricService.getFullMetric();
|
||||
}
|
||||
@RequestMapping(value = "/metric", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Map getMetric() {
|
||||
return metricService.getFullMetric();
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@RequestMapping(value = "/status-metric", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Map getStatusMetric() {
|
||||
return metricService.getStatusMetric();
|
||||
}
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@RequestMapping(value = "/status-metric", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Map getStatusMetric() {
|
||||
return metricService.getStatusMetric();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Object[][] drawMetric() {
|
||||
final Object[][] result = metricService.getGraphData();
|
||||
for (int i = 1; i < result[0].length; i++) {
|
||||
result[0][i] = result[0][i].toString();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Object[][] drawMetric() {
|
||||
final Object[][] result = metricService.getGraphData();
|
||||
for (int i = 1; i < result[0].length; i++) {
|
||||
result[0][i] = result[0][i].toString();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/admin/x", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public String sampleAdminPage() {
|
||||
return "Hello";
|
||||
}
|
||||
@RequestMapping(value = "/admin/x", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public String sampleAdminPage() {
|
||||
return "Hello";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public String sampleErrorPage() {
|
||||
return "Error Occurred";
|
||||
}
|
||||
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public String sampleErrorPage() {
|
||||
return "Error Occurred";
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -37,96 +37,97 @@ import cz.jirutka.rsql.parser.ast.Node;
|
|||
|
||||
//@EnableSpringDataWebSupport
|
||||
@Controller
|
||||
@RequestMapping(value = "/auth/")
|
||||
public class UserController {
|
||||
|
||||
@Autowired
|
||||
private IUserDAO service;
|
||||
@Autowired
|
||||
private IUserDAO service;
|
||||
|
||||
@Autowired
|
||||
private UserRepository dao;
|
||||
@Autowired
|
||||
private UserRepository dao;
|
||||
|
||||
@Autowired
|
||||
private MyUserRepository myUserRepository;
|
||||
@Autowired
|
||||
private MyUserRepository myUserRepository;
|
||||
|
||||
public UserController() {
|
||||
super();
|
||||
}
|
||||
public UserController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API - READ
|
||||
// API - READ
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/users")
|
||||
@ResponseBody
|
||||
public List<User> findAll(@RequestParam(value = "search", required = false) final String search) {
|
||||
final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
|
||||
if (search != null) {
|
||||
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
||||
final Matcher matcher = pattern.matcher(search + ",");
|
||||
while (matcher.find()) {
|
||||
params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
|
||||
}
|
||||
}
|
||||
return service.searchUser(params);
|
||||
}
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/users")
|
||||
@ResponseBody
|
||||
public List<User> findAll(@RequestParam(value = "search", required = false) final String search) {
|
||||
final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
|
||||
if (search != null) {
|
||||
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
||||
final Matcher matcher = pattern.matcher(search + ",");
|
||||
while (matcher.find()) {
|
||||
params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
|
||||
}
|
||||
}
|
||||
return service.searchUser(params);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/users/spec")
|
||||
@ResponseBody
|
||||
public List<User> findAllBySpecification(@RequestParam(value = "search") final String search) {
|
||||
final UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
|
||||
final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
|
||||
final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
|
||||
final Matcher matcher = pattern.matcher(search + ",");
|
||||
while (matcher.find()) {
|
||||
builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5));
|
||||
}
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/users/spec")
|
||||
@ResponseBody
|
||||
public List<User> findAllBySpecification(@RequestParam(value = "search") final String search) {
|
||||
final UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
|
||||
final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
|
||||
final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
|
||||
final Matcher matcher = pattern.matcher(search + ",");
|
||||
while (matcher.find()) {
|
||||
builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5));
|
||||
}
|
||||
|
||||
final Specification<User> spec = builder.build();
|
||||
return dao.findAll(spec);
|
||||
}
|
||||
final Specification<User> spec = builder.build();
|
||||
return dao.findAll(spec);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/myusers")
|
||||
@ResponseBody
|
||||
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") final String search) {
|
||||
final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
|
||||
if (search != null) {
|
||||
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
||||
final Matcher matcher = pattern.matcher(search + ",");
|
||||
while (matcher.find()) {
|
||||
builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
|
||||
}
|
||||
}
|
||||
final BooleanExpression exp = builder.build();
|
||||
return myUserRepository.findAll(exp);
|
||||
}
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/myusers")
|
||||
@ResponseBody
|
||||
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") final String search) {
|
||||
final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
|
||||
if (search != null) {
|
||||
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
|
||||
final Matcher matcher = pattern.matcher(search + ",");
|
||||
while (matcher.find()) {
|
||||
builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
|
||||
}
|
||||
}
|
||||
final BooleanExpression exp = builder.build();
|
||||
return myUserRepository.findAll(exp);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
|
||||
@ResponseBody
|
||||
public List<User> findAllByRsql(@RequestParam(value = "search") final String search) {
|
||||
final Node rootNode = new RSQLParser().parse(search);
|
||||
final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
|
||||
return dao.findAll(spec);
|
||||
}
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
|
||||
@ResponseBody
|
||||
public List<User> findAllByRsql(@RequestParam(value = "search") final String search) {
|
||||
final Node rootNode = new RSQLParser().parse(search);
|
||||
final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
|
||||
return dao.findAll(spec);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
|
||||
@ResponseBody
|
||||
public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) {
|
||||
return myUserRepository.findAll(predicate);
|
||||
}
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
|
||||
@ResponseBody
|
||||
public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) {
|
||||
return myUserRepository.findAll(predicate);
|
||||
}
|
||||
|
||||
// API - WRITE
|
||||
// API - WRITE
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, value = "/users")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public void create(@RequestBody final User resource) {
|
||||
Preconditions.checkNotNull(resource);
|
||||
dao.save(resource);
|
||||
}
|
||||
@RequestMapping(method = RequestMethod.POST, value = "/users")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public void create(@RequestBody final User resource) {
|
||||
Preconditions.checkNotNull(resource);
|
||||
dao.save(resource);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, value = "/myusers")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public void addMyUser(@RequestBody final MyUser resource) {
|
||||
Preconditions.checkNotNull(resource);
|
||||
myUserRepository.save(resource);
|
||||
@RequestMapping(method = RequestMethod.POST, value = "/myusers")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public void addMyUser(@RequestBody final MyUser resource) {
|
||||
Preconditions.checkNotNull(resource);
|
||||
myUserRepository.save(resource);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -23,26 +23,30 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
|||
@WebAppConfiguration
|
||||
public class CsrfAbstractIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext context;
|
||||
@Autowired
|
||||
private WebApplicationContext context;
|
||||
|
||||
@Autowired
|
||||
private Filter springSecurityFilterChain;
|
||||
@Autowired
|
||||
private Filter springSecurityFilterChain;
|
||||
|
||||
protected MockMvc mvc;
|
||||
protected MockMvc mvc;
|
||||
|
||||
//
|
||||
//
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
|
||||
}
|
||||
|
||||
protected RequestPostProcessor testUser() {
|
||||
return user("user").password("userPass").roles("USER");
|
||||
}
|
||||
protected RequestPostProcessor testUser() {
|
||||
return user("user").password("userPass").roles("USER");
|
||||
}
|
||||
|
||||
protected String createFoo() throws JsonProcessingException {
|
||||
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
|
||||
}
|
||||
protected RequestPostProcessor testAdmin() {
|
||||
return user("admin").password("adminPass").roles("USER", "ADMIN");
|
||||
}
|
||||
|
||||
protected String createFoo() throws JsonProcessingException {
|
||||
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package org.baeldung.security.csrf;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
|
@ -13,14 +14,33 @@ import org.springframework.test.context.ContextConfiguration;
|
|||
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
|
||||
public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
|
||||
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
|
||||
}
|
||||
@Test
|
||||
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
|
||||
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuth_whenAddFoo_thenCreated() throws Exception {
|
||||
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
|
||||
}
|
||||
@Test
|
||||
public void givenAuth_whenAddFoo_thenCreated() throws Exception {
|
||||
mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void accessMainPageWithoutAuthorization() throws Exception {
|
||||
mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void accessOtherPages() throws Exception {
|
||||
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100"))
|
||||
.andExpect(status().isUnauthorized()); // without authorization
|
||||
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100").with(testUser()))
|
||||
.andExpect(status().isOk()); // with authorization
|
||||
}
|
||||
|
||||
@Test
|
||||
public void accessAdminPage() throws Exception {
|
||||
mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); //without authorization
|
||||
mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON).with(testAdmin())).andExpect(status().isOk()); //with authorization
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,46 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>xmlunit2-tutorial</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>XMLUnit-2</name>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<source>7</source>
|
||||
<target>7</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<version>1.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.xmlunit</groupId>
|
||||
<artifactId>xmlunit-matchers</artifactId>
|
||||
<version>2.2.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.xmlunit</groupId>
|
||||
<artifactId>xmlunit-core</artifactId>
|
||||
<version>2.2.1</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.xmlunit;
|
||||
|
||||
import org.w3c.dom.Attr;
|
||||
import org.w3c.dom.Node;
|
||||
import org.xmlunit.diff.Comparison;
|
||||
import org.xmlunit.diff.ComparisonResult;
|
||||
import org.xmlunit.diff.DifferenceEvaluator;
|
||||
|
||||
public class IgnoreAttributeDifferenceEvaluator implements DifferenceEvaluator {
|
||||
|
||||
private String attributeName;
|
||||
|
||||
public IgnoreAttributeDifferenceEvaluator(String attributeName) {
|
||||
this.attributeName = attributeName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ComparisonResult evaluate(Comparison comparison,
|
||||
ComparisonResult outcome) {
|
||||
if (outcome == ComparisonResult.EQUAL)
|
||||
return outcome;
|
||||
final Node controlNode = comparison.getControlDetails().getTarget();
|
||||
if (controlNode instanceof Attr) {
|
||||
Attr attr = (Attr) controlNode;
|
||||
if (attr.getName().equals(attributeName)) {
|
||||
return ComparisonResult.SIMILAR;
|
||||
}
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,290 @@
|
|||
package com.baeldung.xmlunit;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.core.IsNot.not;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
|
||||
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
|
||||
import static org.xmlunit.matchers.HasXPathMatcher.hasXPath;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.xmlunit.builder.DiffBuilder;
|
||||
import org.xmlunit.builder.Input;
|
||||
import org.xmlunit.diff.ComparisonControllers;
|
||||
import org.xmlunit.diff.DefaultNodeMatcher;
|
||||
import org.xmlunit.diff.Diff;
|
||||
import org.xmlunit.diff.Difference;
|
||||
import org.xmlunit.diff.ElementSelectors;
|
||||
import org.xmlunit.validation.Languages;
|
||||
import org.xmlunit.validation.ValidationProblem;
|
||||
import org.xmlunit.validation.ValidationResult;
|
||||
import org.xmlunit.validation.Validator;
|
||||
import org.xmlunit.xpath.JAXPXPathEngine;
|
||||
|
||||
public class XMLUnitTest {
|
||||
@Test
|
||||
public void givenWrongXml_whenValidateFailsAgainstXsd_thenCorrect() {
|
||||
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
||||
v.setSchemaSource(Input.fromStream(
|
||||
new XMLUnitTest().getClass().getResourceAsStream(
|
||||
"/students.xsd")).build());
|
||||
ValidationResult r = v.validateInstance(Input.fromStream(
|
||||
new XMLUnitTest().getClass().getResourceAsStream(
|
||||
"/students_with_error.xml")).build());
|
||||
assertFalse(r.isValid());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXmlWithErrors_whenReturnsValidationProblems_thenCorrect() {
|
||||
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
||||
v.setSchemaSource(Input.fromStream(
|
||||
new XMLUnitTest().getClass().getResourceAsStream(
|
||||
"/students.xsd")).build());
|
||||
ValidationResult r = v.validateInstance(Input.fromStream(
|
||||
new XMLUnitTest().getClass().getResourceAsStream(
|
||||
"/students_with_error.xml")).build());
|
||||
Iterator<ValidationProblem> probs = r.getProblems().iterator();
|
||||
int count = 0;
|
||||
while (probs.hasNext()) {
|
||||
count++;
|
||||
probs.next().toString();
|
||||
}
|
||||
assertTrue(count > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXml_whenValidatesAgainstXsd_thenCorrect() {
|
||||
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
||||
v.setSchemaSource(Input.fromStream(
|
||||
new XMLUnitTest().getClass().getResourceAsStream(
|
||||
"/students.xsd")).build());
|
||||
ValidationResult r = v.validateInstance(Input.fromStream(
|
||||
new XMLUnitTest().getClass().getResourceAsStream(
|
||||
"/students.xml")).build());
|
||||
Iterator<ValidationProblem> probs = r.getProblems().iterator();
|
||||
while (probs.hasNext()) {
|
||||
System.out.println(probs.next().toString());
|
||||
}
|
||||
assertTrue(r.isValid());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXPath_whenAbleToRetrieveNodes_thenCorrect() {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
|
||||
Iterable<Node> i = new JAXPXPathEngine().selectNodes(
|
||||
"//teacher",
|
||||
Input.fromFile(
|
||||
new File(classLoader.getResource("teachers.xml")
|
||||
.getFile())).build());
|
||||
assertNotNull(i);
|
||||
int count = 0;
|
||||
for (Iterator<Node> it = i.iterator(); it.hasNext();) {
|
||||
count++;
|
||||
Node node = it.next();
|
||||
assertEquals("teacher", node.getNodeName());
|
||||
NamedNodeMap map = node.getAttributes();
|
||||
assertEquals("department", map.item(0).getNodeName());
|
||||
assertEquals("id", map.item(1).getNodeName());
|
||||
assertEquals("teacher", node.getNodeName());
|
||||
}
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXmlSource_whenAbleToValidateExistingXPath_thenCorrect() {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
||||
"teachers.xml").getFile())), hasXPath("//teachers"));
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
||||
"teachers.xml").getFile())), hasXPath("//teacher"));
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
||||
"teachers.xml").getFile())), hasXPath("//subject"));
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
||||
"teachers.xml").getFile())), hasXPath("//@department"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXmlSource_whenFailsToValidateInExistentXPath_thenCorrect() {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
||||
"teachers.xml").getFile())), not(hasXPath("//sujet")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2XMLs_whenSimilarWithDiff_thenCorrect() throws Exception {
|
||||
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||
|
||||
Diff myDiffSimilar = DiffBuilder
|
||||
.compare(myControlXML)
|
||||
.withTest(myTestXML)
|
||||
.withNodeMatcher(
|
||||
new DefaultNodeMatcher(ElementSelectors.byName))
|
||||
.checkForSimilar().build();
|
||||
assertFalse("XML similar " + myDiffSimilar.toString(),
|
||||
myDiffSimilar.hasDifferences());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2XMLsWithDifferences_whenTestsSimilarWithDifferenceEvaluator_thenCorrect() {
|
||||
final String control = "<a><b attr=\"abc\"></b></a>";
|
||||
final String test = "<a><b attr=\"xyz\"></b></a>";
|
||||
Diff myDiff = DiffBuilder
|
||||
.compare(control)
|
||||
.withTest(test)
|
||||
.withDifferenceEvaluator(
|
||||
new IgnoreAttributeDifferenceEvaluator("attr"))
|
||||
.checkForSimilar().build();
|
||||
|
||||
assertFalse(myDiff.toString(), myDiff.hasDifferences());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2XMLsWithDifferences_whenTestsDifferentWithoutDifferenceEvaluator_thenCorrect() {
|
||||
final String control = "<a><b attr=\"abc\"></b></a>";
|
||||
final String test = "<a><b attr=\"xyz\"></b></a>";
|
||||
|
||||
Diff myDiff = DiffBuilder.compare(control).withTest(test)
|
||||
.checkForSimilar().build();
|
||||
|
||||
assertTrue(myDiff.toString(), myDiff.hasDifferences());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2XMLS_whenSimilarWithCustomElementSelector_thenCorrect() {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||
assertThat(
|
||||
testXml,
|
||||
isSimilarTo(controlXml).withNodeMatcher(
|
||||
new DefaultNodeMatcher(ElementSelectors.byName)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileSourceAsObject_whenAbleToInput_thenCorrect() {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
assertThat(Input.from(new File(classLoader.getResource("test.xml")
|
||||
.getFile())), isSimilarTo(Input.from(new File(classLoader
|
||||
.getResource("control.xml").getFile()))));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStreamAsSource_whenAbleToInput_thenCorrect() {
|
||||
assertThat(Input.fromStream(new XMLUnitTest().getClass()
|
||||
.getResourceAsStream("/test.xml")),
|
||||
isSimilarTo(Input.fromStream(new XMLUnitTest().getClass()
|
||||
.getResourceAsStream("/control.xml"))));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStreamAsObject_whenAbleToInput_thenCorrect() {
|
||||
assertThat(Input.from(new XMLUnitTest().getClass().getResourceAsStream(
|
||||
"/test.xml")), isSimilarTo(Input.from(new XMLUnitTest()
|
||||
.getClass().getResourceAsStream("/control.xml"))));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringSourceAsObject_whenAbleToInput_thenCorrect() {
|
||||
assertThat(
|
||||
Input.from("<struct><int>3</int><boolean>false</boolean></struct>"),
|
||||
isSimilarTo(Input
|
||||
.from("<struct><int>3</int><boolean>false</boolean></struct>")));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileSource_whenAbleToInput_thenCorrect() {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
String testPath = classLoader.getResource("test.xml").getPath();
|
||||
String controlPath = classLoader.getResource("control.xml").getPath();
|
||||
assertThat(Input.fromFile(testPath),
|
||||
isSimilarTo(Input.fromFile(controlPath)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringSource_whenAbleToInput_thenCorrect() {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
assertThat(Input.fromString(testXml),
|
||||
isSimilarTo(Input.fromString(controlXml)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSource_whenAbleToInput_thenCorrect() {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
assertThat(Input.fromString(testXml),
|
||||
isSimilarTo(Input.fromString(controlXml)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2XMLS_whenIdentical_thenCorrect() {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
assertThat(testXml, isIdenticalTo(controlXml));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2XMLSWithSimilarNodesButDifferentSequence_whenNotIdentical_thenCorrect() {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||
assertThat(testXml, not(isIdenticalTo(controlXml)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2XMLS_whenGeneratesDifferences_thenCorrect()
|
||||
throws Exception {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||
Diff myDiff = DiffBuilder.compare(controlXml).withTest(testXml).build();
|
||||
Iterator<Difference> iter = myDiff.getDifferences().iterator();
|
||||
int size = 0;
|
||||
while (iter.hasNext()) {
|
||||
iter.next().toString();
|
||||
size++;
|
||||
}
|
||||
assertThat(size, greaterThan(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2XMLS_whenGeneratesOneDifference_thenCorrect()
|
||||
throws Exception {
|
||||
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||
Diff myDiff = DiffBuilder
|
||||
.compare(myControlXML)
|
||||
.withTest(myTestXML)
|
||||
.withComparisonController(
|
||||
ComparisonControllers.StopWhenDifferent).build();
|
||||
Iterator<Difference> iter = myDiff.getDifferences().iterator();
|
||||
int size = 0;
|
||||
while (iter.hasNext()) {
|
||||
iter.next().toString();
|
||||
size++;
|
||||
}
|
||||
assertThat(size, equalTo(1));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
<struct>
|
||||
<int>3</int>
|
||||
<boolean>false</boolean>
|
||||
</struct>
|
|
@ -0,0 +1,11 @@
|
|||
<?xml version = "1.0"?>
|
||||
<class>
|
||||
<student id="393">
|
||||
<name>Rajiv</name>
|
||||
<age>18</age>
|
||||
</student>
|
||||
<student id="493">
|
||||
<name>Candie</name>
|
||||
<age>19</age>
|
||||
</student>
|
||||
</class>
|
|
@ -0,0 +1,18 @@
|
|||
<?xml version = "1.0"?>
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
|
||||
<xs:element name='class'>
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element name='student' type='StudentObject'
|
||||
minOccurs='0' maxOccurs='unbounded' />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:complexType name="StudentObject">
|
||||
<xs:sequence>
|
||||
<xs:element name="name" type="xs:string" />
|
||||
<xs:element name="age" type="xs:positiveInteger" />
|
||||
</xs:sequence>
|
||||
<xs:attribute name='id' type='xs:positiveInteger' />
|
||||
</xs:complexType>
|
||||
</xs:schema>
|
|
@ -0,0 +1,12 @@
|
|||
<?xml version = "1.0"?>
|
||||
<class>
|
||||
<studet id="393">
|
||||
<name>Rajiv</name>
|
||||
<age>18</age>
|
||||
</student>
|
||||
|
||||
<studet id="493">
|
||||
<name>Candie</name>
|
||||
<age>19</age>
|
||||
</student>
|
||||
</class>
|
|
@ -0,0 +1,10 @@
|
|||
<teachers>
|
||||
<teacher department="science" id='309'>
|
||||
<subject>math</subject>
|
||||
<subject>physics</subject>
|
||||
</teacher>
|
||||
<teacher department="arts" id='310'>
|
||||
<subject>political education</subject>
|
||||
<subject>english</subject>
|
||||
</teacher>
|
||||
</teachers>
|
|
@ -0,0 +1,4 @@
|
|||
<struct>
|
||||
<int>3</int>
|
||||
<boolean>false</boolean>
|
||||
</struct>
|
Loading…
Reference in New Issue