Merge remote-tracking branch 'origin/master'

Conflicts:
	pom.xml
This commit is contained in:
Slavisa Baeldung 2016-07-25 14:33:17 +02:00
commit 45f0774c83
95 changed files with 1770 additions and 1088 deletions

1
apache-cxf/cxf-spring/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
target/

View File

@ -8,18 +8,42 @@
<artifactId>apache-cxf</artifactId> <artifactId>apache-cxf</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<properties>
<cxf.version>3.1.6</cxf.version> <dependencies>
<spring.version>4.3.1.RELEASE</spring.version> <dependency>
<surefire.version>2.19.1</surefire.version> <groupId>org.apache.cxf</groupId>
</properties> <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> <build>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<version>2.6</version> <version>2.6</version>
<configuration> <configuration>
<webXml>src/main/webapp/WEB-INF/web.xml</webXml> <failOnMissingWebXml>false</failOnMissingWebXml>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
@ -33,6 +57,7 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<profiles> <profiles>
<profile> <profile>
<id>integration</id> <id>integration</id>
@ -50,7 +75,7 @@
<configuration> <configuration>
<properties> <properties>
<cargo.hostname>localhost</cargo.hostname> <cargo.hostname>localhost</cargo.hostname>
<cargo.servlet.port>8080</cargo.servlet.port> <cargo.servlet.port>8081</cargo.servlet.port>
</properties> </properties>
</configuration> </configuration>
</configuration> </configuration>
@ -71,6 +96,7 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version> <version>${surefire.version}</version>
@ -91,27 +117,13 @@
</plugins> </plugins>
</build> </build>
</profile> </profile>
</profiles> </profiles>
<dependencies>
<dependency> <properties>
<groupId>org.apache.cxf</groupId> <cxf.version>3.1.6</cxf.version>
<artifactId>cxf-rt-frontend-jaxws</artifactId> <spring.version>4.3.1.RELEASE</spring.version>
<version>${cxf.version}</version> <surefire.version>2.19.1</surefire.version>
</dependency> </properties>
<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>
</project> </project>

View File

@ -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");
}
}

View File

