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..85e68300f0 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 @@ -41,16 +66,16 @@ org.codehaus.cargo cargo-maven2-plugin - 1.5.0 + 1.4.19 - jetty9x + tomcat8x embedded 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..a4faa0f287 --- /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/dozer-tutorial/src/test/java/com/baeldung/dozer/DozerTest.java b/dozer-tutorial/src/test/java/com/baeldung/dozer/DozerTest.java index c02bb2df9d..42ec7ae4bd 100644 --- a/dozer-tutorial/src/test/java/com/baeldung/dozer/DozerTest.java +++ b/dozer-tutorial/src/test/java/com/baeldung/dozer/DozerTest.java @@ -16,15 +16,20 @@ import org.junit.Before; import org.junit.Test; public class DozerTest { +<<<<<<< HEAD DozerBeanMapper mapper = new DozerBeanMapper(); private final long GMT_DIFFERENCE=46800000; +======= + + private DozerBeanMapper mapper = new DozerBeanMapper(); +>>>>>>> 6f2ccdf18729969951fc37e635d24c30dd9b43d5 @Before public void before() throws Exception { mapper = new DozerBeanMapper(); } - BeanMappingBuilder builder = new BeanMappingBuilder() { + private BeanMappingBuilder builder = new BeanMappingBuilder() { @Override protected void configure() { @@ -33,7 +38,7 @@ public class DozerTest { } }; - BeanMappingBuilder builderMinusAge = new BeanMappingBuilder() { + private BeanMappingBuilder builderMinusAge = new BeanMappingBuilder() { @Override protected void configure() { diff --git a/hystrix/pom.xml b/hystrix/pom.xml new file mode 100644 index 0000000000..0ec5fa0411 --- /dev/null +++ b/hystrix/pom.xml @@ -0,0 +1,80 @@ + + + 4.0.0 + com.baeldung + hystrix + 1.0 + + hystrix + + + + + 1.8 + + + 1.4.10 + 0.20.7 + + + 1.3 + 4.12 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + + + + + + + com.netflix.hystrix + hystrix-core + ${hystrix-core.version} + + + + com.netflix.rxjava + rxjava-core + ${rxjava-core.version} + + + + org.hamcrest + hamcrest-all + ${hamcrest-all.version} + test + + + + junit + junit + ${junit.version} + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + + + + diff --git a/hystrix/src/main/java/com/baeldung/hystrix/RemoteServiceSimulator.java b/hystrix/src/main/java/com/baeldung/hystrix/RemoteServiceSimulator.java new file mode 100644 index 0000000000..3efd579d84 --- /dev/null +++ b/hystrix/src/main/java/com/baeldung/hystrix/RemoteServiceSimulator.java @@ -0,0 +1,15 @@ +package com.baeldung.hystrix; + + +public class RemoteServiceSimulator { + + public String checkSomething(final long timeout) throws InterruptedException { + + System.out.print(String.format("Waiting %sms. ", timeout)); + + // to simulate a real world delay in processing. + Thread.sleep(timeout); + + return "Done waiting."; + } +} diff --git a/hystrix/src/test/java/com/baeldung/hystrix/CommandHelloWorld.java b/hystrix/src/test/java/com/baeldung/hystrix/CommandHelloWorld.java new file mode 100644 index 0000000000..4f2b0c38c3 --- /dev/null +++ b/hystrix/src/test/java/com/baeldung/hystrix/CommandHelloWorld.java @@ -0,0 +1,19 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; + +class CommandHelloWorld extends HystrixCommand { + + private final String name; + + CommandHelloWorld(String name) { + super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); + this.name = name; + } + + @Override + protected String run() { + return "Hello " + name + "!"; + } +} diff --git a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java new file mode 100644 index 0000000000..773c76536f --- /dev/null +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutTest.java @@ -0,0 +1,62 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.*; +import com.netflix.hystrix.collapser.RequestCollapserFactory; +import com.netflix.hystrix.exception.HystrixRuntimeException; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +public class HystrixTimeoutTest { + + private static HystrixCommand.Setter config; + private static HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); + + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Before + public void setup() { + config = HystrixCommand + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup1")); + } + + @Test + public void givenInputBob_andDefaultSettings_thenReturnHelloBob(){ + assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!")); + } + + @Test + public void givenTimeoutEqualTo100_andDefaultSettings_thenReturnSuccess() throws InterruptedException { + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(), equalTo("Success")); + } + + @Test + public void givenTimeoutEqualTo10000_andDefaultSettings_thenExpectHystrixRuntimeException() throws InterruptedException { + exception.expect(HystrixRuntimeException.class); + new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute(); + } + + @Test + public void givenTimeoutEqualTo5000_andExecutionTimeoutEqualTo10000_thenReturnSuccess() throws InterruptedException { + commandProperties.withExecutionTimeoutInMilliseconds(10_000); + config.andCommandPropertiesDefaults(commandProperties); + assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(5_000)).execute(), equalTo("Success")); + } + + @Test + public void givenTimeoutEqualTo15000_andExecutionTimeoutEqualTo10000_thenExpectHystrixRuntimeException() throws InterruptedException { + exception.expect(HystrixRuntimeException.class); + commandProperties.withExecutionTimeoutInMilliseconds(10_000); + config.andCommandPropertiesDefaults(commandProperties); + new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(15_000)).execute(); + } + +} diff --git a/hystrix/src/test/java/com/baeldung/hystrix/RemoteServiceTestCommand.java b/hystrix/src/test/java/com/baeldung/hystrix/RemoteServiceTestCommand.java new file mode 100644 index 0000000000..49ea951579 --- /dev/null +++ b/hystrix/src/test/java/com/baeldung/hystrix/RemoteServiceTestCommand.java @@ -0,0 +1,20 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; + + +class RemoteServiceTestCommand extends HystrixCommand { + + private final RemoteServiceTestSimulator remoteService; + + RemoteServiceTestCommand(Setter config, RemoteServiceTestSimulator remoteService) { + super(config); + this.remoteService = remoteService; + } + + @Override + protected String run() throws Exception { + return remoteService.execute(); + } +} diff --git a/hystrix/src/test/java/com/baeldung/hystrix/RemoteServiceTestSimulator.java b/hystrix/src/test/java/com/baeldung/hystrix/RemoteServiceTestSimulator.java new file mode 100644 index 0000000000..54c626a67a --- /dev/null +++ b/hystrix/src/test/java/com/baeldung/hystrix/RemoteServiceTestSimulator.java @@ -0,0 +1,16 @@ +package com.baeldung.hystrix; + + +class RemoteServiceTestSimulator { + + private long wait; + + RemoteServiceTestSimulator(long wait) throws InterruptedException { + this.wait = wait; + } + + String execute() throws InterruptedException { + Thread.sleep(wait); + return "Success"; + } +} diff --git a/immutables/pom.xml b/immutables/pom.xml new file mode 100644 index 0000000000..2b4aba59b1 --- /dev/null +++ b/immutables/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.baeldung + immutables + 1.0.0-SNAPSHOT + + + + org.immutables + value + 2.2.10 + + + junit + junit + 4.12 + test + + + org.assertj + assertj-core + 3.5.2 + test + + + org.mutabilitydetector + MutabilityDetector + 0.9.5 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/immutables/src/main/java/com/baeldung/immutable/Address.java b/immutables/src/main/java/com/baeldung/immutable/Address.java new file mode 100644 index 0000000000..93474dc043 --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/Address.java @@ -0,0 +1,9 @@ +package com.baeldung.immutable; + +import org.immutables.value.Value; + +@Value.Immutable +public interface Address { + String getStreetName(); + Integer getNumber(); +} diff --git a/immutables/src/main/java/com/baeldung/immutable/Person.java b/immutables/src/main/java/com/baeldung/immutable/Person.java new file mode 100644 index 0000000000..466daf42c2 --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/Person.java @@ -0,0 +1,9 @@ +package com.baeldung.immutable; + +import org.immutables.value.Value; + +@Value.Immutable +public abstract class Person { + abstract String getName(); + abstract Integer getAge(); +} diff --git a/immutables/src/main/java/com/baeldung/immutable/auxiliary/Person.java b/immutables/src/main/java/com/baeldung/immutable/auxiliary/Person.java new file mode 100644 index 0000000000..78fe28c50c --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/auxiliary/Person.java @@ -0,0 +1,13 @@ +package com.baeldung.immutable.auxiliary; + + +import org.immutables.value.Value; + +@Value.Immutable +public abstract class Person { + abstract String getName(); + abstract Integer getAge(); + + @Value.Auxiliary + abstract String getAuxiliaryField(); +} \ No newline at end of file diff --git a/immutables/src/main/java/com/baeldung/immutable/default_/Person.java b/immutables/src/main/java/com/baeldung/immutable/default_/Person.java new file mode 100644 index 0000000000..bc48f11a38 --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/default_/Person.java @@ -0,0 +1,14 @@ +package com.baeldung.immutable.default_; + +import org.immutables.value.Value; + +@Value.Immutable(prehash = true) +public abstract class Person { + + abstract String getName(); + + @Value.Default + Integer getAge() { + return 42; + } +} diff --git a/immutables/src/main/java/com/baeldung/immutable/parameter/Person.java b/immutables/src/main/java/com/baeldung/immutable/parameter/Person.java new file mode 100644 index 0000000000..4e8218f99c --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/parameter/Person.java @@ -0,0 +1,14 @@ +package com.baeldung.immutable.parameter; + + +import org.immutables.value.Value; + +@Value.Immutable +public abstract class Person { + + @Value.Parameter + abstract String getName(); + + @Value.Parameter + abstract Integer getAge(); +} \ No newline at end of file diff --git a/immutables/src/main/java/com/baeldung/immutable/prehash/Person.java b/immutables/src/main/java/com/baeldung/immutable/prehash/Person.java new file mode 100644 index 0000000000..5e5dd4d9e9 --- /dev/null +++ b/immutables/src/main/java/com/baeldung/immutable/prehash/Person.java @@ -0,0 +1,9 @@ +package com.baeldung.immutable.prehash; + +import org.immutables.value.Value; + +@Value.Immutable(prehash = true) +public abstract class Person { + abstract String getName(); + abstract Integer getAge(); +} diff --git a/immutables/src/test/java/com/baeldung/immutable/ImmutablePersonTest.java b/immutables/src/test/java/com/baeldung/immutable/ImmutablePersonTest.java new file mode 100644 index 0000000000..bf075569db --- /dev/null +++ b/immutables/src/test/java/com/baeldung/immutable/ImmutablePersonTest.java @@ -0,0 +1,27 @@ +package com.baeldung.immutable; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mutabilitydetector.unittesting.MutabilityAssert.assertImmutable; + +public class ImmutablePersonTest { + + @Test + public void whenModifying_shouldCreateNewInstance() throws Exception { + final ImmutablePerson john = ImmutablePerson.builder() + .age(42) + .name("John") + .build(); + + final ImmutablePerson john43 = john.withAge(43); + + assertThat(john) + .isNotSameAs(john43); + + assertThat(john.getAge()) + .isEqualTo(42); + + assertImmutable(ImmutablePerson.class); + } +} \ No newline at end of file diff --git a/immutables/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryTest.java b/immutables/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryTest.java new file mode 100644 index 0000000000..83f9e51ed5 --- /dev/null +++ b/immutables/src/test/java/com/baeldung/immutable/auxiliary/ImmutablePersonAuxiliaryTest.java @@ -0,0 +1,33 @@ +package com.baeldung.immutable.auxiliary; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ImmutablePersonAuxiliaryTest { + + @Test + public void whenComparing_shouldIgnore() throws Exception { + final ImmutablePerson john1 = ImmutablePerson.builder() + .name("John") + .age(42) + .auxiliaryField("Value1") + .build(); + + final ImmutablePerson john2 = ImmutablePerson.builder() + .name("John") + .age(42) + .auxiliaryField("Value2") + .build(); + + + assertThat(john1.equals(john2)) + .isTrue(); + + assertThat(john1.toString()) + .isEqualTo(john2.toString()); + + assertThat(john1.hashCode()) + .isEqualTo(john2.hashCode()); + } +} \ No newline at end of file diff --git a/immutables/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultTest.java b/immutables/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultTest.java new file mode 100644 index 0000000000..5cf4ac0cf7 --- /dev/null +++ b/immutables/src/test/java/com/baeldung/immutable/default_/ImmutablePersonDefaultTest.java @@ -0,0 +1,17 @@ +package com.baeldung.immutable.default_; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ImmutablePersonDefaultTest { + + @Test + public void whenInstantiating_shouldUseDefaultValue() throws Exception { + + final ImmutablePerson john = ImmutablePerson.builder().name("John").build(); + + assertThat(john.getAge()).isEqualTo(42); + + } +} \ No newline at end of file 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/objectmapper/CustomCarDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java index 88ee1cd673..a3d0b377c6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java @@ -7,18 +7,26 @@ import org.slf4j.LoggerFactory; import com.baeldung.jackson.objectmapper.dto.Car; 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 CustomCarDeserializer extends JsonDeserializer { +public class CustomCarDeserializer extends StdDeserializer { + + private static final long serialVersionUID = -5918629454846356161L; private final Logger Logger = LoggerFactory.getLogger(getClass()); public CustomCarDeserializer() { + this(null); } + public CustomCarDeserializer(final Class vc) { + super(vc); + } + + + @Override public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException { final Car car = new Car(); diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java index 08c7184d29..37bae829b7 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java @@ -1,16 +1,25 @@ package com.baeldung.jackson.objectmapper; +import java.io.IOException; + import com.baeldung.jackson.objectmapper.dto.Car; 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; -import java.io.IOException; - -public class CustomCarSerializer extends JsonSerializer +public class CustomCarSerializer extends StdSerializer { - public CustomCarSerializer() { } + + private static final long serialVersionUID = 1396140685442227917L; + + public CustomCarSerializer() { + this(null); + } + + public CustomCarSerializer(final Class t) { + super(t); + } @Override public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) 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/json/README.md b/json/README.md new file mode 100644 index 0000000000..c47eca3e84 --- /dev/null +++ b/json/README.md @@ -0,0 +1,7 @@ +========= + +## Fast-Json + +### Relevant Articles: +- [Introduction to JSON Schema in Java](http://www.baeldung.com/introduction-to-json-schema-in-java) +- [A Guide to FastJson](http://www.baeldung.com/????????) diff --git a/json/pom.xml b/json/pom.xml index 47f1f25aa2..4d9efe56e4 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -13,6 +13,12 @@ 1.3.0 + + com.alibaba + fastjson + 1.2.13 + + junit junit diff --git a/json/src/test/java/org/baeldung/json/schema/JSONSchemaTest.java b/json/src/test/java/com/baeldung/json/schema/JSONSchemaTest.java similarity index 88% rename from json/src/test/java/org/baeldung/json/schema/JSONSchemaTest.java rename to json/src/test/java/com/baeldung/json/schema/JSONSchemaTest.java index 273fd48bac..bd4aaee682 100644 --- a/json/src/test/java/org/baeldung/json/schema/JSONSchemaTest.java +++ b/json/src/test/java/com/baeldung/json/schema/JSONSchemaTest.java @@ -1,31 +1,32 @@ -package org.baeldung.json.schema; - -import org.everit.json.schema.Schema; -import org.everit.json.schema.loader.SchemaLoader; - -import org.json.JSONObject; -import org.json.JSONTokener; -import org.junit.Test; - -public class JSONSchemaTest { - - @Test - public void givenInvalidInput_whenValidating_thenInvalid() { - - JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json"))); - JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/product_invalid.json"))); - - Schema schema = SchemaLoader.load(jsonSchema); - schema.validate(jsonSubject); - } - - @Test - public void givenValidInput_whenValidating_thenValid() { - - JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json"))); - JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/product_valid.json"))); - - Schema schema = SchemaLoader.load(jsonSchema); - schema.validate(jsonSubject); - } -} +package com.baeldung.json.schema; + +import org.everit.json.schema.Schema; +import org.everit.json.schema.ValidationException; +import org.everit.json.schema.loader.SchemaLoader; + +import org.json.JSONObject; +import org.json.JSONTokener; +import org.junit.Test; + +public class JSONSchemaTest { + + @Test(expected = ValidationException.class) + public void givenInvalidInput_whenValidating_thenInvalid() { + + JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json"))); + JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/product_invalid.json"))); + + Schema schema = SchemaLoader.load(jsonSchema); + schema.validate(jsonSubject); + } + + @Test + public void givenValidInput_whenValidating_thenValid() { + + JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json"))); + JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/product_valid.json"))); + + Schema schema = SchemaLoader.load(jsonSchema); + schema.validate(jsonSubject); + } +} diff --git a/json/src/test/java/fast_json/FastJsonTests.java b/json/src/test/java/fast_json/FastJsonTests.java new file mode 100644 index 0000000000..7b7e3c0434 --- /dev/null +++ b/json/src/test/java/fast_json/FastJsonTests.java @@ -0,0 +1,104 @@ +package fast_json; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.BeanContext; +import com.alibaba.fastjson.serializer.ContextValueFilter; +import com.alibaba.fastjson.serializer.NameFilter; +import com.alibaba.fastjson.serializer.SerializeConfig; +import org.junit.Before; +import org.junit.Test; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class FastJsonTests { + private List listOfPersons; + + @Before + public void setUp() { + listOfPersons = new ArrayList(); + Calendar calendar = Calendar.getInstance(); + calendar.set(2016, 6, 24); + listOfPersons.add(new Person(15, "John", "Doe", calendar.getTime())); + listOfPersons.add(new Person(20, "Janette", "Doe", calendar.getTime())); + } + + @Test + public void whenJavaList_thanConvertToJsonCorrect() { + String personJsonFormat = JSON.toJSONString(listOfPersons); + assertEquals( + personJsonFormat, + "[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":" + + "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":" + + "\"24/07/2016\"}]"); + } + + @Test + public void whenJson_thanConvertToObjectCorrect() { + String personJsonFormat = JSON.toJSONString(listOfPersons.get(0)); + Person newPerson = JSON.parseObject(personJsonFormat, Person.class); + assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute + assertEquals(newPerson.getFirstName(), listOfPersons.get(0).getFirstName()); + assertEquals(newPerson.getLastName(), listOfPersons.get(0).getLastName()); + } + + @Test + public void whenGenerateJson_thanGenerationCorrect() throws ParseException { + JSONArray jsonArray = new JSONArray(); + for (int i = 0; i < 2; i++) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("FIRST NAME", "John" + i); + jsonObject.put("LAST NAME", "Doe" + i); + jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12"); + jsonArray.add(jsonObject); + } + assertEquals( + jsonArray.toString(), + "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" + + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," + + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]"); + } + + @Test + public void givenContextFilter_whenJavaObject_thanJsonCorrect() { + ContextValueFilter valueFilter = new ContextValueFilter() { + public Object process(BeanContext context, Object object, + String name, Object value) { + if (name.equals("DATE OF BIRTH")) { + return "NOT TO DISCLOSE"; + } + if (value.equals("John") || value.equals("Doe")) { + return ((String) value).toUpperCase(); + } else { + return null; + } + } + }; + JSON.toJSONString(listOfPersons, valueFilter); + } + + @Test + public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() { + NameFilter formatName = new NameFilter() { + public String process(Object object, String name, Object value) { + return name.toLowerCase().replace(" ", "_"); + } + }; + SerializeConfig.getGlobalInstance().addFilter(Person.class, formatName); + String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, + "yyyy-MM-dd"); + assertEquals( + jsonOutput, + "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," + + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" + + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]"); + // resetting custom serializer + SerializeConfig.getGlobalInstance().put(Person.class, null); + } +} diff --git a/json/src/test/java/fast_json/Person.java b/json/src/test/java/fast_json/Person.java new file mode 100644 index 0000000000..0eac58cdfd --- /dev/null +++ b/json/src/test/java/fast_json/Person.java @@ -0,0 +1,70 @@ +package fast_json; + +import com.alibaba.fastjson.annotation.JSONField; + +import java.util.Date; + +public class Person { + + @JSONField(name = "AGE", serialize = false, deserialize = false) + private int age; + + @JSONField(name = "LAST NAME", ordinal = 2) + private String lastName; + + @JSONField(name = "FIRST NAME", ordinal = 1) + private String firstName; + + @JSONField(name = "DATE OF BIRTH", format = "dd/MM/yyyy", ordinal = 3) + private Date dateOfBirth; + + public Person() { + + } + + public Person(int age, String lastName, String firstName, Date dateOfBirth) { + super(); + this.age = age; + this.lastName = lastName; + this.firstName = firstName; + this.dateOfBirth = dateOfBirth; + } + + @Override + public String toString() { + return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" + + firstName + ", dateOfBirth=" + dateOfBirth + "]"; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public Date getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(Date dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } +} 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 82cf85208c..419916de86 100644 --- a/pom.xml +++ b/pom.xml @@ -15,39 +15,56 @@ 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 handling-spring-static-resources httpclient + immutables jackson javaxval jjwt jooq-spring + 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-cucumber 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 @@ -61,9 +78,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 @@ -81,9 +101,11 @@ xml lombok redis - + webjars + mutation-testing spring-mvc-velocity + xstream 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-tutorial/README.md b/rest-assured/README.md similarity index 100% rename from rest-assured-tutorial/README.md rename to rest-assured/README.md diff --git a/rest-assured-tutorial/pom.xml b/rest-assured/pom.xml similarity index 98% rename from rest-assured-tutorial/pom.xml rename to rest-assured/pom.xml index 43072d3094..47241b18bd 100644 --- a/rest-assured-tutorial/pom.xml +++ b/rest-assured/pom.xml @@ -2,7 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung - rest-assured-tutorial + rest-assured 1.0 rest-assured @@ -12,8 +12,8 @@ maven-compiler-plugin 3.3 - 7 - 7 + 8 + 8 diff --git a/rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssured2Test.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2Test.java similarity index 100% rename from rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssured2Test.java rename to rest-assured/src/test/java/com/baeldung/restassured/RestAssured2Test.java diff --git a/rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssuredTest.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredTest.java similarity index 95% rename from rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssuredTest.java rename to rest-assured/src/test/java/com/baeldung/restassured/RestAssuredTest.java index 05d0a4d59c..06f54aae24 100644 --- a/rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssuredTest.java +++ b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredTest.java @@ -45,7 +45,7 @@ public class RestAssuredTest { } @Test - public void givenUrl_whenSuccessOnGetsResponse_andJsonHasRequiredKV_thenCorrect() { + public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() { get("/events?id=390").then().statusCode(200).assertThat() .body("id", equalTo("390")); @@ -99,7 +99,7 @@ public class RestAssuredTest { } private static String getEventJson() { - return Util.inputStreamToString(new RestAssuredTest().getClass() + return Util.inputStreamToString(RestAssuredTest.class .getResourceAsStream("/event_0.json")); } diff --git a/rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssuredXML2Test.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2Test.java similarity index 100% rename from rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssuredXML2Test.java rename to rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2Test.java diff --git a/rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssuredXMLTest.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLTest.java similarity index 100% rename from rest-assured-tutorial/src/test/java/com/baeldung/restassured/RestAssuredXMLTest.java rename to rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLTest.java diff --git a/rest-assured-tutorial/src/test/java/com/baeldung/restassured/Util.java b/rest-assured/src/test/java/com/baeldung/restassured/Util.java similarity index 100% rename from rest-assured-tutorial/src/test/java/com/baeldung/restassured/Util.java rename to rest-assured/src/test/java/com/baeldung/restassured/Util.java diff --git a/rest-assured-tutorial/src/test/resources/employees.xml b/rest-assured/src/test/resources/employees.xml similarity index 100% rename from rest-assured-tutorial/src/test/resources/employees.xml rename to rest-assured/src/test/resources/employees.xml diff --git a/rest-assured-tutorial/src/test/resources/event_0.json b/rest-assured/src/test/resources/event_0.json similarity index 100% rename from rest-assured-tutorial/src/test/resources/event_0.json rename to rest-assured/src/test/resources/event_0.json diff --git a/rest-assured-tutorial/src/test/resources/log4j.properties b/rest-assured/src/test/resources/log4j.properties similarity index 84% rename from rest-assured-tutorial/src/test/resources/log4j.properties rename to rest-assured/src/test/resources/log4j.properties index e4b76524e8..d3c6b9e783 100644 --- a/rest-assured-tutorial/src/test/resources/log4j.properties +++ b/rest-assured/src/test/resources/log4j.properties @@ -1,12 +1,11 @@ -## Logger configure file for myproject -log.dir=C:/ProgramData/radixbase/ +## 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/mydebug.log +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 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-all/.settings/.jsdtscope b/spring-all/.settings/.jsdtscope deleted file mode 100644 index b46b9207a8..0000000000 --- a/spring-all/.settings/.jsdtscope +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-all/.settings/org.eclipse.jdt.core.prefs b/spring-all/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index b126d6476b..0000000000 --- a/spring-all/.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=warning -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-all/.settings/org.eclipse.jdt.ui.prefs b/spring-all/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-all/.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-all/.settings/org.eclipse.m2e.core.prefs b/spring-all/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-all/.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-all/.settings/org.eclipse.m2e.wtp.prefs b/spring-all/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-all/.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-all/.settings/org.eclipse.wst.common.component b/spring-all/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 847c6ff698..0000000000 --- a/spring-all/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/spring-all/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-all/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 991897a4ac..0000000000 --- a/spring-all/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/spring-all/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-all/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-all/.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-all/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-all/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-all/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-all/.settings/org.eclipse.wst.validation.prefs b/spring-all/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-all/.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-all/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-all/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-all/.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-all/pom.xml b/spring-all/pom.xml index 5f14d32121..b7a8fcc79e 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -14,6 +14,10 @@ + + com.fasterxml.jackson.core + jackson-databind + @@ -41,11 +45,6 @@ spring-aspects - - org.springframework - spring-orm - - @@ -88,6 +87,14 @@ runtime + + + + com.typesafe.akka + akka-actor_2.11 + 2.4.8 + + diff --git a/spring-all/src/main/java/org/baeldung/akka/AppConfiguration.java b/spring-all/src/main/java/org/baeldung/akka/AppConfiguration.java new file mode 100644 index 0000000000..9211ae0fdb --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/akka/AppConfiguration.java @@ -0,0 +1,26 @@ +package org.baeldung.akka; + +import akka.actor.ActorSystem; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import static org.baeldung.akka.SpringExtension.SPRING_EXTENSION_PROVIDER; + +@Configuration +@ComponentScan +public class AppConfiguration { + + @Autowired + private ApplicationContext applicationContext; + + @Bean + public ActorSystem actorSystem() { + ActorSystem system = ActorSystem.create("akka-spring-demo"); + SPRING_EXTENSION_PROVIDER.get(system).initialize(applicationContext); + return system; + } + +} diff --git a/spring-all/src/main/java/org/baeldung/akka/GreetingActor.java b/spring-all/src/main/java/org/baeldung/akka/GreetingActor.java new file mode 100644 index 0000000000..1a9386c769 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/akka/GreetingActor.java @@ -0,0 +1,43 @@ +package org.baeldung.akka; + +import akka.actor.UntypedActor; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; + +@Component +@Scope(SCOPE_PROTOTYPE) +public class GreetingActor extends UntypedActor { + + private GreetingService greetingService; + + public GreetingActor(GreetingService greetingService) { + this.greetingService = greetingService; + } + + @Override + public void onReceive(Object message) throws Throwable { + if (message instanceof Greet) { + String name = ((Greet) message).getName(); + getSender().tell(greetingService.greet(name), getSelf()); + } else { + unhandled(message); + } + } + + public static class Greet { + + private String name; + + public Greet(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + } + +} diff --git a/spring-all/src/main/java/org/baeldung/akka/GreetingService.java b/spring-all/src/main/java/org/baeldung/akka/GreetingService.java new file mode 100644 index 0000000000..801921887d --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/akka/GreetingService.java @@ -0,0 +1,12 @@ +package org.baeldung.akka; + +import org.springframework.stereotype.Component; + +@Component +public class GreetingService { + + public String greet(String name) { + return "Hello, " + name; + } + +} diff --git a/spring-all/src/main/java/org/baeldung/akka/SpringActorProducer.java b/spring-all/src/main/java/org/baeldung/akka/SpringActorProducer.java new file mode 100644 index 0000000000..20813ab60a --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/akka/SpringActorProducer.java @@ -0,0 +1,28 @@ +package org.baeldung.akka; + +import akka.actor.Actor; +import akka.actor.IndirectActorProducer; +import org.springframework.context.ApplicationContext; + +public class SpringActorProducer implements IndirectActorProducer { + + private ApplicationContext applicationContext; + + private String beanActorName; + + public SpringActorProducer(ApplicationContext applicationContext, String beanActorName) { + this.applicationContext = applicationContext; + this.beanActorName = beanActorName; + } + + @Override + public Actor produce() { + return (Actor) applicationContext.getBean(beanActorName); + } + + @Override + public Class actorClass() { + return (Class) applicationContext.getType(beanActorName); + } + +} diff --git a/spring-all/src/main/java/org/baeldung/akka/SpringExtension.java b/spring-all/src/main/java/org/baeldung/akka/SpringExtension.java new file mode 100644 index 0000000000..624e289812 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/akka/SpringExtension.java @@ -0,0 +1,33 @@ +package org.baeldung.akka; + +import akka.actor.AbstractExtensionId; +import akka.actor.ExtendedActorSystem; +import akka.actor.Extension; +import akka.actor.Props; +import org.springframework.context.ApplicationContext; + +public class SpringExtension extends AbstractExtensionId { + + public static final SpringExtension SPRING_EXTENSION_PROVIDER = new SpringExtension(); + + @Override + public SpringExt createExtension(ExtendedActorSystem system) { + return new SpringExt(); + } + + public static class SpringExt implements Extension { + + private volatile ApplicationContext applicationContext; + + public void initialize(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + public Props props(String actorBeanName) { + return Props.create(SpringActorProducer.class, applicationContext, actorBeanName); + } + + } + + +} diff --git a/spring-controller/src/main/java/com/baledung/controller/RestAnnotatedController.java b/spring-all/src/main/java/org/baeldung/controller/controller/RestAnnotatedController.java similarity index 84% rename from spring-controller/src/main/java/com/baledung/controller/RestAnnotatedController.java rename to spring-all/src/main/java/org/baeldung/controller/controller/RestAnnotatedController.java index 15f9ba14d4..48981fd012 100644 --- a/spring-controller/src/main/java/com/baledung/controller/RestAnnotatedController.java +++ b/spring-all/src/main/java/org/baeldung/controller/controller/RestAnnotatedController.java @@ -1,6 +1,6 @@ -package com.baledung.controller; +package org.baeldung.controller.controller; -import com.baledung.student.Student; +import org.baeldung.controller.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-all/src/main/java/org/baeldung/controller/controller/RestController.java similarity index 84% rename from spring-controller/src/main/java/com/baledung/controller/RestController.java rename to spring-all/src/main/java/org/baeldung/controller/controller/RestController.java index e9afa88471..95903bcc40 100644 --- a/spring-controller/src/main/java/com/baledung/controller/RestController.java +++ b/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java @@ -1,6 +1,6 @@ -package com.baledung.controller; +package org.baeldung.controller.controller; -import com.baledung.student.Student; +import org.baeldung.controller.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-all/src/main/java/org/baeldung/controller/controller/TestController.java similarity index 92% rename from spring-controller/src/main/java/com/baledung/controller/TestController.java rename to spring-all/src/main/java/org/baeldung/controller/controller/TestController.java index 8a9939b371..12ae4e0ab1 100644 --- a/spring-controller/src/main/java/com/baledung/controller/TestController.java +++ b/spring-all/src/main/java/org/baeldung/controller/controller/TestController.java @@ -2,7 +2,7 @@ /** * @author Prashant Dutta */ -package com.baledung.controller; +package org.baeldung.controller.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-all/src/main/java/org/baeldung/controller/student/Student.java similarity index 91% rename from spring-controller/src/main/java/com/baledung/student/Student.java rename to spring-all/src/main/java/org/baeldung/controller/student/Student.java index 7a5606415f..ee706d7028 100644 --- a/spring-controller/src/main/java/com/baledung/student/Student.java +++ b/spring-all/src/main/java/org/baeldung/controller/student/Student.java @@ -1,4 +1,4 @@ -package com.baledung.student; +package org.baeldung.controller.student; public class Student { private String name; diff --git a/spring-controller/src/main/resources/test-mvc.xml b/spring-all/src/main/resources/test-mvc.xml similarity index 93% rename from spring-controller/src/main/resources/test-mvc.xml rename to spring-all/src/main/resources/test-mvc.xml index fec69e2dec..15f950ed4f 100644 --- a/spring-controller/src/main/resources/test-mvc.xml +++ b/spring-all/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/main/webapp/WEB-INF/web.xml b/spring-all/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-controller/src/main/webapp/WEB-INF/web.xml rename to spring-all/src/main/webapp/WEB-INF/web.xml diff --git a/spring-controller/src/main/webapp/WEB-INF/welcome.jsp b/spring-all/src/main/webapp/WEB-INF/welcome.jsp similarity index 100% rename from spring-controller/src/main/webapp/WEB-INF/welcome.jsp rename to spring-all/src/main/webapp/WEB-INF/welcome.jsp diff --git a/spring-all/src/test/java/org/baeldung/akka/SpringAkkaTest.java b/spring-all/src/test/java/org/baeldung/akka/SpringAkkaTest.java new file mode 100644 index 0000000000..6162b02307 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/akka/SpringAkkaTest.java @@ -0,0 +1,48 @@ +package org.baeldung.akka; + +import java.util.concurrent.TimeUnit; + +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.util.Timeout; +import org.baeldung.akka.GreetingActor.Greet; +import org.junit.After; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; +import scala.concurrent.Await; +import scala.concurrent.Future; +import scala.concurrent.duration.FiniteDuration; + +import static akka.pattern.Patterns.ask; +import static org.baeldung.akka.SpringExtension.SPRING_EXTENSION_PROVIDER; + +@ContextConfiguration(classes = AppConfiguration.class) +public class SpringAkkaTest extends AbstractJUnit4SpringContextTests { + + @Autowired + private ActorSystem system; + + @Test + public void whenCallingGreetingActor_thenActorGreetsTheCaller() throws Exception { + ActorRef greeter = system.actorOf( + SPRING_EXTENSION_PROVIDER.get(system) + .props("greetingActor"), "greeter"); + + FiniteDuration duration = FiniteDuration.create(1, TimeUnit.SECONDS); + Timeout timeout = Timeout.durationToTimeout(duration); + + Future result = ask(greeter, new Greet("John"), timeout); + + Assert.assertEquals("Hello, John", Await.result(result, duration)); + } + + @After + public void tearDown() { + system.shutdown(); + system.awaitTermination(); + } + +} diff --git a/spring-controller/src/test/java/com/baledung/test/ControllerTest.java b/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java similarity index 96% rename from spring-controller/src/test/java/com/baledung/test/ControllerTest.java rename to spring-all/src/test/java/org/baeldung/controller/ControllerTest.java index 7f56d09112..f5e41cd5a2 100644 --- a/spring-controller/src/test/java/com/baledung/test/ControllerTest.java +++ b/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java @@ -1,4 +1,4 @@ -package com.baledung.test; +package org.baeldung.controller; 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 org.baeldung.controller.student.Student; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) diff --git a/spring-controller/pom.xml b/spring-controller/pom.xml deleted file mode 100644 index d9fd79c095..0000000000 --- a/spring-controller/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - 4.0.0 - test - spring-controller - 0.0.1-SNAPSHOT - war - - - - org.springframework - spring-webmvc - 4.3.0.RELEASE - - - - javax.servlet - javax.servlet-api - 3.0.1 - compile - - - com.fasterxml.jackson.core - jackson-databind - 2.6.3 - - - com.fasterxml.jackson.core - jackson-annotations - 2.6.3 - - - com.fasterxml.jackson.core - jackson-core - 2.6.3 - - - org.springframework - spring-web - 4.3.0.RELEASE - - - - junit - junit - 4.12 - test - - - org.springframework - spring-test - 4.2.6.RELEASE - - - - - \ No newline at end of file diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml new file mode 100644 index 0000000000..f3b9c983f0 --- /dev/null +++ b/spring-cucumber/pom.xml @@ -0,0 +1,89 @@ + + + 4.0.0 + + com.baeldung + spring-cucumber + 0.0.1-SNAPSHOT + jar + + spring-cucumber + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.3.5.RELEASE + + + + + UTF-8 + 1.8 + 1.2.4 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + info.cukes + cucumber-core + ${cucumber.java.version} + test + + + + info.cukes + cucumber-java + ${cucumber.java.version} + test + + + + info.cukes + cucumber-junit + ${cucumber.java.version} + test + + + + info.cukes + cucumber-spring + ${cucumber.java.version} + test + + + + + org.apache.commons + commons-io + 1.3.2 + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cucumber/src/main/java/com/baeldung/BaeldungController.java b/spring-cucumber/src/main/java/com/baeldung/BaeldungController.java new file mode 100644 index 0000000000..0bb249b814 --- /dev/null +++ b/spring-cucumber/src/main/java/com/baeldung/BaeldungController.java @@ -0,0 +1,22 @@ +package com.baeldung; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class BaeldungController { + + @RequestMapping(method={RequestMethod.GET},value={"/hello"}) + public String sayHello(HttpServletResponse response){ + return "hello"; + } + + @RequestMapping(method={RequestMethod.POST},value={"/baeldung"}) + public String sayHelloPost(HttpServletResponse response){ + return "hello"; + } + +} diff --git a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java new file mode 100644 index 0000000000..d490b23aa2 --- /dev/null +++ b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; + +@SpringBootApplication +public class SpringDemoApplication extends SpringBootServletInitializer{ + + public static void main(String[] args) { + SpringApplication.run(SpringDemoApplication.class, args); + } + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application){ + return application.sources(SpringDemoApplication.class); + } +} diff --git a/spring-cucumber/src/main/java/com/baeldung/VersionController.java b/spring-cucumber/src/main/java/com/baeldung/VersionController.java new file mode 100644 index 0000000000..7c72a78a05 --- /dev/null +++ b/spring-cucumber/src/main/java/com/baeldung/VersionController.java @@ -0,0 +1,14 @@ +package com.baeldung; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class VersionController { + + @RequestMapping(method={RequestMethod.GET},value={"/version"}) + public String getVersion(){ + return "1.0"; + } +} diff --git a/spring-cucumber/src/main/resources/application.properties b/spring-cucumber/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-cucumber/src/test/java/com/baeldung/CucumberTest.java b/spring-cucumber/src/test/java/com/baeldung/CucumberTest.java new file mode 100644 index 0000000000..3e950709b3 --- /dev/null +++ b/spring-cucumber/src/test/java/com/baeldung/CucumberTest.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import cucumber.api.CucumberOptions; +import cucumber.api.junit.Cucumber; +import org.junit.runner.RunWith; + + +@RunWith(Cucumber.class) +@CucumberOptions(features = "src/test/resources") +public class CucumberTest{ +} \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/HeaderSettingRequestCallback.java b/spring-cucumber/src/test/java/com/baeldung/HeaderSettingRequestCallback.java new file mode 100644 index 0000000000..1ea72868eb --- /dev/null +++ b/spring-cucumber/src/test/java/com/baeldung/HeaderSettingRequestCallback.java @@ -0,0 +1,34 @@ +package com.baeldung; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.client.ClientHttpRequest; +import org.springframework.web.client.RequestCallback; + +import java.io.IOException; +import java.util.Map; + + +public class HeaderSettingRequestCallback implements RequestCallback{ + final Map requestHeaders; + + private String body; + + public HeaderSettingRequestCallback(final Map headers){ + this.requestHeaders = headers; + } + + public void setBody(final String postBody ){ + this.body = postBody; + } + + @Override + public void doWithRequest(ClientHttpRequest request) throws IOException{ + final HttpHeaders clientHeaders = request.getHeaders(); + for( final Map.Entry entry : requestHeaders.entrySet() ){ + clientHeaders.add(entry.getKey(),entry.getValue()); + } + if( null != body ){ + request.getBody().write( body.getBytes() ); + } + } +} \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/OtherDefs.java b/spring-cucumber/src/test/java/com/baeldung/OtherDefs.java new file mode 100644 index 0000000000..428343d06a --- /dev/null +++ b/spring-cucumber/src/test/java/com/baeldung/OtherDefs.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import cucumber.api.java.en.Given; +import cucumber.api.java.en.When; + + +public class OtherDefs extends SpringIntegrationTest{ + @When("^the client calls /baeldung$") + public void the_client_issues_POST_hello() throws Throwable{ + executePost("http://localhost:8080/baeldung"); + } + + @Given("^the client calls /hello$") + public void the_client_issues_GET_hello() throws Throwable{ + executeGet("http://localhost:8080/hello"); + } +} \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/ResponseResults.java b/spring-cucumber/src/test/java/com/baeldung/ResponseResults.java new file mode 100644 index 0000000000..6890faf8b5 --- /dev/null +++ b/spring-cucumber/src/test/java/com/baeldung/ResponseResults.java @@ -0,0 +1,34 @@ +package com.baeldung; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import org.apache.commons.io.IOUtils; +import org.springframework.http.client.ClientHttpResponse; + + +public class ResponseResults{ + private final ClientHttpResponse theResponse; + private final String body; + + protected ResponseResults(final ClientHttpResponse response) throws IOException{ + this.theResponse = response; + final InputStream bodyInputStream = response.getBody(); + if (null == bodyInputStream){ + this.body = "{}"; + }else{ + final StringWriter stringWriter = new StringWriter(); + IOUtils.copy(bodyInputStream, stringWriter); + this.body = stringWriter.toString(); + } + } + + protected ClientHttpResponse getTheResponse(){ + return theResponse; + } + + protected String getBody(){ + return body; + } +} \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java new file mode 100644 index 0000000000..5c85dc9400 --- /dev/null +++ b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java @@ -0,0 +1,102 @@ +package com.baeldung; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.runner.RunWith; +import org.springframework.boot.test.IntegrationTest; +import org.springframework.boot.test.SpringApplicationContextLoader; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.web.client.ResponseErrorHandler; +import org.springframework.web.client.ResponseExtractor; +import org.springframework.web.client.RestTemplate; + + +//@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = SpringDemoApplication.class, loader = SpringApplicationContextLoader.class) +@WebAppConfiguration +@IntegrationTest +public class SpringIntegrationTest { + protected static ResponseResults latestResponse = null; + + protected RestTemplate restTemplate = null; + + protected void executeGet(String url) throws IOException{ + final Map headers = new HashMap<>(); + headers.put("Accept","application/json"); + final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers); + final ResponseResultErrorHandler errorHandler = new ResponseResultErrorHandler(); + + if (restTemplate == null){ + restTemplate = new RestTemplate(); + } + + restTemplate.setErrorHandler(errorHandler); + latestResponse = restTemplate.execute(url, + HttpMethod.GET, + requestCallback, + new ResponseExtractor(){ + @Override + public ResponseResults extractData(ClientHttpResponse response) throws IOException { + if (errorHandler.hadError){ + return (errorHandler.getResults()); + } else{ + return (new ResponseResults(response)); + } + } + }); + + } + + protected void executePost(String url) throws IOException{ + final Map headers = new HashMap<>(); + headers.put("Accept","application/json"); + final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers); + final ResponseResultErrorHandler errorHandler = new ResponseResultErrorHandler(); + + if (restTemplate == null){ + restTemplate = new RestTemplate(); + } + + restTemplate.setErrorHandler(errorHandler); + latestResponse = restTemplate.execute(url, + HttpMethod.POST, + requestCallback, + new ResponseExtractor(){ + @Override + public ResponseResults extractData(ClientHttpResponse response) throws IOException { + if (errorHandler.hadError){ + return (errorHandler.getResults()); + } else{ + return (new ResponseResults(response)); + } + } + }); + + } + + private class ResponseResultErrorHandler implements ResponseErrorHandler{ + private ResponseResults results = null; + private Boolean hadError = false; + + private ResponseResults getResults(){ + return results; + } + + @Override + public boolean hasError(ClientHttpResponse response) throws IOException{ + hadError = response.getRawStatusCode() >= 400; + return hadError; + } + + @Override + public void handleError(ClientHttpResponse response) throws IOException { + results = new ResponseResults(response); + } + } +} \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/StepDefs.java b/spring-cucumber/src/test/java/com/baeldung/StepDefs.java new file mode 100644 index 0000000000..3ed25bb09b --- /dev/null +++ b/spring-cucumber/src/test/java/com/baeldung/StepDefs.java @@ -0,0 +1,28 @@ +package com.baeldung; + +import cucumber.api.java.en.And; +import cucumber.api.java.en.Then; +import cucumber.api.java.en.When; +import org.springframework.http.HttpStatus; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +public class StepDefs extends SpringIntegrationTest{ + + @When("^the client calls /version$") + public void the_client_issues_GET_version() throws Throwable{ + executeGet("http://localhost:8080/version"); + } + + @Then("^the client receives status code of (\\d+)$") + public void the_client_receives_status_code_of(int statusCode) throws Throwable{ + final HttpStatus currentStatusCode = latestResponse.getTheResponse().getStatusCode(); + assertThat("status code is incorrect : "+ latestResponse.getBody(), currentStatusCode.value(), is(statusCode) ); + } + + @And("^the client receives server version (.+)$") + public void the_client_receives_server_version_body(String version) throws Throwable{ + assertThat(latestResponse.getBody(), is(version)) ; + } +} \ No newline at end of file diff --git a/spring-cucumber/src/test/resources/baelung.feature b/spring-cucumber/src/test/resources/baelung.feature new file mode 100644 index 0000000000..21f18db3a4 --- /dev/null +++ b/spring-cucumber/src/test/resources/baelung.feature @@ -0,0 +1,9 @@ +Feature: the message can be retrieved + Scenario: client makes call to POST /baeldung + When the client calls /baeldung + Then the client receives status code of 200 + And the client receives server version hello + Scenario: client makes call to GET /hello + Given the client calls /hello + When the client receives status code of 200 + Then the client receives server version hello \ No newline at end of file diff --git a/spring-cucumber/src/test/resources/version.feature b/spring-cucumber/src/test/resources/version.feature new file mode 100644 index 0000000000..12f77137ff --- /dev/null +++ b/spring-cucumber/src/test/resources/version.feature @@ -0,0 +1,6 @@ +Feature: the version can be retrieved + Scenario: client makes call to GET /version + When the client calls /version + Then the client receives status code of 200 + And the client receives server version 1.0 + \ No newline at end of file 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-exceptions/pom.xml b/spring-exceptions/pom.xml index 554bb0c170..9e3cb81ef2 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -130,6 +130,11 @@ test + + javax.el + el-api + 2.2 + diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java new file mode 100644 index 0000000000..266a04b679 --- /dev/null +++ b/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java @@ -0,0 +1,76 @@ +package org.baeldung.ex.nontransientexception.cause; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp.BasicDataSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-mysql.properties" }) +@ComponentScan({ "org.baeldung.persistence" }) +public class Cause1NonTransientConfig { + + @Autowired + private Environment env; + + public Cause1NonTransientConfig() { + super(); + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public DataSource restDataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public HibernateTransactionManager transactionManager() { + final HibernateTransactionManager txManager = new HibernateTransactionManager(); + txManager.setSessionFactory(sessionFactory().getObject()); + + return txManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + +} diff --git a/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java b/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java new file mode 100644 index 0000000000..19e2ceebca --- /dev/null +++ b/spring-exceptions/src/main/java/org/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java @@ -0,0 +1,76 @@ +package org.baeldung.ex.nontransientexception.cause; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp.BasicDataSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-mysql.properties" }) +@ComponentScan({ "org.baeldung.persistence" }) +public class Cause4NonTransientConfig { + + @Autowired + private Environment env; + + public Cause4NonTransientConfig() { + super(); + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public DataSource restDataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public HibernateTransactionManager transactionManager() { + final HibernateTransactionManager txManager = new HibernateTransactionManager(); + txManager.setSessionFactory(sessionFactory().getObject()); + + return txManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + +} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CleanupFailureExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CleanupFailureExceptionTest.java new file mode 100644 index 0000000000..2f0a8fe09d --- /dev/null +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CleanupFailureExceptionTest.java @@ -0,0 +1,39 @@ +package org.baeldung.ex.nontransientdataaccessexception; + +import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; +import org.baeldung.persistence.model.Foo; +import org.baeldung.persistence.service.IFooService; +import org.hibernate.SessionFactory; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.CleanupFailureDataAccessException; +import org.springframework.dao.NonTransientDataAccessException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) +public class CleanupFailureExceptionTest { + + @Autowired + private SessionFactory sessionFactory; + + @Autowired + private IFooService fooService; + + @Test + public void whenCleanupAfterSaving_thenCleanupException() { + try { + final Foo fooEntity = new Foo("foo"); + fooService.create(fooEntity); + } finally { + try { + sessionFactory.close(); + } catch (final NonTransientDataAccessException exc) { + throw new CleanupFailureDataAccessException("Closing connection failed", exc.getCause()); + } + } + } +} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java new file mode 100644 index 0000000000..aa504223f3 --- /dev/null +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java @@ -0,0 +1,26 @@ +package org.baeldung.ex.nontransientdataaccessexception; + +import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; +import org.baeldung.persistence.model.Foo; +import org.baeldung.persistence.service.IFooService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) +public class DataIntegrityExceptionTest { + + @Autowired + private IFooService fooService; + + @Test(expected = DataIntegrityViolationException.class) + public void whenSavingNullValue_thenDataIntegrityException() { + final Foo fooEntity = new Foo(); + fooService.create(fooEntity); + } +} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java new file mode 100644 index 0000000000..f5e24e3546 --- /dev/null +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java @@ -0,0 +1,28 @@ +package org.baeldung.ex.nontransientdataaccessexception; + +import javax.sql.DataSource; + +import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataRetrievalFailureException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) +public class DataRetrievalExceptionTest { + + @Autowired + private DataSource restDataSource; + + @Test(expected = DataRetrievalFailureException.class) + public void whenRetrievingNonExistentValue_thenDataRetrievalException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + + jdbcTemplate.queryForObject("select * from foo where id=3", Integer.class); + } +} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionTest.java new file mode 100644 index 0000000000..036f99ac8f --- /dev/null +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionTest.java @@ -0,0 +1,24 @@ +package org.baeldung.ex.nontransientdataaccessexception; + +import javax.sql.DataSource; + +import org.baeldung.ex.nontransientexception.cause.Cause4NonTransientConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException; +import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Cause4NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) +public class DataSourceLookupExceptionTest { + + @Test(expected = DataSourceLookupFailureException.class) + public void whenLookupNonExistentDataSource_thenDataSourceLookupFailureException() { + final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup(); + dsLookup.setResourceRef(true); + final DataSource dataSource = dsLookup.getDataSource("java:comp/env/jdbc/example_db"); + } +} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java new file mode 100644 index 0000000000..9afe2533de --- /dev/null +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java @@ -0,0 +1,38 @@ +package org.baeldung.ex.nontransientdataaccessexception; + +import javax.sql.DataSource; + +import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; +import org.baeldung.persistence.service.IFooService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.InvalidDataAccessResourceUsageException; +import org.springframework.jdbc.BadSqlGrammarException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) +public class InvalidResourceUsageExceptionTest { + @Autowired + private IFooService fooService; + + @Autowired + private DataSource restDataSource; + + @Test(expected = InvalidDataAccessResourceUsageException.class) + public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() { + fooService.findAll(); + } + + @Test(expected = BadSqlGrammarException.class) + public void whenIncorrectSql_thenBadSqlGrammarException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + + jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class); + } + +} diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/PermissionDeniedException.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/PermissionDeniedException.java new file mode 100644 index 0000000000..7f91b52e00 --- /dev/null +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/PermissionDeniedException.java @@ -0,0 +1,27 @@ +package org.baeldung.ex.nontransientdataaccessexception; + +import org.baeldung.ex.nontransientexception.cause.Cause1NonTransientConfig; +import org.baeldung.persistence.model.Foo; +import org.baeldung.persistence.service.IFooService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.PermissionDeniedDataAccessException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) +public class PermissionDeniedException { + + @Autowired + private IFooService fooService; + + @Test(expected = PermissionDeniedDataAccessException.class) + public void whenRetrievingDataUserNoSelectRights_thenPermissionDeniedException() { + final Foo foo = new Foo("foo"); + fooService.create(foo); + } + +} 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/pom.xml b/spring-mvc-velocity/pom.xml index 597e638cf7..6c63e0be18 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -128,6 +128,9 @@ org.apache.maven.plugins maven-war-plugin ${maven-war-plugin.version} + + false + diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java index fe88705b90..679a455f3f 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java @@ -1,7 +1,7 @@ package com.baeldung.mvc.velocity.controller; import com.baeldung.mvc.velocity.domain.Tutorial; -import com.baeldung.mvc.velocity.service.TutorialsService; +import com.baeldung.mvc.velocity.service.ITutorialsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -14,21 +14,29 @@ import java.util.List; @RequestMapping("/") public class MainController { - private final TutorialsService tutService; - @Autowired - public MainController(TutorialsService tutService) { - this.tutService = tutService; - } + private ITutorialsService tutService; - @RequestMapping(method = RequestMethod.GET) + @RequestMapping(value ="/", method = RequestMethod.GET) + public String welcomePage() { + return "index"; + } + + + @RequestMapping(value ="/list", method = RequestMethod.GET) public String listTutorialsPage(Model model) { List list = tutService.listTutorials(); model.addAttribute("tutorials", list); - return "index"; + return "list"; } - public TutorialsService getTutService() { + public ITutorialsService getTutService() { return tutService; } + + public void setTutService(ITutorialsService tutService) { + this.tutService = tutService; + } + + } \ No newline at end of file diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/domain/Tutorial.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/domain/Tutorial.java index 47265aa98c..ccbaa0e905 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/domain/Tutorial.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/domain/Tutorial.java @@ -14,21 +14,20 @@ public class Tutorial { this.author = author; } - public Integer getTutId() { - return tutId; - } + public Integer getTutId() { + return tutId; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } + + public String getAuthor() { + return author; + } - public String getAuthor() { - return author; - } - - } 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-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/MainWebAppInitializer.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/MainWebAppInitializer.java new file mode 100644 index 0000000000..a2871716df --- /dev/null +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/MainWebAppInitializer.java @@ -0,0 +1,36 @@ +package com.baeldung.mvc.velocity.spring.config; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.context.support.GenericWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; +import java.util.Set; + +public class MainWebAppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(final ServletContext sc) throws ServletException { + + // Create the 'root' Spring application context + final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); + root.register(WebConfig.class); + + // Manages the lifecycle of the root application context + sc.addListener(new ContextLoaderListener(root)); + + // Handles requests into the application + final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext())); + appServlet.setLoadOnStartup(1); + + final Set mappingConflicts = appServlet.addMapping("/"); + if (!mappingConflicts.isEmpty()) { + throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); + } + } + +} diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java new file mode 100644 index 0000000000..ce8ce1919a --- /dev/null +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java @@ -0,0 +1,45 @@ +package com.baeldung.mvc.velocity.spring.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.velocity.VelocityConfigurer; +import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service"}) +public class WebConfig extends WebMvcConfigurerAdapter { + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + + @Override + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Bean + public ViewResolver viewResolver() { + final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver(); + bean.setCache(true); + bean.setPrefix("/WEB-INF/views/"); + bean.setLayoutUrl("/WEB-INF/layouts/layout.vm"); + bean.setSuffix(".vm"); + return bean; + } + + @Bean + public VelocityConfigurer velocityConfig() { + VelocityConfigurer velocityConfigurer = new VelocityConfigurer(); + velocityConfigurer.setResourceLoaderPath("/"); + return velocityConfigurer; + } +} diff --git a/spring-mvc-velocity/src/main/webapp/WEB-INF/layouts/layout.vm b/spring-mvc-velocity/src/main/webapp/WEB-INF/layouts/layout.vm index 203e675cfb..3bac96aaae 100644 --- a/spring-mvc-velocity/src/main/webapp/WEB-INF/layouts/layout.vm +++ b/spring-mvc-velocity/src/main/webapp/WEB-INF/layouts/layout.vm @@ -1,6 +1,6 @@ - Spring & Velocity + Spring with Velocity
diff --git a/spring-mvc-velocity/src/main/webapp/WEB-INF/views/index.vm b/spring-mvc-velocity/src/main/webapp/WEB-INF/views/index.vm index d1ae0b02cb..8883a50658 100644 --- a/spring-mvc-velocity/src/main/webapp/WEB-INF/views/index.vm +++ b/spring-mvc-velocity/src/main/webapp/WEB-INF/views/index.vm @@ -1,19 +1,4 @@

Index

-

Tutorials list

- - - - - - - -#foreach($tut in $tutorials) - - - - - - -#end -
Tutorial IdTutorial TitleTutorial DescriptionTutorial Author
$tut.tutId$tut.title$tut.description$tut.author
\ No newline at end of file +

Welcome page

+This is just the welcome page \ No newline at end of file diff --git a/spring-mvc-velocity/src/main/webapp/WEB-INF/views/list.vm b/spring-mvc-velocity/src/main/webapp/WEB-INF/views/list.vm new file mode 100644 index 0000000000..9e06a09e4f --- /dev/null +++ b/spring-mvc-velocity/src/main/webapp/WEB-INF/views/list.vm @@ -0,0 +1,19 @@ +

Index

+ +

Tutorials list

+ + + + + + + +#foreach($tut in $tutorials) + + + + + + +#end +
Tutorial IdTutorial TitleTutorial DescriptionTutorial Author
$tut.tutId$tut.title$tut.description$tut.author
\ No newline at end of file diff --git a/spring-mvc-velocity/src/main/webapp/WEB-INF/web.xml b/spring-mvc-velocity/src/main/webapp/WEB-INF/web_old.xml similarity index 100% rename from spring-mvc-velocity/src/main/webapp/WEB-INF/web.xml rename to spring-mvc-velocity/src/main/webapp/WEB-INF/web_old.xml diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java index 36453eef92..a9fb242755 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java @@ -1,12 +1,19 @@ package com.baeldung.mvc.velocity.test; -import com.baeldung.mvc.velocity.domain.Tutorial; -import com.baeldung.mvc.velocity.service.ITutorialsService; -import com.baeldung.mvc.velocity.service.TutorialsService; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -15,72 +22,40 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import java.util.Arrays; - -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; +import com.baeldung.mvc.velocity.spring.config.WebConfig; +import com.baeldung.mvc.velocity.test.config.TestConfig; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:mvc-servlet.xml"}) +// @ContextConfiguration(locations = {"classpath:mvc-servlet.xml"}) +@ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) @WebAppConfiguration public class DataContentControllerTest { - private MockMvc mockMvc; - @Autowired - private ITutorialsService tutServiceMock; - @Autowired private WebApplicationContext webApplicationContext; - + @Before public void setUp() { - tutServiceMock = Mockito.mock(TutorialsService.class); - Mockito.reset(tutServiceMock); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } - - @Test - public void testModel() throws Exception{ - Mockito.when(tutServiceMock.listTutorials()).thenReturn(Arrays.asList( - new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), - new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor") - )); - - mockMvc.perform(get("/")) - .andExpect(status().isOk()) - .andExpect(view().name("index")) - .andExpect(content().string(containsString("GuavaAuthor"))) - .andExpect(content().string(containsString("Introduction to Guava"))) - .andExpect(content().string(containsString("AndroidAuthor"))) - .andExpect(content().string(containsString("Introduction to Android"))) - .andExpect(model().attribute("tutorials", hasSize(2))) - .andExpect(model().attribute("tutorials", hasSize(2))) - .andExpect(model().attribute("tutorials", hasItem( - allOf( - hasProperty("tutId", is(1)), - hasProperty("author", is("GuavaAuthor")), - hasProperty("title", is("Guava")) - ) - ))) - .andExpect(model().attribute("tutorials", hasItem( - allOf( - hasProperty("tutId", is(2)), - hasProperty("author", is("AndroidAuthor")), - hasProperty("title", is("Android")) - ) - ))); - } + @Test + public void whenCallingList_ThenModelAndContentOK() throws Exception { + + mockMvc.perform(get("/list")).andExpect(status().isOk()).andExpect(view().name("list")).andExpect(model().attribute("tutorials", hasSize(2))) + .andExpect(model().attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(1)), hasProperty("author", is("GuavaAuthor")), hasProperty("title", is("Guava")))))) + .andExpect(model().attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(2)), hasProperty("author", is("AndroidAuthor")), hasProperty("title", is("Android")))))); + + mockMvc.perform(get("/list")).andExpect(xpath("//table").exists()); + mockMvc.perform(get("/list")).andExpect(xpath("//td[@id='tutId_1']").exists()); + } + + @Test + public void whenCallingIndex_thenViewOK() throws Exception{ + mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index")).andExpect(model().size(0)); + } } diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/NavigationControllerTest.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/NavigationControllerTest.java deleted file mode 100644 index e007cf3f94..0000000000 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/NavigationControllerTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.mvc.velocity.test; - - -import com.baeldung.mvc.velocity.controller.MainController; -import com.baeldung.mvc.velocity.domain.Tutorial; -import com.baeldung.mvc.velocity.service.TutorialsService; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.ui.ExtendedModelMap; -import org.springframework.ui.Model; - -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(locations = {"classpath:mvc-servlet.xml"}) -public class NavigationControllerTest { - - private MainController mainController = new MainController(Mockito.mock(TutorialsService.class)); - - private final Model model = new ExtendedModelMap(); - - - @Test - public void shouldGoToTutorialListView() { - Mockito.when(mainController.getTutService().listTutorials()) - .thenReturn(createTutorialList()); - - final String view = mainController.listTutorialsPage(model); - final List tutorialListAttribute = (List) model.asMap().get("tutorials"); - - assertEquals("index", view); - assertNotNull(tutorialListAttribute); - } - - @Test - public void testContent() throws Exception{ - - List tutorials = Arrays.asList( - new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), - new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor") - ); - Mockito.when(mainController.getTutService().listTutorials()).thenReturn(tutorials); - - String view = mainController.listTutorialsPage(model); - - verify(mainController.getTutService(), times(1)).listTutorials(); - verifyNoMoreInteractions(mainController.getTutService()); - - assertEquals("index", view); - assertEquals(tutorials, model.asMap().get("tutorials")); - } - - private static List createTutorialList() { - return Arrays.asList(new Tutorial(1, "TestAuthor", "Test Title", "Test Description")); - } -} diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java new file mode 100644 index 0000000000..8b84bcdd23 --- /dev/null +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java @@ -0,0 +1,32 @@ +package com.baeldung.mvc.velocity.test.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.view.velocity.VelocityConfigurer; +import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; + +@Configuration +public class TestConfig { + + + @Bean + public ViewResolver viewResolver() { + final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver(); + bean.setCache(true); + bean.setPrefix("/WEB-INF/views/"); + bean.setLayoutUrl("/WEB-INF/layouts/layout.vm"); + bean.setSuffix(".vm"); + return bean; + } + + @Bean + public VelocityConfigurer velocityConfig() { + VelocityConfigurer velocityConfigurer = new VelocityConfigurer(); + velocityConfigurer.setResourceLoaderPath("/"); + return velocityConfigurer; + } + + + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/pom.xml b/spring-rest-angular-pagination/StudentDirectory/pom.xml new file mode 100644 index 0000000000..8dab851ef2 --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + angular-spring-rest-sample + angular-spring-rest-sample + com.baeldung + 1.0 + war + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + 1.12.2.RELEASE + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.data + spring-data-commons + + + org.springframework + spring-test + test + + + org.apache.commons + commons-lang3 + 3.3 + + + com.google.guava + guava + 19.0 + + + junit + junit + test + + + io.rest-assured + rest-assured + 3.0.0 + test + + + io.rest-assured + spring-mock-mvc + 3.0.0 + test + + + + angular-spring-rest-sample + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + + diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/mock/MockStudentData.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/mock/MockStudentData.java new file mode 100644 index 0000000000..df70780a87 --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/mock/MockStudentData.java @@ -0,0 +1,39 @@ +package org.baeldung.mock; + +import java.util.ArrayList; +import java.util.List; + +import org.baeldung.web.vo.Student; + +public class MockStudentData { + + private static List studentList = new ArrayList<>(); + + static { + studentList.add(new Student("1", "Bryan", "Male", 20)); + studentList.add(new Student("2", "Ben", "Male", 22)); + studentList.add(new Student("3", "Lisa", "Female", 24)); + studentList.add(new Student("4", "Sarah", "Female", 26)); + studentList.add(new Student("5", "Jay", "Male", 20)); + studentList.add(new Student("6", "John", "Male", 22)); + studentList.add(new Student("7", "Jordan", "Male", 24)); + studentList.add(new Student("8", "Rob", "Male", 26)); + studentList.add(new Student("9", "Will", "Male", 20)); + studentList.add(new Student("10", "Shawn", "Male", 22)); + studentList.add(new Student("11", "Taylor", "Female", 24)); + studentList.add(new Student("12", "Venus", "Female", 26)); + studentList.add(new Student("13", "Vince", "Male", 20)); + studentList.add(new Student("14", "Carol", "Female", 22)); + studentList.add(new Student("15", "Joana", "Female", 24)); + studentList.add(new Student("16", "Dion", "Male", 26)); + studentList.add(new Student("17", "Evans", "Male", 20)); + studentList.add(new Student("18", "Bart", "Male", 22)); + studentList.add(new Student("19", "Jenny", "Female", 24)); + studentList.add(new Student("20", "Kristine", "Female", 26)); + } + + public static List getMockDataStudents(){ + return studentList; + } + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java new file mode 100644 index 0000000000..3105d1cb11 --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java @@ -0,0 +1,27 @@ +package org.baeldung.web.exception; + +public class MyResourceNotFoundException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 4088649120307193208L; + + public MyResourceNotFoundException() { + super(); + } + + public MyResourceNotFoundException(final String message, final Throwable cause) { + super(message, cause); + } + + public MyResourceNotFoundException(final String message) { + super(message); + } + + public MyResourceNotFoundException(final Throwable cause) { + super(cause); + } + + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/main/Application.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/main/Application.java new file mode 100644 index 0000000000..b3b0dad98a --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/main/Application.java @@ -0,0 +1,26 @@ +package org.baeldung.web.main; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.web.filter.ShallowEtagHeaderFilter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@SpringBootApplication +@EnableAutoConfiguration +@ComponentScan("org.baeldung") +public class Application extends WebMvcConfigurerAdapter { + + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { + return new ShallowEtagHeaderFilter(); + } + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java new file mode 100644 index 0000000000..5ff24ec0f2 --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/rest/StudentDirectoryRestController.java @@ -0,0 +1,26 @@ +package org.baeldung.web.rest; + +import org.baeldung.web.service.StudentService; +import org.baeldung.web.vo.Student; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class StudentDirectoryRestController { + + @Autowired + private StudentService service; + + @RequestMapping(value = "/student/get", params = { "page", "size" }, method = RequestMethod.GET) + public Page findPaginated(@RequestParam("page") int page, @RequestParam("size") int size){ + + Page resultPage = service.findPaginated(page, size); + + return resultPage; + } + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/IOperations.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/IOperations.java new file mode 100644 index 0000000000..0b408106ce --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/IOperations.java @@ -0,0 +1,9 @@ +package org.baeldung.web.service; + +import org.springframework.data.domain.Page; + +public interface IOperations { + + Page findPaginated(int page, int size); + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentService.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentService.java new file mode 100644 index 0000000000..5c4487254a --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentService.java @@ -0,0 +1,7 @@ +package org.baeldung.web.service; + +import org.baeldung.web.vo.Student; + +public interface StudentService extends IOperations{ + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentServiceImpl.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentServiceImpl.java new file mode 100644 index 0000000000..3b6dda6fb1 --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/service/StudentServiceImpl.java @@ -0,0 +1,36 @@ +package org.baeldung.web.service; + +import java.util.List; + +import org.baeldung.mock.MockStudentData; +import org.baeldung.web.exception.MyResourceNotFoundException; +import org.baeldung.web.vo.Student; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +@Service +public class StudentServiceImpl implements StudentService { + + private List mockDataStudent = MockStudentData.getMockDataStudents(); + + @Override + public Page findPaginated(int page, int size){ + Page studentPage = getPage(page, size); + return studentPage; + } + + private Page getPage(int page, int size) { + page = page != 0?page - 1:page; + int from = Math.max(0, page * size); + int to = Math.min(mockDataStudent.size(), (page + 1) * size); + if(from > to){ + throw new MyResourceNotFoundException("page number is higher than total pages."); + } + return new PageImpl(mockDataStudent.subList(from, to), + new PageRequest(page,size), + mockDataStudent.size()); + } + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/vo/Student.java b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/vo/Student.java new file mode 100644 index 0000000000..11c503815d --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/java/org/baeldung/web/vo/Student.java @@ -0,0 +1,60 @@ +package org.baeldung.web.vo; + +import java.io.Serializable; + +public class Student implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public Student() { + } + + public Student(String studentId, String name, String gender, Integer age) { + super(); + this.studentId = studentId; + this.name = name; + this.gender = gender; + this.age = age; + } + + private String studentId; + private String name; + private String gender; + private Integer age; + + public String getStudentId() { + return studentId; + } + + public void setStudentId(String studentId) { + this.studentId = studentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + +} diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/resources/application.properties b/spring-rest-angular-pagination/StudentDirectory/src/main/resources/application.properties new file mode 100644 index 0000000000..a9bf6ca218 --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/resources/application.properties @@ -0,0 +1 @@ +server.contextPath=/StudentDirectory \ No newline at end of file diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/WEB-INF/web.xml b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..ff65bd6b96 --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,11 @@ + + + + + index.html + + + \ No newline at end of file diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/index.html b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/index.html new file mode 100644 index 0000000000..56a1273588 --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/index.html @@ -0,0 +1,14 @@ + + + + + + + + + +
+
+
+ + \ No newline at end of file diff --git a/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/view/app.js b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/view/app.js new file mode 100644 index 0000000000..522c49c8cb --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/main/webapp/view/app.js @@ -0,0 +1,54 @@ +var app = angular.module('app', ['ui.grid','ui.grid.pagination']); + +app.controller('StudentCtrl', ['$scope','StudentService', function ($scope,StudentService) { + var paginationOptions = { + pageNumber: 1, + pageSize: 5, + sort: null + }; + + StudentService.getStudents(paginationOptions.pageNumber, + paginationOptions.pageSize).success(function(data){ + $scope.gridOptions.data = data.content; + $scope.gridOptions.totalItems = data.totalElements; + }); + + $scope.gridOptions = { + paginationPageSizes: [5, 10, 20], + paginationPageSize: paginationOptions.pageSize, + enableColumnMenus:false, + columnDefs: [ + { name: 'studentId' }, + { name: 'name' }, + { name: 'gender' }, + { name: 'age' } + ], + onRegisterApi: function(gridApi) { + $scope.gridApi = gridApi; + gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) { + paginationOptions.pageNumber = newPage; + paginationOptions.pageSize = pageSize; + StudentService.getStudents(newPage,pageSize).success(function(data){ + $scope.gridOptions.data = data.content; + $scope.gridOptions.totalItems = data.totalElements; + }); + }); + } + }; + +}]); + +app.service('StudentService',['$http', function ($http) { + + function getStudents(pageNumber,size) { + return $http({ + method: 'GET', + url: 'student/get?page='+pageNumber+'&size='+size + }); + } + + return { + getStudents:getStudents + }; + +}]); \ No newline at end of file diff --git a/spring-rest-angular-pagination/StudentDirectory/src/test/java/org/baeldung/web/service/StudentServiceTest.java b/spring-rest-angular-pagination/StudentDirectory/src/test/java/org/baeldung/web/service/StudentServiceTest.java new file mode 100644 index 0000000000..3e476bf0d0 --- /dev/null +++ b/spring-rest-angular-pagination/StudentDirectory/src/test/java/org/baeldung/web/service/StudentServiceTest.java @@ -0,0 +1,49 @@ +package org.baeldung.web.service; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.lang3.RandomStringUtils; +import org.baeldung.web.main.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.IntegrationTest; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import io.restassured.RestAssured; +import io.restassured.response.Response; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = Application.class) +@WebAppConfiguration +@IntegrationTest("server.port:8080") +public class StudentServiceTest{ + + private String getURL() { + return "/StudentDirectory/student/get"; + } + + @Test + public void whenResourcesAreRetrievedPaged_then200IsReceived(){ + Response response = RestAssured.given().get(getURL()+ "?page=0&size=2").andReturn(); + + assertTrue(response.getStatusCode() == 200 ); + } + + @Test + public void whenPageOfResourcesAreRetrievedOutOfBounds_then404IsReceived(){ + String url = getURL()+ "?page=" + RandomStringUtils.randomNumeric(5) + "&size=2"; + Response response = RestAssured.given().get(url); + + assertTrue(response.getStatusCode() == 500 ); + } + + @Test + public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources(){ + Response response = RestAssured.given().get(getURL() + "?page=1&size=2" ); + assertFalse(response.getBody().jsonPath().getList("content").isEmpty() ); + } + +} diff --git a/spring-rest-docs/src/main/java/com/example/CRUDController.java b/spring-rest-docs/src/main/java/com/example/CRUDController.java index 818b29d3a6..ff8c91d6cd 100644 --- a/spring-rest-docs/src/main/java/com/example/CRUDController.java +++ b/spring-rest-docs/src/main/java/com/example/CRUDController.java @@ -17,39 +17,39 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/crud") public class CRUDController { - - @RequestMapping(method=RequestMethod.GET) - @ResponseStatus(HttpStatus.OK) - public List read(@RequestBody CrudInput crudInput) { - List returnList=new ArrayList(); - returnList.add(crudInput); - return returnList; - } - - @ResponseStatus(HttpStatus.CREATED) - @RequestMapping(method=RequestMethod.POST) - public HttpHeaders save(@RequestBody CrudInput crudInput) { - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getTitle()).toUri()); - return httpHeaders; - } - - @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) - @ResponseStatus(HttpStatus.OK) - HttpHeaders delete(@RequestBody CrudInput crudInput) { - HttpHeaders httpHeaders = new HttpHeaders(); - return httpHeaders; - } - - @RequestMapping(value = "/{id}", method = RequestMethod.PUT) - @ResponseStatus(HttpStatus.ACCEPTED) - void put(@PathVariable("id") long id, @RequestBody CrudInput crudInput) { - - } - - @RequestMapping(value = "/{id}", method = RequestMethod.PATCH) - @ResponseStatus(HttpStatus.NO_CONTENT) - void patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) { - - } + + @RequestMapping(method = RequestMethod.GET) + @ResponseStatus(HttpStatus.OK) + public List read(@RequestBody CrudInput crudInput) { + List returnList = new ArrayList(); + returnList.add(crudInput); + return returnList; + } + + @ResponseStatus(HttpStatus.CREATED) + @RequestMapping(method = RequestMethod.POST) + public HttpHeaders save(@RequestBody CrudInput crudInput) { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getTitle()).toUri()); + return httpHeaders; + } + + @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) + @ResponseStatus(HttpStatus.OK) + HttpHeaders delete(@RequestBody CrudInput crudInput) { + HttpHeaders httpHeaders = new HttpHeaders(); + return httpHeaders; + } + + @RequestMapping(value = "/{id}", method = RequestMethod.PUT) + @ResponseStatus(HttpStatus.ACCEPTED) + void put(@PathVariable("id") long id, @RequestBody CrudInput crudInput) { + + } + + @RequestMapping(value = "/{id}", method = RequestMethod.PATCH) + @ResponseStatus(HttpStatus.NO_CONTENT) + void patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) { + + } } diff --git a/spring-rest-docs/src/main/java/com/example/CrudInput.java b/spring-rest-docs/src/main/java/com/example/CrudInput.java index 3d91b7d45a..36ad67eb21 100644 --- a/spring-rest-docs/src/main/java/com/example/CrudInput.java +++ b/spring-rest-docs/src/main/java/com/example/CrudInput.java @@ -10,33 +10,32 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class CrudInput { - - //@NotBlank - private final String title; - private final String body; + // @NotBlank + private final String title; - private final List tagUris; + private final String body; - @JsonCreator - public CrudInput(@JsonProperty("title") String title, - @JsonProperty("body") String body, @JsonProperty("tags") List tagUris) { - this.title = title; - this.body = body; - this.tagUris = tagUris == null ? Collections.emptyList() : tagUris; - } + private final List tagUris; - public String getTitle() { - return title; - } + @JsonCreator + public CrudInput(@JsonProperty("title") String title, @JsonProperty("body") String body, @JsonProperty("tags") List tagUris) { + this.title = title; + this.body = body; + this.tagUris = tagUris == null ? Collections. emptyList() : tagUris; + } - public String getBody() { - return body; - } + public String getTitle() { + return title; + } - @JsonProperty("tags") - public List getTagUris() { - return this.tagUris; - } + public String getBody() { + return body; + } + + @JsonProperty("tags") + public List getTagUris() { + return this.tagUris; + } } \ No newline at end of file diff --git a/spring-rest-docs/src/main/java/com/example/IndexController.java b/spring-rest-docs/src/main/java/com/example/IndexController.java index a6b4537c43..6b896da416 100644 --- a/spring-rest-docs/src/main/java/com/example/IndexController.java +++ b/spring-rest-docs/src/main/java/com/example/IndexController.java @@ -1,6 +1,5 @@ package com.example; - import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import org.springframework.hateoas.ResourceSupport; @@ -12,11 +11,11 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/") public class IndexController { - @RequestMapping(method=RequestMethod.GET) - public ResourceSupport index() { - ResourceSupport index = new ResourceSupport(); - index.add(linkTo(CRUDController.class).withRel("crud")); - return index; - } + @RequestMapping(method = RequestMethod.GET) + public ResourceSupport index() { + ResourceSupport index = new ResourceSupport(); + index.add(linkTo(CRUDController.class).withRel("crud")); + return index; + } } \ No newline at end of file diff --git a/spring-rest-docs/src/main/java/com/example/SpringRestDocsApplication.java b/spring-rest-docs/src/main/java/com/example/SpringRestDocsApplication.java index dd20ef324e..da09f9accc 100644 --- a/spring-rest-docs/src/main/java/com/example/SpringRestDocsApplication.java +++ b/spring-rest-docs/src/main/java/com/example/SpringRestDocsApplication.java @@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringRestDocsApplication { - public static void main(String[] args) { - SpringApplication.run(SpringRestDocsApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(SpringRestDocsApplication.class, args); + } } diff --git a/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java b/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java index 195b9dc514..5b753aff0c 100644 --- a/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java +++ b/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java @@ -56,55 +56,35 @@ public class ApiDocumentation { @Before public void setUp() { this.document = document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())); - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)) - .alwaysDo(this.document) - .build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(documentationConfiguration(this.restDocumentation)).alwaysDo(this.document).build(); } - @Test public void headersExample() throws Exception { - this.document.snippets(responseHeaders(headerWithName("Content-Type") - .description("The Content-Type of the payload, e.g. `application/hal+json`"))); - this.mockMvc.perform(get("/")) - .andExpect(status().isOk()); + this.document.snippets(responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`"))); + this.mockMvc.perform(get("/")).andExpect(status().isOk()); } @Test public void indexExample() throws Exception { - this.document.snippets( - links(linkWithRel("crud").description("The <>")), - responseFields(fieldWithPath("_links").description("<> to other resources")) - ); - this.mockMvc.perform(get("/")) - .andExpect(status().isOk()); + this.document.snippets(links(linkWithRel("crud").description("The <>")), responseFields(fieldWithPath("_links").description("<> to other resources"))); + this.mockMvc.perform(get("/")).andExpect(status().isOk()); } - @Test public void crudGetExample() throws Exception { Map tag = new HashMap<>(); tag.put("name", "GET"); - String tagLocation = this.mockMvc.perform(get("/crud") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isOk()) - .andReturn() - .getResponse() - .getHeader("Location"); + String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isOk()).andReturn().getResponse().getHeader("Location"); Map crud = new HashMap<>(); crud.put("title", "Sample Model"); crud.put("body", "http://www.baeldung.com/"); crud.put("tags", singletonList(tagLocation)); - this.mockMvc.perform(get("/crud") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(crud))) - .andExpect(status().isOk()); + this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isOk()); } @Test @@ -112,13 +92,7 @@ public class ApiDocumentation { Map tag = new HashMap<>(); tag.put("name", "CREATE"); - String tagLocation = this.mockMvc.perform(post("/crud") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()) - .andReturn() - .getResponse() - .getHeader("Location"); + String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isCreated()).andReturn().getResponse().getHeader("Location"); Map crud = new HashMap<>(); crud.put("title", "Sample Model"); @@ -126,13 +100,9 @@ public class ApiDocumentation { crud.put("tags", singletonList(tagLocation)); ConstrainedFields fields = new ConstrainedFields(CrudInput.class); - this.document.snippets(requestFields( - fields.withPath("title").description("The title of the note"), - fields.withPath("body").description("The body of the note"), - fields.withPath("tags").description("An array of tag resource URIs"))); + this.document.snippets(requestFields(fields.withPath("title").description("The title of the note"), fields.withPath("body").description("The body of the note"), fields.withPath("tags").description("An array of tag resource URIs"))); this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isCreated()); - } @Test @@ -141,23 +111,14 @@ public class ApiDocumentation { Map tag = new HashMap<>(); tag.put("name", "DELETE"); - String tagLocation = this.mockMvc.perform(delete("/crud/10") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isOk()) - .andReturn() - .getResponse() - .getHeader("Location"); + String tagLocation = this.mockMvc.perform(delete("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isOk()).andReturn().getResponse().getHeader("Location"); Map crud = new HashMap<>(); crud.put("title", "Sample Model"); crud.put("body", "http://www.baeldung.com/"); crud.put("tags", singletonList(tagLocation)); - this.mockMvc.perform(delete("/crud/10") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(crud))) - .andExpect(status().isOk()); + this.mockMvc.perform(delete("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isOk()); } @Test @@ -166,51 +127,31 @@ public class ApiDocumentation { Map tag = new HashMap<>(); tag.put("name", "PATCH"); - String tagLocation = this.mockMvc.perform(patch("/crud/10") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isNoContent()) - .andReturn() - .getResponse() - .getHeader("Location"); + String tagLocation = this.mockMvc.perform(patch("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isNoContent()).andReturn().getResponse().getHeader("Location"); Map crud = new HashMap<>(); crud.put("title", "Sample Model"); crud.put("body", "http://www.baeldung.com/"); crud.put("tags", singletonList(tagLocation)); - this.mockMvc.perform(patch("/crud/10") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(crud))) - .andExpect(status().isNoContent()); + this.mockMvc.perform(patch("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isNoContent()); } - @Test public void crudPutExample() throws Exception { Map tag = new HashMap<>(); tag.put("name", "PUT"); - String tagLocation = this.mockMvc.perform(put("/crud/10") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isAccepted()) - .andReturn() - .getResponse() - .getHeader("Location"); + String tagLocation = this.mockMvc.perform(put("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isAccepted()).andReturn().getResponse().getHeader("Location"); Map crud = new HashMap<>(); crud.put("title", "Sample Model"); crud.put("body", "http://www.baeldung.com/"); crud.put("tags", singletonList(tagLocation)); - this.mockMvc.perform(put("/crud/10") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(crud))) - .andExpect(status().isAccepted()); + this.mockMvc.perform(put("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isAccepted()); } - @Test public void contextLoads() { } @@ -224,11 +165,8 @@ public class ApiDocumentation { } private FieldDescriptor withPath(String path) { - return fieldWithPath(path) - .attributes(key("constraints") - .value(collectionToDelimitedString(this.constraintDescriptions.descriptionsForProperty(path), ". "))); + return fieldWithPath(path).attributes(key("constraints").value(collectionToDelimitedString(this.constraintDescriptions.descriptionsForProperty(path), ". "))); } } - } diff --git a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java index 7f3c4db1f9..7aea9d303c 100644 --- a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java +++ b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java @@ -46,113 +46,105 @@ public class GettingStartedDocumentation { private MockMvc mockMvc; - @Before public void setUp() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)) - .alwaysDo(document("{method-name}/{step}/", - preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()))) - .build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(documentationConfiguration(this.restDocumentation)).alwaysDo(document("{method-name}/{step}/", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()))).build(); } @Test public void index() throws Exception { - this.mockMvc.perform(get("/").accept(MediaTypes.HAL_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("_links.crud", is(notNullValue()))) - .andExpect(jsonPath("_links.crud", is(notNullValue()))); + this.mockMvc.perform(get("/").accept(MediaTypes.HAL_JSON)).andExpect(status().isOk()).andExpect(jsonPath("_links.crud", is(notNullValue()))).andExpect(jsonPath("_links.crud", is(notNullValue()))); } -// String createNote() throws Exception { -// Map note = new HashMap(); -// note.put("title", "Note creation with cURL"); -// note.put("body", "An example of how to create a note using curl"); -// String noteLocation = this.mockMvc.perform(post("/crud") -// .contentType(MediaTypes.HAL_JSON) -// .content(objectMapper.writeValueAsString(note))) -// .andExpect(status().isCreated()) -// .andExpect(header().string("Location", notNullValue())) -// .andReturn() -// .getResponse() -// .getHeader("Location"); -// return noteLocation; -// } -// -// MvcResult getNote(String noteLocation) throws Exception { -// return this.mockMvc.perform(get(noteLocation)) -// .andExpect(status().isOk()) -// .andExpect(jsonPath("title", is(notNullValue()))) -// .andExpect(jsonPath("body", is(notNullValue()))) -// .andExpect(jsonPath("_links.crud", is(notNullValue()))) -// .andReturn(); -// } -// -// -// String createTag() throws Exception, JsonProcessingException { -// Map tag = new HashMap(); -// tag.put("name", "getting-started"); -// String tagLocation = this.mockMvc.perform(post("/crud") -// .contentType(MediaTypes.HAL_JSON) -// .content(objectMapper.writeValueAsString(tag))) -// .andExpect(status().isCreated()) -// .andExpect(header().string("Location", notNullValue())) -// .andReturn() -// .getResponse() -// .getHeader("Location"); -// return tagLocation; -// } -// -// void getTag(String tagLocation) throws Exception { -// this.mockMvc.perform(get(tagLocation)).andExpect(status().isOk()) -// .andExpect(jsonPath("name", is(notNullValue()))) -// .andExpect(jsonPath("_links.tagged-notes", is(notNullValue()))); -// } -// -// String createTaggedNote(String tag) throws Exception { -// Map note = new HashMap(); -// note.put("title", "Tagged note creation with cURL"); -// note.put("body", "An example of how to create a tagged note using cURL"); -// note.put("tags", Arrays.asList(tag)); -// -// String noteLocation = this.mockMvc.perform(post("/notes") -// .contentType(MediaTypes.HAL_JSON) -// .content(objectMapper.writeValueAsString(note))) -// .andExpect(status().isCreated()) -// .andExpect(header().string("Location", notNullValue())) -// .andReturn() -// .getResponse() -// .getHeader("Location"); -// return noteLocation; -// } -// -// void getTags(String noteTagsLocation) throws Exception { -// this.mockMvc.perform(get(noteTagsLocation)) -// .andExpect(status().isOk()) -// .andExpect(jsonPath("_embedded.tags", hasSize(1))); -// } -// -// void tagExistingNote(String noteLocation, String tagLocation) throws Exception { -// Map update = new HashMap(); -// update.put("tags", Arrays.asList(tagLocation)); -// this.mockMvc.perform(patch(noteLocation) -// .contentType(MediaTypes.HAL_JSON) -// .content(objectMapper.writeValueAsString(update))) -// .andExpect(status().isNoContent()); -// } -// -// MvcResult getTaggedExistingNote(String noteLocation) throws Exception { -// return this.mockMvc.perform(get(noteLocation)).andExpect(status().isOk()).andReturn(); -// } -// -// void getTagsForExistingNote(String noteTagsLocation) throws Exception { -// this.mockMvc.perform(get(noteTagsLocation)) -// .andExpect(status().isOk()).andExpect(jsonPath("_embedded.tags", hasSize(1))); -// } -// -// private String getLink(MvcResult result, String rel) -// throws UnsupportedEncodingException { -// return JsonPath.parse(result.getResponse().getContentAsString()).read("_links." + rel + ".href"); -// } + // String createNote() throws Exception { + // Map note = new HashMap(); + // note.put("title", "Note creation with cURL"); + // note.put("body", "An example of how to create a note using curl"); + // String noteLocation = this.mockMvc.perform(post("/crud") + // .contentType(MediaTypes.HAL_JSON) + // .content(objectMapper.writeValueAsString(note))) + // .andExpect(status().isCreated()) + // .andExpect(header().string("Location", notNullValue())) + // .andReturn() + // .getResponse() + // .getHeader("Location"); + // return noteLocation; + // } + // + // MvcResult getNote(String noteLocation) throws Exception { + // return this.mockMvc.perform(get(noteLocation)) + // .andExpect(status().isOk()) + // .andExpect(jsonPath("title", is(notNullValue()))) + // .andExpect(jsonPath("body", is(notNullValue()))) + // .andExpect(jsonPath("_links.crud", is(notNullValue()))) + // .andReturn(); + // } + // + // + // String createTag() throws Exception, JsonProcessingException { + // Map tag = new HashMap(); + // tag.put("name", "getting-started"); + // String tagLocation = this.mockMvc.perform(post("/crud") + // .contentType(MediaTypes.HAL_JSON) + // .content(objectMapper.writeValueAsString(tag))) + // .andExpect(status().isCreated()) + // .andExpect(header().string("Location", notNullValue())) + // .andReturn() + // .getResponse() + // .getHeader("Location"); + // return tagLocation; + // } + // + // void getTag(String tagLocation) throws Exception { + // this.mockMvc.perform(get(tagLocation)).andExpect(status().isOk()) + // .andExpect(jsonPath("name", is(notNullValue()))) + // .andExpect(jsonPath("_links.tagged-notes", is(notNullValue()))); + // } + // + // String createTaggedNote(String tag) throws Exception { + // Map note = new HashMap(); + // note.put("title", "Tagged note creation with cURL"); + // note.put("body", "An example of how to create a tagged note using cURL"); + // note.put("tags", Arrays.asList(tag)); + // + // String noteLocation = this.mockMvc.perform(post("/notes") + // .contentType(MediaTypes.HAL_JSON) + // .content(objectMapper.writeValueAsString(note))) + // .andExpect(status().isCreated()) + // .andExpect(header().string("Location", notNullValue())) + // .andReturn() + // .getResponse() + // .getHeader("Location"); + // return noteLocation; + // } + // + // void getTags(String noteTagsLocation) throws Exception { + // this.mockMvc.perform(get(noteTagsLocation)) + // .andExpect(status().isOk()) + // .andExpect(jsonPath("_embedded.tags", hasSize(1))); + // } + // + // void tagExistingNote(String noteLocation, String tagLocation) throws Exception { + // Map update = new HashMap(); + // update.put("tags", Arrays.asList(tagLocation)); + // this.mockMvc.perform(patch(noteLocation) + // .contentType(MediaTypes.HAL_JSON) + // .content(objectMapper.writeValueAsString(update))) + // .andExpect(status().isNoContent()); + // } + // + // MvcResult getTaggedExistingNote(String noteLocation) throws Exception { + // return this.mockMvc.perform(get(noteLocation)).andExpect(status().isOk()).andReturn(); + // } + // + // void getTagsForExistingNote(String noteTagsLocation) throws Exception { + // this.mockMvc.perform(get(noteTagsLocation)) + // .andExpect(status().isOk()).andExpect(jsonPath("_embedded.tags", hasSize(1))); + // } + // + // private String getLink(MvcResult result, String rel) + // throws UnsupportedEncodingException { + // return JsonPath.parse(result.getResponse().getContentAsString()).read("_links." + rel + ".href"); + // } } 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-custom-permission/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java index 86b81cdcee..112d502105 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java @@ -1,8 +1,5 @@ package org.baeldung.persistence.model; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; import java.util.Set; import javax.persistence.Column; @@ -16,14 +13,8 @@ import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - @Entity -public class User implements UserDetails { - - private static final long serialVersionUID = 1L; +public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @@ -57,7 +48,6 @@ public class User implements UserDetails { this.id = id; } - @Override public String getUsername() { return username; } @@ -66,7 +56,6 @@ public class User implements UserDetails { this.username = username; } - @Override public String getPassword() { return password; } @@ -93,37 +82,6 @@ public class User implements UserDetails { // - @Override - public Collection getAuthorities() { - final List authorities = new ArrayList(); - for (final Privilege privilege : this.getPrivileges()) { - authorities.add(new SimpleGrantedAuthority(privilege.getName())); - } - return authorities; - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isEnabled() { - return true; - } - - // - @Override public String toString() { final StringBuilder builder = new StringBuilder(); diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java index a3f4644592..2d84536a14 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java @@ -16,7 +16,7 @@ public class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot i // public boolean isMember(Long OrganizationId) { - final User user = (User) this.getPrincipal(); + final User user = ((MyUserPrincipal) this.getPrincipal()).getUser(); return user.getOrganization().getId().longValue() == OrganizationId.longValue(); } diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java index e81f9f8939..5d96673a8f 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java @@ -10,17 +10,10 @@ public class CustomPermissionEvaluator implements PermissionEvaluator { @Override public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) { - System.out.println(auth); if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)) { return false; } - String targetType = ""; - if (targetDomainObject instanceof String) { - targetType = targetDomainObject.toString().toUpperCase(); - } else { - targetType = targetDomainObject.getClass().getSimpleName().toUpperCase(); - System.out.println(targetType); - } + final String targetType = targetDomainObject.getClass().getSimpleName().toUpperCase(); return hasPrivilege(auth, targetType, permission.toString().toUpperCase()); } diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java index a09d166798..4d3561b325 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java @@ -47,6 +47,14 @@ public class MySecurityExpressionRoot implements MethodSecurityExpressionOperati throw new RuntimeException("method hasAuthority() not allowed"); } + // + public boolean isMember(Long OrganizationId) { + final User user = ((MyUserPrincipal) this.getPrincipal()).getUser(); + return user.getOrganization().getId().longValue() == OrganizationId.longValue(); + } + + // + @Override public final boolean hasAnyAuthority(String... authorities) { return hasAnyAuthorityName(null, authorities); @@ -168,14 +176,6 @@ public class MySecurityExpressionRoot implements MethodSecurityExpressionOperati return defaultRolePrefix + role; } - // - public boolean isMember(Long OrganizationId) { - final User user = (User) this.getPrincipal(); - return user.getOrganization().getId().longValue() == OrganizationId.longValue(); - } - - // - @Override public Object getFilterObject() { return this.filterObject; diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java index 19276a906e..685219728f 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -26,6 +26,6 @@ public class MyUserDetailsService implements UserDetailsService { if (user == null) { throw new UsernameNotFoundException(username); } - return user; + return new MyUserPrincipal(user); } } diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserPrincipal.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserPrincipal.java new file mode 100644 index 0000000000..437bb02cdb --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserPrincipal.java @@ -0,0 +1,72 @@ +package org.baeldung.security; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.baeldung.persistence.model.Privilege; +import org.baeldung.persistence.model.User; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +public class MyUserPrincipal implements UserDetails { + + private static final long serialVersionUID = 1L; + + private final User user; + + // + + public MyUserPrincipal(User user) { + this.user = user; + } + + // + + @Override + public String getUsername() { + return user.getUsername(); + } + + @Override + public String getPassword() { + return user.getPassword(); + } + + @Override + public Collection getAuthorities() { + final List authorities = new ArrayList(); + for (final Privilege privilege : user.getPrivileges()) { + authorities.add(new SimpleGrantedAuthority(privilege.getName())); + } + return authorities; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + // + + public User getUser() { + return user; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java b/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java index 7e279907c6..4752f7bdd9 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java @@ -21,7 +21,8 @@ public class MainController { @Autowired private OrganizationRepository organizationRepository; - @PreAuthorize("hasPermission('Foo', 'read')") + // @PostAuthorize("hasPermission(returnObject, 'read')") + @PreAuthorize("hasPermission(#id, 'Foo', 'read')") @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { 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/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java index d0e099e591..175250f47b 100644 --- a/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java +++ b/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java @@ -15,6 +15,7 @@ import static org.xmlunit.matchers.HasXPathMatcher.hasXPath; import java.io.File; import java.util.Iterator; +import org.junit.Ignore; import org.junit.Test; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; @@ -36,10 +37,10 @@ public class XMLUnitTest { public void givenWrongXml_whenValidateFailsAgainstXsd_thenCorrect() { Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI); v.setSchemaSource(Input.fromStream( - new XMLUnitTest().getClass().getResourceAsStream( + XMLUnitTest.class.getResourceAsStream( "/students.xsd")).build()); ValidationResult r = v.validateInstance(Input.fromStream( - new XMLUnitTest().getClass().getResourceAsStream( + XMLUnitTest.class.getResourceAsStream( "/students_with_error.xml")).build()); assertFalse(r.isValid()); } @@ -48,10 +49,10 @@ public class XMLUnitTest { public void givenXmlWithErrors_whenReturnsValidationProblems_thenCorrect() { Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI); v.setSchemaSource(Input.fromStream( - new XMLUnitTest().getClass().getResourceAsStream( + XMLUnitTest.class.getResourceAsStream( "/students.xsd")).build()); ValidationResult r = v.validateInstance(Input.fromStream( - new XMLUnitTest().getClass().getResourceAsStream( + XMLUnitTest.class.getResourceAsStream( "/students_with_error.xml")).build()); Iterator probs = r.getProblems().iterator(); int count = 0; @@ -66,10 +67,10 @@ public class XMLUnitTest { public void givenXml_whenValidatesAgainstXsd_thenCorrect() { Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI); v.setSchemaSource(Input.fromStream( - new XMLUnitTest().getClass().getResourceAsStream( + XMLUnitTest.class.getResourceAsStream( "/students.xsd")).build()); ValidationResult r = v.validateInstance(Input.fromStream( - new XMLUnitTest().getClass().getResourceAsStream( + XMLUnitTest.class.getResourceAsStream( "/students.xml")).build()); Iterator probs = r.getProblems().iterator(); while (probs.hasNext()) { @@ -117,11 +118,27 @@ public class XMLUnitTest { @Test public void givenXmlSource_whenFailsToValidateInExistentXPath_thenCorrect() { ClassLoader classLoader = getClass().getClassLoader(); - assertThat(Input.fromFile(new File(classLoader.getResource( "teachers.xml").getFile())), not(hasXPath("//sujet"))); } + // NOTE: ignore as this test demonstrates that two XMLs that contain the same data + // will fail the isSimilarTo test. + @Test @Ignore + public void given2XMLS_whenSimilar_thenCorrect_fails() { + String controlXml = "3false"; + String testXml = "false3"; + assertThat(testXml, isSimilarTo(controlXml)); + } + + @Test + public void given2XMLS_whenSimilar_thenCorrect() { + String controlXml = "3false"; + String testXml = "false3"; + assertThat(testXml,isSimilarTo(controlXml).withNodeMatcher( + new DefaultNodeMatcher(ElementSelectors.byName))); + } + @Test public void given2XMLs_whenSimilarWithDiff_thenCorrect() throws Exception { String myControlXML = "3false"; @@ -160,6 +177,7 @@ public class XMLUnitTest { Diff myDiff = DiffBuilder.compare(control).withTest(test) .checkForSimilar().build(); + // assertFalse(myDiff.toString(), myDiff.hasDifferences()); assertTrue(myDiff.toString(), myDiff.hasDifferences()); } @@ -177,27 +195,23 @@ public class XMLUnitTest { @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())))); - + 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() + assertThat(Input.fromStream(XMLUnitTest.class .getResourceAsStream("/test.xml")), - isSimilarTo(Input.fromStream(new XMLUnitTest().getClass() + isSimilarTo(Input.fromStream(XMLUnitTest.class .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")))); - + assertThat(Input.from(XMLUnitTest.class.getResourceAsStream("/test.xml")), + isSimilarTo(Input.from(XMLUnitTest.class.getResourceAsStream("/control.xml")))); } @Test @@ -206,7 +220,6 @@ public class XMLUnitTest { Input.from("3false"), isSimilarTo(Input .from("3false"))); - } @Test @@ -216,7 +229,6 @@ public class XMLUnitTest { String controlPath = classLoader.getResource("control.xml").getPath(); assertThat(Input.fromFile(testPath), isSimilarTo(Input.fromFile(controlPath))); - } @Test