diff --git a/apache-cxf/cxf-spring/.gitignore b/apache-cxf/cxf-spring/.gitignore new file mode 100644 index 0000000000..2f7896d1d1 --- /dev/null +++ b/apache-cxf/cxf-spring/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml index 431c35c51d..b9dbda7c11 100644 --- a/apache-cxf/cxf-spring/pom.xml +++ b/apache-cxf/cxf-spring/pom.xml @@ -8,18 +8,42 @@ apache-cxf 0.0.1-SNAPSHOT - - 3.1.6 - 4.3.1.RELEASE - 2.19.1 - + + + + org.apache.cxf + cxf-rt-frontend-jaxws + ${cxf.version} + + + org.apache.cxf + cxf-rt-transports-http-jetty + ${cxf.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + javax.servlet + javax.servlet-api + 3.1.0 + + + maven-war-plugin 2.6 - src/main/webapp/WEB-INF/web.xml + false @@ -33,6 +57,7 @@ + integration @@ -50,7 +75,7 @@ localhost - 8080 + 8081 @@ -71,6 +96,7 @@ + maven-surefire-plugin ${surefire.version} @@ -91,27 +117,13 @@ + - - - org.apache.cxf - cxf-rt-frontend-jaxws - ${cxf.version} - - - org.apache.cxf - cxf-rt-transports-http-jetty - ${cxf.version} - - - org.springframework - spring-context - ${spring.version} - - - org.springframework - spring-web - ${spring.version} - - + + + 3.1.6 + 4.3.1.RELEASE + 2.19.1 + + diff --git a/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/AppInitializer.java b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/AppInitializer.java new file mode 100644 index 0000000000..036bf66a52 --- /dev/null +++ b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/AppInitializer.java @@ -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"); + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/Baeldung.java b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/Baeldung.java index 4f880e6ada..b66e4c2fbf 100644 --- a/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/Baeldung.java +++ b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/Baeldung.java @@ -5,5 +5,6 @@ import javax.jws.WebService; @WebService public interface Baeldung { String hello(String name); + String register(Student student); } \ No newline at end of file diff --git a/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ClientConfiguration.java b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ClientConfiguration.java new file mode 100644 index 0000000000..021bcc6f66 --- /dev/null +++ b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ClientConfiguration.java @@ -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; + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ServiceConfiguration.java b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ServiceConfiguration.java new file mode 100644 index 0000000000..0bc60fb790 --- /dev/null +++ b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ServiceConfiguration.java @@ -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; + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-spring/src/main/resources/client-beans.xml b/apache-cxf/cxf-spring/src/main/resources/client-beans.xml deleted file mode 100644 index 626252b565..0000000000 --- a/apache-cxf/cxf-spring/src/main/resources/client-beans.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - diff --git a/apache-cxf/cxf-spring/src/main/webapp/WEB-INF/cxf-servlet.xml b/apache-cxf/cxf-spring/src/main/webapp/WEB-INF/cxf-servlet.xml deleted file mode 100644 index 9fe87ba9ee..0000000000 --- a/apache-cxf/cxf-spring/src/main/webapp/WEB-INF/cxf-servlet.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/apache-cxf/cxf-spring/src/main/webapp/WEB-INF/web.xml b/apache-cxf/cxf-spring/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 43a03b1d8b..0000000000 --- a/apache-cxf/cxf-spring/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - cxf - org.apache.cxf.transport.servlet.CXFServlet - 1 - - - cxf - /services/* - - diff --git a/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java b/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java index 44a9d11687..7466944e04 100644 --- a/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java +++ b/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java @@ -3,15 +3,12 @@ package com.baeldung.cxf.spring; import static org.junit.Assert.assertEquals; import org.junit.Test; -import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class StudentTest { - private ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "client-beans.xml" }); - private Baeldung baeldungProxy; - - { - baeldungProxy = (Baeldung) context.getBean("client"); - } + private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class); + private Baeldung baeldungProxy = (Baeldung) context.getBean("client"); @Test public void whenUsingHelloMethod_thenCorrect() { @@ -25,7 +22,7 @@ public class StudentTest { Student student2 = new Student("Eve"); String student1Response = baeldungProxy.register(student1); String student2Response = baeldungProxy.register(student2); - + assertEquals("Adam is registered student number 1", student1Response); assertEquals("Eve is registered student number 2", student2Response); } diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml index 667ea87402..9e78a66ad6 100644 --- a/dependency-injection/pom.xml +++ b/dependency-injection/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 @@ -9,7 +8,7 @@ 0.0.1-SNAPSHOT war - Resource vs Inject vs Autowired + dependency-injection Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely Resource, Inject, and Autowired @@ -54,6 +53,7 @@ + maven-compiler-plugin @@ -71,13 +71,29 @@ + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + + + 2.6 + + java.net https://maven.java.net/content/repositories/releases/ + diff --git a/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListDeserializer.java index 5f1f1edf2b..c00316e365 100644 --- a/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListDeserializer.java @@ -7,9 +7,19 @@ import java.util.List; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -public class CustomListDeserializer extends JsonDeserializer> { +public class CustomListDeserializer extends StdDeserializer> { + + private static final long serialVersionUID = 1095767961632979804L; + + public CustomListDeserializer() { + this(null); + } + + public CustomListDeserializer(final Class vc) { + super(vc); + } @Override public List deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException { diff --git a/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java b/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java index 1d8ca011ea..75e0a4ecb7 100644 --- a/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java @@ -6,11 +6,20 @@ import java.util.List; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; -public class CustomListSerializer extends JsonSerializer> { +public class CustomListSerializer extends StdSerializer> { + private static final long serialVersionUID = 3698763098000900856L; + + public CustomListSerializer() { + this(null); + } + + public CustomListSerializer(final Class> t) { + super(t); + } @Override public void serialize(final List items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { final List ids = new ArrayList(); diff --git a/jackson/src/test/java/com/baeldung/jackson/date/CustomDateDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/date/CustomDateDeserializer.java index a63190c8f5..90c7d9fbac 100644 --- a/jackson/src/test/java/com/baeldung/jackson/date/CustomDateDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/date/CustomDateDeserializer.java @@ -8,12 +8,21 @@ import java.util.Date; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -public class CustomDateDeserializer extends JsonDeserializer { +public class CustomDateDeserializer extends StdDeserializer { + private static final long serialVersionUID = -5451717385630622729L; private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); + public CustomDateDeserializer() { + this(null); + } + + public CustomDateDeserializer(final Class vc) { + super(vc); + } + @Override public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException { final String date = jsonparser.getText(); diff --git a/jackson/src/test/java/com/baeldung/jackson/date/CustomDateSerializer.java b/jackson/src/test/java/com/baeldung/jackson/date/CustomDateSerializer.java index 8d435b7b69..d840e1940f 100644 --- a/jackson/src/test/java/com/baeldung/jackson/date/CustomDateSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/date/CustomDateSerializer.java @@ -6,13 +6,22 @@ import java.util.Date; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; -public class CustomDateSerializer extends JsonSerializer { +public class CustomDateSerializer extends StdSerializer { + private static final long serialVersionUID = -2894356342227378312L; private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); + public CustomDateSerializer() { + this(null); + } + + public CustomDateSerializer(final Class t) { + super(t); + } + @Override public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException { gen.writeString(formatter.format(value)); diff --git a/jackson/src/test/java/com/baeldung/jackson/date/CustomDateTimeSerializer.java b/jackson/src/test/java/com/baeldung/jackson/date/CustomDateTimeSerializer.java index 88c069419b..ab4f4bbec7 100644 --- a/jackson/src/test/java/com/baeldung/jackson/date/CustomDateTimeSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/date/CustomDateTimeSerializer.java @@ -8,10 +8,20 @@ import org.joda.time.format.DateTimeFormatter; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; -public class CustomDateTimeSerializer extends JsonSerializer { +public class CustomDateTimeSerializer extends StdSerializer { + + private static final long serialVersionUID = -3927232057990121460L; + + public CustomDateTimeSerializer() { + this(null); + } + + public CustomDateTimeSerializer(final Class t) { + super(t); + } private static DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"); diff --git a/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java b/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java index 3f8f5e098e..dbcf42488e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java @@ -6,13 +6,23 @@ import java.time.format.DateTimeFormatter; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; -public class CustomLocalDateTimeSerializer extends JsonSerializer { +public class CustomLocalDateTimeSerializer extends StdSerializer { + + private static final long serialVersionUID = -7449444168934819290L; private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + public CustomLocalDateTimeSerializer() { + this(null); + } + + public CustomLocalDateTimeSerializer(final Class t) { + super(t); + } + @Override public void serialize(final LocalDateTime value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException { gen.writeString(formatter.format(value)); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java index 3be6685103..e9c89b8c78 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java @@ -2,17 +2,26 @@ package com.baeldung.jackson.deserialization; import java.io.IOException; -import com.baeldung.jackson.dtos.User; import com.baeldung.jackson.dtos.Item; - +import com.baeldung.jackson.dtos.User; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.node.IntNode; -public class ItemDeserializer extends JsonDeserializer { +public class ItemDeserializer extends StdDeserializer { + + private static final long serialVersionUID = 1883547683050039861L; + + public ItemDeserializer() { + this(null); + } + + public ItemDeserializer(final Class vc) { + super(vc); + } /** * {"id":1,"itemNr":"theItem","owner":2} diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java index 169a5c1c50..2036780e99 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java @@ -4,15 +4,24 @@ import java.io.IOException; import com.baeldung.jackson.dtos.ItemWithSerializer; import com.baeldung.jackson.dtos.User; - import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.node.IntNode; -public class ItemDeserializerOnClass extends JsonDeserializer { +public class ItemDeserializerOnClass extends StdDeserializer { + + private static final long serialVersionUID = 5579141241817332594L; + + public ItemDeserializerOnClass() { + this(null); + } + + public ItemDeserializerOnClass(final Class vc) { + super(vc); + } /** * {"id":1,"itemNr":"theItem","owner":2} diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeSerializer.java b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeSerializer.java index c5d5d7e0a8..fc5011137c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeSerializer.java @@ -4,10 +4,20 @@ import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; -public class TypeSerializer extends JsonSerializer { +public class TypeSerializer extends StdSerializer { + + private static final long serialVersionUID = -7650668914169390772L; + + public TypeSerializer() { + this(null); + } + + public TypeSerializer(final Class t) { + super(t); + } @Override public void serialize(final TypeEnumWithCustomSerializer value, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/ItemSerializer.java b/jackson/src/test/java/com/baeldung/jackson/serialization/ItemSerializer.java index cb93f9cb03..b5624c566a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/ItemSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/ItemSerializer.java @@ -3,13 +3,22 @@ package com.baeldung.jackson.serialization; import java.io.IOException; import com.baeldung.jackson.dtos.Item; - import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; -public class ItemSerializer extends JsonSerializer { +public class ItemSerializer extends StdSerializer { + + private static final long serialVersionUID = 6739170890621978901L; + + public ItemSerializer() { + this(null); + } + + public ItemSerializer(final Class t) { + super(t); + } @Override public final void serialize(final Item value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/ItemSerializerOnClass.java b/jackson/src/test/java/com/baeldung/jackson/serialization/ItemSerializerOnClass.java index 79b450d7f1..1fdf44e17c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/ItemSerializerOnClass.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/ItemSerializerOnClass.java @@ -3,13 +3,22 @@ package com.baeldung.jackson.serialization; import java.io.IOException; import com.baeldung.jackson.dtos.ItemWithSerializer; - import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; -public class ItemSerializerOnClass extends JsonSerializer { +public class ItemSerializerOnClass extends StdSerializer { + + private static final long serialVersionUID = -1760959597313610409L; + + public ItemSerializerOnClass() { + this(null); + } + + public ItemSerializerOnClass(final Class t) { + super(t); + } @Override public final void serialize(final ItemWithSerializer value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/MyDtoNullKeySerializer.java b/jackson/src/test/java/com/baeldung/jackson/serialization/MyDtoNullKeySerializer.java index e915378498..d0b2d7f5e9 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/MyDtoNullKeySerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/MyDtoNullKeySerializer.java @@ -4,10 +4,20 @@ import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; -public class MyDtoNullKeySerializer extends JsonSerializer { +public class MyDtoNullKeySerializer extends StdSerializer { + + private static final long serialVersionUID = -4478531309177369056L; + + public MyDtoNullKeySerializer() { + this(null); + } + + public MyDtoNullKeySerializer(final Class t) { + super(t); + } @Override public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { diff --git a/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java index 849607586d..529c05ddcc 100644 --- a/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java @@ -6,10 +6,19 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -public class RestLoaderRequestDeserializer extends JsonDeserializer> { +public class RestLoaderRequestDeserializer extends StdDeserializer> { + private static final long serialVersionUID = -4245207329377196889L; + + public RestLoaderRequestDeserializer() { + this(null); + } + + public RestLoaderRequestDeserializer(final Class vc) { + super(vc); + } @Override public RestLoaderRequest deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { diff --git a/mocks/jmockit/README.md b/mocks/jmockit/README.md index c310463c26..d04a07fdc5 100644 --- a/mocks/jmockit/README.md +++ b/mocks/jmockit/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [JMockit 101](http://www.baeldung.com/jmockit-101) +- [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations) diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java index ef271b9aff..60da12fa7c 100644 --- a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java +++ b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java @@ -1,9 +1,11 @@ package org.baeldung.mocks.jmockit; public class Collaborator { + public boolean collaborate(String string){ return false; } + public void receive(boolean bool){ //NOOP } diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java index c3b63d11b4..79ae24c2f5 100644 --- a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java +++ b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java @@ -1,7 +1,7 @@ package org.baeldung.mocks.jmockit; public class Model { - public String getInfo(){ - return "info"; + public String getInfo() { + return "info"; } } diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsTest.java b/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsTest.java index d1f3fa9e85..1c72647133 100644 --- a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsTest.java +++ b/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsTest.java @@ -1,21 +1,20 @@ package org.baeldung.mocks.jmockit; -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.List; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.junit.Test; -import org.junit.runner.RunWith; - import mockit.Delegate; import mockit.Expectations; import mockit.Mocked; import mockit.StrictExpectations; import mockit.Verifications; import mockit.integration.junit4.JMockit; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; @RunWith(JMockit.class) @SuppressWarnings("unchecked") @@ -23,130 +22,103 @@ public class ExpectationsTest { @Test public void testForAny(@Mocked ExpectationsCollaborator mock) throws Exception { - new Expectations() { - { - mock.methodForAny1(anyString, anyInt, anyBoolean); - result = "any"; - } - }; + new Expectations() {{ + mock.methodForAny1(anyString, anyInt, anyBoolean); + result = "any"; + }}; assertEquals("any", mock.methodForAny1("barfooxyz", 0, Boolean.FALSE)); mock.methodForAny2(2L, new ArrayList<>()); - new Verifications() { - { - mock.methodForAny2(anyLong, (List) any); - } - }; + new Verifications() {{ + mock.methodForAny2(anyLong, (List) any); + }}; } @Test public void testForWith(@Mocked ExpectationsCollaborator mock) throws Exception { - new Expectations() { - { - mock.methodForWith1(withSubstring("foo"), withNotEqual(1)); - result = "with"; - } - }; - + new Expectations() {{ + mock.methodForWith1(withSubstring("foo"), withNotEqual(1)); + result = "with"; + }}; + assertEquals("with", mock.methodForWith1("barfooxyz", 2)); mock.methodForWith2(Boolean.TRUE, new ArrayList<>()); - - new Verifications() { - { - mock.methodForWith2(withNotNull(), withInstanceOf(List.class)); - } - }; + + new Verifications() {{ + mock.methodForWith2(withNotNull(), withInstanceOf(List.class)); + }}; } @Test public void testWithNulls(@Mocked ExpectationsCollaborator mock) { - new Expectations() { - { - mock.methodForNulls1(anyString, null); - result = "null"; - } - }; - + new Expectations() {{ + mock.methodForNulls1(anyString, null); + result = "null"; + }}; + assertEquals("null", mock.methodForNulls1("blablabla", new ArrayList())); mock.methodForNulls2("blablabla", null); - - new Verifications() { - { - mock.methodForNulls2(anyString, (List) withNull()); - } - }; + + new Verifications() {{ + mock.methodForNulls2(anyString, (List) withNull()); + }}; } @Test public void testWithTimes(@Mocked ExpectationsCollaborator mock) { - new Expectations() { - { - // exactly 2 invocations are expected - mock.methodForTimes1(); - times = 2; - mock.methodForTimes2(); // "minTimes = 1" is implied - } - }; - + new Expectations() {{ + mock.methodForTimes1(); + times = 2; + mock.methodForTimes2(); + }}; + mock.methodForTimes1(); mock.methodForTimes1(); mock.methodForTimes2(); mock.methodForTimes3(); mock.methodForTimes3(); mock.methodForTimes3(); - - new Verifications() { - { - // we expect from 1 to 3 invocations - mock.methodForTimes3(); - minTimes = 1; - maxTimes = 3; - } - }; + + new Verifications() {{ + mock.methodForTimes3(); + minTimes = 1; + maxTimes = 3; + }}; } @Test public void testCustomArgumentMatching(@Mocked ExpectationsCollaborator mock) { - new Expectations() { - { - mock.methodForArgThat(withArgThat(new BaseMatcher() { - @Override - public boolean matches(Object item) { - return item instanceof Model && "info".equals(((Model) item).getInfo()); - } + new Expectations() {{ + mock.methodForArgThat(withArgThat(new BaseMatcher() { + @Override + public boolean matches(Object item) { + return item instanceof Model && "info".equals(((Model) item).getInfo()); + } - @Override - public void describeTo(Description description) { - // NOOP - } - })); - } - }; + @Override + public void describeTo(Description description) { + } + })); + }}; mock.methodForArgThat(new Model()); } @Test public void testResultAndReturns(@Mocked ExpectationsCollaborator mock) { - new StrictExpectations() { - { - // return "foo", an exception and lastly "bar" - mock.methodReturnsString(); - result = "foo"; - result = new Exception(); - result = "bar"; - // return 1, 2, 3 - mock.methodReturnsInt(); - result = new int[] { 1, 2, 3 }; - // return "foo" and "bar" - mock.methodReturnsString(); - returns("foo", "bar"); - // return only 1 - mock.methodReturnsInt(); - result = 1; - } - }; - + new StrictExpectations() {{ + mock.methodReturnsString(); + result = "foo"; + result = new Exception(); + result = "bar"; + mock.methodReturnsInt(); + result = new int[]{1, 2, 3}; + mock.methodReturnsString(); + returns("foo", "bar"); + mock.methodReturnsInt(); + result = 1; + }}; + assertEquals("Should return foo", "foo", mock.methodReturnsString()); try { mock.methodReturnsString(); @@ -164,27 +136,23 @@ public class ExpectationsTest { @Test public void testDelegate(@Mocked ExpectationsCollaborator mock) { - new StrictExpectations() { - { - // return "foo", an exception and lastly "bar" - mock.methodForDelegate(anyInt); - times = 2; - result = new Delegate() { - public int delegate(int i) throws Exception { - if (i < 3) { - return 5; - } else { - throw new Exception(); - } + new Expectations() {{ + mock.methodForDelegate(anyInt); + result = new Delegate() { + public int delegate(int i) throws Exception { + if (i < 3) { + return 5; + } else { + throw new Exception(); } - }; - } - }; + } + }; + }}; + assertEquals("Should return 5", 5, mock.methodForDelegate(1)); try { mock.methodForDelegate(3); } catch (Exception e) { - // NOOP } } } diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerTest.java b/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerTest.java index c99ae844c3..2b1b3be0f7 100644 --- a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerTest.java +++ b/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerTest.java @@ -21,7 +21,9 @@ public class PerformerTest { model.getInfo();result = "bar"; collaborator.collaborate("bar"); result = true; }}; + performer.perform(model); + new Verifications() {{ collaborator.receive(true); }}; diff --git a/pom.xml b/pom.xml index 469e0a0b74..074f330bcf 100644 --- a/pom.xml +++ b/pom.xml @@ -15,10 +15,17 @@ assertj apache-cxf + apache-fop core-java core-java-8 + couchbase-sdk-intro + couchbase-sdk-spring-service + + dependency-injection + gatling + gson - + gson-jackson-performance guava guava18 guava19 @@ -28,27 +35,35 @@ javaxval jjwt jooq-spring - json-path + jpa-storedprocedure json + json-path + junit5 mockito mocks jee7schedule querydsl + rest-assured rest-testing resteasy log4j spring-all spring-apache-camel + spring-autowire spring-batch spring-boot spring-controller spring-data-cassandra + spring-data-couchbase-2 + spring-data-couchbase-2b spring-data-elasticsearch + spring-data-neo4j spring-data-mongodb spring-data-redis + spring-data-rest spring-exceptions spring-freemarker spring-hibernate3 @@ -62,9 +77,12 @@ spring-openid spring-protobuf spring-quartz + spring-spel spring-rest + spring-rest-docs spring-security-basic-auth + spring-security-custom-permission spring-security-mvc-custom spring-security-mvc-digest-auth spring-security-mvc-ldap @@ -82,9 +100,11 @@ xml lombok redis - + webjars + mutation-testing spring-mvc-velocity + xstream diff --git a/rest-assured-tutorial/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/rest-assured-tutorial/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/rest-assured-tutorial/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/rest-assured-tutorial/README.md b/rest-assured-tutorial/README.md deleted file mode 100644 index 8b81626967..0000000000 --- a/rest-assured-tutorial/README.md +++ /dev/null @@ -1,7 +0,0 @@ -========= - -## A Guide To REST-Assured - - -### Relevant Articles: - diff --git a/rest-assured-tutorial/pom.xml b/rest-assured-tutorial/pom.xml deleted file mode 100644 index 51b22fa0ff..0000000000 --- a/rest-assured-tutorial/pom.xml +++ /dev/null @@ -1,143 +0,0 @@ - - 4.0.0 - com.baeldung - rest-assured - 0.1.0-SNAPSHOT - - rest-assured - - - - 3.5.1 - 2.19.1 - - 1.10.19 - 4.12 - 2.1.7 - 1.3 - 1.2.5 - 2.2.6 - 3.0.0 - - - 1.7.13 - 1.1.3 - - - - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - runtime - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - io.rest-assured - rest-assured - ${rest-assured.version} - test - - - - io.rest-assured - json-schema-validator - ${rest-assured.version} - - - - com.github.fge - json-schema-validator - ${json-schema-validator.version} - - - - com.github.fge - json-schema-core - ${json-schema-core.version} - - - - - - junit - junit - ${junit.version} - test - - - - com.github.tomakehurst - wiremock - ${wiremock.version} - test - - - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - - - - org.mockito - mockito-core - ${mockito.version} - test - - - - - - rest-assured - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - - - - - \ No newline at end of file diff --git a/rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssuredTest.java b/rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssuredTest.java deleted file mode 100644 index 6ac2d91ee0..0000000000 --- a/rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssuredTest.java +++ /dev/null @@ -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)); - } - -} diff --git a/rest-assured-tutorial/src/test/resources/.gitignore b/rest-assured-tutorial/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/rest-assured-tutorial/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/rest-assured-tutorial/src/test/resources/employees.xml b/rest-assured-tutorial/src/test/resources/employees.xml deleted file mode 100644 index 64e382976d..0000000000 --- a/rest-assured-tutorial/src/test/resources/employees.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - Jane - Daisy - f - - - John - Doe - m - - - Billy - Getty - m - - - Hill - Clinton - f - - \ No newline at end of file diff --git a/rest-assured-tutorial/.gitignore b/rest-assured/.gitignore similarity index 100% rename from rest-assured-tutorial/.gitignore rename to rest-assured/.gitignore diff --git a/rest-assured/README.md b/rest-assured/README.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/rest-assured/pom.xml b/rest-assured/pom.xml new file mode 100644 index 0000000000..47241b18bd --- /dev/null +++ b/rest-assured/pom.xml @@ -0,0 +1,257 @@ + + 4.0.0 + com.baeldung + rest-assured + 1.0 + rest-assured + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 8 + 8 + + + + + + + + javax.servlet + javax.servlet-api + 3.1-b06 + + + + + javax.servlet + servlet-api + 2.5 + + + + + org.eclipse.jetty + jetty-security + 9.2.0.M1 + + + + + org.eclipse.jetty + jetty-servlet + 9.2.0.M1 + + + + + org.eclipse.jetty + jetty-servlets + 9.2.0.M1 + + + + + org.eclipse.jetty + jetty-io + 9.2.0.M1 + + + + + org.eclipse.jetty + jetty-http + 9.2.0.M1 + + + + + + + org.eclipse.jetty + jetty-server + 9.2.0.M1 + + + + + org.eclipse.jetty + jetty-util + 9.2.0.M1 + + + + + + org.slf4j + slf4j-api + 1.7.21 + + + + + log4j + log4j + 1.2.17 + + + + org.slf4j + slf4j-log4j12 + 1.7.21 + + + + + + commons-logging + commons-logging + 1.2 + + + + org.apache.httpcomponents + httpcore + 4.4.5 + + + + + org.apache.commons + commons-lang3 + 3.4 + + + + + + com.github.fge + uri-template + 0.9 + + + + + com.googlecode.libphonenumber + libphonenumber + 7.4.5 + + + + javax.mail + mail + 1.4.7 + + + + joda-time + joda-time + 2.9.4 + + + + com.fasterxml.jackson.core + jackson-annotations + 2.8.0 + + + + com.fasterxml.jackson.core + jackson-databind + 2.8.0 + + + + com.fasterxml.jackson.core + jackson-core + 2.8.0 + + + + com.github.fge + msg-simple + 1.1 + + + + com.github.fge + jackson-coreutils + 1.8 + + + + + + com.google.guava + guava + 18.0 + + + com.github.fge + btf + 1.2 + + + + org.apache.httpcomponents + httpclient + 4.5.2 + + + + org.codehaus.groovy + groovy-all + 2.4.7 + + + + com.github.tomakehurst + wiremock + 2.1.7 + + + io.rest-assured + rest-assured + 3.0.0 + test + + + io.rest-assured + json-schema-validator + 3.0.0 + + + com.github.fge + json-schema-validator + 2.2.6 + + + com.github.fge + json-schema-core + 1.2.5 + + + junit + junit + 4.3 + test + + + + org.hamcrest + hamcrest-all + 1.3 + + + + commons-collections + commons-collections + 3.2.2 + + + + diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2Test.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2Test.java new file mode 100644 index 0000000000..067756823b --- /dev/null +++ b/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2Test.java @@ -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(); + } + +} diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredTest.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredTest.java new file mode 100644 index 0000000000..06f54aae24 --- /dev/null +++ b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredTest.java @@ -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")); + } + +} diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2Test.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2Test.java new file mode 100644 index 0000000000..597280c7c0 --- /dev/null +++ b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2Test.java @@ -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(); +} + +} diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLTest.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLTest.java new file mode 100644 index 0000000000..315dc76169 --- /dev/null +++ b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLTest.java @@ -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(); +} +} diff --git a/rest-assured/src/test/java/com/baeldung/restassured/Util.java b/rest-assured/src/test/java/com/baeldung/restassured/Util.java new file mode 100644 index 0000000000..c75c52eb34 --- /dev/null +++ b/rest-assured/src/test/java/com/baeldung/restassured/Util.java @@ -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(); + + } +} diff --git a/rest-assured/src/test/resources/employees.xml b/rest-assured/src/test/resources/employees.xml new file mode 100644 index 0000000000..388b422210 --- /dev/null +++ b/rest-assured/src/test/resources/employees.xml @@ -0,0 +1,7 @@ + + + Jane + Daisy + f + + \ No newline at end of file diff --git a/rest-assured-tutorial/src/test/resources/event0.json b/rest-assured/src/test/resources/event_0.json similarity index 71% rename from rest-assured-tutorial/src/test/resources/event0.json rename to rest-assured/src/test/resources/event_0.json index 77e26c347e..a6e45239ec 100644 --- a/rest-assured-tutorial/src/test/resources/event0.json +++ b/rest-assured/src/test/resources/event_0.json @@ -1,5 +1,11 @@ { "id": "390", + "odd": { + "price": "1.20", + "status": 2, + "ck": 12.2, + "name": "2" + }, "data": { "countryId": 35, "countryName": "Norway", @@ -9,25 +15,25 @@ "time": "2016-06-12T12:00:00Z" }, "odds": [{ - "price": 1.30, + "price": "1.30", "status": 0, "ck": 12.2, "name": "1" }, { - "price": 5.25, + "price":"5.25", "status": 1, "ck": 13.1, "name": "X" }, { - "price": 2.70, + "price": "2.70", "status": 0, "ck": 12.2, "name": "0" }, { - "price": 1.20, + "price": "1.20", "status": 2, "ck": 13.1, "name": "2" diff --git a/rest-assured/src/test/resources/log4j.properties b/rest-assured/src/test/resources/log4j.properties new file mode 100644 index 0000000000..d3c6b9e783 --- /dev/null +++ b/rest-assured/src/test/resources/log4j.properties @@ -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 \ No newline at end of file diff --git a/rest-assured-tutorial/src/test/resources/odds.json b/rest-assured/src/test/resources/odds.json similarity index 100% rename from rest-assured-tutorial/src/test/resources/odds.json rename to rest-assured/src/test/resources/odds.json diff --git a/rest-assured-tutorial/src/test/resources/teachers.xml b/rest-assured/src/test/resources/teachers.xml similarity index 100% rename from rest-assured-tutorial/src/test/resources/teachers.xml rename to rest-assured/src/test/resources/teachers.xml diff --git a/spring-controller/src/main/java/com/baledung/controller/RestAnnotatedController.java b/spring-controller/src/main/java/com/baeldung/controller/RestAnnotatedController.java similarity index 87% rename from spring-controller/src/main/java/com/baledung/controller/RestAnnotatedController.java rename to spring-controller/src/main/java/com/baeldung/controller/RestAnnotatedController.java index 15f9ba14d4..01c9ed4122 100644 --- a/spring-controller/src/main/java/com/baledung/controller/RestAnnotatedController.java +++ b/spring-controller/src/main/java/com/baeldung/controller/RestAnnotatedController.java @@ -1,6 +1,6 @@ -package com.baledung.controller; +package com.baeldung.controller; -import com.baledung.student.Student; +import com.baeldung.student.Student; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-controller/src/main/java/com/baledung/controller/RestController.java b/spring-controller/src/main/java/com/baeldung/controller/RestController.java similarity index 87% rename from spring-controller/src/main/java/com/baledung/controller/RestController.java rename to spring-controller/src/main/java/com/baeldung/controller/RestController.java index e9afa88471..1281eeee57 100644 --- a/spring-controller/src/main/java/com/baledung/controller/RestController.java +++ b/spring-controller/src/main/java/com/baeldung/controller/RestController.java @@ -1,6 +1,6 @@ -package com.baledung.controller; +package com.baeldung.controller; -import com.baledung.student.Student; +import com.baeldung.student.Student; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-controller/src/main/java/com/baledung/controller/TestController.java b/spring-controller/src/main/java/com/baeldung/controller/TestController.java similarity index 94% rename from spring-controller/src/main/java/com/baledung/controller/TestController.java rename to spring-controller/src/main/java/com/baeldung/controller/TestController.java index 8a9939b371..7397e7a2d3 100644 --- a/spring-controller/src/main/java/com/baledung/controller/TestController.java +++ b/spring-controller/src/main/java/com/baeldung/controller/TestController.java @@ -2,7 +2,7 @@ /** * @author Prashant Dutta */ -package com.baledung.controller; +package com.baeldung.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-controller/src/main/java/com/baledung/student/Student.java b/spring-controller/src/main/java/com/baeldung/student/Student.java similarity index 93% rename from spring-controller/src/main/java/com/baledung/student/Student.java rename to spring-controller/src/main/java/com/baeldung/student/Student.java index 7a5606415f..ca38360928 100644 --- a/spring-controller/src/main/java/com/baledung/student/Student.java +++ b/spring-controller/src/main/java/com/baeldung/student/Student.java @@ -1,4 +1,4 @@ -package com.baledung.student; +package com.baeldung.student; public class Student { private String name; diff --git a/spring-controller/src/main/resources/test-mvc.xml b/spring-controller/src/main/resources/test-mvc.xml index fec69e2dec..858c1b4fe5 100644 --- a/spring-controller/src/main/resources/test-mvc.xml +++ b/spring-controller/src/main/resources/test-mvc.xml @@ -10,7 +10,7 @@ http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> - + diff --git a/spring-controller/src/test/java/com/baledung/test/ControllerTest.java b/spring-controller/src/test/java/com/baeldung/test/ControllerTest.java similarity index 97% rename from spring-controller/src/test/java/com/baledung/test/ControllerTest.java rename to spring-controller/src/test/java/com/baeldung/test/ControllerTest.java index 7f56d09112..8375002213 100644 --- a/spring-controller/src/test/java/com/baledung/test/ControllerTest.java +++ b/spring-controller/src/test/java/com/baeldung/test/ControllerTest.java @@ -1,4 +1,4 @@ -package com.baledung.test; +package com.baeldung.test; import org.junit.Assert; import org.junit.Before; @@ -14,7 +14,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; -import com.baledung.student.Student; +import com.baeldung.student.Student; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) diff --git a/spring-data-neo4j/pom.xml b/spring-data-neo4j/pom.xml index a5a2e9220a..b0cf62ef2e 100644 --- a/spring-data-neo4j/pom.xml +++ b/spring-data-neo4j/pom.xml @@ -1,6 +1,6 @@ - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 com.baeldung spring-data-neo4j @@ -32,6 +32,7 @@ org.springframework.boot spring-boot-starter-test + 1.3.6.RELEASE test diff --git a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml index 9ca0d1c1b7..b1c99d7726 100644 --- a/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml +++ b/spring-jpa/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -3,4 +3,5 @@ + diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java index 42d6149151..24059f2662 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java @@ -1,10 +1,10 @@ package com.baeldung.mvc.velocity.service; -import java.util.List; - import com.baeldung.mvc.velocity.domain.Tutorial; +import java.util.List; + public interface ITutorialsService { - public List listTutorials(); + List listTutorials(); } diff --git a/spring-scurity-custom-permission/README.MD b/spring-scurity-custom-permission/README.MD deleted file mode 100644 index 8fb14fa522..0000000000 --- a/spring-scurity-custom-permission/README.MD +++ /dev/null @@ -1,2 +0,0 @@ -###The Course -The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity diff --git a/spring-security-basic-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-basic-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-security-basic-auth/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-security-basic-auth/.settings/.jsdtscope b/spring-security-basic-auth/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/spring-security-basic-auth/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-basic-auth/.settings/org.eclipse.jdt.core.prefs b/spring-security-basic-auth/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index fb671a82a6..0000000000 --- a/spring-security-basic-auth/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -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 diff --git a/spring-security-basic-auth/.settings/org.eclipse.jdt.ui.prefs b/spring-security-basic-auth/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-security-basic-auth/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -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 diff --git a/spring-security-basic-auth/.settings/org.eclipse.m2e.core.prefs b/spring-security-basic-auth/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-security-basic-auth/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/spring-security-basic-auth/.settings/org.eclipse.m2e.wtp.prefs b/spring-security-basic-auth/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-security-basic-auth/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.common.component b/spring-security-basic-auth/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 9a8276c85b..0000000000 --- a/spring-security-basic-auth/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-basic-auth/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f5888c1411..0000000000 --- a/spring-security-basic-auth/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-security-basic-auth/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.validation.prefs b/spring-security-basic-auth/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-security-basic-auth/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -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 diff --git a/spring-security-basic-auth/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-security-basic-auth/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-security-basic-auth/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java index fcb28f6ae2..aeb2428326 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java @@ -44,8 +44,9 @@ public class SecurityWithoutCsrfConfig extends WebSecurityConfigurerAdapter { http .csrf().disable() .authorizeRequests() - .antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN") - .anyRequest().authenticated() + .antMatchers("/auth/admin/*").hasRole("ADMIN") + .antMatchers("/auth/*").hasAnyRole("ADMIN","USER") + .antMatchers("/*").permitAll() .and() .httpBasic() .and() diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java index 143e52d94e..3e5d6435b3 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java @@ -14,24 +14,25 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { - public WebConfig() { - super(); - } + public WebConfig() { + super(); + } - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/WEB-INF/view/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setPrefix("/WEB-INF/view/"); + viewResolver.setSuffix(".jsp"); + return viewResolver; + } - // API - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/graph.html"); - registry.addViewController("/csrfHome.html"); - } + // API + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/graph.html"); + registry.addViewController("/csrfHome.html"); + registry.addViewController("/homepage.html"); + } } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java index 1a4322c611..64a29f20d3 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/BankController.java @@ -12,21 +12,22 @@ import org.springframework.web.bind.annotation.ResponseStatus; // to test csrf @Controller +@RequestMapping(value = "/auth/") public class BankController { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); - @RequestMapping(value = "/transfer", method = RequestMethod.GET) - @ResponseBody - public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { - logger.info("Transfer to {}", accountNo); - return amount; - } + @RequestMapping(value = "/transfer", method = RequestMethod.GET) + @ResponseBody + public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { + logger.info("Transfer to {}", accountNo); + return amount; + } - // write - just for test - @RequestMapping(value = "/transfer", method = RequestMethod.POST) - @ResponseStatus(HttpStatus.OK) - public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { - logger.info("Transfer to {}", accountNo); + // write - just for test + @RequestMapping(value = "/transfer", method = RequestMethod.POST) + @ResponseStatus(HttpStatus.OK) + public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { + logger.info("Transfer to {}", accountNo); - } + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java index 20307447b2..1e00d6350b 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java @@ -29,93 +29,93 @@ import org.springframework.web.util.UriComponentsBuilder; import com.google.common.base.Preconditions; @Controller -@RequestMapping(value = "/foos") +@RequestMapping(value = "/auth/foos") public class FooController { - @Autowired - private ApplicationEventPublisher eventPublisher; + @Autowired + private ApplicationEventPublisher eventPublisher; - @Autowired - private IFooService service; + @Autowired + private IFooService service; - public FooController() { - super(); - } + public FooController() { + super(); + } - // API + // API - @RequestMapping(method = RequestMethod.GET, value = "/count") - @ResponseBody - @ResponseStatus(value = HttpStatus.OK) - public long count() { - return 2l; - } + @RequestMapping(method = RequestMethod.GET, value = "/count") + @ResponseBody + @ResponseStatus(value = HttpStatus.OK) + public long count() { + return 2l; + } - // read - one + // read - one - @RequestMapping(value = "/{id}", method = RequestMethod.GET) - @ResponseBody - public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { - final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { + final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); - eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); - return resourceById; - } + eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); + return resourceById; + } - // read - all + // read - all - @RequestMapping(method = RequestMethod.GET) - @ResponseBody - public List findAll() { - return service.findAll(); - } + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public List findAll() { + return service.findAll(); + } - @RequestMapping(params = { "page", "size" }, method = RequestMethod.GET) - @ResponseBody - public List findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { - final Page resultPage = service.findPaginated(page, size); - if (page > resultPage.getTotalPages()) { - throw new MyResourceNotFoundException(); - } - eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size)); + @RequestMapping(params = { "page", "size" }, method = RequestMethod.GET) + @ResponseBody + public List findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { + final Page resultPage = service.findPaginated(page, size); + if (page > resultPage.getTotalPages()) { + throw new MyResourceNotFoundException(); + } + eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size)); - return resultPage.getContent(); - } + return resultPage.getContent(); + } - // write + // write - @RequestMapping(method = RequestMethod.POST) - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { - Preconditions.checkNotNull(resource); - final Foo foo = service.create(resource); - final Long idOfCreatedResource = foo.getId(); + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { + Preconditions.checkNotNull(resource); + final Foo foo = service.create(resource); + final Long idOfCreatedResource = foo.getId(); - eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource)); + eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource)); - return foo; - } + return foo; + } - @RequestMapping(value = "/{id}", method = RequestMethod.PUT) - @ResponseStatus(HttpStatus.OK) - public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { - Preconditions.checkNotNull(resource); - RestPreconditions.checkFound(service.findOne(resource.getId())); - service.update(resource); - } + @RequestMapping(value = "/{id}", method = RequestMethod.PUT) + @ResponseStatus(HttpStatus.OK) + public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { + Preconditions.checkNotNull(resource); + RestPreconditions.checkFound(service.findOne(resource.getId())); + service.update(resource); + } - @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) - @ResponseStatus(HttpStatus.OK) - public void delete(@PathVariable("id") final Long id) { - service.deleteById(id); - } + @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) + @ResponseStatus(HttpStatus.OK) + public void delete(@PathVariable("id") final Long id) { + service.deleteById(id); + } - @RequestMapping(method = RequestMethod.HEAD) - @ResponseStatus(HttpStatus.OK) - public void head(final HttpServletResponse resp) { - resp.setContentType(MediaType.APPLICATION_JSON_VALUE); - resp.setHeader("bar", "baz"); - } + @RequestMapping(method = RequestMethod.HEAD) + @ResponseStatus(HttpStatus.OK) + public void head(final HttpServletResponse resp) { + resp.setContentType(MediaType.APPLICATION_JSON_VALUE); + resp.setHeader("bar", "baz"); + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java new file mode 100644 index 0000000000..3e6a6627df --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java @@ -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"; + } + +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java index e83b8cf5ba..bcf0ceb5e6 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java @@ -20,65 +20,66 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.util.UriTemplate; @Controller +@RequestMapping(value = "/auth/") public class RootController { - @Autowired - private IMetricService metricService; + @Autowired + private IMetricService metricService; - @Autowired - private IActuatorMetricService actMetricService; + @Autowired + private IActuatorMetricService actMetricService; - public RootController() { - super(); - } + public RootController() { + super(); + } - // API + // API - // discover + // discover - @RequestMapping(value = "admin", method = RequestMethod.GET) - @ResponseStatus(value = HttpStatus.NO_CONTENT) - public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) { - final String rootUri = request.getRequestURL().toString(); + @RequestMapping(value = "admin", method = RequestMethod.GET) + @ResponseStatus(value = HttpStatus.NO_CONTENT) + public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) { + final String rootUri = request.getRequestURL().toString(); - final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo"); - final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); - response.addHeader("Link", linkToFoo); - } + final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo"); + final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); + response.addHeader("Link", linkToFoo); + } - @RequestMapping(value = "/metric", method = RequestMethod.GET) - @ResponseBody - public Map getMetric() { - return metricService.getFullMetric(); - } + @RequestMapping(value = "/metric", method = RequestMethod.GET) + @ResponseBody + public Map getMetric() { + return metricService.getFullMetric(); + } - @PreAuthorize("hasRole('ROLE_ADMIN')") - @RequestMapping(value = "/status-metric", method = RequestMethod.GET) - @ResponseBody - public Map getStatusMetric() { - return metricService.getStatusMetric(); - } + @PreAuthorize("hasRole('ROLE_ADMIN')") + @RequestMapping(value = "/status-metric", method = RequestMethod.GET) + @ResponseBody + public Map getStatusMetric() { + return metricService.getStatusMetric(); + } - @RequestMapping(value = "/metric-graph", method = RequestMethod.GET) - @ResponseBody - public Object[][] drawMetric() { - final Object[][] result = metricService.getGraphData(); - for (int i = 1; i < result[0].length; i++) { - result[0][i] = result[0][i].toString(); - } - return result; - } + @RequestMapping(value = "/metric-graph", method = RequestMethod.GET) + @ResponseBody + public Object[][] drawMetric() { + final Object[][] result = metricService.getGraphData(); + for (int i = 1; i < result[0].length; i++) { + result[0][i] = result[0][i].toString(); + } + return result; + } - @RequestMapping(value = "/admin/x", method = RequestMethod.GET) - @ResponseBody - public String sampleAdminPage() { - return "Hello"; - } + @RequestMapping(value = "/admin/x", method = RequestMethod.GET) + @ResponseBody + public String sampleAdminPage() { + return "Hello"; + } - @RequestMapping(value = "/my-error-page", method = RequestMethod.GET) - @ResponseBody - public String sampleErrorPage() { - return "Error Occurred"; - } + @RequestMapping(value = "/my-error-page", method = RequestMethod.GET) + @ResponseBody + public String sampleErrorPage() { + return "Error Occurred"; + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java index 7c28ed8e80..2228287f4d 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java @@ -37,96 +37,97 @@ import cz.jirutka.rsql.parser.ast.Node; //@EnableSpringDataWebSupport @Controller +@RequestMapping(value = "/auth/") public class UserController { - @Autowired - private IUserDAO service; + @Autowired + private IUserDAO service; - @Autowired - private UserRepository dao; + @Autowired + private UserRepository dao; - @Autowired - private MyUserRepository myUserRepository; + @Autowired + private MyUserRepository myUserRepository; - public UserController() { - super(); - } + public UserController() { + super(); + } - // API - READ + // API - READ - @RequestMapping(method = RequestMethod.GET, value = "/users") - @ResponseBody - public List findAll(@RequestParam(value = "search", required = false) final String search) { - final List params = new ArrayList(); - if (search != null) { - final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); - final Matcher matcher = pattern.matcher(search + ","); - while (matcher.find()) { - params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3))); - } - } - return service.searchUser(params); - } + @RequestMapping(method = RequestMethod.GET, value = "/users") + @ResponseBody + public List findAll(@RequestParam(value = "search", required = false) final String search) { + final List params = new ArrayList(); + if (search != null) { + final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); + final Matcher matcher = pattern.matcher(search + ","); + while (matcher.find()) { + params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3))); + } + } + return service.searchUser(params); + } - @RequestMapping(method = RequestMethod.GET, value = "/users/spec") - @ResponseBody - public List findAllBySpecification(@RequestParam(value = "search") final String search) { - final UserSpecificationsBuilder builder = new UserSpecificationsBuilder(); - final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET); - final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),"); - final Matcher matcher = pattern.matcher(search + ","); - while (matcher.find()) { - builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5)); - } + @RequestMapping(method = RequestMethod.GET, value = "/users/spec") + @ResponseBody + public List findAllBySpecification(@RequestParam(value = "search") final String search) { + final UserSpecificationsBuilder builder = new UserSpecificationsBuilder(); + final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET); + final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),"); + final Matcher matcher = pattern.matcher(search + ","); + while (matcher.find()) { + builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5)); + } - final Specification spec = builder.build(); - return dao.findAll(spec); - } + final Specification spec = builder.build(); + return dao.findAll(spec); + } - @RequestMapping(method = RequestMethod.GET, value = "/myusers") - @ResponseBody - public Iterable findAllByQuerydsl(@RequestParam(value = "search") final String search) { - final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder(); - if (search != null) { - final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); - final Matcher matcher = pattern.matcher(search + ","); - while (matcher.find()) { - builder.with(matcher.group(1), matcher.group(2), matcher.group(3)); - } - } - final BooleanExpression exp = builder.build(); - return myUserRepository.findAll(exp); - } + @RequestMapping(method = RequestMethod.GET, value = "/myusers") + @ResponseBody + public Iterable findAllByQuerydsl(@RequestParam(value = "search") final String search) { + final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder(); + if (search != null) { + final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); + final Matcher matcher = pattern.matcher(search + ","); + while (matcher.find()) { + builder.with(matcher.group(1), matcher.group(2), matcher.group(3)); + } + } + final BooleanExpression exp = builder.build(); + return myUserRepository.findAll(exp); + } - @RequestMapping(method = RequestMethod.GET, value = "/users/rsql") - @ResponseBody - public List findAllByRsql(@RequestParam(value = "search") final String search) { - final Node rootNode = new RSQLParser().parse(search); - final Specification spec = rootNode.accept(new CustomRsqlVisitor()); - return dao.findAll(spec); - } + @RequestMapping(method = RequestMethod.GET, value = "/users/rsql") + @ResponseBody + public List findAllByRsql(@RequestParam(value = "search") final String search) { + final Node rootNode = new RSQLParser().parse(search); + final Specification spec = rootNode.accept(new CustomRsqlVisitor()); + return dao.findAll(spec); + } - @RequestMapping(method = RequestMethod.GET, value = "/api/myusers") - @ResponseBody - public Iterable findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) { - return myUserRepository.findAll(predicate); - } + @RequestMapping(method = RequestMethod.GET, value = "/api/myusers") + @ResponseBody + public Iterable findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) { + return myUserRepository.findAll(predicate); + } - // API - WRITE + // API - WRITE - @RequestMapping(method = RequestMethod.POST, value = "/users") - @ResponseStatus(HttpStatus.CREATED) - public void create(@RequestBody final User resource) { - Preconditions.checkNotNull(resource); - dao.save(resource); - } + @RequestMapping(method = RequestMethod.POST, value = "/users") + @ResponseStatus(HttpStatus.CREATED) + public void create(@RequestBody final User resource) { + Preconditions.checkNotNull(resource); + dao.save(resource); + } - @RequestMapping(method = RequestMethod.POST, value = "/myusers") - @ResponseStatus(HttpStatus.CREATED) - public void addMyUser(@RequestBody final MyUser resource) { - Preconditions.checkNotNull(resource); - myUserRepository.save(resource); + @RequestMapping(method = RequestMethod.POST, value = "/myusers") + @ResponseStatus(HttpStatus.CREATED) + public void addMyUser(@RequestBody final MyUser resource) { + Preconditions.checkNotNull(resource); + myUserRepository.save(resource); - } + } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index 3af91b82a2..35b840a649 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -23,26 +23,30 @@ import com.fasterxml.jackson.databind.ObjectMapper; @WebAppConfiguration public class CsrfAbstractIntegrationTest { - @Autowired - private WebApplicationContext context; + @Autowired + private WebApplicationContext context; - @Autowired - private Filter springSecurityFilterChain; + @Autowired + private Filter springSecurityFilterChain; - protected MockMvc mvc; + protected MockMvc mvc; - // + // - @Before - public void setup() { - mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); - } + @Before + public void setup() { + mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); + } - protected RequestPostProcessor testUser() { - return user("user").password("userPass").roles("USER"); - } + protected RequestPostProcessor testUser() { + return user("user").password("userPass").roles("USER"); + } - protected String createFoo() throws JsonProcessingException { - return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6))); - } + protected RequestPostProcessor testAdmin() { + return user("admin").password("adminPass").roles("USER", "ADMIN"); + } + + protected String createFoo() throws JsonProcessingException { + return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6))); + } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java index 50b8ae3b44..1f5cf078f3 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java @@ -1,5 +1,6 @@ package org.baeldung.security.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -13,14 +14,33 @@ import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest { - @Test - public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception { - mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized()); - } + @Test + public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception { + mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized()); + } - @Test - public void givenAuth_whenAddFoo_thenCreated() throws Exception { - mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated()); - } + @Test + public void givenAuth_whenAddFoo_thenCreated() throws Exception { + mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated()); + } + + @Test + public void accessMainPageWithoutAuthorization() throws Exception { + mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); + } + + @Test + public void accessOtherPages() throws Exception { + mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100")) + .andExpect(status().isUnauthorized()); // without authorization + mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100").with(testUser())) + .andExpect(status().isOk()); // with authorization + } + + @Test + public void accessAdminPage() throws Exception { + mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); //without authorization + mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON).with(testAdmin())).andExpect(status().isOk()); //with authorization + } } diff --git a/webjars/webjarsdemo/pom.xml b/webjars/pom.xml similarity index 100% rename from webjars/webjarsdemo/pom.xml rename to webjars/pom.xml diff --git a/webjars/webjarsdemo/src/main/java/com/baeldung/TestController.java b/webjars/src/main/java/com/baeldung/TestController.java similarity index 100% rename from webjars/webjarsdemo/src/main/java/com/baeldung/TestController.java rename to webjars/src/main/java/com/baeldung/TestController.java diff --git a/webjars/webjarsdemo/src/main/java/com/baeldung/WebjarsdemoApplication.java b/webjars/src/main/java/com/baeldung/WebjarsdemoApplication.java similarity index 100% rename from webjars/webjarsdemo/src/main/java/com/baeldung/WebjarsdemoApplication.java rename to webjars/src/main/java/com/baeldung/WebjarsdemoApplication.java diff --git a/webjars/webjarsdemo/src/main/resources/templates/index.html b/webjars/src/main/resources/templates/index.html similarity index 100% rename from webjars/webjarsdemo/src/main/resources/templates/index.html rename to webjars/src/main/resources/templates/index.html diff --git a/webjars/webjarsdemo/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java b/webjars/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java similarity index 100% rename from webjars/webjarsdemo/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java rename to webjars/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java diff --git a/xmlunit2-tutorial/README.md b/xmlunit2-tutorial/README.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xmlunit2-tutorial/pom.xml b/xmlunit2-tutorial/pom.xml new file mode 100644 index 0000000000..b4cb684f65 --- /dev/null +++ b/xmlunit2-tutorial/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + com.baeldung + xmlunit2-tutorial + 1.0 + XMLUnit-2 + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 7 + 7 + + + + + + + junit + junit + 4.3 + test + + + org.hamcrest + hamcrest-all + 1.3 + + + org.xmlunit + xmlunit-matchers + 2.2.1 + + + + org.xmlunit + xmlunit-core + 2.2.1 + + + + diff --git a/xmlunit2-tutorial/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java b/xmlunit2-tutorial/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java new file mode 100644 index 0000000000..2f644e0114 --- /dev/null +++ b/xmlunit2-tutorial/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java @@ -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; + } +} diff --git a/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java new file mode 100644 index 0000000000..d0e099e591 --- /dev/null +++ b/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java @@ -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 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 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 i = new JAXPXPathEngine().selectNodes( + "//teacher", + Input.fromFile( + new File(classLoader.getResource("teachers.xml") + .getFile())).build()); + assertNotNull(i); + int count = 0; + for (Iterator 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 = "3false"; + String myTestXML = "false3"; + + 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 = ""; + final String test = ""; + 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 = ""; + final String test = ""; + + Diff myDiff = DiffBuilder.compare(control).withTest(test) + .checkForSimilar().build(); + + assertTrue(myDiff.toString(), myDiff.hasDifferences()); + } + + @Test + public void given2XMLS_whenSimilarWithCustomElementSelector_thenCorrect() { + String controlXml = "3false"; + String testXml = "false3"; + 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("3false"), + isSimilarTo(Input + .from("3false"))); + + } + + @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 = "3false"; + String testXml = "3false"; + assertThat(Input.fromString(testXml), + isSimilarTo(Input.fromString(controlXml))); + + } + + @Test + public void givenSource_whenAbleToInput_thenCorrect() { + String controlXml = "3false"; + String testXml = "3false"; + assertThat(Input.fromString(testXml), + isSimilarTo(Input.fromString(controlXml))); + + } + + @Test + public void given2XMLS_whenIdentical_thenCorrect() { + String controlXml = "3false"; + String testXml = "3false"; + assertThat(testXml, isIdenticalTo(controlXml)); + + } + + @Test + public void given2XMLSWithSimilarNodesButDifferentSequence_whenNotIdentical_thenCorrect() { + String controlXml = "3false"; + String testXml = "false3"; + assertThat(testXml, not(isIdenticalTo(controlXml))); + + } + + @Test + public void given2XMLS_whenGeneratesDifferences_thenCorrect() + throws Exception { + String controlXml = "3false"; + String testXml = "false3"; + Diff myDiff = DiffBuilder.compare(controlXml).withTest(testXml).build(); + Iterator 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 = "3false"; + String myTestXML = "false3"; + Diff myDiff = DiffBuilder + .compare(myControlXML) + .withTest(myTestXML) + .withComparisonController( + ComparisonControllers.StopWhenDifferent).build(); + Iterator iter = myDiff.getDifferences().iterator(); + int size = 0; + while (iter.hasNext()) { + iter.next().toString(); + size++; + } + assertThat(size, equalTo(1)); + } + +} diff --git a/xmlunit2-tutorial/src/test/resources/control.xml b/xmlunit2-tutorial/src/test/resources/control.xml new file mode 100644 index 0000000000..afc0f53f91 --- /dev/null +++ b/xmlunit2-tutorial/src/test/resources/control.xml @@ -0,0 +1,4 @@ + + 3 + false + \ No newline at end of file diff --git a/xmlunit2-tutorial/src/test/resources/students.xml b/xmlunit2-tutorial/src/test/resources/students.xml new file mode 100644 index 0000000000..413e73fd07 --- /dev/null +++ b/xmlunit2-tutorial/src/test/resources/students.xml @@ -0,0 +1,11 @@ + + + + Rajiv + 18 + + + Candie + 19 + + \ No newline at end of file diff --git a/xmlunit2-tutorial/src/test/resources/students.xsd b/xmlunit2-tutorial/src/test/resources/students.xsd new file mode 100644 index 0000000000..15b10279f9 --- /dev/null +++ b/xmlunit2-tutorial/src/test/resources/students.xsd @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/xmlunit2-tutorial/src/test/resources/students_with_error.xml b/xmlunit2-tutorial/src/test/resources/students_with_error.xml new file mode 100644 index 0000000000..e9ce77faf0 --- /dev/null +++ b/xmlunit2-tutorial/src/test/resources/students_with_error.xml @@ -0,0 +1,12 @@ + + + + Rajiv + 18 + + + + Candie + 19 + + \ No newline at end of file diff --git a/xmlunit2-tutorial/src/test/resources/teachers.xml b/xmlunit2-tutorial/src/test/resources/teachers.xml new file mode 100644 index 0000000000..9c073d5a38 --- /dev/null +++ b/xmlunit2-tutorial/src/test/resources/teachers.xml @@ -0,0 +1,10 @@ + + + math + physics + + + political education + english + + \ No newline at end of file diff --git a/xmlunit2-tutorial/src/test/resources/test.xml b/xmlunit2-tutorial/src/test/resources/test.xml new file mode 100644 index 0000000000..afc0f53f91 --- /dev/null +++ b/xmlunit2-tutorial/src/test/resources/test.xml @@ -0,0 +1,4 @@ + + 3 + false + \ No newline at end of file