@ -5,5 +5,6 @@ import javax.jws.WebService;
@WebService @WebService
public interface Baeldung { public interface Baeldung {
String hello(String name); String hello(String name);
String register(Student student); String register(Student student);
} }

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -3,15 +3,12 @@ package com.baeldung.cxf.spring;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import org.junit.Test; import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class StudentTest { public class StudentTest {
private ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "client-beans.xml" }); private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class);
private Baeldung baeldungProxy; private Baeldung baeldungProxy = (Baeldung) context.getBean("client");
{
baeldungProxy = (Baeldung) context.getBean("client");
}
@Test @Test
public void whenUsingHelloMethod_thenCorrect() { public void whenUsingHelloMethod_thenCorrect() {

View File

@ -1,5 +1,4 @@
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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"> 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> <modelVersion>4.0.0</modelVersion>
@ -9,7 +8,7 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging> <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 <description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely
Resource, Inject, and Autowired Resource, Inject, and Autowired
</description> </description>
@ -54,6 +53,7 @@
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
@ -71,13 +71,29 @@
</includes> </includes>
</configuration> </configuration>
</plugin> </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> </plugins>
</build> </build>
<properties>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
</properties>
<repositories> <repositories>
<repository> <repository>
<id>java.net</id> <id>java.net</id>
<url>https://maven.java.net/content/repositories/releases/</url> <url>https://maven.java.net/content/repositories/releases/</url>
</repository> </repository>
</repositories> </repositories>
</project> </project>

View File

@ -7,9 +7,19 @@ import java.util.List;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext; 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 @Override
public List<ItemWithSerializer> deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException { public List<ItemWithSerializer> deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {

View File

@ -6,11 +6,20 @@ import java.util.List;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; 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 @Override
public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
final List<Integer> ids = new ArrayList<Integer>(); final List<Integer> ids = new ArrayList<Integer>();

View File

@ -8,12 +8,21 @@ import java.util.Date;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext; 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"); private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
public CustomDateDeserializer() {
this(null);
}
public CustomDateDeserializer(final Class<?> vc) {
super(vc);
}
@Override @Override
public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException { public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {
final String date = jsonparser.getText(); final String date = jsonparser.getText();

View File

@ -6,13 +6,22 @@ import java.util.Date;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; 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"); private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
public CustomDateSerializer() {
this(null);
}
public CustomDateSerializer(final Class<Date> t) {
super(t);
}
@Override @Override
public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException { public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
gen.writeString(formatter.format(value)); gen.writeString(formatter.format(value));

View File

@ -8,10 +8,20 @@ import org.joda.time.format.DateTimeFormatter;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; 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"); private static DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");

View File

@ -6,13 +6,23 @@ import java.time.format.DateTimeFormatter;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; 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"); private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
public CustomLocalDateTimeSerializer() {
this(null);
}
public CustomLocalDateTimeSerializer(final Class<LocalDateTime> t) {
super(t);
}
@Override @Override
public void serialize(final LocalDateTime value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException { public void serialize(final LocalDateTime value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
gen.writeString(formatter.format(value)); gen.writeString(formatter.format(value));

View File

@ -2,17 +2,26 @@ package com.baeldung.jackson.deserialization;
import java.io.IOException; import java.io.IOException;
import com.baeldung.jackson.dtos.User;
import com.baeldung.jackson.dtos.Item; import com.baeldung.jackson.dtos.Item;
import com.baeldung.jackson.dtos.User;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.node.IntNode; 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} * {"id":1,"itemNr":"theItem","owner":2}

View File

@ -4,15 +4,24 @@ import java.io.IOException;
import com.baeldung.jackson.dtos.ItemWithSerializer; import com.baeldung.jackson.dtos.ItemWithSerializer;
import com.baeldung.jackson.dtos.User; import com.baeldung.jackson.dtos.User;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.node.IntNode; 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} * {"id":1,"itemNr":"theItem","owner":2}

View File

@ -4,10 +4,20 @@ import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; 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 @Override
public void serialize(final TypeEnumWithCustomSerializer value, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { public void serialize(final TypeEnumWithCustomSerializer value, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {

View File

@ -3,13 +3,22 @@ package com.baeldung.jackson.serialization;
import java.io.IOException; import java.io.IOException;
import com.baeldung.jackson.dtos.Item; import com.baeldung.jackson.dtos.Item;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; 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 @Override
public final void serialize(final Item value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { public final void serialize(final Item value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {

View File

@ -3,13 +3,22 @@ package com.baeldung.jackson.serialization;
import java.io.IOException; import java.io.IOException;
import com.baeldung.jackson.dtos.ItemWithSerializer; import com.baeldung.jackson.dtos.ItemWithSerializer;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; 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 @Override
public final void serialize(final ItemWithSerializer value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { public final void serialize(final ItemWithSerializer value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {

View File

@ -4,10 +4,20 @@ import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; 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 @Override
public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {

View File

@ -6,10 +6,19 @@ import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode; 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 @Override
public RestLoaderRequest<IEntity> deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { public RestLoaderRequest<IEntity> deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {

View File

@ -5,3 +5,4 @@
### Relevant Articles: ### Relevant Articles:
- [JMockit 101](http://www.baeldung.com/jmockit-101) - [JMockit 101](http://www.baeldung.com/jmockit-101)
- [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations)

View File

@ -1,9 +1,11 @@
package org.baeldung.mocks.jmockit; package org.baeldung.mocks.jmockit;
public class Collaborator { public class Collaborator {
public boolean collaborate(String string){ public boolean collaborate(String string){
return false; return false;
} }
public void receive(boolean bool){ public void receive(boolean bool){
//NOOP //NOOP
} }

View File

@ -1,7 +1,7 @@
package org.baeldung.mocks.jmockit; package org.baeldung.mocks.jmockit;
public class Model { public class Model {
public String getInfo(){ public String getInfo() {
return "info"; return "info";
} }
} }

View File

@ -1,21 +1,20 @@
package org.baeldung.mocks.jmockit; 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.Delegate;
import mockit.Expectations; import mockit.Expectations;
import mockit.Mocked; import mockit.Mocked;
import mockit.StrictExpectations; import mockit.StrictExpectations;
import mockit.Verifications; import mockit.Verifications;
import mockit.integration.junit4.JMockit; 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) @RunWith(JMockit.class)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -23,71 +22,56 @@ public class ExpectationsTest {
@Test @Test
public void testForAny(@Mocked ExpectationsCollaborator mock) throws Exception { public void testForAny(@Mocked ExpectationsCollaborator mock) throws Exception {
new Expectations() { new Expectations() {{
{
mock.methodForAny1(anyString, anyInt, anyBoolean); mock.methodForAny1(anyString, anyInt, anyBoolean);
result = "any"; result = "any";
} }};
};
assertEquals("any", mock.methodForAny1("barfooxyz", 0, Boolean.FALSE)); assertEquals("any", mock.methodForAny1("barfooxyz", 0, Boolean.FALSE));
mock.methodForAny2(2L, new ArrayList<>()); mock.methodForAny2(2L, new ArrayList<>());
new Verifications() { new Verifications() {{
{
mock.methodForAny2(anyLong, (List<String>) any); mock.methodForAny2(anyLong, (List<String>) any);
} }};
};
} }
@Test @Test
public void testForWith(@Mocked ExpectationsCollaborator mock) throws Exception { public void testForWith(@Mocked ExpectationsCollaborator mock) throws Exception {
new Expectations() { new Expectations() {{
{
mock.methodForWith1(withSubstring("foo"), withNotEqual(1)); mock.methodForWith1(withSubstring("foo"), withNotEqual(1));
result = "with"; result = "with";
} }};
};
assertEquals("with", mock.methodForWith1("barfooxyz", 2)); assertEquals("with", mock.methodForWith1("barfooxyz", 2));
mock.methodForWith2(Boolean.TRUE, new ArrayList<>()); mock.methodForWith2(Boolean.TRUE, new ArrayList<>());
new Verifications() { new Verifications() {{
{
mock.methodForWith2(withNotNull(), withInstanceOf(List.class)); mock.methodForWith2(withNotNull(), withInstanceOf(List.class));
} }};
};
} }
@Test @Test
public void testWithNulls(@Mocked ExpectationsCollaborator mock) { public void testWithNulls(@Mocked ExpectationsCollaborator mock) {
new Expectations() { new Expectations() {{
{
mock.methodForNulls1(anyString, null); mock.methodForNulls1(anyString, null);
result = "null"; result = "null";
} }};
};
assertEquals("null", mock.methodForNulls1("blablabla", new ArrayList<String>())); assertEquals("null", mock.methodForNulls1("blablabla", new ArrayList<String>()));
mock.methodForNulls2("blablabla", null); mock.methodForNulls2("blablabla", null);
new Verifications() { new Verifications() {{
{
mock.methodForNulls2(anyString, (List<String>) withNull()); mock.methodForNulls2(anyString, (List<String>) withNull());
} }};
};
} }
@Test @Test
public void testWithTimes(@Mocked ExpectationsCollaborator mock) { public void testWithTimes(@Mocked ExpectationsCollaborator mock) {
new Expectations() { new Expectations() {{
{
// exactly 2 invocations are expected
mock.methodForTimes1(); mock.methodForTimes1();
times = 2; times = 2;
mock.methodForTimes2(); // "minTimes = 1" is implied mock.methodForTimes2();
} }};
};
mock.methodForTimes1(); mock.methodForTimes1();
mock.methodForTimes1(); mock.methodForTimes1();
@ -96,20 +80,16 @@ public class ExpectationsTest {
mock.methodForTimes3(); mock.methodForTimes3();
mock.methodForTimes3(); mock.methodForTimes3();
new Verifications() { new Verifications() {{
{
// we expect from 1 to 3 invocations
mock.methodForTimes3(); mock.methodForTimes3();
minTimes = 1; minTimes = 1;
maxTimes = 3; maxTimes = 3;
} }};
};
} }
@Test @Test
public void testCustomArgumentMatching(@Mocked ExpectationsCollaborator mock) { public void testCustomArgumentMatching(@Mocked ExpectationsCollaborator mock) {
new Expectations() { new Expectations() {{
{
mock.methodForArgThat(withArgThat(new BaseMatcher<Object>() { mock.methodForArgThat(withArgThat(new BaseMatcher<Object>() {
@Override @Override
public boolean matches(Object item) { public boolean matches(Object item) {
@ -118,34 +98,26 @@ public class ExpectationsTest {
@Override @Override
public void describeTo(Description description) { public void describeTo(Description description) {
// NOOP
} }
})); }));
} }};
};
mock.methodForArgThat(new Model()); mock.methodForArgThat(new Model());
} }
@Test @Test
public void testResultAndReturns(@Mocked ExpectationsCollaborator mock) { public void testResultAndReturns(@Mocked ExpectationsCollaborator mock) {
new StrictExpectations() { new StrictExpectations() {{
{
// return "foo", an exception and lastly "bar"
mock.methodReturnsString(); mock.methodReturnsString();
result = "foo"; result = "foo";
result = new Exception(); result = new Exception();
result = "bar"; result = "bar";
// return 1, 2, 3
mock.methodReturnsInt(); mock.methodReturnsInt();
result = new int[] { 1, 2, 3 }; result = new int[]{1, 2, 3};
// return "foo" and "bar"
mock.methodReturnsString(); mock.methodReturnsString();
returns("foo", "bar"); returns("foo", "bar");
// return only 1
mock.methodReturnsInt(); mock.methodReturnsInt();
result = 1; result = 1;
} }};
};
assertEquals("Should return foo", "foo", mock.methodReturnsString()); assertEquals("Should return foo", "foo", mock.methodReturnsString());
try { try {
@ -164,11 +136,8 @@ public class ExpectationsTest {
@Test @Test
public void testDelegate(@Mocked ExpectationsCollaborator mock) { public void testDelegate(@Mocked ExpectationsCollaborator mock) {
new StrictExpectations() { new Expectations() {{
{
// return "foo", an exception and lastly "bar"
mock.methodForDelegate(anyInt); mock.methodForDelegate(anyInt);
times = 2;
result = new Delegate() { result = new Delegate() {
public int delegate(int i) throws Exception { public int delegate(int i) throws Exception {
if (i < 3) { if (i < 3) {
@ -178,13 +147,12 @@ public class ExpectationsTest {
} }
} }
}; };
} }};
};
assertEquals("Should return 5", 5, mock.methodForDelegate(1)); assertEquals("Should return 5", 5, mock.methodForDelegate(1));
try { try {
mock.methodForDelegate(3); mock.methodForDelegate(3);
} catch (Exception e) { } catch (Exception e) {
// NOOP
} }
} }
} }

View File

@ -21,7 +21,9 @@ public class PerformerTest {
model.getInfo();result = "bar"; model.getInfo();result = "bar";
collaborator.collaborate("bar"); result = true; collaborator.collaborate("bar"); result = true;
}}; }};
performer.perform(model); performer.perform(model);
new Verifications() {{ new Verifications() {{
collaborator.receive(true); collaborator.receive(true);
}}; }};

24
pom.xml
View File

@ -15,10 +15,17 @@
<modules> <modules>
<module>assertj</module> <module>assertj</module>
<module>apache-cxf</module> <module>apache-cxf</module>
<module>apache-fop</module>
<module>core-java</module> <module>core-java</module>
<module>core-java-8</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</module>
<!-- <module>gson-jackson-performance</module> --> <module>gson-jackson-performance</module>
<module>guava</module> <module>guava</module>
<module>guava18</module> <module>guava18</module>
<module>guava19</module> <module>guava19</module>
@ -28,27 +35,35 @@
<module>javaxval</module> <module>javaxval</module>
<module>jjwt</module> <module>jjwt</module>
<module>jooq-spring</module> <module>jooq-spring</module>
<module>json-path</module> <module>jpa-storedprocedure</module>
<module>json</module> <module>json</module>
<module>json-path</module>
<module>junit5</module>
<module>mockito</module> <module>mockito</module>
<module>mocks</module> <module>mocks</module>
<module>jee7schedule</module> <module>jee7schedule</module>
<!-- <module>jpa-storedprocedure</module> --> <!-- <module>jpa-storedprocedure</module> -->
<module>querydsl</module> <module>querydsl</module>
<!-- <module>raml</module> --> <!-- <module>raml</module> -->
<module>rest-assured</module>
<module>rest-testing</module> <module>rest-testing</module>
<module>resteasy</module> <module>resteasy</module>
<module>log4j</module> <module>log4j</module>
<module>spring-all</module> <module>spring-all</module>
<module>spring-apache-camel</module> <module>spring-apache-camel</module>
<module>spring-autowire</module>
<module>spring-batch</module> <module>spring-batch</module>
<module>spring-boot</module> <module>spring-boot</module>
<module>spring-controller</module> <module>spring-controller</module>
<module>spring-data-cassandra</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-elasticsearch</module>
<module>spring-data-neo4j</module>
<module>spring-data-mongodb</module> <module>spring-data-mongodb</module>
<module>spring-data-redis</module> <module>spring-data-redis</module>
<module>spring-data-rest</module>
<module>spring-exceptions</module> <module>spring-exceptions</module>
<module>spring-freemarker</module> <module>spring-freemarker</module>
<module>spring-hibernate3</module> <module>spring-hibernate3</module>
@ -62,9 +77,12 @@
<module>spring-openid</module> <module>spring-openid</module>
<module>spring-protobuf</module> <module>spring-protobuf</module>
<module>spring-quartz</module> <module>spring-quartz</module>
<module>spring-spel</module>
<module>spring-rest</module> <module>spring-rest</module>
<module>spring-rest-docs</module>
<module>spring-security-basic-auth</module> <module>spring-security-basic-auth</module>
<module>spring-security-custom-permission</module>
<module>spring-security-mvc-custom</module> <module>spring-security-mvc-custom</module>
<module>spring-security-mvc-digest-auth</module> <module>spring-security-mvc-digest-auth</module>
<module>spring-security-mvc-ldap</module> <module>spring-security-mvc-ldap</module>
@ -82,9 +100,11 @@
<module>xml</module> <module>xml</module>
<module>lombok</module> <module>lombok</module>
<module>redis</module> <module>redis</module>
<module>webjars</module>
<module>mutation-testing</module> <module>mutation-testing</module>
<module>spring-mvc-velocity</module> <module>spring-mvc-velocity</module>
<module>xstream</module>
</modules> </modules>
</project> </project>

View File

@ -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>

View File

@ -1,7 +0,0 @@
=========
## A Guide To REST-Assured
### Relevant Articles:

View File

@ -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>

View File

@ -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));
}
}

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -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
rest-assured/README.md Normal file
View File

257
rest-assured/pom.xml Normal file
View File

@ -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>

View File

@ -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();
}
}

View File

@ -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"));
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,7 @@
<employees>
<employee category="skilled">
<first-name>Jane</first-name>
<last-name>Daisy</last-name>
<sex>f</sex>
</employee>
</employees>

View File

@ -1,5 +1,11 @@
{ {
"id": "390", "id": "390",
"odd": {
"price": "1.20",
"status": 2,
"ck": 12.2,
"name": "2"
},
"data": { "data": {
"countryId": 35, "countryId": 35,
"countryName": "Norway", "countryName": "Norway",
@ -9,25 +15,25 @@
"time": "2016-06-12T12:00:00Z" "time": "2016-06-12T12:00:00Z"
}, },
"odds": [{ "odds": [{
"price": 1.30, "price": "1.30",
"status": 0, "status": 0,
"ck": 12.2, "ck": 12.2,
"name": "1" "name": "1"
}, },
{ {
"price": 5.25, "price":"5.25",
"status": 1, "status": 1,
"ck": 13.1, "ck": 13.1,
"name": "X" "name": "X"
}, },
{ {
"price": 2.70, "price": "2.70",
"status": 0, "status": 0,
"ck": 12.2, "ck": 12.2,
"name": "0" "name": "0"
}, },
{ {
"price": 1.20, "price": "1.20",
"status": 2, "status": 2,
"ck": 13.1, "ck": 13.1,
"name": "2" "name": "2"

View File

@ -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

View File

@ -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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;

View File

@ -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.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;

View File

@ -2,7 +2,7 @@
/** /**
* @author Prashant Dutta * @author Prashant Dutta
*/ */
package com.baledung.controller; package com.baeldung.controller;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;

View File

@ -1,4 +1,4 @@
package com.baledung.student; package com.baeldung.student;
public class Student { public class Student {
private String name; private String name;

View File

@ -10,7 +10,7 @@
http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 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 /> <mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

View File

@ -1,4 +1,4 @@
package com.baledung.test; package com.baeldung.test;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; 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.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import com.baledung.student.Student; import com.baeldung.student.Student;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)

View File

@ -32,6 +32,7 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<version>1.3.6.RELEASE</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>

View File

@ -3,4 +3,5 @@
<installed facet="wst.jsdt.web" version="1.0"/> <installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="jst.web" version="3.0"/> <installed facet="jst.web" version="3.0"/>
<installed facet="java" version="1.8"/> <installed facet="java" version="1.8"/>
<installed facet="jpt.jpa" version="2.1"/>
</faceted-project> </faceted-project>

View File

@ -1,10 +1,10 @@
package com.baeldung.mvc.velocity.service; package com.baeldung.mvc.velocity.service;
import java.util.List;
import com.baeldung.mvc.velocity.domain.Tutorial; import com.baeldung.mvc.velocity.domain.Tutorial;
import java.util.List;
public interface ITutorialsService { public interface ITutorialsService {
public List<Tutorial> listTutorials(); List<Tutorial> listTutorials();
} }

View File

@ -1,2 +0,0 @@
###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity

View File

@ -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>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<classpathentry kind="output" path=""/>
</classpath>

View File

@ -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

View File

@ -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

View File

@ -1,4 +0,0 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@ -1,2 +0,0 @@
eclipse.preferences.version=1
org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false

View File

@ -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>

View File

@ -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>

View File

@ -1 +0,0 @@
org.eclipse.wst.jsdt.launching.baseBrowserLibrary

View File

@ -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

View File

@ -1,2 +0,0 @@
eclipse.preferences.version=1
org.eclipse.wst.ws.service.policy.projectEnabled=false

View File

@ -44,8 +44,9 @@ public class SecurityWithoutCsrfConfig extends WebSecurityConfigurerAdapter {
http http
.csrf().disable() .csrf().disable()
.authorizeRequests() .authorizeRequests()
.antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN") .antMatchers("/auth/admin/*").hasRole("ADMIN")
.anyRequest().authenticated() .antMatchers("/auth/*").hasAnyRole("ADMIN","USER")
.antMatchers("/*").permitAll()
.and() .and()
.httpBasic() .httpBasic()
.and() .and()

View File

@ -32,6 +32,7 @@ public class WebConfig extends WebMvcConfigurerAdapter {
super.addViewControllers(registry); super.addViewControllers(registry);
registry.addViewController("/graph.html"); registry.addViewController("/graph.html");
registry.addViewController("/csrfHome.html"); registry.addViewController("/csrfHome.html");
registry.addViewController("/homepage.html");
} }
} }

View File

@ -12,6 +12,7 @@ import org.springframework.web.bind.annotation.ResponseStatus;
// to test csrf // to test csrf
@Controller @Controller
@RequestMapping(value = "/auth/")
public class BankController { public class BankController {
private final Logger logger = LoggerFactory.getLogger(getClass()); private final Logger logger = LoggerFactory.getLogger(getClass());

View File

@ -29,7 +29,7 @@ import org.springframework.web.util.UriComponentsBuilder;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
@Controller @Controller
@RequestMapping(value = "/foos") @RequestMapping(value = "/auth/foos")
public class FooController { public class FooController {
@Autowired @Autowired

View File

@ -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";
}
}

View File

@ -20,6 +20,7 @@ import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.util.UriTemplate; import org.springframework.web.util.UriTemplate;
@Controller @Controller
@RequestMapping(value = "/auth/")
public class RootController { public class RootController {
@Autowired @Autowired

View File

@ -37,6 +37,7 @@ import cz.jirutka.rsql.parser.ast.Node;
//@EnableSpringDataWebSupport //@EnableSpringDataWebSupport
@Controller @Controller
@RequestMapping(value = "/auth/")
public class UserController { public class UserController {
@Autowired @Autowired

View File

@ -42,6 +42,10 @@ public class CsrfAbstractIntegrationTest {
return user("user").password("userPass").roles("USER"); return user("user").password("userPass").roles("USER");
} }
protected RequestPostProcessor testAdmin() {
return user("admin").password("adminPass").roles("USER", "ADMIN");
}
protected String createFoo() throws JsonProcessingException { protected String createFoo() throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6))); return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
} }

View File

@ -1,5 +1,6 @@
package org.baeldung.security.csrf; 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.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -15,12 +16,31 @@ public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
@Test @Test
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception { public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized()); mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
} }
@Test @Test
public void givenAuth_whenAddFoo_thenCreated() throws Exception { public void givenAuth_whenAddFoo_thenCreated() throws Exception {
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated()); 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
} }
} }

View File

46
xmlunit2-tutorial/pom.xml Normal file
View File

@ -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>

View File

@ -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;
}
}

View File

@ -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));
}
}

View File

@ -0,0 +1,4 @@
<struct>
<int>3</int>
<boolean>false</boolean>
</struct>

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -0,0 +1,4 @@
<struct>
<int>3</int>
<boolean>false</boolean>
</struct>