From 33c3faf140b5b236a13cd4e42a4bd22ce83208ab Mon Sep 17 00:00:00 2001 From: Alex V Date: Thu, 3 Dec 2015 01:45:51 +0200 Subject: [PATCH 001/309] Fixed code for Setting Up Swagger 2 with a Spring REST API article --- spring-security-rest/pom.xml | 17 ++++++ .../org/baeldung/spring/SwaggerConfig.java | 53 +++++++++++++++++++ .../java/org/baeldung/spring/WebConfig.java | 10 ++++ 3 files changed, 80 insertions(+) create mode 100644 spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 2f9855d05c..4fd64b5289 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -167,6 +167,19 @@ test + + + io.springfox + springfox-swagger2 + 2.2.2 + + + + io.springfox + springfox-swagger-ui + 2.2.2 + + @@ -260,6 +273,10 @@ 4.11 1.10.19 + + 2.2.2 + 2.2.2 + 4.4.1 4.5 diff --git a/spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java b/spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java new file mode 100644 index 0000000000..64f61055f2 --- /dev/null +++ b/spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java @@ -0,0 +1,53 @@ +package org.baeldung.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.RequestMethod; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.builders.ResponseMessageBuilder; +import springfox.documentation.schema.ModelRef; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import static com.google.common.collect.Lists.newArrayList; + +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + + @Bean + public Docket api(){ + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("org.baeldung.web.controller")) + .paths(PathSelectors.ant("/foos/*")) + .build() + .apiInfo(apiInfo()) + .useDefaultResponseMessages(false) + .globalResponseMessage(RequestMethod.GET, + newArrayList(new ResponseMessageBuilder() + .code(500) + .message("500 message") + .responseModel(new ModelRef("Error")) + .build(), + new ResponseMessageBuilder() + .code(403) + .message("Forbidden!!!!!") + .build())); + } + + private ApiInfo apiInfo() { + ApiInfo apiInfo = new ApiInfo( + "My REST API", + "Some custom description of API.", + "API TOS", + "Terms of service", + "myeaddress@company.com", + "License of API", + "API license URL"); + return apiInfo; + } +} diff --git a/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java index 4d1d6e6403..7e1e9cfcc3 100644 --- a/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java @@ -3,6 +3,7 @@ package org.baeldung.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @@ -14,4 +15,13 @@ public class WebConfig extends WebMvcConfigurerAdapter { super(); } + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("swagger-ui.html") + .addResourceLocations("classpath:/META-INF/resources/"); + + registry.addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); + } + } From 175f1195738a8a747085507c8f3d98bb53763c80 Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Thu, 3 Dec 2015 13:46:25 +0300 Subject: [PATCH 002/309] Create AOP examples - Use different types of advice - Use various types of pointcut expressions --- .../java/org/baeldung/aop/LoggingAspect.java | 34 ++++++++++ .../org/baeldung/aop/PerformanceAspect.java | 2 +- .../org/baeldung/aop/PublishingAspect.java | 36 ++++++++++ .../main/java/org/baeldung/dao/FooDao.java | 6 ++ .../org/baeldung/events/FooCreationEvent.java | 10 +++ .../events/FooCreationEventListener.java | 17 +++++ .../src/main/java/org/baeldung/model/Foo.java | 19 ++++++ .../main/resources/org/baeldung/aop/beans.xml | 19 ++++++ .../java/org/baeldung/aop/AopLoggingTest.java | 67 +++++++++++++++++++ .../org/baeldung/aop/AopPublishingTest.java | 67 +++++++++++++++++++ .../aop/AopXmlConfigPerformanceTest.java | 67 +++++++++++++++++++ .../java/org/baeldung/config/TestConfig.java | 2 +- 12 files changed, 344 insertions(+), 2 deletions(-) create mode 100644 spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java create mode 100644 spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java create mode 100644 spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java create mode 100644 spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java create mode 100644 spring-mvc-java/src/main/java/org/baeldung/model/Foo.java create mode 100644 spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml create mode 100644 spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java create mode 100644 spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java create mode 100644 spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java b/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java new file mode 100644 index 0000000000..9317677fe2 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java @@ -0,0 +1,34 @@ +package org.baeldung.aop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.logging.Logger; + +@Component +@Aspect +public class LoggingAspect { + + private static Logger logger = Logger.getLogger(LoggingAspect.class.getName()); + + private ThreadLocal sdf = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat("[yyyy-mm-dd hh:mm:ss:SSS]"); + } + }; + + @Pointcut("@target(org.springframework.stereotype.Repository)") + public void repositoryMethods() {} + + @Before("repositoryMethods()") + public void logMethodCall(JoinPoint jp) throws Throwable { + String methodName = jp.getSignature().getName(); + logger.info(sdf.get().format(new Date()) + methodName); + } +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java b/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java index 12d6bc4e69..57f5bc5edd 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java @@ -16,7 +16,7 @@ public class PerformanceAspect { private static Logger logger = Logger.getLogger(PerformanceAspect.class.getName()); @Pointcut("within(@org.springframework.stereotype.Repository *)") - public void repositoryClassMethods() {}; + public void repositoryClassMethods() {} @Around("repositoryClassMethods()") public Object measureMethodExecutionTime(ProceedingJoinPoint pjp) throws Throwable { diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java b/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java new file mode 100644 index 0000000000..20a10f4f6a --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java @@ -0,0 +1,36 @@ +package org.baeldung.aop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.baeldung.events.FooCreationEvent; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Component; + +@Component +@Aspect +public class PublishingAspect { + + private ApplicationEventPublisher eventPublisher; + + @Autowired + public void setEventPublisher(ApplicationEventPublisher eventPublisher) { + this.eventPublisher = eventPublisher; + } + + @Pointcut("@target(org.springframework.stereotype.Repository)") + public void repositoryMethods() {} + + @Pointcut("execution(* *..create*(Long,..))") + public void firstLongParamMethods() {} + + @Pointcut("repositoryMethods() && firstLongParamMethods()") + public void entityCreationMethods() {} + + @AfterReturning(value = "entityCreationMethods()", returning = "entity") + public void logMethodCall(JoinPoint jp, Object entity) throws Throwable { + eventPublisher.publishEvent(new FooCreationEvent(entity)); + } +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java b/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java index fbd7f4c717..e0da61c547 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java +++ b/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java @@ -1,10 +1,16 @@ package org.baeldung.dao; +import org.baeldung.model.Foo; import org.springframework.stereotype.Repository; @Repository public class FooDao { + public String findById(Long id) { return "Bazz"; } + + public Foo create(Long id, String name) { + return new Foo(id, name); + } } diff --git a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java b/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java new file mode 100644 index 0000000000..af11f3a4be --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java @@ -0,0 +1,10 @@ +package org.baeldung.events; + +import org.springframework.context.ApplicationEvent; + +public class FooCreationEvent extends ApplicationEvent { + + public FooCreationEvent(Object source) { + super(source); + } +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java b/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java new file mode 100644 index 0000000000..35dcfd2bc3 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java @@ -0,0 +1,17 @@ +package org.baeldung.events; + +import org.springframework.context.ApplicationListener; +import org.springframework.stereotype.Component; + +import java.util.logging.Logger; + +@Component +public class FooCreationEventListener implements ApplicationListener { + + private static Logger logger = Logger.getLogger(FooCreationEventListener.class.getName()); + + @Override + public void onApplicationEvent(FooCreationEvent event) { + logger.info("Created foo instance: " + event.getSource().toString()); + } +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java b/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java new file mode 100644 index 0000000000..17510f4836 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java @@ -0,0 +1,19 @@ +package org.baeldung.model; + +public class Foo { + private Long id; + private String name; + + public Foo(Long id, String name) { + this.id = id; + this.name = name; + } + + @Override + public String toString() { + return "Foo{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } +} diff --git a/spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml b/spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml new file mode 100644 index 0000000000..17c63e39e4 --- /dev/null +++ b/spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java b/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java new file mode 100644 index 0000000000..7aff17c424 --- /dev/null +++ b/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java @@ -0,0 +1,67 @@ +package org.baeldung.aop; + +import org.baeldung.config.TestConfig; +import org.baeldung.dao.FooDao; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +public class AopLoggingTest { + + @Before + public void setUp() { + logEventHandler = new Handler() { + @Override + public void publish(LogRecord record) { + messages.add(record.getMessage()); + } + + @Override + public void flush() { + } + + @Override + public void close() throws SecurityException { + } + }; + + messages = new ArrayList<>(); + } + + @Autowired + private FooDao dao; + + private Handler logEventHandler; + + private List messages; + + @Test + public void givenLoggingAspect_whenCallDaoMethod_thenBeforeAdviceIsCalled() { + Logger logger = Logger.getLogger(LoggingAspect.class.getName()); + logger.addHandler(logEventHandler); + + dao.findById(1L); + assertThat(messages, hasSize(1)); + + String logMessage = messages.get(0); + Pattern pattern = Pattern.compile("^\\[\\d{4}\\-\\d{2}\\-\\d{2} \\d{2}:\\d{2}:\\d{2}:\\d{3}\\]findById$"); + assertTrue(pattern.matcher(logMessage).matches()); + } +} diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java b/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java new file mode 100644 index 0000000000..561eec06ec --- /dev/null +++ b/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java @@ -0,0 +1,67 @@ +package org.baeldung.aop; + +import org.baeldung.config.TestConfig; +import org.baeldung.dao.FooDao; +import org.baeldung.events.FooCreationEventListener; +import org.baeldung.model.Foo; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +public class AopPublishingTest { + + @Before + public void setUp() { + logEventHandler = new Handler() { + @Override + public void publish(LogRecord record) { + messages.add(record.getMessage()); + } + + @Override + public void flush() { + } + + @Override + public void close() throws SecurityException { + } + }; + + messages = new ArrayList<>(); + } + + @Autowired + private FooDao dao; + + private Handler logEventHandler; + + private List messages; + + @Test + public void givenPublishingAspect_whenCallCreate_thenCreationEventIsPublished() { + Logger logger = Logger.getLogger(FooCreationEventListener.class.getName()); + logger.addHandler(logEventHandler); + + dao.create(1L, "Bar"); + + String logMessage = messages.get(0); + Pattern pattern = Pattern.compile("Created foo instance: " + + Pattern.quote(new Foo(1L, "Bar").toString())); + assertTrue(pattern.matcher(logMessage).matches()); + } +} diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java b/spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java new file mode 100644 index 0000000000..7ef25d743c --- /dev/null +++ b/spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java @@ -0,0 +1,67 @@ +package org.baeldung.aop; + +import org.baeldung.dao.FooDao; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/org/baeldung/aop/beans.xml") +public class AopXmlConfigPerformanceTest { + + @Before + public void setUp() { + logEventHandler = new Handler() { + @Override + public void publish(LogRecord record) { + messages.add(record.getMessage()); + } + + @Override + public void flush() { + } + + @Override + public void close() throws SecurityException { + } + }; + + messages = new ArrayList<>(); + } + + @Autowired + private FooDao dao; + + private Handler logEventHandler; + + private List messages; + + @Test + public void givenPerformanceAspect_whenCallDaoMethod_thenPerformanceMeasurementAdviceIsCalled() { + Logger logger = Logger.getLogger(PerformanceAspect.class.getName()); + logger.addHandler(logEventHandler); + + final String entity = dao.findById(1L); + assertThat(entity, notNullValue()); + assertThat(messages, hasSize(1)); + + String logMessage = messages.get(0); + Pattern pattern = Pattern.compile("Execution of findById took \\d+ ms"); + assertTrue(pattern.matcher(logMessage).matches()); + } +} diff --git a/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java b/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java index 60786a108c..0d103f1029 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java +++ b/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java @@ -5,7 +5,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration -@ComponentScan(basePackages = {"org.baeldung.dao", "org.baeldung.aop"}) +@ComponentScan(basePackages = {"org.baeldung.dao", "org.baeldung.aop", "org.baeldung.events"}) @EnableAspectJAutoProxy public class TestConfig { } From de70a8595cbf891e5885be2220f5a3ecd5a623f8 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 3 Dec 2015 21:58:00 +0200 Subject: [PATCH 003/309] minor fix --- .../main/java/org/baeldung/config/ServerSecurityConfig.java | 2 +- .../src/main/java/org/baeldung/config/UiWebConfig.java | 3 ++- .../src/main/resources/templates/header.html | 2 +- .../src/main/java/org/baeldung/config/UiWebConfig.java | 1 + 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerSecurityConfig.java b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerSecurityConfig.java index 5a09bb7e03..3e1a8a8ccb 100644 --- a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerSecurityConfig.java +++ b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerSecurityConfig.java @@ -28,7 +28,7 @@ public class ServerSecurityConfig extends WebSecurityConfigurerAdapter { http.authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() - // .and().formLogin().permitAll() + .and().formLogin().permitAll() ; // @formatter:on } diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/java/org/baeldung/config/UiWebConfig.java b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/java/org/baeldung/config/UiWebConfig.java index 2ee0585615..71197ce5d2 100644 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/java/org/baeldung/config/UiWebConfig.java +++ b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/java/org/baeldung/config/UiWebConfig.java @@ -26,8 +26,9 @@ public class UiWebConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { super.addViewControllers(registry); - registry.addViewController("/index"); + registry.addViewController("/").setViewName("forward:/index"); registry.addViewController("/oauthTemp"); + registry.addViewController("/index"); } @Override diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html index f56ff0ce99..a62bce9747 100644 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html +++ b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html @@ -12,7 +12,7 @@ diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiWebConfig.java b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiWebConfig.java index 46e7f6db42..0732182354 100644 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiWebConfig.java +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiWebConfig.java @@ -26,6 +26,7 @@ public class UiWebConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); registry.addViewController("/index"); registry.addViewController("/login"); } From f54c2fcae445a7b9d7e57293811339b37b4941ef Mon Sep 17 00:00:00 2001 From: DOHA Date: Sun, 6 Dec 2015 13:01:52 +0200 Subject: [PATCH 004/309] caching java config --- ....eclipse.wst.common.project.facet.core.xml | 2 +- .../caching/config/CachingConfig.java | 29 +++++++++++++++++++ .../baeldung/caching/config/MyAppConfig.java | 10 ------- .../caching/example/CustomerDataService.java | 8 ++++- spring-all/src/main/resources/config.xml | 6 ++-- .../test/SpringCachingBehaviorTest.java | 14 +++++---- 6 files changed, 48 insertions(+), 21 deletions(-) create mode 100644 spring-all/src/main/java/org/baeldung/caching/config/CachingConfig.java delete mode 100644 spring-all/src/main/java/org/baeldung/caching/config/MyAppConfig.java 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 index 9ca0d1c1b7..991897a4ac 100644 --- a/spring-all/.settings/org.eclipse.wst.common.project.facet.core.xml +++ b/spring-all/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -1,6 +1,6 @@ - + diff --git a/spring-all/src/main/java/org/baeldung/caching/config/CachingConfig.java b/spring-all/src/main/java/org/baeldung/caching/config/CachingConfig.java new file mode 100644 index 0000000000..4153ec9636 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/caching/config/CachingConfig.java @@ -0,0 +1,29 @@ +package org.baeldung.caching.config; + +import java.util.Arrays; + +import org.baeldung.caching.example.CustomerDataService; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.concurrent.ConcurrentMapCache; +import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableCaching +public class CachingConfig { + + @Bean + public CustomerDataService customerDataService() { + return new CustomerDataService(); + } + + @Bean + public CacheManager cacheManager() { + final SimpleCacheManager cacheManager = new SimpleCacheManager(); + cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("directory"), new ConcurrentMapCache("addresses"))); + return cacheManager; + } + +} diff --git a/spring-all/src/main/java/org/baeldung/caching/config/MyAppConfig.java b/spring-all/src/main/java/org/baeldung/caching/config/MyAppConfig.java deleted file mode 100644 index 467e50c15e..0000000000 --- a/spring-all/src/main/java/org/baeldung/caching/config/MyAppConfig.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.caching.config; - -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableCaching -public class MyAppConfig { - // Your configuration code goes here. -} diff --git a/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java b/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java index 86026de93a..fe4de5d282 100644 --- a/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java +++ b/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java @@ -10,12 +10,18 @@ import org.springframework.cache.annotation.Caching; import org.springframework.stereotype.Component; @Component -@CacheConfig(cacheNames = { "addressDemo" }) +@CacheConfig(cacheNames = { "addresses" }) public class CustomerDataService { @Autowired CacheManager cacheManager; + // this method configuration is equivalent to xml configuration + @Cacheable(value = "addresses", key = "#customer.name") + public String getAddress(final Customer customer) { + return customer.getAddress(); + } + /** * The method returns the customer's address, only it doesn't find it the cache- addresses and directory. diff --git a/spring-all/src/main/resources/config.xml b/spring-all/src/main/resources/config.xml index 244e9027ec..23458539b0 100644 --- a/spring-all/src/main/resources/config.xml +++ b/spring-all/src/main/resources/config.xml @@ -10,8 +10,7 @@ - - + @@ -21,7 +20,6 @@ - @@ -34,7 +32,7 @@ - + diff --git a/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingBehaviorTest.java b/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingBehaviorTest.java index 0b3edaffb3..a4a3733dd8 100644 --- a/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingBehaviorTest.java +++ b/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingBehaviorTest.java @@ -1,11 +1,11 @@ package org.baeldung.caching.test; +import org.baeldung.caching.config.CachingConfig; import org.baeldung.caching.example.Customer; import org.baeldung.caching.example.CustomerDataService; import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Component; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; @Component public class SpringCachingBehaviorTest { @@ -13,12 +13,16 @@ public class SpringCachingBehaviorTest { @Test public void testCaching() { @SuppressWarnings("resource") - final ApplicationContext context = new ClassPathXmlApplicationContext("config.xml"); + final + // final ApplicationContext context = new ClassPathXmlApplicationContext("config.xml"); + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.register(CachingConfig.class); + context.refresh(); final CustomerDataService service = context.getBean(CustomerDataService.class); final Customer cust = new Customer("Tom", "67-2, Downing Street, NY"); - service.getAddress1(cust); - service.getAddress1(cust); + service.getAddress(cust); + service.getAddress(cust); // fail("Unable to instantiate the CustomerDataService"); } From b94d10d82a4e30010d0cd64633be5fe84de119db Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Sun, 6 Dec 2015 18:44:56 +0300 Subject: [PATCH 005/309] Add more pointcut expressions examples - Add examples for '@arg' and '@annotation' PCDs --- .../java/org/baeldung/aop/LoggingAspect.java | 19 ++++++++++++++- .../org/baeldung/aop/annotations/Entity.java | 11 +++++++++ .../baeldung/aop/annotations/Loggable.java | 11 +++++++++ .../main/java/org/baeldung/dao/FooDao.java | 6 +++++ .../src/main/java/org/baeldung/model/Foo.java | 3 +++ .../java/org/baeldung/aop/AopLoggingTest.java | 23 +++++++++++++++---- 6 files changed, 68 insertions(+), 5 deletions(-) create mode 100644 spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java create mode 100644 spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java b/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java index 9317677fe2..72ac610abd 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java @@ -26,9 +26,26 @@ public class LoggingAspect { @Pointcut("@target(org.springframework.stereotype.Repository)") public void repositoryMethods() {} + @Pointcut("@annotation(org.baeldung.aop.annotations.Loggable)") + public void loggableMethods() {} + + @Pointcut("@args(org.baeldung.aop.annotations.Entity)") + public void methodsAcceptingEntities() {} + @Before("repositoryMethods()") - public void logMethodCall(JoinPoint jp) throws Throwable { + public void logMethodCall(JoinPoint jp) { String methodName = jp.getSignature().getName(); logger.info(sdf.get().format(new Date()) + methodName); } + + @Before("loggableMethods()") + public void logMethod(JoinPoint jp) { + String methodName = jp.getSignature().getName(); + logger.info("Executing method: " + methodName); + } + + @Before("methodsAcceptingEntities()") + public void logMethodAcceptionEntityAnnotatedBean(JoinPoint jp) { + logger.info("Accepting beans with @Entity annotation: " + jp.getArgs()[0]); + } } diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java b/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java new file mode 100644 index 0000000000..f964c3979e --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java @@ -0,0 +1,11 @@ +package org.baeldung.aop.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface Entity { +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java b/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java new file mode 100644 index 0000000000..ef2863957f --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java @@ -0,0 +1,11 @@ +package org.baeldung.aop.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Loggable { +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java b/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java index e0da61c547..f204440b2d 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java +++ b/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java @@ -1,5 +1,6 @@ package org.baeldung.dao; +import org.baeldung.aop.annotations.Loggable; import org.baeldung.model.Foo; import org.springframework.stereotype.Repository; @@ -10,7 +11,12 @@ public class FooDao { return "Bazz"; } + @Loggable public Foo create(Long id, String name) { return new Foo(id, name); } + + public Foo merge(Foo foo) { + return foo; + } } diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java b/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java index 17510f4836..0b1a553afc 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java +++ b/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java @@ -1,5 +1,8 @@ package org.baeldung.model; +import org.baeldung.aop.annotations.Entity; + +@Entity public class Foo { private Long id; private String name; diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java b/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java index 7aff17c424..4c8fcd50a8 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java +++ b/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java @@ -2,6 +2,7 @@ package org.baeldung.aop; import org.baeldung.config.TestConfig; import org.baeldung.dao.FooDao; +import org.baeldung.model.Foo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,6 +19,7 @@ import java.util.logging.Logger; import java.util.regex.Pattern; import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.core.IsCollectionContaining.hasItem; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -27,6 +29,8 @@ public class AopLoggingTest { @Before public void setUp() { + messages = new ArrayList<>(); + logEventHandler = new Handler() { @Override public void publish(LogRecord record) { @@ -42,7 +46,8 @@ public class AopLoggingTest { } }; - messages = new ArrayList<>(); + Logger logger = Logger.getLogger(LoggingAspect.class.getName()); + logger.addHandler(logEventHandler); } @Autowired @@ -54,9 +59,6 @@ public class AopLoggingTest { @Test public void givenLoggingAspect_whenCallDaoMethod_thenBeforeAdviceIsCalled() { - Logger logger = Logger.getLogger(LoggingAspect.class.getName()); - logger.addHandler(logEventHandler); - dao.findById(1L); assertThat(messages, hasSize(1)); @@ -64,4 +66,17 @@ public class AopLoggingTest { Pattern pattern = Pattern.compile("^\\[\\d{4}\\-\\d{2}\\-\\d{2} \\d{2}:\\d{2}:\\d{2}:\\d{3}\\]findById$"); assertTrue(pattern.matcher(logMessage).matches()); } + + @Test + public void givenLoggingAspect_whenCallLoggableAnnotatedMethod_thenMethodIsLogged() { + dao.create(42L, "baz"); + assertThat(messages, hasItem("Executing method: create")); + } + + @Test + public void givenLoggingAspect_whenCallMethodAcceptingAnnotatedArgument_thenArgumentIsLogged() { + Foo foo = new Foo(42L, "baz"); + dao.merge(foo); + assertThat(messages, hasItem("Accepting beans with @Entity annotation: " + foo)); + } } From b470c21842205f08f3bcad7541d6a763070a1daf Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 7 Dec 2015 12:03:39 +0200 Subject: [PATCH 006/309] upgrade httpClient --- .../ClientPreemptiveDigestAuthentication.java | 17 +++++++++++------ ...nentsClientHttpRequestFactoryDigestAuth.java | 4 ++-- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/spring-security-rest-digest-auth/src/main/java/org/baeldung/client/ClientPreemptiveDigestAuthentication.java b/spring-security-rest-digest-auth/src/main/java/org/baeldung/client/ClientPreemptiveDigestAuthentication.java index 5887d2dcab..de94a6e393 100644 --- a/spring-security-rest-digest-auth/src/main/java/org/baeldung/client/ClientPreemptiveDigestAuthentication.java +++ b/spring-security-rest-digest-auth/src/main/java/org/baeldung/client/ClientPreemptiveDigestAuthentication.java @@ -6,11 +6,14 @@ import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; +import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.protocol.ClientContext; +import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.auth.DigestScheme; import org.apache.http.impl.client.BasicAuthCache; -import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.util.EntityUtils; @@ -27,9 +30,11 @@ public class ClientPreemptiveDigestAuthentication { public static void main(final String[] args) throws Exception { final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); - final DefaultHttpClient httpclient = new DefaultHttpClient(); + final CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user1", "user1Pass")); + + final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try { - httpclient.getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user1", "user1Pass")); // Create AuthCache instance final AuthCache authCache = new BasicAuthCache(); @@ -43,7 +48,7 @@ public class ClientPreemptiveDigestAuthentication { // Add AuthCache to the execution context final BasicHttpContext localcontext = new BasicHttpContext(); - localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); + localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"); @@ -63,7 +68,7 @@ public class ClientPreemptiveDigestAuthentication { } } finally { // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); + httpclient.close(); } } diff --git a/spring-security-rest-digest-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java b/spring-security-rest-digest-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java index 698ab4cb92..49487da545 100644 --- a/spring-security-rest-digest-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java +++ b/spring-security-rest-digest-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java @@ -5,7 +5,7 @@ import java.net.URI; import org.apache.http.HttpHost; import org.apache.http.client.AuthCache; import org.apache.http.client.HttpClient; -import org.apache.http.client.protocol.ClientContext; +import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.auth.DigestScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.protocol.BasicHttpContext; @@ -41,7 +41,7 @@ public class HttpComponentsClientHttpRequestFactoryDigestAuth extends HttpCompon // Add AuthCache to the execution context final BasicHttpContext localcontext = new BasicHttpContext(); - localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); + localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); return localcontext; } From 0c8f855ff76c2445e80af0fa1eb19c1214ed5637 Mon Sep 17 00:00:00 2001 From: gmaipady Date: Wed, 9 Dec 2015 17:42:35 +0530 Subject: [PATCH 007/309] Added spring-thymeleaf initial version --- spring-thymeleaf/.classpath | 32 +++++ spring-thymeleaf/.project | 42 ++++++ spring-thymeleaf/pom.xml | 128 ++++++++++++++++++ .../thymeleaf/controller/HomeController.java | 27 ++++ .../controller/StudentController.java | 65 +++++++++ .../thymeleaf/formatter/NameFormatter.java | 30 ++++ .../org/baeldung/thymeleaf/model/Student.java | 40 ++++++ .../src/main/resources/logback.xml | 20 +++ .../main/resources/messages_en_US.properties | 4 + .../WEB-INF/appServlet/servlet-context.xml | 53 ++++++++ .../src/main/webapp/WEB-INF/root-context.xml | 8 ++ .../main/webapp/WEB-INF/views/addStudent.html | 30 ++++ .../src/main/webapp/WEB-INF/views/home.html | 15 ++ .../webapp/WEB-INF/views/listStudents.html | 24 ++++ .../src/main/webapp/WEB-INF/web.xml | 34 +++++ 15 files changed, 552 insertions(+) create mode 100644 spring-thymeleaf/.classpath create mode 100644 spring-thymeleaf/.project create mode 100644 spring-thymeleaf/pom.xml create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java create mode 100644 spring-thymeleaf/src/main/resources/logback.xml create mode 100644 spring-thymeleaf/src/main/resources/messages_en_US.properties create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/web.xml diff --git a/spring-thymeleaf/.classpath b/spring-thymeleaf/.classpath new file mode 100644 index 0000000000..28e4a52cd4 --- /dev/null +++ b/spring-thymeleaf/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-thymeleaf/.project b/spring-thymeleaf/.project new file mode 100644 index 0000000000..3c898c7e84 --- /dev/null +++ b/spring-thymeleaf/.project @@ -0,0 +1,42 @@ + + + spring-thymeleaf + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml new file mode 100644 index 0000000000..770f67d59c --- /dev/null +++ b/spring-thymeleaf/pom.xml @@ -0,0 +1,128 @@ + + 4.0.0 + org.baeldung + spring-thymeleaf + 0.1-SNAPSHOT + war + + 1.7 + + 4.1.8.RELEASE + 3.0.1 + + 1.7.12 + 1.1.3 + + 2.1.4.RELEASE + + 1.1.0.Final + 5.1.2.Final + + 3.3 + 2.6 + 2.18.1 + + + + + org.springframework + spring-context + ${org.springframework-version} + + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + ${org.springframework-version} + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + javax.servlet + javax.servlet-api + ${javax.servlet-version} + provided + + + + javax.validation + validation-api + ${javax.validation-version} + + + org.hibernate + hibernate-validator + ${org.hibernate-version} + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java-version} + ${java-version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + + diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java new file mode 100644 index 0000000000..505dc8303b --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java @@ -0,0 +1,27 @@ +package org.baeldung.thymeleaf.controller; + +import java.text.DateFormat; +import java.util.Date; +import java.util.Locale; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * Handles requests for the application home page. + * + */ +@Controller +public class HomeController { + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String getHome(Model model) { + + DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.getDefault()); + model.addAttribute("serverTime", dateFormat.format(new Date())); + return "home"; + } + +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java new file mode 100644 index 0000000000..fb7f52f853 --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java @@ -0,0 +1,65 @@ +package org.baeldung.thymeleaf.controller; + +import java.util.ArrayList; +import java.util.List; + +import javax.validation.Valid; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import org.baeldung.thymeleaf.model.Student; + +/** + * Handles requests for the student model. + * + */ +@Controller +public class StudentController { + + @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) + public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { + if (!errors.hasErrors()) { + // get mock objects + List students = buildStudents(); + // add current student + students.add(student); + model.addAttribute("students", students); + } + return ((errors.hasErrors()) ? "addStudent" : "listStudents"); + } + + @RequestMapping(value = "/addStudent", method = RequestMethod.GET) + public String addStudent(Model model) { + model.addAttribute("student", new Student()); + return "addStudent"; + } + + @RequestMapping(value = "/listStudents", method = RequestMethod.GET) + public String listStudent(Model model) { + + model.addAttribute("students", buildStudents()); + + return "listStudents"; + } + + private List buildStudents() { + List students = new ArrayList(); + + Student student1 = new Student(); + student1.setId(1001); + student1.setName("John Smith"); + students.add(student1); + + Student student2 = new Student(); + student2.setId(1002); + student2.setName("Jane Williams"); + students.add(student2); + + return students; + } +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java new file mode 100644 index 0000000000..9c07ef8d14 --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java @@ -0,0 +1,30 @@ +package org.baeldung.thymeleaf.formatter; + +import java.text.ParseException; +import java.util.Locale; + +import org.springframework.format.Formatter; +import org.thymeleaf.util.StringUtils; + +/** + * + * Name formatter class that implements the Spring Formatter interface. + * Formats a name(String) and return the value with spaces replaced by commas. + * + */ +public class NameFormatter implements Formatter { + + @Override + public String print(String input, Locale locale) { + return formatName(input, locale); + } + + @Override + public String parse(String input, Locale locale) throws ParseException { + return formatName(input, locale); + } + + private String formatName(String input, Locale locale) { + return StringUtils.replace(input, " ", ","); + } +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java new file mode 100644 index 0000000000..d34af3961e --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java @@ -0,0 +1,40 @@ +package org.baeldung.thymeleaf.model; + +import java.io.Serializable; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +/** + * + * Simple student POJO with two fields - id and name + * + */ +public class Student implements Serializable { + + private static final long serialVersionUID = -8582553475226281591L; + + @NotNull(message = "Student ID is required.") + @Min(value = 1000, message = "Student ID must be atleast 4 digits.") + private Integer id; + + @NotNull(message = "Student Name is required.") + private String name; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-thymeleaf/src/main/resources/logback.xml b/spring-thymeleaf/src/main/resources/logback.xml new file mode 100644 index 0000000000..1146dade63 --- /dev/null +++ b/spring-thymeleaf/src/main/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-thymeleaf/src/main/resources/messages_en_US.properties b/spring-thymeleaf/src/main/resources/messages_en_US.properties new file mode 100644 index 0000000000..0cfe16cd84 --- /dev/null +++ b/spring-thymeleaf/src/main/resources/messages_en_US.properties @@ -0,0 +1,4 @@ +msg.id=ID +msg.name=Name +welcome.message=Welcome Student !!! + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml new file mode 100644 index 0000000000..38a4233c64 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml new file mode 100644 index 0000000000..5cb2a94d73 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html new file mode 100644 index 0000000000..9358c991e9 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html @@ -0,0 +1,30 @@ + + + +Add Student + + +

Add Student

+
+
    +
  • +
  • +
+ + + + + + + + + + + + +
+
+ + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html new file mode 100644 index 0000000000..7d9d5852e4 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html @@ -0,0 +1,15 @@ + + + +Home + + +

+ +

+

+ Current time is +

+ + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html new file mode 100644 index 0000000000..e35082be50 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html @@ -0,0 +1,24 @@ + + + +Student List + + +

Student List

+ + + + + + + + + + + + + +
+ + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..275a482c6f --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,34 @@ + + + + + + contextConfigLocation + /WEB-INF/root-context.xml + + + + + org.springframework.web.context.ContextLoaderListener + + + + + appServlet + org.springframework.web.servlet.DispatcherServlet + + contextConfigLocation + /WEB-INF/appServlet/servlet-context.xml + + 1 + + + + appServlet + / + + \ No newline at end of file From cd4d7beb86665560fa4f47f44ae5ec27f0d27523 Mon Sep 17 00:00:00 2001 From: gmaipady Date: Wed, 9 Dec 2015 18:13:30 +0530 Subject: [PATCH 008/309] Updated README file --- spring-thymeleaf/README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 spring-thymeleaf/README.md diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md new file mode 100644 index 0000000000..ef86ae055a --- /dev/null +++ b/spring-thymeleaf/README.md @@ -0,0 +1,17 @@ +========= + +## Spring Thymeleaf Example Project + + +### Relevant Articles: + + +### Build the Project +``` +mvn clean install +``` + +Access sample pages using the URLs: +http://localhost:8080/spring-thymeleaf/ +http://localhost:8080/spring-thymeleaf/addStudent/ +http://localhost:8080/spring-thymeleaf/listStudents/ From c565c1e1810b2ce3483a1f65b2eaa9f38e8d57c1 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 9 Dec 2015 17:08:33 +0200 Subject: [PATCH 009/309] metrics improve --- .../web/controller/RootController.java | 4 +- .../web/metric/ActuatorMetricService2.java | 93 +++++++++++++++++++ 2 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService2.java 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 42fc78f611..595312b477 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 @@ -6,7 +6,7 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.baeldung.web.metric.IActuatorMetricService; +import org.baeldung.web.metric.ActuatorMetricService2; import org.baeldung.web.metric.IMetricService; import org.baeldung.web.util.LinkUtil; import org.springframework.beans.factory.annotation.Autowired; @@ -25,7 +25,7 @@ public class RootController { private IMetricService metricService; @Autowired - private IActuatorMetricService actMetricService; + private ActuatorMetricService2 actMetricService; public RootController() { super(); diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService2.java b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService2.java new file mode 100644 index 0000000000..2e6efef62c --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService2.java @@ -0,0 +1,93 @@ +package org.baeldung.web.metric; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.actuate.endpoint.MetricReaderPublicMetrics; +import org.springframework.boot.actuate.metrics.Metric; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +@Service +public class ActuatorMetricService2 { + + @Autowired + private MetricReaderPublicMetrics publicMetrics; + + private final List> statusMetric; + private final List statusList; + private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + + public ActuatorMetricService2() { + super(); + statusMetric = new ArrayList>(); + statusList = new ArrayList(); + } + + + public Object[][] getGraphData() { + final Date current = new Date(); + final int colCount = statusList.size() + 1; + final int rowCount = statusMetric.size() + 1; + final Object[][] result = new Object[rowCount][colCount]; + result[0][0] = "Time"; + int j = 1; + for (final String status : statusList) { + result[0][j] = status; + j++; + } + + List temp; + List last = new ArrayList(); + for (int i = 1; i < rowCount; i++) { + temp = statusMetric.get(i - 1); + result[i][0] = dateFormat.format(new Date(current.getTime() - (60000 * (rowCount - i)))); + for (j = 1; j <= temp.size(); j++) { + System.out.println(last); + result[i][j] = temp.get(j - 1) - (last.size() >= j ? last.get(j - 1) : 0); + } + while (j < colCount) { + result[i][j] = 0; + j++; + } + last = temp; + } + return result; + } + + // Non - API + + @Scheduled(fixedDelay = 60000) + private void exportMetrics() { + final ArrayList statusCount = new ArrayList(); + String status = ""; + int index = -1; + int old = 0; + for (int i = 0; i < statusList.size(); i++) { + statusCount.add(0); + } + for (final Metric metric : publicMetrics.metrics()) { + if (metric.getName().contains("counter.status.")) { + status = metric.getName().substring(15, 18); + if (!statusList.contains(status)) { + statusList.add(status); + statusCount.add(0); + } + System.out.println(statusList + " == " + statusCount); + index = statusList.indexOf(status); + old = statusCount.get(index) == null ? 0 : statusCount.get(index); + statusCount.set(index, metric.getValue().intValue() + old); + // metric.set(0); + // repo.reset(metric.getName()); + } + } + statusMetric.add(statusCount); + + // for (final Metric metric : publicMetrics.metrics()) { + // System.out.println(metric.getName() + " = " + metric.getValue() + " = " + metric.getTimestamp()); + // } + } +} \ No newline at end of file From de2dfa5178ca696786183e0795279ea058540a92 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 9 Dec 2015 19:48:34 +0200 Subject: [PATCH 010/309] metric cleanup --- .../web/controller/RootController.java | 4 +- .../web/metric/ActuatorMetricService.java | 65 +++++++++++-------- ....java => CustomActuatorMetricService.java} | 61 +++++++++-------- .../web/metric/IActuatorMetricService.java | 3 - .../metric/ICustomActuatorMetricService.java | 8 +++ .../org/baeldung/web/metric/MetricFilter.java | 4 +- .../src/main/webapp/WEB-INF/view/graph.jsp | 2 +- 7 files changed, 80 insertions(+), 67 deletions(-) rename spring-security-rest-full/src/main/java/org/baeldung/web/metric/{ActuatorMetricService2.java => CustomActuatorMetricService.java} (55%) create mode 100644 spring-security-rest-full/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java 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 595312b477..42fc78f611 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 @@ -6,7 +6,7 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.baeldung.web.metric.ActuatorMetricService2; +import org.baeldung.web.metric.IActuatorMetricService; import org.baeldung.web.metric.IMetricService; import org.baeldung.web.util.LinkUtil; import org.springframework.beans.factory.annotation.Autowired; @@ -25,7 +25,7 @@ public class RootController { private IMetricService metricService; @Autowired - private ActuatorMetricService2 actMetricService; + private IActuatorMetricService actMetricService; public RootController() { super(); diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java index 3d13fb5b59..d0ed765c68 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java @@ -6,20 +6,16 @@ import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.metrics.CounterService; +import org.springframework.boot.actuate.endpoint.MetricReaderPublicMetrics; import org.springframework.boot.actuate.metrics.Metric; -import org.springframework.boot.actuate.metrics.repository.InMemoryMetricRepository; -import org.springframework.boot.actuate.metrics.repository.MetricRepository; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service public class ActuatorMetricService implements IActuatorMetricService { - private MetricRepository repo; - @Autowired - private CounterService counter; + private MetricReaderPublicMetrics publicMetrics; private final List> statusMetric; private final List statusList; @@ -27,20 +23,10 @@ public class ActuatorMetricService implements IActuatorMetricService { public ActuatorMetricService() { super(); - repo = new InMemoryMetricRepository(); statusMetric = new ArrayList>(); statusList = new ArrayList(); } - // API - - @Override - public void increaseCount(final int status) { - counter.increment("status." + status); - if (!statusList.contains("counter.status." + status)) { - statusList.add("counter.status." + status); - } - } @Override public Object[][] getGraphData() { @@ -49,24 +35,26 @@ public class ActuatorMetricService implements IActuatorMetricService { final int rowCount = statusMetric.size() + 1; final Object[][] result = new Object[rowCount][colCount]; result[0][0] = "Time"; - int j = 1; + for (final String status : statusList) { result[0][j] = status; j++; } List temp; + List last = new ArrayList(); for (int i = 1; i < rowCount; i++) { temp = statusMetric.get(i - 1); result[i][0] = dateFormat.format(new Date(current.getTime() - (60000 * (rowCount - i)))); for (j = 1; j <= temp.size(); j++) { - result[i][j] = temp.get(j - 1); + result[i][j] = temp.get(j - 1) - (last.size() >= j ? last.get(j - 1) : 0); } while (j < colCount) { result[i][j] = 0; j++; } + last = temp; } return result; } @@ -75,18 +63,39 @@ public class ActuatorMetricService implements IActuatorMetricService { @Scheduled(fixedDelay = 60000) private void exportMetrics() { - Metric metric; - final ArrayList statusCount = new ArrayList(); - for (final String status : statusList) { - metric = repo.findOne(status); - if (metric != null) { - statusCount.add(metric.getValue().intValue()); - repo.reset(status); - } else { - statusCount.add(0); - } + final ArrayList statusCount = initializeCounterList(statusList.size()); + for (final Metric counterMetric : publicMetrics.metrics()) { + updateStatusCount(counterMetric, statusCount); } + statusMetric.add(statusCount); } + + private ArrayList initializeCounterList(final int size) { + final ArrayList counterList = new ArrayList(); + for (int i = 0; i < size; i++) { + counterList.add(0); + } + return counterList; + } + + private void updateStatusCount(final Metric counterMetric, final ArrayList statusCount) { + String status = ""; + int index = -1; + int oldCount = 0; + + if (counterMetric.getName().contains("counter.status.")) { + status = counterMetric.getName().substring(15, 18); // example 404, 200 + if (!statusList.contains(status)) { + statusList.add(status); + statusCount.add(0); + } + index = statusList.indexOf(status); + oldCount = statusCount.get(index) == null ? 0 : statusCount.get(index); + statusCount.set(index, counterMetric.getValue().intValue() + oldCount); + } + } + + // } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService2.java b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java similarity index 55% rename from spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService2.java rename to spring-security-rest-full/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java index 2e6efef62c..7df7e199b4 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService2.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java @@ -6,34 +6,50 @@ import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.endpoint.MetricReaderPublicMetrics; +import org.springframework.boot.actuate.metrics.CounterService; import org.springframework.boot.actuate.metrics.Metric; +import org.springframework.boot.actuate.metrics.repository.InMemoryMetricRepository; +import org.springframework.boot.actuate.metrics.repository.MetricRepository; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service -public class ActuatorMetricService2 { +public class CustomActuatorMetricService implements ICustomActuatorMetricService { + + private MetricRepository repo; @Autowired - private MetricReaderPublicMetrics publicMetrics; + private CounterService counter; private final List> statusMetric; private final List statusList; private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - public ActuatorMetricService2() { + public CustomActuatorMetricService() { super(); + repo = new InMemoryMetricRepository(); statusMetric = new ArrayList>(); statusList = new ArrayList(); } + // API + @Override + public void increaseCount(final int status) { + counter.increment("status." + status); + if (!statusList.contains("counter.status." + status)) { + statusList.add("counter.status." + status); + } + } + + @Override public Object[][] getGraphData() { final Date current = new Date(); final int colCount = statusList.size() + 1; final int rowCount = statusMetric.size() + 1; final Object[][] result = new Object[rowCount][colCount]; result[0][0] = "Time"; + int j = 1; for (final String status : statusList) { result[0][j] = status; @@ -41,19 +57,16 @@ public class ActuatorMetricService2 { } List temp; - List last = new ArrayList(); for (int i = 1; i < rowCount; i++) { temp = statusMetric.get(i - 1); result[i][0] = dateFormat.format(new Date(current.getTime() - (60000 * (rowCount - i)))); for (j = 1; j <= temp.size(); j++) { - System.out.println(last); - result[i][j] = temp.get(j - 1) - (last.size() >= j ? last.get(j - 1) : 0); + result[i][j] = temp.get(j - 1); } while (j < colCount) { result[i][j] = 0; j++; } - last = temp; } return result; } @@ -62,32 +75,18 @@ public class ActuatorMetricService2 { @Scheduled(fixedDelay = 60000) private void exportMetrics() { + Metric metric; final ArrayList statusCount = new ArrayList(); - String status = ""; - int index = -1; - int old = 0; - for (int i = 0; i < statusList.size(); i++) { - statusCount.add(0); - } - for (final Metric metric : publicMetrics.metrics()) { - if (metric.getName().contains("counter.status.")) { - status = metric.getName().substring(15, 18); - if (!statusList.contains(status)) { - statusList.add(status); - statusCount.add(0); - } - System.out.println(statusList + " == " + statusCount); - index = statusList.indexOf(status); - old = statusCount.get(index) == null ? 0 : statusCount.get(index); - statusCount.set(index, metric.getValue().intValue() + old); - // metric.set(0); - // repo.reset(metric.getName()); + for (final String status : statusList) { + metric = repo.findOne(status); + if (metric != null) { + statusCount.add(metric.getValue().intValue()); + repo.reset(status); + } else { + statusCount.add(0); } + } statusMetric.add(statusCount); - - // for (final Metric metric : publicMetrics.metrics()) { - // System.out.println(metric.getName() + " = " + metric.getValue() + " = " + metric.getTimestamp()); - // } } } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java index b7528ce372..191d347070 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java @@ -1,8 +1,5 @@ package org.baeldung.web.metric; public interface IActuatorMetricService { - - void increaseCount(final int status); - Object[][] getGraphData(); } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java new file mode 100644 index 0000000000..19ab7164ac --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java @@ -0,0 +1,8 @@ +package org.baeldung.web.metric; + +public interface ICustomActuatorMetricService { + + void increaseCount(final int status); + + Object[][] getGraphData(); +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java index 06665f820b..d77aec7919 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java @@ -20,13 +20,13 @@ public class MetricFilter implements Filter { private IMetricService metricService; @Autowired - private IActuatorMetricService actMetricService; + private ICustomActuatorMetricService actMetricService; @Override public void init(final FilterConfig config) throws ServletException { if (metricService == null || actMetricService == null) { metricService = (IMetricService) WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean("metricService"); - actMetricService = (IActuatorMetricService) WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean("actuatorMetricService"); + actMetricService = (ICustomActuatorMetricService) WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean("actuatorMetricService"); } } diff --git a/spring-security-rest-full/src/main/webapp/WEB-INF/view/graph.jsp b/spring-security-rest-full/src/main/webapp/WEB-INF/view/graph.jsp index cb037f5f6c..e1d5fdc987 100644 --- a/spring-security-rest-full/src/main/webapp/WEB-INF/view/graph.jsp +++ b/spring-security-rest-full/src/main/webapp/WEB-INF/view/graph.jsp @@ -11,7 +11,7 @@ }); function drawChart() { - $.get("", + $.get("", function(mydata) { var data = google.visualization.arrayToDataTable(mydata); From ffd0759d5aa5446bec5d3a915d434ff6250983bf Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 10 Dec 2015 14:09:06 +0200 Subject: [PATCH 011/309] inputStream guava improvement --- .../org/baeldung/java/io/JavaInputStreamToXUnitTest.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java index 53bbe8a8d3..55a0904499 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java @@ -32,7 +32,6 @@ import com.google.common.io.ByteSource; import com.google.common.io.ByteStreams; import com.google.common.io.CharStreams; import com.google.common.io.Files; -import com.google.common.io.InputSupplier; @SuppressWarnings("unused") public class JavaInputStreamToXUnitTest { @@ -75,16 +74,14 @@ public class JavaInputStreamToXUnitTest { final String originalString = randomAlphabetic(DEFAULT_SIZE); final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes()); - final InputSupplier inputSupplier = new InputSupplier() { + final ByteSource byteSource = new ByteSource() { @Override - public final InputStream getInput() throws IOException { + public final InputStream openStream() throws IOException { return inputStream; } }; - final InputSupplier readerSupplier = CharStreams.newReaderSupplier(inputSupplier, Charsets.UTF_8); - // When - final String text = CharStreams.toString(readerSupplier); + final String text = byteSource.asCharSource(Charsets.UTF_8).read(); assertThat(text, equalTo(originalString)); } From 9b2b856661948c6bec5bfee2c8191d203c8cf191 Mon Sep 17 00:00:00 2001 From: Devendra Desale Date: Fri, 11 Dec 2015 15:16:48 +0800 Subject: [PATCH 012/309] Adding spring batch project --- spring-batch-intro/.classpath | 27 ++++++++ spring-batch-intro/.project | 23 +++++++ spring-batch-intro/pom.xml | 45 ++++++++++++++ .../org/baeldung/spring_batch_intro/App.java | 28 +++++++++ .../spring_batch_intro/model/Transaction.java | 54 ++++++++++++++++ .../service/CustomItemProcessor.java | 14 +++++ .../service/RecordFieldSetMapper.java | 33 ++++++++++ .../src/main/resources/input/record.csv | 3 + .../src/main/resources/spring-batch-intro.xml | 61 +++++++++++++++++++ .../src/main/resources/spring.xml | 44 +++++++++++++ spring-batch-intro/xml/output.xml | 1 + 11 files changed, 333 insertions(+) create mode 100644 spring-batch-intro/.classpath create mode 100644 spring-batch-intro/.project create mode 100644 spring-batch-intro/pom.xml create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java create mode 100644 spring-batch-intro/src/main/resources/input/record.csv create mode 100644 spring-batch-intro/src/main/resources/spring-batch-intro.xml create mode 100644 spring-batch-intro/src/main/resources/spring.xml create mode 100644 spring-batch-intro/xml/output.xml diff --git a/spring-batch-intro/.classpath b/spring-batch-intro/.classpath new file mode 100644 index 0000000000..395dbde027 --- /dev/null +++ b/spring-batch-intro/.classpath @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-batch-intro/.project b/spring-batch-intro/.project new file mode 100644 index 0000000000..032f8a9541 --- /dev/null +++ b/spring-batch-intro/.project @@ -0,0 +1,23 @@ + + + spring-batch-intro + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/spring-batch-intro/pom.xml b/spring-batch-intro/pom.xml new file mode 100644 index 0000000000..c68608d4ae --- /dev/null +++ b/spring-batch-intro/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + + org.baeldung + spring-batch-intro + 0.1-SNAPSHOT + jar + + spring-batch-intro + http://maven.apache.org + + + UTF-8 + 4.0.2.RELEASE + 3.0.5.RELEASE + 3.8.11.2 + + + + + + org.xerial + sqlite-jdbc + ${sqlite.version} + + + org.springframework + spring-oxm + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + + org.springframework.batch + spring-batch-core + ${spring.batch.version} + + + + diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java new file mode 100644 index 0000000000..7e6b080851 --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java @@ -0,0 +1,28 @@ +package org.baeldung.spring_batch_intro; + +import org.springframework.batch.core.Job; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.JobParameters; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class App { + public static void main(String[] args) { + + ApplicationContext context = new ClassPathXmlApplicationContext( + "/spring-batch-intro.xml"); + + JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); + Job job = (Job) context.getBean("firstBatchJob"); + System.out.println("Starting the batch job"); + try { + JobExecution execution = jobLauncher.run(job, new JobParameters()); + System.out.println("Job Status : " + execution.getStatus()); + System.out.println("Job completed"); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Job failed"); + } + } +} \ No newline at end of file diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java new file mode 100644 index 0000000000..815af78cd4 --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java @@ -0,0 +1,54 @@ +package org.baeldung.spring_batch_intro.model; + +import java.util.Date; + +import javax.xml.bind.annotation.XmlRootElement; + +@SuppressWarnings("restriction") +@XmlRootElement(name = "transactionRecord") +public class Transaction { + private String username; + private int userId; + private Date transactionDate; + private double amount; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public Date getTransactionDate() { + return transactionDate; + } + + public void setTransactionDate(Date transactionDate) { + this.transactionDate = transactionDate; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } + + @Override + public String toString() { + return "Transaction [username=" + username + ", userId=" + userId + + ", transactionDate=" + transactionDate + ", amount=" + amount + + "]"; + } + +} diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java new file mode 100644 index 0000000000..be1127c5e7 --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java @@ -0,0 +1,14 @@ +package org.baeldung.spring_batch_intro.service; + + +import org.baeldung.spring_batch_intro.model.Transaction; +import org.springframework.batch.item.ItemProcessor; + +public class CustomItemProcessor implements ItemProcessor { + + public Transaction process(Transaction item) throws Exception { + + System.out.println("Processing..." + item); + return item; + } +} \ No newline at end of file diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java new file mode 100644 index 0000000000..2b8f897e2a --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java @@ -0,0 +1,33 @@ +package org.baeldung.spring_batch_intro.service; + +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import org.baeldung.spring_batch_intro.model.Transaction; +import org.springframework.batch.item.file.mapping.FieldSetMapper; +import org.springframework.batch.item.file.transform.FieldSet; +import org.springframework.validation.BindException; + +public class RecordFieldSetMapper implements FieldSetMapper { + + public Transaction mapFieldSet(FieldSet fieldSet) throws BindException { + + SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); + Transaction transaction = new Transaction(); + + transaction.setUsername(fieldSet.readString("username")); + transaction.setUserId(fieldSet.readInt(1)); + transaction.setAmount(fieldSet.readDouble(3)); + //Converting the date + String dateString = fieldSet.readString(2); + try { + transaction.setTransactionDate(dateFormat.parse(dateString)); + } catch (ParseException e) { + e.printStackTrace(); + } + + return transaction; + + } + +} diff --git a/spring-batch-intro/src/main/resources/input/record.csv b/spring-batch-intro/src/main/resources/input/record.csv new file mode 100644 index 0000000000..3a1437eed5 --- /dev/null +++ b/spring-batch-intro/src/main/resources/input/record.csv @@ -0,0 +1,3 @@ +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch-intro/src/main/resources/spring-batch-intro.xml b/spring-batch-intro/src/main/resources/spring-batch-intro.xml new file mode 100644 index 0000000000..06918d8754 --- /dev/null +++ b/spring-batch-intro/src/main/resources/spring-batch-intro.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.baeldung.spring_batch_intro.model.Transaction + + + + + + + + + + + + + + diff --git a/spring-batch-intro/src/main/resources/spring.xml b/spring-batch-intro/src/main/resources/spring.xml new file mode 100644 index 0000000000..d286662002 --- /dev/null +++ b/spring-batch-intro/src/main/resources/spring.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-batch-intro/xml/output.xml b/spring-batch-intro/xml/output.xml new file mode 100644 index 0000000000..9e57fa38f2 --- /dev/null +++ b/spring-batch-intro/xml/output.xml @@ -0,0 +1 @@ +10000.02015-10-31T00:00:00+08:001234devendra12321.02015-12-03T00:00:00+08:002134john23411.02015-02-02T00:00:00+08:002134robin \ No newline at end of file From 418be41d9c4d49fb6bc0c4aefa1596cb410a54b2 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 12 Dec 2015 13:19:57 +0200 Subject: [PATCH 013/309] prevent brute force improve --- .../java/org/baeldung/security/MyUserDetailsService.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java index d9c3e586b1..567fa7717d 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -45,7 +45,7 @@ public class MyUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException { - final String ip = request.getRemoteAddr(); + final String ip = getClientIP(); if (loginAttemptService.isBlocked(ip)) { throw new RuntimeException("blocked"); } @@ -88,4 +88,10 @@ public class MyUserDetailsService implements UserDetailsService { return authorities; } + private String getClientIP() { + final String xfHeader = request.getHeader("X-Forwarded-For"); + if (xfHeader == null) + return request.getRemoteAddr(); + return xfHeader.split(",")[0]; + } } From 57b27f6c9c952a96aed157935873d54dd814bd4e Mon Sep 17 00:00:00 2001 From: Devendra Desale Date: Sun, 13 Dec 2015 22:12:09 +0800 Subject: [PATCH 014/309] adding java based spring batch configuration --- spring-batch-intro/pom.xml | 75 ++++++------- .../org/baeldung/spring_batch_intro/App.java | 42 ++++--- .../spring_batch_intro/SpringBatchConfig.java | 92 +++++++++++++++ .../spring_batch_intro/SpringConfig.java | 75 +++++++++++++ .../spring_batch_intro/model/Transaction.java | 68 ++++++------ .../service/CustomItemProcessor.java | 13 +-- .../service/RecordFieldSetMapper.java | 34 +++--- .../src/main/resources/spring-batch-intro.xml | 105 +++++++++--------- .../src/main/resources/spring.xml | 67 +++++------ 9 files changed, 376 insertions(+), 195 deletions(-) create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java diff --git a/spring-batch-intro/pom.xml b/spring-batch-intro/pom.xml index c68608d4ae..28d48c594e 100644 --- a/spring-batch-intro/pom.xml +++ b/spring-batch-intro/pom.xml @@ -1,45 +1,44 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - org.baeldung - spring-batch-intro - 0.1-SNAPSHOT - jar + org.baeldung + spring-batch-intro + 0.1-SNAPSHOT + jar - spring-batch-intro - http://maven.apache.org + spring-batch-intro + http://maven.apache.org - - UTF-8 - 4.0.2.RELEASE - 3.0.5.RELEASE - 3.8.11.2 - + + UTF-8 + 4.2.0.RELEASE + 3.0.5.RELEASE + 3.8.11.2 + - - - - org.xerial - sqlite-jdbc - ${sqlite.version} - - - org.springframework - spring-oxm - ${spring.version} - - - org.springframework - spring-jdbc - ${spring.version} - - - - org.springframework.batch - spring-batch-core - ${spring.batch.version} - - + + + + org.xerial + sqlite-jdbc + ${sqlite.version} + + + org.springframework + spring-oxm + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + org.springframework.batch + spring-batch-core + ${spring.batch.version} + + diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java index 7e6b080851..a2f8f38e0f 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java @@ -1,28 +1,38 @@ package org.baeldung.spring_batch_intro; +import javax.swing.Spring; + import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { - public static void main(String[] args) { + public static void main(String[] args) { + // Spring Java config + AnnotationConfigApplicationContext context = new + AnnotationConfigApplicationContext(); + context.register(SpringConfig.class); + context.register(SpringBatchConfig.class); + context.refresh(); - ApplicationContext context = new ClassPathXmlApplicationContext( - "/spring-batch-intro.xml"); - - JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); - Job job = (Job) context.getBean("firstBatchJob"); - System.out.println("Starting the batch job"); - try { - JobExecution execution = jobLauncher.run(job, new JobParameters()); - System.out.println("Job Status : " + execution.getStatus()); - System.out.println("Job completed"); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Job failed"); - } - } + // Spring xml config +// ApplicationContext context = new ClassPathXmlApplicationContext( +// "spring-batch-intro.xml"); + + JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); + Job job = (Job) context.getBean("firstBatchJob"); + System.out.println("Starting the batch job"); + try { + JobExecution execution = jobLauncher.run(job, new JobParameters()); + System.out.println("Job Status : " + execution.getStatus()); + System.out.println("Job completed"); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Job failed"); + } + } } \ No newline at end of file diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java new file mode 100644 index 0000000000..c892e24fd8 --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java @@ -0,0 +1,92 @@ +package org.baeldung.spring_batch_intro; + +import java.net.MalformedURLException; +import java.text.ParseException; + +import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.spring_batch_intro.service.CustomItemProcessor; +import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.item.ItemProcessor; +import org.springframework.batch.item.ItemReader; +import org.springframework.batch.item.ItemWriter; +import org.springframework.batch.item.UnexpectedInputException; +import org.springframework.batch.item.file.FlatFileItemReader; +import org.springframework.batch.item.file.mapping.DefaultLineMapper; +import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; +import org.springframework.batch.item.xml.StaxEventItemWriter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.core.io.Resource; +import org.springframework.oxm.Marshaller; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; + +public class SpringBatchConfig { + @Autowired + private JobBuilderFactory jobs; + + @Autowired + private StepBuilderFactory steps; + + @Value("input/record.csv") + private Resource inputCsv; + + @Value("file:xml/output.xml") + private Resource outputXml; + + @Bean + public ItemReader itemReader() + throws UnexpectedInputException, ParseException, Exception { + FlatFileItemReader reader = new FlatFileItemReader(); + DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); + String[] tokens = { "username", "userid", "transactiondate", "amount" }; + tokenizer.setNames(tokens); + reader.setResource(inputCsv); + DefaultLineMapper lineMapper = new DefaultLineMapper(); + lineMapper.setLineTokenizer(tokenizer); + lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); + reader.setLineMapper(lineMapper); + return reader; + } + + @Bean + public ItemProcessor itemProcessor() { + return new CustomItemProcessor(); + } + + @Bean + public ItemWriter itemWriter(Marshaller marshaller) + throws MalformedURLException { + StaxEventItemWriter itemWriter = new StaxEventItemWriter(); + itemWriter.setMarshaller(marshaller); + itemWriter.setRootTagName("transactionRecord"); + itemWriter.setResource(outputXml); + return itemWriter; + } + + @Bean + public Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + marshaller.setClassesToBeBound(new Class[] { Transaction.class }); + return marshaller; + } + + @Bean + protected Step step1(ItemReader reader, + ItemProcessor processor, + ItemWriter writer) { + return steps.get("step1"). chunk(10) + .reader(reader).processor(processor).writer(writer).build(); + } + + @Bean(name = "firstBatchJob") + public Job job(@Qualifier("step1") Step step1) { + return jobs.get("firstBatchJob").start(step1).build(); + } + +} diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java new file mode 100644 index 0000000000..79676fbe4e --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java @@ -0,0 +1,75 @@ +package org.baeldung.spring_batch_intro; + +import java.net.MalformedURLException; + +import javax.sql.DataSource; + +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.batch.core.launch.support.SimpleJobLauncher; +import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; +import org.springframework.batch.support.transaction.ResourcelessTransactionManager; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.init.DataSourceInitializer; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.transaction.PlatformTransactionManager; + +@Configuration +@EnableBatchProcessing +public class SpringConfig { + + @Value("org/springframework/batch/core/schema-drop-sqlite.sql") + private Resource dropReopsitoryTables; + + @Value("org/springframework/batch/core/schema-sqlite.sql") + private Resource dataReopsitorySchema; + + @Bean + public DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.sqlite.JDBC"); + dataSource.setUrl("jdbc:sqlite:repository.sqlite"); + return dataSource; + } + + @Bean + public DataSourceInitializer dataSourceInitializer(DataSource dataSource) + throws MalformedURLException { + ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); + + databasePopulator.addScript(dropReopsitoryTables); + databasePopulator.addScript(dataReopsitorySchema); + databasePopulator.setIgnoreFailedDrops(true); + + DataSourceInitializer initializer = new DataSourceInitializer(); + initializer.setDataSource(dataSource); + initializer.setDatabasePopulator(databasePopulator); + + return initializer; + } + + private JobRepository getJobRepository() throws Exception { + JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); + factory.setDataSource(dataSource()); + factory.setTransactionManager(getTransactionManager()); + factory.afterPropertiesSet(); + return (JobRepository) factory.getObject(); + } + + private PlatformTransactionManager getTransactionManager() { + return new ResourcelessTransactionManager(); + } + + public JobLauncher getJobLauncher() throws Exception { + SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); + jobLauncher.setJobRepository(getJobRepository()); + jobLauncher.afterPropertiesSet(); + return jobLauncher; + } + +} \ No newline at end of file diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java index 815af78cd4..0108dcf501 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java @@ -7,48 +7,48 @@ import javax.xml.bind.annotation.XmlRootElement; @SuppressWarnings("restriction") @XmlRootElement(name = "transactionRecord") public class Transaction { - private String username; - private int userId; - private Date transactionDate; - private double amount; + private String username; + private int userId; + private Date transactionDate; + private double amount; - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public int getUserId() { - return userId; - } + public int getUserId() { + return userId; + } - public void setUserId(int userId) { - this.userId = userId; - } + public void setUserId(int userId) { + this.userId = userId; + } - public Date getTransactionDate() { - return transactionDate; - } + public Date getTransactionDate() { + return transactionDate; + } - public void setTransactionDate(Date transactionDate) { - this.transactionDate = transactionDate; - } + public void setTransactionDate(Date transactionDate) { + this.transactionDate = transactionDate; + } - public double getAmount() { - return amount; - } + public double getAmount() { + return amount; + } - public void setAmount(double amount) { - this.amount = amount; - } + public void setAmount(double amount) { + this.amount = amount; + } - @Override - public String toString() { - return "Transaction [username=" + username + ", userId=" + userId - + ", transactionDate=" + transactionDate + ", amount=" + amount - + "]"; - } + @Override + public String toString() { + return "Transaction [username=" + username + ", userId=" + userId + + ", transactionDate=" + transactionDate + ", amount=" + amount + + "]"; + } } diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java index be1127c5e7..487dbb5efb 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java @@ -1,14 +1,13 @@ package org.baeldung.spring_batch_intro.service; - import org.baeldung.spring_batch_intro.model.Transaction; import org.springframework.batch.item.ItemProcessor; -public class CustomItemProcessor implements ItemProcessor { +public class CustomItemProcessor implements + ItemProcessor { - public Transaction process(Transaction item) throws Exception { - - System.out.println("Processing..." + item); - return item; - } + public Transaction process(Transaction item) throws Exception { + System.out.println("Processing..." + item); + return item; + } } \ No newline at end of file diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java index 2b8f897e2a..0955b57c76 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java @@ -10,24 +10,24 @@ import org.springframework.validation.BindException; public class RecordFieldSetMapper implements FieldSetMapper { - public Transaction mapFieldSet(FieldSet fieldSet) throws BindException { - - SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); - Transaction transaction = new Transaction(); - - transaction.setUsername(fieldSet.readString("username")); - transaction.setUserId(fieldSet.readInt(1)); - transaction.setAmount(fieldSet.readDouble(3)); - //Converting the date - String dateString = fieldSet.readString(2); - try { - transaction.setTransactionDate(dateFormat.parse(dateString)); - } catch (ParseException e) { - e.printStackTrace(); - } + public Transaction mapFieldSet(FieldSet fieldSet) throws BindException { - return transaction; + SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); + Transaction transaction = new Transaction(); - } + transaction.setUsername(fieldSet.readString("username")); + transaction.setUserId(fieldSet.readInt(1)); + transaction.setAmount(fieldSet.readDouble(3)); + // Converting the date + String dateString = fieldSet.readString(2); + try { + transaction.setTransactionDate(dateFormat.parse(dateString)); + } catch (ParseException e) { + e.printStackTrace(); + } + + return transaction; + + } } diff --git a/spring-batch-intro/src/main/resources/spring-batch-intro.xml b/spring-batch-intro/src/main/resources/spring-batch-intro.xml index 06918d8754..6daa0358d9 100644 --- a/spring-batch-intro/src/main/resources/spring-batch-intro.xml +++ b/spring-batch-intro/src/main/resources/spring-batch-intro.xml @@ -1,61 +1,66 @@ - - - - - + - + - - - - - - - - - + - - - - - - - - - - - - + - - - - org.baeldung.spring_batch_intro.model.Transaction - - - + + + + + + + + + - - - - - - - - - + + + + + + + + + + + + + + + + + org.baeldung.spring_batch_intro.model.Transaction + + + + + + + + + + + + + + diff --git a/spring-batch-intro/src/main/resources/spring.xml b/spring-batch-intro/src/main/resources/spring.xml index d286662002..dea261c5e6 100644 --- a/spring-batch-intro/src/main/resources/spring.xml +++ b/spring-batch-intro/src/main/resources/spring.xml @@ -1,44 +1,45 @@ + http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd"> - - - - - - - + + + + + + + - - - - - + + + + + - - + + - - - - - - + + + + + + - + - - - + + + \ No newline at end of file From 09bc7399ddddd88c744b37afad6bbf321a36c4e0 Mon Sep 17 00:00:00 2001 From: Devendra Desale Date: Mon, 14 Dec 2015 14:35:09 +0800 Subject: [PATCH 015/309] updating generic Exception and linewrappings. --- .../org/baeldung/spring_batch_intro/App.java | 16 +++++++--------- .../spring_batch_intro/SpringBatchConfig.java | 10 +++++----- .../spring_batch_intro/SpringConfig.java | 6 +++++- .../spring_batch_intro/model/Transaction.java | 6 ++++-- .../service/CustomItemProcessor.java | 4 ++-- .../service/RecordFieldSetMapper.java | 6 ++++-- .../src/main/resources/spring-batch-intro.xml | 2 -- 7 files changed, 27 insertions(+), 23 deletions(-) diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java index a2f8f38e0f..db963fff20 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java @@ -1,7 +1,5 @@ package org.baeldung.spring_batch_intro; -import javax.swing.Spring; - import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; @@ -10,18 +8,18 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; + public class App { public static void main(String[] args) { // Spring Java config - AnnotationConfigApplicationContext context = new - AnnotationConfigApplicationContext(); - context.register(SpringConfig.class); - context.register(SpringBatchConfig.class); - context.refresh(); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.register(SpringConfig.class); + context.register(SpringBatchConfig.class); + context.refresh(); // Spring xml config -// ApplicationContext context = new ClassPathXmlApplicationContext( -// "spring-batch-intro.xml"); + // ApplicationContext context = new ClassPathXmlApplicationContext( + // "spring-batch-intro.xml"); JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); Job job = (Job) context.getBean("firstBatchJob"); diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java index c892e24fd8..f0e3b364b6 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java @@ -41,7 +41,7 @@ public class SpringBatchConfig { @Bean public ItemReader itemReader() - throws UnexpectedInputException, ParseException, Exception { + throws UnexpectedInputException, ParseException { FlatFileItemReader reader = new FlatFileItemReader(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); String[] tokens = { "username", "userid", "transactiondate", "amount" }; @@ -61,7 +61,7 @@ public class SpringBatchConfig { @Bean public ItemWriter itemWriter(Marshaller marshaller) - throws MalformedURLException { + throws MalformedURLException { StaxEventItemWriter itemWriter = new StaxEventItemWriter(); itemWriter.setMarshaller(marshaller); itemWriter.setRootTagName("transactionRecord"); @@ -78,10 +78,10 @@ public class SpringBatchConfig { @Bean protected Step step1(ItemReader reader, - ItemProcessor processor, - ItemWriter writer) { + ItemProcessor processor, + ItemWriter writer) { return steps.get("step1"). chunk(10) - .reader(reader).processor(processor).writer(writer).build(); + .reader(reader).processor(processor).writer(writer).build(); } @Bean(name = "firstBatchJob") diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java index 79676fbe4e..91366d8721 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java @@ -39,7 +39,7 @@ public class SpringConfig { @Bean public DataSourceInitializer dataSourceInitializer(DataSource dataSource) - throws MalformedURLException { + throws MalformedURLException { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(dropReopsitoryTables); @@ -57,6 +57,8 @@ public class SpringConfig { JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(dataSource()); factory.setTransactionManager(getTransactionManager()); + // JobRepositoryFactoryBean's methods Throws Generic Exception, + // it would have been better to have a specific one factory.afterPropertiesSet(); return (JobRepository) factory.getObject(); } @@ -67,6 +69,8 @@ public class SpringConfig { public JobLauncher getJobLauncher() throws Exception { SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); + // SimpleJobLauncher's methods Throws Generic Exception, + // it would have been better to have a specific one jobLauncher.setJobRepository(getJobRepository()); jobLauncher.afterPropertiesSet(); return jobLauncher; diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java index 0108dcf501..6e80298ff0 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java @@ -12,6 +12,8 @@ public class Transaction { private Date transactionDate; private double amount; + /* getters and setters for the attributes */ + public String getUsername() { return username; } @@ -47,8 +49,8 @@ public class Transaction { @Override public String toString() { return "Transaction [username=" + username + ", userId=" + userId - + ", transactionDate=" + transactionDate + ", amount=" + amount - + "]"; + + ", transactionDate=" + transactionDate + ", amount=" + amount + + "]"; } } diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java index 487dbb5efb..baabe79409 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java @@ -4,9 +4,9 @@ import org.baeldung.spring_batch_intro.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class CustomItemProcessor implements - ItemProcessor { + ItemProcessor { - public Transaction process(Transaction item) throws Exception { + public Transaction process(Transaction item) { System.out.println("Processing..." + item); return item; } diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java index 0955b57c76..94f9e7d94e 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java @@ -14,9 +14,11 @@ public class RecordFieldSetMapper implements FieldSetMapper { SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); Transaction transaction = new Transaction(); - + // you can either use the indices or custom names + // I personally prefer the custom names easy for debugging and + // validating the pipelines transaction.setUsername(fieldSet.readString("username")); - transaction.setUserId(fieldSet.readInt(1)); + transaction.setUserId(fieldSet.readInt("userid")); transaction.setAmount(fieldSet.readDouble(3)); // Converting the date String dateString = fieldSet.readString(2); diff --git a/spring-batch-intro/src/main/resources/spring-batch-intro.xml b/spring-batch-intro/src/main/resources/spring-batch-intro.xml index 6daa0358d9..3b1f11521f 100644 --- a/spring-batch-intro/src/main/resources/spring-batch-intro.xml +++ b/spring-batch-intro/src/main/resources/spring-batch-intro.xml @@ -8,8 +8,6 @@ - - From bbcacc07bf50608ec7e97c97ba5445f213e17e76 Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 14 Dec 2015 17:05:11 +0200 Subject: [PATCH 016/309] fix error message --- .../CustomAuthenticationFailureHandler.java | 44 +++++++++++++++++++ .../baeldung/spring/SecSecurityConfig.java | 5 +++ .../src/main/webapp/WEB-INF/view/login.jsp | 36 ++++----------- 3 files changed, 57 insertions(+), 28 deletions(-) create mode 100644 spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java new file mode 100644 index 0000000000..8ae1ccf8bc --- /dev/null +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java @@ -0,0 +1,44 @@ +package org.baeldung.security; + +import java.io.IOException; +import java.util.Locale; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.LocaleResolver; + +@Component +public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { + + @Autowired + private MessageSource messages; + + @Autowired + private LocaleResolver localeResolver; + + @Override + public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException exception) throws IOException, ServletException { + setDefaultFailureUrl("/login.html?error=true"); + + super.onAuthenticationFailure(request, response, exception); + + final Locale locale = localeResolver.resolveLocale(request); + + if (exception.getMessage().equalsIgnoreCase("User is disabled")) { + request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", messages.getMessage("auth.message.disabled", null, locale)); + } else if (exception.getMessage().equalsIgnoreCase("User account has expired")) { + request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", messages.getMessage("auth.message.expired", null, locale)); + } else if (exception.getMessage().equalsIgnoreCase("blocked")) { + request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", messages.getMessage("auth.message.blocked", null, locale)); + } else { + request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", messages.getMessage("message.badCredentials", null, locale)); + } + } +} \ No newline at end of file diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 814ed92b33..4863187bba 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -13,6 +13,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; @Configuration @@ -26,6 +27,9 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationSuccessHandler myAuthenticationSuccessHandler; + @Autowired + private AuthenticationFailureHandler authenticationFailureHandler; + public SecSecurityConfig() { super(); } @@ -59,6 +63,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .defaultSuccessUrl("/homepage.html") .failureUrl("/login.html?error=true") .successHandler(myAuthenticationSuccessHandler) + .failureHandler(authenticationFailureHandler) .usernameParameter("j_username") .passwordParameter("j_password") .permitAll() diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp index d1be07060a..949b8164de 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp @@ -7,34 +7,7 @@ <%@ page session="true"%> - - - -
- -
-
- -
- -
-
- -
- -
-
- -
- - -
-
-
-
+ @@ -72,6 +45,13 @@ ${param.message} + + +
+${SPRING_SECURITY_LAST_EXCEPTION} +
+
+

From 06ded372a4a2cd38e8f391d2f3362ef3b221515b Mon Sep 17 00:00:00 2001 From: gmaipady Date: Tue, 15 Dec 2015 15:52:52 +0530 Subject: [PATCH 017/309] Minor changes --- .../controller/StudentController.java | 71 ++++++++++--------- .../org/baeldung/thymeleaf/model/Student.java | 58 ++++++++++----- .../main/resources/messages_en_US.properties | 5 ++ .../WEB-INF/appServlet/servlet-context.xml | 6 +- .../main/webapp/WEB-INF/views/addStudent.html | 17 ++++- .../src/main/webapp/WEB-INF/views/home.html | 16 +++-- .../webapp/WEB-INF/views/listStudents.html | 20 ++++-- 7 files changed, 128 insertions(+), 65 deletions(-) diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java index fb7f52f853..3bef22cdae 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java @@ -21,45 +21,50 @@ import org.baeldung.thymeleaf.model.Student; @Controller public class StudentController { - @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) - public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { - if (!errors.hasErrors()) { - // get mock objects - List students = buildStudents(); - // add current student - students.add(student); - model.addAttribute("students", students); - } - return ((errors.hasErrors()) ? "addStudent" : "listStudents"); - } + @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) + public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { + if (!errors.hasErrors()) { + // get mock objects + List students = buildStudents(); + // add current student + students.add(student); + model.addAttribute("students", students); + } + return ((errors.hasErrors()) ? "addStudent" : "listStudents"); + } - @RequestMapping(value = "/addStudent", method = RequestMethod.GET) - public String addStudent(Model model) { - model.addAttribute("student", new Student()); - return "addStudent"; - } + @RequestMapping(value = "/addStudent", method = RequestMethod.GET) + public String addStudent(Model model) { + model.addAttribute("student", new Student()); + return "addStudent"; + } - @RequestMapping(value = "/listStudents", method = RequestMethod.GET) - public String listStudent(Model model) { + @RequestMapping(value = "/listStudents", method = RequestMethod.GET) + public String listStudent(Model model) { - model.addAttribute("students", buildStudents()); + model.addAttribute("students", buildStudents()); - return "listStudents"; - } + return "listStudents"; + } - private List buildStudents() { - List students = new ArrayList(); + private List buildStudents() { + List students = new ArrayList(); - Student student1 = new Student(); - student1.setId(1001); - student1.setName("John Smith"); - students.add(student1); + Student student1 = new Student(); + student1.setId(1001); + student1.setName("John Smith"); + student1.setGender('M'); + student1.setPercentage(Float.valueOf("80.45")); - Student student2 = new Student(); - student2.setId(1002); - student2.setName("Jane Williams"); - students.add(student2); + students.add(student1); - return students; - } + Student student2 = new Student(); + student2.setId(1002); + student2.setName("Jane Williams"); + student2.setGender('F'); + student2.setPercentage(Float.valueOf("60.25")); + + students.add(student2); + return students; + } } diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java index d34af3961e..d4d8ea1d6c 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java @@ -7,34 +7,54 @@ import javax.validation.constraints.NotNull; /** * - * Simple student POJO with two fields - id and name + * Simple student POJO with few fields * */ public class Student implements Serializable { - private static final long serialVersionUID = -8582553475226281591L; + private static final long serialVersionUID = -8582553475226281591L; - @NotNull(message = "Student ID is required.") - @Min(value = 1000, message = "Student ID must be atleast 4 digits.") - private Integer id; + @NotNull(message = "Student ID is required.") + @Min(value = 1000, message = "Student ID must be atleast 4 digits.") + private Integer id; - @NotNull(message = "Student Name is required.") - private String name; + @NotNull(message = "Student name is required.") + private String name; - public Integer getId() { - return id; - } + @NotNull(message = "Student gender is required.") + private Character gender; - public void setId(Integer id) { - this.id = id; - } + private Float percentage; - public String getName() { - return name; - } + public Integer getId() { + return id; + } - public void setName(String name) { - this.name = name; - } + public void setId(Integer id) { + this.id = id; + } + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Character getGender() { + return gender; + } + + public void setGender(Character gender) { + this.gender = gender; + } + + public Float getPercentage() { + return percentage; + } + + public void setPercentage(Float percentage) { + this.percentage = percentage; + } } diff --git a/spring-thymeleaf/src/main/resources/messages_en_US.properties b/spring-thymeleaf/src/main/resources/messages_en_US.properties index 0cfe16cd84..33295968e0 100644 --- a/spring-thymeleaf/src/main/resources/messages_en_US.properties +++ b/spring-thymeleaf/src/main/resources/messages_en_US.properties @@ -1,4 +1,9 @@ msg.id=ID msg.name=Name +msg.gender=Gender +msg.percent=Percentage welcome.message=Welcome Student !!! +msg.AddStudent=Add Student +msg.ListStudents=List Students +msg.Home=Home diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml index 38a4233c64..ef42557429 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml @@ -26,7 +26,7 @@ - + - org.springframework spring-web @@ -21,64 +18,53 @@ spring-webmvc ${org.springframework.version} - - javax.servlet javax.servlet-api 3.0.1 provided - javax.servlet jstl 1.2 runtime - org.springframework spring-aop ${org.springframework.version} - org.aspectj aspectjrt ${aspectj.version} - org.aspectj aspectjweaver ${aspectj.version} - org.slf4j slf4j-api ${org.slf4j.version} - org.slf4j slf4j-log4j12 ${org.slf4j.version} - - junit junit-dep ${junit.version} test - org.hamcrest hamcrest-core @@ -91,23 +77,30 @@ ${org.hamcrest.version} test - org.mockito mockito-core ${mockito.version} test - org.springframework spring-test ${org.springframework.version} test - + + + org.thymeleaf + thymeleaf-spring4 + ${thymeleaf.version} + + + org.thymeleaf + thymeleaf + ${thymeleaf.version} + - spring-mvc-java @@ -116,9 +109,7 @@ true - - org.apache.maven.plugins maven-compiler-plugin @@ -128,7 +119,10 @@ 1.8 - + + maven-resources-plugin + 2.7 + org.apache.maven.plugins maven-war-plugin @@ -137,7 +131,6 @@ false - org.apache.maven.plugins maven-surefire-plugin @@ -151,7 +144,6 @@ - org.codehaus.cargo cargo-maven2-plugin @@ -172,50 +164,46 @@ - + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + / + + - - 4.2.2.RELEASE 4.0.2.RELEASE - + 2.1.4.RELEASE 4.3.11.Final 5.1.36 - 1.7.12 1.1.3 - 5.2.1.Final - 18.0 3.4 - 1.3 4.11 1.10.19 - 4.4.1 4.5 - 2.4.1 - 3.3 2.6 2.18.1 2.7 1.4.15 - 1.8.7 - \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java b/spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java new file mode 100644 index 0000000000..3203296a17 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java @@ -0,0 +1,31 @@ +package org.baeldung.controller; + +import org.baeldung.model.UserDetails; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/") +public class UserController { + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String showForm(final Model model) { + final UserDetails user = new UserDetails(); + user.setFirstname("John"); + user.setLastname("Roy"); + user.setEmailId("John.Roy@gmail.com"); + model.addAttribute("user", user); + return "index"; + } + + @RequestMapping(value = "/processForm", method = RequestMethod.POST) + public String processForm(@ModelAttribute(value = "user") final UserDetails user, final Model model) { + // Insert userDetails into DB + model.addAttribute("name", user.getFirstname() + " " + user.getLastname()); + return "hello"; + } + +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java b/spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java new file mode 100644 index 0000000000..e6d1ad6b74 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java @@ -0,0 +1,24 @@ +package org.baeldung.dialect; + +import java.util.HashSet; +import java.util.Set; + +import org.baeldung.processor.NameProcessor; +import org.thymeleaf.dialect.AbstractDialect; +import org.thymeleaf.processor.IProcessor; + +public class CustomDialect extends AbstractDialect { + + @Override + public String getPrefix() { + return "custom"; + } + + @Override + public Set getProcessors() { + final Set processors = new HashSet(); + processors.add(new NameProcessor()); + return processors; + } + +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java b/spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java new file mode 100644 index 0000000000..d0b37fae8a --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java @@ -0,0 +1,32 @@ +package org.baeldung.model; + +public class UserDetails { + private String firstname; + private String lastname; + private String emailId; + + public String getFirstname() { + return firstname; + } + + public void setFirstname(final String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(final String lastname) { + this.lastname = lastname; + } + + public String getEmailId() { + return emailId; + } + + public void setEmailId(final String emailId) { + this.emailId = emailId; + } + +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java b/spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java new file mode 100644 index 0000000000..df9a4da7f0 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java @@ -0,0 +1,23 @@ +package org.baeldung.processor; + +import org.thymeleaf.Arguments; +import org.thymeleaf.dom.Element; +import org.thymeleaf.processor.attr.AbstractTextChildModifierAttrProcessor; + +public class NameProcessor extends AbstractTextChildModifierAttrProcessor { + + public NameProcessor() { + super("name"); + } + + @Override + protected String getText(final Arguments arguements, final Element elements, final String attributeName) { + return "Hello, " + elements.getAttributeValue(attributeName) + "!"; + } + + @Override + public int getPrecedence() { + return 1000; + } + +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java index 945c1794fb..50681e88f6 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java @@ -1,16 +1,28 @@ package org.baeldung.spring.web.config; +import java.util.HashSet; +import java.util.Set; + +import org.baeldung.dialect.CustomDialect; +import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Description; +import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; +import org.thymeleaf.dialect.IDialect; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @EnableWebMvc @Configuration +@ComponentScan("org.baeldung.controller") public class ClientWebConfig extends WebMvcConfigurerAdapter { public ClientWebConfig() { @@ -28,12 +40,49 @@ public class ClientWebConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - + /*final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); + bean.setSuffix(".jsp");*/ - return bean; + final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + + return viewResolver; } + + @Bean + @Description("Thymeleaf template resolver serving HTML 5") + public ServletContextTemplateResolver templateResolver() { + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } + + @Bean + @Description("Thymeleaf template engine with Spring integration") + public SpringTemplateEngine templateEngine() { + final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + final Set dialects = new HashSet<>(); + dialects.add(new CustomDialect()); + templateEngine.setAdditionalDialects(dialects); + return templateEngine; + } + + @Bean + @Description("Spring message resolver") + public MessageSource messageSource() { + final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + } \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/templates/footer.html b/spring-mvc-java/src/main/webapp/WEB-INF/templates/footer.html new file mode 100644 index 0000000000..f72d553303 --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/templates/footer.html @@ -0,0 +1,6 @@ + + + +
© 2013 Footer
+ + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/templates/hello.html b/spring-mvc-java/src/main/webapp/WEB-INF/templates/hello.html new file mode 100644 index 0000000000..1eddd85166 --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/templates/hello.html @@ -0,0 +1,14 @@ + + + + + + + Hi + John ! + Test +
© 2013 The Static + Templates
+ + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/templates/index.html b/spring-mvc-java/src/main/webapp/WEB-INF/templates/index.html new file mode 100644 index 0000000000..9b4159c193 --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/templates/index.html @@ -0,0 +1,36 @@ + + + + +Thymeleaf Spring Example + + + Hello John! +

+
Please confirm your details
+

+
+ + + + + + + + + + + + + + + + +
Firstname :
Lastname :
EmailId :
+
+ + \ No newline at end of file From 1e91b46d1e28b0c4899afa8ac00504b1a35ae4b5 Mon Sep 17 00:00:00 2001 From: vkadapa Date: Fri, 18 Dec 2015 06:46:29 +0530 Subject: [PATCH 021/309] Missed messages.properties --- spring-mvc-java/src/main/resources/messages_en.properties | 1 + 1 file changed, 1 insertion(+) create mode 100644 spring-mvc-java/src/main/resources/messages_en.properties diff --git a/spring-mvc-java/src/main/resources/messages_en.properties b/spring-mvc-java/src/main/resources/messages_en.properties new file mode 100644 index 0000000000..549024372b --- /dev/null +++ b/spring-mvc-java/src/main/resources/messages_en.properties @@ -0,0 +1 @@ +welcome.text=Hello \ No newline at end of file From 7fef26916994c488de0b515f5e3f930e846eaa4f Mon Sep 17 00:00:00 2001 From: vkadapa Date: Fri, 18 Dec 2015 07:14:51 +0530 Subject: [PATCH 022/309] Modified code to support both thymeleaf and existing viewResolvers --- .../spring/web/config/ClientWebConfig.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java index 50681e88f6..fe31e3581e 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java @@ -15,6 +15,8 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; import org.thymeleaf.dialect.IDialect; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; @@ -39,18 +41,23 @@ public class ClientWebConfig extends WebMvcConfigurerAdapter { } @Bean - public ViewResolver viewResolver() { - /*final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp");*/ - + public ViewResolver thymeleafViewResolver() { final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); - + viewResolver.setOrder(1); return viewResolver; } + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(0); + return bean; + } + @Bean @Description("Thymeleaf template resolver serving HTML 5") public ServletContextTemplateResolver templateResolver() { From 5aaeb7308a3618c2f8a372c1035ac3b0d411f4a5 Mon Sep 17 00:00:00 2001 From: vkadapa Date: Fri, 18 Dec 2015 15:51:12 +0530 Subject: [PATCH 023/309] Removed Tomcat Plugin from pom.xml, rename Userdetails to User and moved the controller to web --- spring-mvc-java/pom.xml | 8 --- .../model/{UserDetails.java => User.java} | 64 +++++++++---------- .../spring/web/config/ClientWebConfig.java | 2 - .../{ => web}/controller/UserController.java | 63 +++++++++--------- 4 files changed, 64 insertions(+), 73 deletions(-) rename spring-mvc-java/src/main/java/org/baeldung/model/{UserDetails.java => User.java} (92%) rename spring-mvc-java/src/main/java/org/baeldung/{ => web}/controller/UserController.java (54%) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index a9bbf71ba3..56054b0c47 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -164,14 +164,6 @@ - - org.apache.tomcat.maven - tomcat7-maven-plugin - 2.2 - - / - - diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java b/spring-mvc-java/src/main/java/org/baeldung/model/User.java similarity index 92% rename from spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java rename to spring-mvc-java/src/main/java/org/baeldung/model/User.java index d0b37fae8a..df549cd21d 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java +++ b/spring-mvc-java/src/main/java/org/baeldung/model/User.java @@ -1,32 +1,32 @@ -package org.baeldung.model; - -public class UserDetails { - private String firstname; - private String lastname; - private String emailId; - - public String getFirstname() { - return firstname; - } - - public void setFirstname(final String firstname) { - this.firstname = firstname; - } - - public String getLastname() { - return lastname; - } - - public void setLastname(final String lastname) { - this.lastname = lastname; - } - - public String getEmailId() { - return emailId; - } - - public void setEmailId(final String emailId) { - this.emailId = emailId; - } - -} +package org.baeldung.model; + +public class User { + private String firstname; + private String lastname; + private String emailId; + + public String getFirstname() { + return firstname; + } + + public void setFirstname(final String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(final String lastname) { + this.lastname = lastname; + } + + public String getEmailId() { + return emailId; + } + + public void setEmailId(final String emailId) { + this.emailId = emailId; + } + +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java index fe31e3581e..db57b4716b 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java @@ -6,7 +6,6 @@ import java.util.Set; import org.baeldung.dialect.CustomDialect; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import org.springframework.context.support.ResourceBundleMessageSource; @@ -24,7 +23,6 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @EnableWebMvc @Configuration -@ComponentScan("org.baeldung.controller") public class ClientWebConfig extends WebMvcConfigurerAdapter { public ClientWebConfig() { diff --git a/spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java b/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java similarity index 54% rename from spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java rename to spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java index 3203296a17..731424c336 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java +++ b/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java @@ -1,31 +1,32 @@ -package org.baeldung.controller; - -import org.baeldung.model.UserDetails; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@Controller -@RequestMapping("/") -public class UserController { - - @RequestMapping(value = "/", method = RequestMethod.GET) - public String showForm(final Model model) { - final UserDetails user = new UserDetails(); - user.setFirstname("John"); - user.setLastname("Roy"); - user.setEmailId("John.Roy@gmail.com"); - model.addAttribute("user", user); - return "index"; - } - - @RequestMapping(value = "/processForm", method = RequestMethod.POST) - public String processForm(@ModelAttribute(value = "user") final UserDetails user, final Model model) { - // Insert userDetails into DB - model.addAttribute("name", user.getFirstname() + " " + user.getLastname()); - return "hello"; - } - -} +package org.baeldung.web.controller; + +import org.baeldung.model.User; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/") +public class UserController { + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String showForm(final Model model) { + final User user = new User(); + user.setFirstname("John"); + user.setLastname("Roy"); + user.setEmailId("John.Roy@gmail.com"); + model.addAttribute("user", user); + return "index"; + } + + @RequestMapping(value = "/processForm", method = RequestMethod.POST) + public String processForm(@ModelAttribute(value = "user") final User user, + final Model model) { + // Insert User into DB + model.addAttribute("name", user.getFirstname() + " " + user.getLastname()); + return "hello"; + } + +} From 55b0827420ab29cafc6d0080703f02266e26a06f Mon Sep 17 00:00:00 2001 From: eugenp Date: Fri, 18 Dec 2015 13:14:30 +0200 Subject: [PATCH 024/309] minor cleanup --- spring-mvc-java/pom.xml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 56054b0c47..1a462fabaa 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -1,5 +1,4 @@ - + 4.0.0 org.baeldung spring-mvc-java @@ -101,6 +100,7 @@ ${thymeleaf.version} + spring-mvc-java @@ -109,6 +109,7 @@ true + org.apache.maven.plugins @@ -119,10 +120,12 @@ 1.8 + maven-resources-plugin 2.7 + org.apache.maven.plugins maven-war-plugin From 2ea5de304b19e47be4fb798cf26c53f36677be94 Mon Sep 17 00:00:00 2001 From: gmaipady Date: Sun, 20 Dec 2015 21:43:31 +0530 Subject: [PATCH 025/309] Fixed minor comments --- spring-thymeleaf/README.md | 20 ++++++++++++------- spring-thymeleaf/pom.xml | 20 +++++++++++++++++++ .../org/baeldung/thymeleaf/model/Student.java | 2 +- 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index ef86ae055a..8cb1c2e982 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -7,11 +7,17 @@ ### Build the Project -``` -mvn clean install -``` -Access sample pages using the URLs: -http://localhost:8080/spring-thymeleaf/ -http://localhost:8080/spring-thymeleaf/addStudent/ -http://localhost:8080/spring-thymeleaf/listStudents/ +mvn clean install + +### Run the Project +mvn cargo:run +- **note**: starts on port '8082' + +Access the pages using the URLs: + +http://localhost:8082/spring-thymeleaf/ +http://localhost:8082/spring-thymeleaf/addStudent/ +http://localhost:8082/spring-thymeleaf/listStudents/ + +The first URL is the home page of the application. The home page has links to the other two pages. diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 770f67d59c..1a8dff671e 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -22,6 +22,7 @@ 3.3 2.6 2.18.1 + 1.4.15 @@ -123,6 +124,25 @@ + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + 8082 + + + + diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java index d4d8ea1d6c..f21169dbcf 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java @@ -15,7 +15,7 @@ public class Student implements Serializable { private static final long serialVersionUID = -8582553475226281591L; @NotNull(message = "Student ID is required.") - @Min(value = 1000, message = "Student ID must be atleast 4 digits.") + @Min(value = 1000, message = "Student ID must be at least 4 digits.") private Integer id; @NotNull(message = "Student name is required.") From 8238c11c809e78f0c7b5dd0c91e51a14a36214b9 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 21 Dec 2015 11:34:42 +0200 Subject: [PATCH 026/309] maven upgrades --- apache-fop/pom.xml | 6 ++--- core-java-8/pom.xml | 4 ++-- core-java/pom.xml | 10 ++++---- gson/pom.xml | 8 +++---- guava/pom.xml | 8 +++---- handling-spring-static-resources/pom.xml | 8 +++---- httpclient/pom.xml | 8 +++---- jackson/pom.xml | 10 ++++---- mockito/pom.xml | 8 +++---- rest-testing/pom.xml | 10 ++++---- sandbox/pom.xml | 8 +++---- spring-all/pom.xml | 16 ++++++------- spring-exceptions/pom.xml | 16 ++++++------- spring-hibernate3/pom.xml | 16 ++++++------- spring-hibernate4/pom.xml | 16 ++++++------- spring-jpa/pom.xml | 14 +++++------ spring-mvc-java/pom.xml | 16 ++++++------- spring-mvc-no-xml/pom.xml | 8 +++---- spring-mvc-xml/pom.xml | 8 +++---- spring-rest/pom.xml | 18 +++++++------- spring-security-basic-auth/pom.xml | 16 ++++++------- .../pom.xml | 8 +++---- spring-security-mvc-custom/pom.xml | 16 ++++++------- spring-security-mvc-digest-auth/pom.xml | 16 ++++++------- spring-security-mvc-ldap/pom.xml | 14 +++++------ spring-security-mvc-login/pom.xml | 16 ++++++------- spring-security-mvc-session/pom.xml | 16 ++++++------- spring-security-rest-basic-auth/pom.xml | 22 ++++++++--------- spring-security-rest-custom/pom.xml | 16 ++++++------- spring-security-rest-digest-auth/pom.xml | 24 +++++++++---------- spring-security-rest-full/pom.xml | 18 +++++++------- spring-security-rest/pom.xml | 16 ++++++------- 32 files changed, 207 insertions(+), 207 deletions(-) diff --git a/apache-fop/pom.xml b/apache-fop/pom.xml index 13fc2257cf..95505f9374 100644 --- a/apache-fop/pom.xml +++ b/apache-fop/pom.xml @@ -37,7 +37,7 @@ junit - junit-dep + junit ${junit.version} test @@ -151,7 +151,7 @@ 5.1.34 - 2.4.4 + 2.5.5 1.7.9 @@ -166,7 +166,7 @@ 1.3 - 4.11 + 4.12 1.10.19 4.4 diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 9db2562fb4..07d3bcd146 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -98,14 +98,14 @@ - 1.7.12 + 1.7.13 1.0.13 5.1.3.Final - 18.0 + 19.0 3.4 diff --git a/core-java/pom.xml b/core-java/pom.xml index c6f2b32cd8..b439b41f22 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -79,7 +79,7 @@ junit - junit-dep + junit ${junit.version} test @@ -152,22 +152,22 @@ 5.1.35 - 2.4.4 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/gson/pom.xml b/gson/pom.xml index 500d14c40c..c0640abcbf 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -53,7 +53,7 @@ junit - junit-dep + junit ${junit.version} test @@ -124,19 +124,19 @@ 2.3 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/guava/pom.xml b/guava/pom.xml index 78c5a14e41..2b07be71bf 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -34,7 +34,7 @@ junit - junit-dep + junit ${junit.version} test @@ -102,19 +102,19 @@ 5.1.35 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml index 67591e1844..677d705932 100644 --- a/handling-spring-static-resources/pom.xml +++ b/handling-spring-static-resources/pom.xml @@ -190,22 +190,22 @@ - 2.4.4 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/httpclient/pom.xml b/httpclient/pom.xml index a6df3842fd..0098c40d52 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -89,7 +89,7 @@ junit - junit-dep + junit ${junit.version} test @@ -157,19 +157,19 @@ 5.1.35 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/jackson/pom.xml b/jackson/pom.xml index b2c2465436..9996330361 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -72,7 +72,7 @@ junit - junit-dep + junit ${junit.version} test @@ -140,22 +140,22 @@ 5.1.35 - 2.4.4 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/mockito/pom.xml b/mockito/pom.xml index a97a017c5c..a73eea7647 100644 --- a/mockito/pom.xml +++ b/mockito/pom.xml @@ -28,7 +28,7 @@ junit - junit-dep + junit ${junit.version} test @@ -96,19 +96,19 @@ 5.1.35 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/rest-testing/pom.xml b/rest-testing/pom.xml index 488a8a3cdb..b8fdc50a01 100644 --- a/rest-testing/pom.xml +++ b/rest-testing/pom.xml @@ -78,7 +78,7 @@ junit - junit-dep + junit ${junit.version} test @@ -141,22 +141,22 @@ 4.1.5.RELEASE - 2.4.4 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/sandbox/pom.xml b/sandbox/pom.xml index 55cb9f11f2..95b2df2cb3 100644 --- a/sandbox/pom.xml +++ b/sandbox/pom.xml @@ -73,7 +73,7 @@ junit - junit-dep + junit ${junit.version} test @@ -141,10 +141,10 @@ 5.1.35 - 2.4.4 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 @@ -156,7 +156,7 @@ 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 0551abe5a5..16ff340d81 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -127,7 +127,7 @@ junit - junit-dep + junit ${junit.version} test @@ -221,29 +221,29 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 3.20.0-GA 1.2 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index f4c0acec85..324b7475b3 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -105,7 +105,7 @@ junit - junit-dep + junit ${junit.version} test @@ -203,30 +203,30 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 3.20.0-GA 1.2 4.3.11.Final - 5.1.36 + 5.1.37 7.0.42 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-hibernate3/pom.xml b/spring-hibernate3/pom.xml index 29682a97c3..d88358168f 100644 --- a/spring-hibernate3/pom.xml +++ b/spring-hibernate3/pom.xml @@ -73,7 +73,7 @@ junit - junit-dep + junit ${junit.version} test @@ -162,29 +162,29 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 3.20.0-GA 3.6.10.Final - 5.1.36 + 5.1.37 7.0.47 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml index 3b0e3b6a00..c8ab1866e2 100644 --- a/spring-hibernate4/pom.xml +++ b/spring-hibernate4/pom.xml @@ -80,7 +80,7 @@ junit - junit-dep + junit ${junit.version} test @@ -169,29 +169,29 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 3.20.0-GA 4.3.11.Final - 5.1.36 + 5.1.37 7.0.42 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index f065fe1a81..63d97c337b 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -85,7 +85,7 @@ junit - junit-dep + junit ${junit.version} test @@ -174,29 +174,29 @@ - 4.2.2.RELEASE + 4.2.4.RELEASE 4.0.2.RELEASE 3.20.0-GA 4.3.11.Final - 5.1.36 + 5.1.37 1.7.2.RELEASE - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 1a462fabaa..ef6ac59dd4 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -60,7 +60,7 @@ junit - junit-dep + junit ${junit.version} test @@ -171,23 +171,23 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 2.1.4.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 4.5 diff --git a/spring-mvc-no-xml/pom.xml b/spring-mvc-no-xml/pom.xml index ecb159f82e..da71a699db 100644 --- a/spring-mvc-no-xml/pom.xml +++ b/spring-mvc-no-xml/pom.xml @@ -67,7 +67,7 @@ junit - junit-dep + junit ${junit.version} test @@ -144,15 +144,15 @@ - 4.2.2.RELEASE + 4.2.4.RELEASE - 1.7.12 + 1.7.13 1.1.3 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 378d2be339..896d744e99 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -73,7 +73,7 @@ junit - junit-dep + junit ${junit.version} test @@ -146,15 +146,15 @@ - 4.2.2.RELEASE + 4.2.4.RELEASE - 1.7.12 + 1.7.13 1.1.3 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 7bc0905542..e2cf9d7c3e 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -128,7 +128,7 @@ junit - junit-dep + junit ${junit.version} test @@ -229,27 +229,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 2.5.1 + 2.5.5 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 @@ -258,7 +258,7 @@ 2.4.1 - 1.7.12 + 1.7.13 1.1.3 diff --git a/spring-security-basic-auth/pom.xml b/spring-security-basic-auth/pom.xml index 72914dd0d5..6abefbd7ec 100644 --- a/spring-security-basic-auth/pom.xml +++ b/spring-security-basic-auth/pom.xml @@ -130,7 +130,7 @@ junit - junit-dep + junit ${junit.version} test @@ -225,27 +225,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-login-and-registration/pom.xml b/spring-security-login-and-registration/pom.xml index df7e639660..ffa8be484b 100644 --- a/spring-security-login-and-registration/pom.xml +++ b/spring-security-login-and-registration/pom.xml @@ -235,10 +235,10 @@ 1.7 4.1.6.RELEASE - 4.0.2.RELEASE + 4.0.3.RELEASE - 1.7.12 + 1.7.13 1.1.3 @@ -251,10 +251,10 @@ 1.8.0.RELEASE - 18.0 + 19.0 - 1.4.16 + 1.4.17 3.3 2.6 2.18.1 diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index d6ac323104..2e2d434fb2 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -135,7 +135,7 @@ junit - junit-dep + junit ${junit.version} test @@ -230,27 +230,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.5 diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index f7ca086881..2dce2835f5 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -130,7 +130,7 @@ junit - junit-dep + junit ${junit.version} test @@ -225,27 +225,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index a11bc4c374..00165bd740 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -87,27 +87,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index 1f824f5003..3d76fcb22f 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -127,7 +127,7 @@ junit - junit-dep + junit ${junit.version} test @@ -222,27 +222,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index f6cd575d57..c9a919e684 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -135,7 +135,7 @@ junit - junit-dep + junit ${junit.version} test @@ -230,27 +230,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.5 diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index a6d5b36381..1fbeeaa9a9 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -189,7 +189,7 @@ junit - junit-dep + junit ${junit.version} test @@ -287,40 +287,40 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 4.4.3 + 4.4.4 4.5.1 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 - 2.6.0 + 2.8.0 3.3 2.6 2.19 - 1.4.16 + 1.4.17 diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index cfe3afbc54..20984ba6dd 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -140,7 +140,7 @@ junit - junit-dep + junit ${junit.version} test @@ -258,27 +258,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-rest-digest-auth/pom.xml b/spring-security-rest-digest-auth/pom.xml index 1bc107dda2..d20220ac36 100644 --- a/spring-security-rest-digest-auth/pom.xml +++ b/spring-security-rest-digest-auth/pom.xml @@ -177,7 +177,7 @@ junit - junit-dep + junit ${junit.version} test @@ -274,43 +274,43 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 4.4.3 + 4.4.4 4.5.1 - 1.7.12 + 1.7.13 1.1.3 - 2.5.1 + 2.5.5 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 - 2.6.0 + 2.8.0 3.3 2.6 2.19 - 1.4.16 + 1.4.17 diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index 04ade99195..bed716897b 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -242,7 +242,7 @@ junit - junit-dep + junit ${junit.version} test @@ -426,32 +426,32 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 1.7.2.RELEASE - 2.5.1 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 4fd64b5289..42381bf607 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -142,7 +142,7 @@ junit - junit-dep + junit ${junit.version} test @@ -250,27 +250,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 From 30f53b76eecd399deff96e41bc932253406d19dc Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 21 Dec 2015 11:37:37 +0200 Subject: [PATCH 027/309] new set test --- .../org/baeldung/guava/GuavaCollectionTypesTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java index 26d3fa90ca..2eb5141f8d 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java @@ -148,6 +148,15 @@ public class GuavaCollectionTypesTest { assertThat(intersection, containsInAnyOrder('b', 'c')); } + @Test + public void whenCalculatingSetSymetricDifference_thenCorrect() { + final Set first = ImmutableSet.of('a', 'b', 'c'); + final Set second = ImmutableSet.of('b', 'c', 'd'); + + final Set intersection = Sets.symmetricDifference(first, second); + assertThat(intersection, containsInAnyOrder('a', 'd')); + } + @Test public void whenCalculatingPowerSet_thenCorrect() { final Set chars = ImmutableSet.of('a', 'b'); From f0284f3fbaf43992afb5d66d9dc60784f70fa493 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 21 Dec 2015 11:53:17 +0200 Subject: [PATCH 028/309] fixes - spelling and security work --- .../org/baeldung/guava/GuavaCollectionTypesTest.java | 2 +- .../org/baeldung/security/MyUserDetailsService.java | 10 +++------- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java index 2eb5141f8d..9c38afbcc2 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java @@ -149,7 +149,7 @@ public class GuavaCollectionTypesTest { } @Test - public void whenCalculatingSetSymetricDifference_thenCorrect() { + public void whenCalculatingSetSymmetricDifference_thenCorrect() { final Set first = ImmutableSet.of('a', 'b', 'c'); final Set second = ImmutableSet.of('b', 'c', 'd'); diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java index 567fa7717d..d4b77878be 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -1,13 +1,11 @@ package org.baeldung.security; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; import javax.servlet.http.HttpServletRequest; -import org.baeldung.persistence.dao.RoleRepository; import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.model.Privilege; import org.baeldung.persistence.model.Role; @@ -28,9 +26,6 @@ public class MyUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; - @Autowired - private RoleRepository roleRepository; - @Autowired private LoginAttemptService loginAttemptService; @@ -53,7 +48,7 @@ public class MyUserDetailsService implements UserDetailsService { try { final User user = userRepository.findByEmail(email); if (user == null) { - return new org.springframework.security.core.userdetails.User(" ", " ", true, true, true, true, getAuthorities(Arrays.asList(roleRepository.findByName("ROLE_USER")))); + throw new UsernameNotFoundException("No user found with username: " + email); } return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, getAuthorities(user.getRoles())); @@ -90,8 +85,9 @@ public class MyUserDetailsService implements UserDetailsService { private String getClientIP() { final String xfHeader = request.getHeader("X-Forwarded-For"); - if (xfHeader == null) + if (xfHeader == null) { return request.getRemoteAddr(); + } return xfHeader.split(",")[0]; } } From b4738d8cd6440a0d2710d2d176c98b7cd5dfe6ad Mon Sep 17 00:00:00 2001 From: oborkovskyi Date: Mon, 21 Dec 2015 13:40:09 +0200 Subject: [PATCH 029/309] Removed extra files --- guava18/.classpath | 36 ------------------- ...e.wst.jsdt.core.javascriptValidator.launch | 7 ---- guava18/.gitignore | 13 ------- guava18/.project | 36 ------------------- guava18/.springBeans | 14 -------- 5 files changed, 106 deletions(-) delete mode 100644 guava18/.classpath delete mode 100644 guava18/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch delete mode 100644 guava18/.gitignore delete mode 100644 guava18/.project delete mode 100644 guava18/.springBeans diff --git a/guava18/.classpath b/guava18/.classpath deleted file mode 100644 index 8ebf6d9c31..0000000000 --- a/guava18/.classpath +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/guava18/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/guava18/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/guava18/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/guava18/.gitignore b/guava18/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/guava18/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/guava18/.project b/guava18/.project deleted file mode 100644 index 829dc83809..0000000000 --- a/guava18/.project +++ /dev/null @@ -1,36 +0,0 @@ - - - guava - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - - diff --git a/guava18/.springBeans b/guava18/.springBeans deleted file mode 100644 index a79097f40d..0000000000 --- a/guava18/.springBeans +++ /dev/null @@ -1,14 +0,0 @@ - - - 1 - - - - - - - src/main/webapp/WEB-INF/api-servlet.xml - - - - From 6c83190bdc457d5e39e95d1cacf0f8c016778c9f Mon Sep 17 00:00:00 2001 From: oborkovskyi Date: Mon, 21 Dec 2015 13:52:26 +0200 Subject: [PATCH 030/309] Splitted test to grouped by methods used tests. --- .../baeldung/guava/FluentIterableTest.java | 80 ++++++++ .../baeldung/guava/GuavaMiscUtilsTest.java | 41 ++++ .../java/com/baeldung/guava/GuavaTest.java | 177 ------------------ .../com/baeldung/guava/MoreExecutorsTest.java | 51 +++++ .../com/baeldung/guava/MoreObjectsTest.java | 33 ++++ 5 files changed, 205 insertions(+), 177 deletions(-) create mode 100644 guava18/src/test/java/com/baeldung/guava/FluentIterableTest.java create mode 100644 guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java delete mode 100644 guava18/src/test/java/com/baeldung/guava/GuavaTest.java create mode 100644 guava18/src/test/java/com/baeldung/guava/MoreExecutorsTest.java create mode 100644 guava18/src/test/java/com/baeldung/guava/MoreObjectsTest.java diff --git a/guava18/src/test/java/com/baeldung/guava/FluentIterableTest.java b/guava18/src/test/java/com/baeldung/guava/FluentIterableTest.java new file mode 100644 index 0000000000..82552fca8f --- /dev/null +++ b/guava18/src/test/java/com/baeldung/guava/FluentIterableTest.java @@ -0,0 +1,80 @@ +package com.baeldung.guava; + +import com.baeldung.guava.entity.User; +import com.google.common.base.Functions; +import com.google.common.base.Joiner; +import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.CoreMatchers.equalTo; + +public class FluentIterableTest { + + private static final int ADULT_AGE = 18; + + @Test + public void whenFilteringByAge_shouldFilterOnlyAdultUsers() throws Exception { + List users = new ArrayList<>(); + users.add(new User(1L, "John", 45)); + users.add(new User(2L, "Michael", 27)); + users.add(new User(3L, "Max", 16)); + users.add(new User(4L, "Bob", 10)); + users.add(new User(5L, "Bill", 65)); + + Predicate byAge = input -> input.getAge() > ADULT_AGE; + + List results = FluentIterable.from(users) + .filter(byAge) + .transform(Functions.toStringFunction()) + .toList(); + + Assert.assertThat(results.size(), equalTo(3)); + } + + @Test + public void whenCreatingFluentIterableFromArray_shouldContainAllUsers() throws Exception { + User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; + FluentIterable users = FluentIterable.of(usersArray); + + Assert.assertThat(users.size(), equalTo(2)); + } + + @Test + public void whenAppendingElementsToFluentIterable_shouldContainAllUsers() throws Exception { + User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; + + FluentIterable users = FluentIterable.of(usersArray).append( + new User(3L, "Bob", 23), + new User(4L, "Bill", 17) + ); + + Assert.assertThat(users.size(), equalTo(4)); + } + + @Test + public void whenAppendingListToFluentIterable_shouldContainAllUsers() throws Exception { + User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; + + List usersList = new ArrayList<>(); + usersList.add(new User(3L, "David", 32)); + + FluentIterable users = FluentIterable.of(usersArray).append(usersList); + + Assert.assertThat(users.size(), equalTo(3)); + } + + @Test + public void whenJoiningFluentIterableElements_shouldOutputAllUsers() throws Exception { + User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; + + FluentIterable users = FluentIterable.of(usersArray); + + Assert.assertThat(users.join(Joiner.on("; ")), + equalTo("User{id=1, name=John, age=45}; User{id=2, name=Max, age=15}")); + } +} \ No newline at end of file diff --git a/guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java new file mode 100644 index 0000000000..db82ea6da8 --- /dev/null +++ b/guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java @@ -0,0 +1,41 @@ +package com.baeldung.guava; + +import com.google.common.hash.HashCode; +import com.google.common.hash.Hashing; +import com.google.common.net.InetAddresses; +import org.junit.Assert; +import org.junit.Test; + +import java.net.InetAddress; +import java.util.concurrent.ConcurrentHashMap; + +import static org.hamcrest.CoreMatchers.equalTo; + +public class GuavaMiscUtilsTest { + @Test + public void whenHashingData_shouldReturnCorrectHashCode() throws Exception { + int receivedData = 123; + + HashCode hashCode = Hashing.crc32c().hashInt(receivedData); + Assert.assertThat(hashCode.toString(), equalTo("495be649")); + } + + @Test + public void whenDecrementingIpAddress_shouldReturnOneLessIpAddress() throws Exception { + InetAddress address = InetAddress.getByName("127.0.0.5"); + InetAddress decrementedAddress = InetAddresses.decrement(address); + + Assert.assertThat(decrementedAddress.toString(), equalTo("/127.0.0.4")); + } + + @Test + public void whenExecutingRunnableInThread_shouldLogThreadExecution() throws Exception { + ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); + Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); + + Thread t = new Thread(logThreadRun); + t.run(); + + Assert.assertTrue(threadExecutions.get("main")); + } +} diff --git a/guava18/src/test/java/com/baeldung/guava/GuavaTest.java b/guava18/src/test/java/com/baeldung/guava/GuavaTest.java deleted file mode 100644 index 5d1d1c074a..0000000000 --- a/guava18/src/test/java/com/baeldung/guava/GuavaTest.java +++ /dev/null @@ -1,177 +0,0 @@ -import com.baeldung.guava.entity.Administrator; -import com.baeldung.guava.entity.Player; -import com.baeldung.guava.entity.User; -import com.google.common.base.Functions; -import com.google.common.base.Joiner; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; -import com.google.common.hash.HashCode; -import com.google.common.hash.Hashing; -import com.google.common.net.InetAddresses; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; -import org.junit.Assert; -import org.junit.Test; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.*; - -import static org.hamcrest.CoreMatchers.equalTo; - -public class GuavaTest { - - private static final int ADULT_AGE = 18; - - @Test - public void whenToString_shouldIncludeAllFields() throws Exception { - User user = new User(12L, "John Doe", 25); - - Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}")); - } - - @Test - public void whenPlayerToString_shouldCallParentToString() throws Exception { - User user = new Player(12L, "John Doe", 25); - - Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}")); - } - - @Test - public void whenAdministratorToString_shouldExecuteAdministratorToString() throws Exception { - User user = new Administrator(12L, "John Doe", 25); - - Assert.assertThat(user.toString(), equalTo("Administrator{id=12, name=John Doe, age=25}")); - } - - @Test - public void whenFilteringByAge_shouldFilterOnlyAdultUsers() throws Exception { - List users = new ArrayList<>(); - users.add(new User(1L, "John", 45)); - users.add(new User(2L, "Michael", 27)); - users.add(new User(3L, "Max", 16)); - users.add(new User(4L, "Bob", 10)); - users.add(new User(5L, "Bill", 65)); - - Predicate byAge = input -> input.getAge() > ADULT_AGE; - - List results = FluentIterable.from(users) - .filter(byAge) - .transform(Functions.toStringFunction()) - .toList(); - - Assert.assertThat(results.size(), equalTo(3)); - } - - @Test - public void whenCreatingFluentIterableFromArray_shouldContainAllUsers() throws Exception { - User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)} ; - FluentIterable users = FluentIterable.of(usersArray); - - Assert.assertThat(users.size(), equalTo(2)); - } - - @Test - public void whenAppendingElementsToFluentIterable_shouldContainAllUsers() throws Exception { - User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; - - FluentIterable users = FluentIterable.of(usersArray).append( - new User(3L, "Bob", 23), - new User(4L, "Bill", 17) - ); - - Assert.assertThat(users.size(), equalTo(4)); - } - - @Test - public void whenAppendingListToFluentIterable_shouldContainAllUsers() throws Exception { - User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; - - List usersList = new ArrayList<>(); - usersList.add(new User(3L, "David", 32)); - - FluentIterable users = FluentIterable.of(usersArray).append(usersList); - - Assert.assertThat(users.size(), equalTo(3)); - } - - @Test - public void whenJoiningFluentIterableElements_shouldOutputAllUsers() throws Exception { - User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; - - FluentIterable users = FluentIterable.of(usersArray); - - Assert.assertThat(users.join(Joiner.on("; ")), - equalTo("User{id=1, name=John, age=45}; User{id=2, name=Max, age=15}")); - } - - @Test - public void whenHashingData_shouldReturnCorrectHashCode() throws Exception { - int receivedData = 123; - - HashCode hashCode = Hashing.crc32c().hashInt(receivedData); - Assert.assertThat(hashCode.toString(), equalTo("495be649")); - } - - @Test - public void whenDecrementingIpAddress_shouldReturnOneLessIpAddress() throws Exception { - InetAddress address = InetAddress.getByName("127.0.0.5"); - InetAddress decrementedAddress = InetAddresses.decrement(address); - - Assert.assertThat(decrementedAddress.toString(), equalTo("/127.0.0.4")); - - } - - @Test - public void whenExecutingRunnableInThread_shouldLogThreadExecution() throws Exception { - ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); - Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); - - Thread t = new Thread(logThreadRun); - t.run(); - - Assert.assertTrue(threadExecutions.get("main")); - } - - @Test - public void whenExecutingRunnableInThreadPool_shouldLogAllThreadsExecutions() throws Exception { - ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); - - Runnable logThreadRun= () -> threadExecutions.put(Thread.currentThread().getName(), true); - - ExecutorService executorService = Executors.newFixedThreadPool(2); - executorService.submit(logThreadRun); - executorService.submit(logThreadRun); - executorService.shutdown(); - - executorService.awaitTermination(100, TimeUnit.MILLISECONDS); - - Assert.assertTrue(threadExecutions.get("pool-1-thread-1")); - Assert.assertTrue(threadExecutions.get("pool-1-thread-2")); - } - - @Test - public void whenExecutingRunnableInDirectExecutor_shouldLogThreadExecution() throws Exception { - ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); - - Runnable logThreadRun= () -> threadExecutions.put(Thread.currentThread().getName(), true); - - Executor executor = MoreExecutors.directExecutor(); - executor.execute(logThreadRun); - - Assert.assertTrue(threadExecutions.get("main")); - } - - @Test - public void whenExecutingRunnableInListeningExecutor_shouldLogThreadExecution() throws Exception { - ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); - - Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); - - ListeningExecutorService executor = MoreExecutors.newDirectExecutorService(); - executor.execute(logThreadRun); - - Assert.assertTrue(threadExecutions.get("main")); - } -} \ No newline at end of file diff --git a/guava18/src/test/java/com/baeldung/guava/MoreExecutorsTest.java b/guava18/src/test/java/com/baeldung/guava/MoreExecutorsTest.java new file mode 100644 index 0000000000..ec173499f1 --- /dev/null +++ b/guava18/src/test/java/com/baeldung/guava/MoreExecutorsTest.java @@ -0,0 +1,51 @@ +package com.baeldung.guava; + +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import org.junit.Assert; +import org.junit.Test; + +import java.util.concurrent.*; + +public class MoreExecutorsTest { + @Test + public void whenExecutingRunnableInThreadPool_shouldLogAllThreadsExecutions() throws Exception { + ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); + + Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); + + ExecutorService executorService = Executors.newFixedThreadPool(2); + executorService.submit(logThreadRun); + executorService.submit(logThreadRun); + executorService.shutdown(); + + executorService.awaitTermination(100, TimeUnit.MILLISECONDS); + + Assert.assertTrue(threadExecutions.get("pool-1-thread-1")); + Assert.assertTrue(threadExecutions.get("pool-1-thread-2")); + } + + @Test + public void whenExecutingRunnableInDirectExecutor_shouldLogThreadExecution() throws Exception { + ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); + + Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); + + Executor executor = MoreExecutors.directExecutor(); + executor.execute(logThreadRun); + + Assert.assertTrue(threadExecutions.get("main")); + } + + @Test + public void whenExecutingRunnableInListeningExecutor_shouldLogThreadExecution() throws Exception { + ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); + + Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); + + ListeningExecutorService executor = MoreExecutors.newDirectExecutorService(); + executor.execute(logThreadRun); + + Assert.assertTrue(threadExecutions.get("main")); + } +} diff --git a/guava18/src/test/java/com/baeldung/guava/MoreObjectsTest.java b/guava18/src/test/java/com/baeldung/guava/MoreObjectsTest.java new file mode 100644 index 0000000000..5e46b5aba9 --- /dev/null +++ b/guava18/src/test/java/com/baeldung/guava/MoreObjectsTest.java @@ -0,0 +1,33 @@ +package com.baeldung.guava; + +import com.baeldung.guava.entity.Administrator; +import com.baeldung.guava.entity.Player; +import com.baeldung.guava.entity.User; +import org.junit.Assert; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.equalTo; + +public class MoreObjectsTest { + + @Test + public void whenToString_shouldIncludeAllFields() throws Exception { + User user = new User(12L, "John Doe", 25); + + Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}")); + } + + @Test + public void whenPlayerToString_shouldCallParentToString() throws Exception { + User user = new Player(12L, "John Doe", 25); + + Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}")); + } + + @Test + public void whenAdministratorToString_shouldExecuteAdministratorToString() throws Exception { + User user = new Administrator(12L, "John Doe", 25); + + Assert.assertThat(user.toString(), equalTo("Administrator{id=12, name=John Doe, age=25}")); + } +} From bb6166986e993a66172f73142057ed9dbed93aaf Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 22 Dec 2015 17:43:44 +0200 Subject: [PATCH 031/309] add some gson deserialization examples --- .../baeldung/gson/deserialization/Foo.java | 26 ++++++++++++------ .../deserialization/FooInstanceCreator.java | 14 ++++++++++ .../gson/deserialization/FooWithInner.java | 24 +++++++++++++++++ .../test/GsonDeserializationTest.java | 27 +++++++++++++++++++ 4 files changed, 83 insertions(+), 8 deletions(-) create mode 100644 gson/src/test/java/org/baeldung/gson/deserialization/FooInstanceCreator.java create mode 100644 gson/src/test/java/org/baeldung/gson/deserialization/FooWithInner.java diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java b/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java index 64720f63f9..84f8aaef13 100644 --- a/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java +++ b/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java @@ -9,6 +9,10 @@ public class Foo { this.stringValue = stringValue; } + public Foo(final String stringValue) { + this.stringValue = stringValue; + } + public Foo() { super(); } @@ -19,27 +23,33 @@ public class Foo { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + intValue; - result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode()); + result = (prime * result) + intValue; + result = (prime * result) + ((stringValue == null) ? 0 : stringValue.hashCode()); return result; } @Override public boolean equals(final Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } final Foo other = (Foo) obj; - if (intValue != other.intValue) + if (intValue != other.intValue) { return false; + } if (stringValue == null) { - if (other.stringValue != null) + if (other.stringValue != null) { return false; - } else if (!stringValue.equals(other.stringValue)) + } + } else if (!stringValue.equals(other.stringValue)) { return false; + } return true; } diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/FooInstanceCreator.java b/gson/src/test/java/org/baeldung/gson/deserialization/FooInstanceCreator.java new file mode 100644 index 0000000000..4df3986ec3 --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/deserialization/FooInstanceCreator.java @@ -0,0 +1,14 @@ +package org.baeldung.gson.deserialization; + +import java.lang.reflect.Type; + +import com.google.gson.InstanceCreator; + +public class FooInstanceCreator implements InstanceCreator { + + @Override + public Foo createInstance(Type type) { + return new Foo("sample"); + } + +} diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/FooWithInner.java b/gson/src/test/java/org/baeldung/gson/deserialization/FooWithInner.java new file mode 100644 index 0000000000..705e534e77 --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/deserialization/FooWithInner.java @@ -0,0 +1,24 @@ +package org.baeldung.gson.deserialization; + +public class FooWithInner { + public int intValue; + public String stringValue; + public InnerFoo innerFoo; + + public FooWithInner(int intValue, String stringValue, String name) { + super(); + this.intValue = intValue; + this.stringValue = stringValue; + this.innerFoo = new InnerFoo(name); + } + + public class InnerFoo { + public String name; + + public InnerFoo(String name) { + super(); + this.name = name; + } + + } +} diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java b/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java index 342b3096d7..072a25e749 100644 --- a/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java +++ b/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java @@ -12,6 +12,8 @@ import java.util.Collection; import org.baeldung.gson.deserialization.Foo; import org.baeldung.gson.deserialization.FooDeserializerFromJsonWithDifferentFields; +import org.baeldung.gson.deserialization.FooInstanceCreator; +import org.baeldung.gson.deserialization.FooWithInner; import org.baeldung.gson.deserialization.GenericFoo; import org.junit.Test; @@ -108,4 +110,29 @@ public class GsonDeserializationTest { assertEquals(targetObject.stringValue, "seven"); } + // new examples + + @Test + public void whenDeserializingToNestedObjects_thenCorrect() { + final String json = "{\"intValue\":1,\"stringValue\":\"one\",\"innerFoo\":{\"name\":\"inner\"}}"; + + final FooWithInner targetObject = new Gson().fromJson(json, FooWithInner.class); + + assertEquals(targetObject.intValue, 1); + assertEquals(targetObject.stringValue, "one"); + assertEquals(targetObject.innerFoo.name, "inner"); + } + + @Test + public void whenDeserializingUsingInstanceCreator_thenCorrect() { + final String json = "{\"intValue\":1}"; + + final GsonBuilder gsonBldr = new GsonBuilder(); + gsonBldr.registerTypeAdapter(Foo.class, new FooInstanceCreator()); + final Foo targetObject = gsonBldr.create().fromJson(json, Foo.class); + + assertEquals(targetObject.intValue, 1); + assertEquals(targetObject.stringValue, "sample"); + } + } From b7bbd201557feeaa79e129c5284234e15687a71d Mon Sep 17 00:00:00 2001 From: Devendra Desale Date: Wed, 23 Dec 2015 14:17:31 +0530 Subject: [PATCH 032/309] updated header to csv --- .../org/baeldung/spring_batch_intro/App.java | 2 +- .../spring_batch_intro/SpringBatchConfig.java | 1 + .../src/main/resources/input/record.csv | 1 + .../src/main/resources/spring-batch-intro.xml | 31 +++++++------------ spring-batch-intro/xml/output.xml | 2 +- 5 files changed, 16 insertions(+), 21 deletions(-) diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java index db963fff20..d6af37595c 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java @@ -27,7 +27,7 @@ public class App { try { JobExecution execution = jobLauncher.run(job, new JobParameters()); System.out.println("Job Status : " + execution.getStatus()); - System.out.println("Job completed"); + System.out.println("Job succeeded"); } catch (Exception e) { e.printStackTrace(); System.out.println("Job failed"); diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java index f0e3b364b6..a024cbc04e 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java @@ -50,6 +50,7 @@ public class SpringBatchConfig { DefaultLineMapper lineMapper = new DefaultLineMapper(); lineMapper.setLineTokenizer(tokenizer); lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); + reader.setLinesToSkip(1); reader.setLineMapper(lineMapper); return reader; } diff --git a/spring-batch-intro/src/main/resources/input/record.csv b/spring-batch-intro/src/main/resources/input/record.csv index 3a1437eed5..e554becb2a 100644 --- a/spring-batch-intro/src/main/resources/input/record.csv +++ b/spring-batch-intro/src/main/resources/input/record.csv @@ -1,3 +1,4 @@ +username, user_id, transaction_date, transaction_amount devendra, 1234, 31/10/2015, 10000 john, 2134, 3/12/2015, 12321 robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch-intro/src/main/resources/spring-batch-intro.xml b/spring-batch-intro/src/main/resources/spring-batch-intro.xml index 3b1f11521f..93606d232f 100644 --- a/spring-batch-intro/src/main/resources/spring-batch-intro.xml +++ b/spring-batch-intro/src/main/resources/spring-batch-intro.xml @@ -1,18 +1,15 @@ - + http://www.springframework.org/schema/batch/spring-batch-3.0.xsd + http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans-4.2.xsd +"> - - + - @@ -20,23 +17,21 @@ + value="username,userid,transaction_date,transaction_amount" /> - + - + - + @@ -45,13 +40,11 @@ - org.baeldung.spring_batch_intro.model.Transaction - + org.baeldung.spring_batch_intro.model.Transaction - diff --git a/spring-batch-intro/xml/output.xml b/spring-batch-intro/xml/output.xml index 9e57fa38f2..acf4969341 100644 --- a/spring-batch-intro/xml/output.xml +++ b/spring-batch-intro/xml/output.xml @@ -1 +1 @@ -10000.02015-10-31T00:00:00+08:001234devendra12321.02015-12-03T00:00:00+08:002134john23411.02015-02-02T00:00:00+08:002134robin \ No newline at end of file +10000.02015-10-31T00:00:00+05:301234devendra12321.02015-12-03T00:00:00+05:302134john23411.02015-02-02T00:00:00+05:302134robin \ No newline at end of file From 62fd1e6eda38346f8a02481767953d0e52907767 Mon Sep 17 00:00:00 2001 From: eugenp Date: Thu, 24 Dec 2015 11:39:47 +0200 Subject: [PATCH 033/309] minor cleanup --- spring-data-cassandra/.classpath | 31 +++++++ spring-data-cassandra/.project | 29 ++++++ .../cassandra/config/CassandraConfig.java | 6 +- .../spring/data/cassandra/model/Book.java | 22 +++-- .../cassandra/repository/BookRepository.java | 2 + .../BookRepositoryIntegrationTest.java | 63 +++++++------ .../repository/CQLQueriesIntegrationTest.java | 73 ++++++++------- .../CassandraTemplateIntegrationTest.java | 88 ++++++++++--------- spring-data-mongodb/.classpath | 37 ++++++++ spring-data-mongodb/.project | 29 ++++++ spring-mvc-java/pom.xml | 4 +- 11 files changed, 269 insertions(+), 115 deletions(-) create mode 100644 spring-data-cassandra/.classpath create mode 100644 spring-data-cassandra/.project create mode 100644 spring-data-mongodb/.classpath create mode 100644 spring-data-mongodb/.project diff --git a/spring-data-cassandra/.classpath b/spring-data-cassandra/.classpath new file mode 100644 index 0000000000..698778fef3 --- /dev/null +++ b/spring-data-cassandra/.classpath @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-data-cassandra/.project b/spring-data-cassandra/.project new file mode 100644 index 0000000000..239fa4f002 --- /dev/null +++ b/spring-data-cassandra/.project @@ -0,0 +1,29 @@ + + + spring-data-cassandra + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java index 5f2c4c6d47..2edd5551a5 100644 --- a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java +++ b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java @@ -17,8 +17,8 @@ import org.springframework.data.cassandra.repository.config.EnableCassandraRepos @PropertySource(value = { "classpath:cassandra.properties" }) @EnableCassandraRepositories(basePackages = "org.baeldung.spring.data.cassandra.repository") public class CassandraConfig extends AbstractCassandraConfiguration { - private static final Log LOGGER = LogFactory.getLog(CassandraConfig.class); + @Autowired private Environment environment; @@ -27,15 +27,17 @@ public class CassandraConfig extends AbstractCassandraConfiguration { return environment.getProperty("cassandra.keyspace"); } + @Override @Bean public CassandraClusterFactoryBean cluster() { - CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean(); + final CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean(); cluster.setContactPoints(environment.getProperty("cassandra.contactpoints")); cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port"))); LOGGER.info("Cluster created with contact points [" + environment.getProperty("cassandra.contactpoints") + "] " + "& port [" + Integer.parseInt(environment.getProperty("cassandra.port")) + "]."); return cluster; } + @Override @Bean public CassandraMappingContext cassandraMapping() throws ClassNotFoundException { return new BasicCassandraMappingContext(); diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java index 6c099d99bc..a8ec81d6b5 100644 --- a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java +++ b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java @@ -1,28 +1,31 @@ package org.baeldung.spring.data.cassandra.model; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + import org.springframework.cassandra.core.Ordering; import org.springframework.cassandra.core.PrimaryKeyType; import org.springframework.data.cassandra.mapping.Column; import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; import org.springframework.data.cassandra.mapping.Table; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - @Table public class Book { + @PrimaryKeyColumn(name = "id", ordinal = 0, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING) private UUID id; + @PrimaryKeyColumn(name = "title", ordinal = 1, type = PrimaryKeyType.PARTITIONED) private String title; @PrimaryKeyColumn(name = "publisher", ordinal = 2, type = PrimaryKeyType.PARTITIONED) private String publisher; + @Column private Set tags = new HashSet<>(); - public Book(UUID id, String title, String publisher, Set tags) { + public Book(final UUID id, final String title, final String publisher, final Set tags) { this.id = id; this.title = title; this.publisher = publisher; @@ -45,19 +48,20 @@ public class Book { return tags; } - public void setId(UUID id) { + public void setId(final UUID id) { this.id = id; } - public void setTitle(String title) { + public void setTitle(final String title) { this.title = title; } - public void setPublisher(String publisher) { + public void setPublisher(final String publisher) { this.publisher = publisher; } - public void setTags(Set tags) { + public void setTags(final Set tags) { this.tags = tags; } + } diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java index e37ae78b59..66d656ac3a 100644 --- a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java +++ b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java @@ -7,6 +7,8 @@ import org.springframework.stereotype.Repository; @Repository public interface BookRepository extends CassandraRepository { + @Query("select * from book where title = ?0 and publisher=?1") Iterable findByTitleAndPublisher(String title, String publisher); + } diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java index e5a7237145..8cbcdc3195 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java @@ -1,9 +1,11 @@ package org.baeldung.spring.data.cassandra.repository; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.utils.UUIDs; -import com.google.common.collect.ImmutableSet; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.io.IOException; +import java.util.HashMap; + import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -11,7 +13,11 @@ import org.apache.thrift.transport.TTransportException; import org.baeldung.spring.data.cassandra.config.CassandraConfig; import org.baeldung.spring.data.cassandra.model.Book; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cassandra.core.cql.CqlIdentifier; @@ -19,16 +25,14 @@ import org.springframework.data.cassandra.core.CassandraAdminOperations; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.IOException; -import java.util.HashMap; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CassandraConfig.class) public class BookRepositoryIntegrationTest { - private static final Log LOGGER = LogFactory.getLog(BookRepositoryIntegrationTest.class); public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; @@ -43,13 +47,14 @@ public class BookRepositoryIntegrationTest { @Autowired private CassandraAdminOperations adminTemplate; + // + @BeforeClass public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { EmbeddedCassandraServerHelper.startEmbeddedCassandra(); - Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1") - .withPort(9142).build(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); LOGGER.info("Server Started at 127.0.0.1:9142... "); - Session session = cluster.connect(); + final Session session = cluster.connect(); session.execute(KEYSPACE_CREATION_QUERY); session.execute(KEYSPACE_ACTIVATE_QUERY); LOGGER.info("KeySpace created and activated."); @@ -63,54 +68,54 @@ public class BookRepositoryIntegrationTest { @Test public void whenSavingBook_thenAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", - "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); bookRepository.save(ImmutableSet.of(javaBook)); - Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); assertEquals(javaBook.getId(), books.iterator().next().getId()); } @Test public void whenUpdatingBooks_thenAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); bookRepository.save(ImmutableSet.of(javaBook)); - Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); javaBook.setTitle("Head First Java Second Edition"); bookRepository.save(ImmutableSet.of(javaBook)); - Iterable updateBooks = bookRepository.findByTitleAndPublisher("Head First Java Second Edition", "O'Reilly Media"); + final Iterable updateBooks = bookRepository.findByTitleAndPublisher("Head First Java Second Edition", "O'Reilly Media"); assertEquals(javaBook.getTitle(), updateBooks.iterator().next().getTitle()); } @Test(expected = java.util.NoSuchElementException.class) public void whenDeletingExistingBooks_thenNotAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); bookRepository.save(ImmutableSet.of(javaBook)); bookRepository.delete(javaBook); - Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); assertNotEquals(javaBook.getId(), books.iterator().next().getId()); } @Test public void whenSavingBooks_thenAllShouldAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", - "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", - "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); bookRepository.save(ImmutableSet.of(javaBook)); bookRepository.save(ImmutableSet.of(dPatternBook)); - Iterable books = bookRepository.findAll(); + final Iterable books = bookRepository.findAll(); int bookCount = 0; - for (Book book : books) bookCount++; + for (final Book book : books) { + bookCount++; + } assertEquals(bookCount, 2); } @After public void dropTable() { - adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); } @AfterClass public static void stopCassandraEmbedded() { EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); } + } diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java index 031b5c0b6f..584d5f868b 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java @@ -1,12 +1,13 @@ package org.baeldung.spring.data.cassandra.repository; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.querybuilder.Insert; -import com.datastax.driver.core.querybuilder.QueryBuilder; -import com.datastax.driver.core.querybuilder.Select; -import com.datastax.driver.core.utils.UUIDs; -import com.google.common.collect.ImmutableSet; +import static junit.framework.TestCase.assertEquals; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -14,7 +15,11 @@ import org.apache.thrift.transport.TTransportException; import org.baeldung.spring.data.cassandra.config.CassandraConfig; import org.baeldung.spring.data.cassandra.model.Book; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cassandra.core.cql.CqlIdentifier; @@ -23,18 +28,17 @@ import org.springframework.data.cassandra.core.CassandraOperations; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; - -import static junit.framework.TestCase.assertEquals; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.querybuilder.Insert; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CassandraConfig.class) public class CQLQueriesIntegrationTest { - private static final Log LOGGER = LogFactory.getLog(CQLQueriesIntegrationTest.class); public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; @@ -49,12 +53,14 @@ public class CQLQueriesIntegrationTest { @Autowired private CassandraOperations cassandraTemplate; + // + @BeforeClass public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { EmbeddedCassandraServerHelper.startEmbeddedCassandra(25000); - Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); LOGGER.info("Server Started at 127.0.0.1:9142... "); - Session session = cluster.connect(); + final Session session = cluster.connect(); session.execute(KEYSPACE_CREATION_QUERY); session.execute(KEYSPACE_ACTIVATE_QUERY); LOGGER.info("KeySpace created and activated."); @@ -68,40 +74,40 @@ public class CQLQueriesIntegrationTest { @Test public void whenSavingBook_thenAvailableOnRetrieval_usingQueryBuilder() { - UUID uuid = UUIDs.timeBased(); - Insert insert = QueryBuilder.insertInto(DATA_TABLE_NAME).value("id", uuid).value("title", "Head First Java").value("publisher", "OReilly Media").value("tags", ImmutableSet.of("Software")); + final UUID uuid = UUIDs.timeBased(); + final Insert insert = QueryBuilder.insertInto(DATA_TABLE_NAME).value("id", uuid).value("title", "Head First Java").value("publisher", "OReilly Media").value("tags", ImmutableSet.of("Software")); cassandraTemplate.execute(insert); - Select select = QueryBuilder.select().from("book").limit(10); - Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); assertEquals(uuid, retrievedBook.getId()); } @Test public void whenSavingBook_thenAvailableOnRetrieval_usingCQLStatements() { - UUID uuid = UUIDs.timeBased(); - String insertCql = "insert into book (id, title, publisher, tags) values " + "(" + uuid + ", 'Head First Java', 'OReilly Media', {'Software'})"; + final UUID uuid = UUIDs.timeBased(); + final String insertCql = "insert into book (id, title, publisher, tags) values " + "(" + uuid + ", 'Head First Java', 'OReilly Media', {'Software'})"; cassandraTemplate.execute(insertCql); - Select select = QueryBuilder.select().from("book").limit(10); - Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); assertEquals(uuid, retrievedBook.getId()); } @Test public void whenSavingBook_thenAvailableOnRetrieval_usingPreparedStatements() throws InterruptedException { - UUID uuid = UUIDs.timeBased(); - String insertPreparedCql = "insert into book (id, title, publisher, tags) values (?, ?, ?, ?)"; - List singleBookArgsList = new ArrayList<>(); - List> bookList = new ArrayList<>(); + final UUID uuid = UUIDs.timeBased(); + final String insertPreparedCql = "insert into book (id, title, publisher, tags) values (?, ?, ?, ?)"; + final List singleBookArgsList = new ArrayList<>(); + final List> bookList = new ArrayList<>(); singleBookArgsList.add(uuid); singleBookArgsList.add("Head First Java"); singleBookArgsList.add("OReilly Media"); singleBookArgsList.add(ImmutableSet.of("Software")); bookList.add(singleBookArgsList); cassandraTemplate.ingest(insertPreparedCql, bookList); - //This may not be required, just added to avoid any transient issues + // This may not be required, just added to avoid any transient issues Thread.sleep(5000); - Select select = QueryBuilder.select().from("book"); - Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book"); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); assertEquals(uuid, retrievedBook.getId()); } @@ -114,4 +120,5 @@ public class CQLQueriesIntegrationTest { public static void stopCassandraEmbedded() { EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); } + } diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java index 35de508641..e331ac3cd4 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java @@ -1,11 +1,15 @@ package org.baeldung.spring.data.cassandra.repository; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.querybuilder.QueryBuilder; -import com.datastax.driver.core.querybuilder.Select; -import com.datastax.driver.core.utils.UUIDs; -import com.google.common.collect.ImmutableSet; +import static junit.framework.TestCase.assertNull; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -13,7 +17,11 @@ import org.apache.thrift.transport.TTransportException; import org.baeldung.spring.data.cassandra.config.CassandraConfig; import org.baeldung.spring.data.cassandra.model.Book; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cassandra.core.cql.CqlIdentifier; @@ -22,20 +30,16 @@ import org.springframework.data.cassandra.core.CassandraOperations; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import static junit.framework.TestCase.assertNull; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CassandraConfig.class) public class CassandraTemplateIntegrationTest { - private static final Log LOGGER = LogFactory.getLog(CassandraTemplateIntegrationTest.class); public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; @@ -50,12 +54,14 @@ public class CassandraTemplateIntegrationTest { @Autowired private CassandraOperations cassandraTemplate; + // + @BeforeClass public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { EmbeddedCassandraServerHelper.startEmbeddedCassandra(); - Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); LOGGER.info("Server Started at 127.0.0.1:9142... "); - Session session = cluster.connect(); + final Session session = cluster.connect(); session.execute(KEYSPACE_CREATION_QUERY); session.execute(KEYSPACE_ACTIVATE_QUERY); LOGGER.info("KeySpace created and activated."); @@ -69,24 +75,24 @@ public class CassandraTemplateIntegrationTest { @Test public void whenSavingBook_thenAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); cassandraTemplate.insert(javaBook); - Select select = QueryBuilder.select().from("book").where(QueryBuilder.eq("title", "Head First Java")).and(QueryBuilder.eq("publisher", "O'Reilly Media")).limit(10); - Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").where(QueryBuilder.eq("title", "Head First Java")).and(QueryBuilder.eq("publisher", "O'Reilly Media")).limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); assertEquals(javaBook.getId(), retrievedBook.getId()); } @Test public void whenSavingBooks_thenAllAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - List bookList = new ArrayList<>(); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final List bookList = new ArrayList<>(); bookList.add(javaBook); bookList.add(dPatternBook); cassandraTemplate.insert(bookList); - Select select = QueryBuilder.select().from("book").limit(10); - List retrievedBooks = cassandraTemplate.select(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final List retrievedBooks = cassandraTemplate.select(select, Book.class); assertThat(retrievedBooks.size(), is(2)); assertEquals(javaBook.getId(), retrievedBooks.get(0).getId()); assertEquals(dPatternBook.getId(), retrievedBooks.get(1).getId()); @@ -94,45 +100,45 @@ public class CassandraTemplateIntegrationTest { @Test public void whenUpdatingBook_thenShouldUpdatedOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); cassandraTemplate.insert(javaBook); - Select select = QueryBuilder.select().from("book").limit(10); - Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); retrievedBook.setTags(ImmutableSet.of("Java", "Programming")); cassandraTemplate.update(retrievedBook); - Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); + final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); assertEquals(retrievedBook.getTags(), retrievedUpdatedBook.getTags()); } @Test public void whenDeletingASelectedBook_thenNotAvailableOnRetrieval() throws InterruptedException { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "OReilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "OReilly Media", ImmutableSet.of("Computer", "Software")); cassandraTemplate.insert(javaBook); cassandraTemplate.delete(javaBook); - Select select = QueryBuilder.select().from("book").limit(10); - Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); assertNull(retrievedUpdatedBook); } @Test public void whenDeletingAllBooks_thenNotAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); cassandraTemplate.insert(javaBook); cassandraTemplate.insert(dPatternBook); cassandraTemplate.deleteAll(Book.class); - Select select = QueryBuilder.select().from("book").limit(10); - Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); assertNull(retrievedUpdatedBook); } @Test public void whenAddingBooks_thenCountShouldBeCorrectOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); cassandraTemplate.insert(javaBook); cassandraTemplate.insert(dPatternBook); - long bookCount = cassandraTemplate.count(Book.class); + final long bookCount = cassandraTemplate.count(Book.class); assertEquals(2, bookCount); } diff --git a/spring-data-mongodb/.classpath b/spring-data-mongodb/.classpath new file mode 100644 index 0000000000..baf7c98131 --- /dev/null +++ b/spring-data-mongodb/.classpath @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-data-mongodb/.project b/spring-data-mongodb/.project new file mode 100644 index 0000000000..e3d7687573 --- /dev/null +++ b/spring-data-mongodb/.project @@ -0,0 +1,29 @@ + + + spring-data-mongodb + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index ef6ac59dd4..d9a578cb8c 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -169,6 +169,7 @@ + 4.2.4.RELEASE @@ -197,8 +198,9 @@ 2.6 2.18.1 2.7 - 1.4.15 + 1.4.17 1.8.7 + \ No newline at end of file From 1a0d627c19d246d6667065ec9a389075cc2ca051 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 24 Dec 2015 14:15:21 +0200 Subject: [PATCH 034/309] update xml configuration --- .../baeldung/spring/SecSecurityConfig.java | 1 + .../resources/webSecurityConfig-basic.xml | 41 +++++++++++++++++++ .../src/main/resources/webSecurityConfig.xml | 16 ++++++-- 3 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 spring-security-login-and-registration/src/main/resources/webSecurityConfig-basic.xml diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 4863187bba..677ad514e5 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -18,6 +18,7 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand @Configuration @ComponentScan(basePackages = { "org.baeldung.security" }) +// @ImportResource({ "classpath:webSecurityConfig.xml" }) @EnableWebSecurity public class SecSecurityConfig extends WebSecurityConfigurerAdapter { diff --git a/spring-security-login-and-registration/src/main/resources/webSecurityConfig-basic.xml b/spring-security-login-and-registration/src/main/resources/webSecurityConfig-basic.xml new file mode 100644 index 0000000000..bf85a09b62 --- /dev/null +++ b/spring-security-login-and-registration/src/main/resources/webSecurityConfig-basic.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml b/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml index 677b0864c4..3141b19142 100644 --- a/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml +++ b/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml @@ -1,9 +1,10 @@ @@ -36,5 +37,14 @@ + + + + + + + + + \ No newline at end of file From d52ab2212ae46b66fe7b1fa534bfe1d32e263c04 Mon Sep 17 00:00:00 2001 From: dasvipin5585 Date: Fri, 25 Dec 2015 23:02:13 +0530 Subject: [PATCH 035/309] Java - Try with resources code commit --- .../java8/JavaTryWithResourcesTest.java | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java diff --git a/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java b/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java new file mode 100644 index 0000000000..ae56099e0d --- /dev/null +++ b/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java @@ -0,0 +1,94 @@ +package org.baeldung.java8; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.Scanner; + +import org.junit.Assert; +import org.junit.Test; + +public class JavaTryWithResourcesTest { + + private static final String TEST_STRING_HELLO_WORLD = "Hello World"; + private Date resource1Date, resource2Date; + + /* + * Example for using Try_with_resources + */ + @Test + public void whenWritingToStringWriter_thenCorrectlyWritten() { + + StringWriter sw = new StringWriter(); + try (PrintWriter pw = new PrintWriter(sw, true)) { + pw.print(TEST_STRING_HELLO_WORLD); + } + + Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD); + } + + /* + * Example for using multiple resources + */ + @Test + public void givenStringToScanner_whenWritingToStringWriter_thenCorrectlyWritten() { + + StringWriter sw = new StringWriter(); + try (Scanner sc = new Scanner(TEST_STRING_HELLO_WORLD); PrintWriter pw = new PrintWriter(sw, true)) { + while (sc.hasNext()) { + pw.print(sc.nextLine()); + } + } + + Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD); + } + + /* + * Example to show order in which the resources are closed + */ + @Test + public void whenFirstAutoClosableResourceIsinitializedFirst_thenFirstAutoClosableResourceIsReleasedFirst() throws Exception { + + try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) { + af.doSomething(); + as.doSomething(); + } + Assert.assertTrue(resource1Date.after(resource2Date)); + } + + class AutoCloseableResourcesFirst implements AutoCloseable { + + public AutoCloseableResourcesFirst() { + System.out.println("Constructor -> AutoCloseableResources_First"); + } + + public void doSomething() { + System.out.println("Something -> AutoCloseableResources_First"); + } + + @Override + public void close() throws Exception { + System.out.println("Closed AutoCloseableResources_First"); + resource1Date = new Date(); + + } + } + + class AutoCloseableResourcesSecond implements AutoCloseable { + + public AutoCloseableResourcesSecond() { + System.out.println("Constructor -> AutoCloseableResources_Second"); + } + + public void doSomething() { + System.out.println("Something -> AutoCloseableResources_Second"); + } + + @Override + public void close() throws Exception { + System.out.println("Closed AutoCloseableResources_Second"); + resource2Date = new Date(); + Thread.sleep(10000); + } + } +} From eea69135f75df9ec7beec5dd5aff3fc5aecb6ac4 Mon Sep 17 00:00:00 2001 From: eugenp Date: Fri, 25 Dec 2015 20:45:45 +0200 Subject: [PATCH 036/309] general cleanup work --- .../java8/JavaTryWithResourcesTest.java | 24 +++++++------------ ...st.java => CqlQueriesIntegrationTest.java} | 4 ++-- 2 files changed, 10 insertions(+), 18 deletions(-) rename spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/{CQLQueriesIntegrationTest.java => CqlQueriesIntegrationTest.java} (98%) diff --git a/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java b/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java index ae56099e0d..a59682c535 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java +++ b/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java @@ -13,13 +13,12 @@ public class JavaTryWithResourcesTest { private static final String TEST_STRING_HELLO_WORLD = "Hello World"; private Date resource1Date, resource2Date; - /* - * Example for using Try_with_resources - */ + // tests + + /* Example for using Try_with_resources */ @Test public void whenWritingToStringWriter_thenCorrectlyWritten() { - - StringWriter sw = new StringWriter(); + final StringWriter sw = new StringWriter(); try (PrintWriter pw = new PrintWriter(sw, true)) { pw.print(TEST_STRING_HELLO_WORLD); } @@ -27,13 +26,11 @@ public class JavaTryWithResourcesTest { Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD); } - /* - * Example for using multiple resources - */ + /* Example for using multiple resources */ @Test public void givenStringToScanner_whenWritingToStringWriter_thenCorrectlyWritten() { - StringWriter sw = new StringWriter(); + final StringWriter sw = new StringWriter(); try (Scanner sc = new Scanner(TEST_STRING_HELLO_WORLD); PrintWriter pw = new PrintWriter(sw, true)) { while (sc.hasNext()) { pw.print(sc.nextLine()); @@ -43,12 +40,9 @@ public class JavaTryWithResourcesTest { Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD); } - /* - * Example to show order in which the resources are closed - */ + /* Example to show order in which the resources are closed */ @Test public void whenFirstAutoClosableResourceIsinitializedFirst_thenFirstAutoClosableResourceIsReleasedFirst() throws Exception { - try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) { af.doSomething(); as.doSomething(); @@ -57,7 +51,6 @@ public class JavaTryWithResourcesTest { } class AutoCloseableResourcesFirst implements AutoCloseable { - public AutoCloseableResourcesFirst() { System.out.println("Constructor -> AutoCloseableResources_First"); } @@ -70,12 +63,10 @@ public class JavaTryWithResourcesTest { public void close() throws Exception { System.out.println("Closed AutoCloseableResources_First"); resource1Date = new Date(); - } } class AutoCloseableResourcesSecond implements AutoCloseable { - public AutoCloseableResourcesSecond() { System.out.println("Constructor -> AutoCloseableResources_Second"); } @@ -91,4 +82,5 @@ public class JavaTryWithResourcesTest { Thread.sleep(10000); } } + } diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java similarity index 98% rename from spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java rename to spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java index 584d5f868b..f7e42ae23b 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java @@ -38,8 +38,8 @@ import com.google.common.collect.ImmutableSet; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CassandraConfig.class) -public class CQLQueriesIntegrationTest { - private static final Log LOGGER = LogFactory.getLog(CQLQueriesIntegrationTest.class); +public class CqlQueriesIntegrationTest { + private static final Log LOGGER = LogFactory.getLog(CqlQueriesIntegrationTest.class); public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; From 93d6e3f67a4e218933950c22ee03f63f4fc18b20 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 27 Dec 2015 23:55:25 +0200 Subject: [PATCH 037/309] testing work --- spring-hibernate4/pom.xml | 5 +++++ spring-jpa/pom.xml | 5 +++++ .../baeldung/persistence/service/FooServiceSortingTests.java | 4 ---- .../{JPAMultipleDBTest.java => JpaMultipleDBTest.java} | 5 ++++- .../baeldung/persistence/service/PersistenceTestSuite.java | 1 + 5 files changed, 15 insertions(+), 5 deletions(-) rename spring-jpa/src/test/java/org/baeldung/persistence/service/{JPAMultipleDBTest.java => JpaMultipleDBTest.java} (98%) diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml index c8ab1866e2..8fabb56ab7 100644 --- a/spring-hibernate4/pom.xml +++ b/spring-hibernate4/pom.xml @@ -53,6 +53,11 @@ hibernate-validator ${hibernate-validator.version} + + javax.el + javax.el-api + 2.2.5 + diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index 63d97c337b..20be07ca5b 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -58,6 +58,11 @@ hibernate-validator ${hibernate-validator.version} + + javax.el + javax.el-api + 2.2.5 + diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingTests.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingTests.java index c12dfda50c..319d36151e 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingTests.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingTests.java @@ -15,7 +15,6 @@ import org.baeldung.persistence.model.Bar; import org.baeldung.persistence.model.Foo; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @@ -28,9 +27,6 @@ public class FooServiceSortingTests { @PersistenceContext private EntityManager entityManager; - @Autowired - private FooService service; - // tests @Test diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/JPAMultipleDBTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBTest.java similarity index 98% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/JPAMultipleDBTest.java rename to spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBTest.java index 4c6b02ec3d..427e182d9e 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/JPAMultipleDBTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBTest.java @@ -21,13 +21,16 @@ import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { UserConfig.class, ProductConfig.class }) @TransactionConfiguration -public class JPAMultipleDBTest { +public class JpaMultipleDBTest { + @Autowired private UserRepository userRepository; @Autowired private ProductRepository productRepository; + // tests + @Test @Transactional("userTransactionManager") public void whenCreatingUser_thenCreated() { diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java index f6c41258d4..919171de9f 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java @@ -8,6 +8,7 @@ import org.junit.runners.Suite; FooPaginationPersistenceIntegrationTest.class ,FooServicePersistenceIntegrationTest.class ,FooServiceSortingTests.class + ,JpaMultipleDBTest.class // manual only // ,FooServiceSortingWitNullsManualTest.class }) // @formatter:on From c5eb1c570a7d9708d51c1420be5d9314cbd6cf94 Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 28 Dec 2015 12:04:08 +0200 Subject: [PATCH 038/309] modify ldap configuration --- spring-security-mvc-ldap/pom.xml | 19 +--------- .../org/baeldung/SampleLDAPApplication.java | 4 +-- .../org/baeldung/security/SecurityConfig.java | 13 +++---- .../src/main/resources/templates/login.html | 2 +- .../src/main/resources/webSecurityConfig.xml | 36 +++++++++++++++++++ 5 files changed, 44 insertions(+), 30 deletions(-) create mode 100644 spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index 00165bd740..5282f76a7e 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -35,29 +35,13 @@ spring-security-ldap - - org.springframework.ldap - spring-ldap-core - 2.0.3.RELEASE - - - org.springframework.ldap - spring-ldap-core-tiger - 2.0.3.RELEASE - - org.apache.directory.server apacheds-server-jndi 1.5.5 - - org.apache.mina - mina-core - 2.0.9 - - + @@ -74,7 +58,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} 1.8 1.8 diff --git a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java index 454e52d1d5..4bcb255046 100644 --- a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java +++ b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java @@ -3,16 +3,14 @@ package org.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; -import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Main Application Class - uses Spring Boot. Just run this as a normal Java * class to run up a Jetty Server (on http://localhost:8080) - * + * */ -@EnableScheduling @EnableAutoConfiguration @ComponentScan("org.baeldung") public class SampleLDAPApplication extends WebMvcConfigurerAdapter { diff --git a/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java b/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java index c9bb5b74ae..ee72ee7891 100644 --- a/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java +++ b/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java @@ -1,29 +1,26 @@ package org.baeldung.security; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.stereotype.Controller; /** * Security Configuration - LDAP and HTTP Authorizations. */ -@EnableAutoConfiguration -@ComponentScan -@Controller +@Configuration +// @ImportResource({ "classpath:webSecurityConfig.xml" }) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.ldapAuthentication().userSearchBase("ou=people").userSearchFilter("(uid={0})").groupSearchBase("ou=groups").groupSearchFilter("member={0}").contextSource().root("dc=baeldung,dc=com").ldif("classpath:users.ldif"); + auth.ldapAuthentication().userSearchBase("ou=people").userSearchFilter("(uid={0})").groupSearchBase("ou=groups").groupSearchFilter("(member={0})").contextSource().root("dc=baeldung,dc=com").ldif("classpath:users.ldif"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/", "/home").permitAll().anyRequest().authenticated(); - http.formLogin().loginPage("/login").permitAll().and().logout().logoutSuccessUrl("/"); + http.formLogin().loginPage("/login").permitAll().loginProcessingUrl("/j_spring_security_check").and().logout().logoutSuccessUrl("/"); } } diff --git a/spring-security-mvc-ldap/src/main/resources/templates/login.html b/spring-security-mvc-ldap/src/main/resources/templates/login.html index e3a18c2e48..81f62fde13 100644 --- a/spring-security-mvc-ldap/src/main/resources/templates/login.html +++ b/spring-security-mvc-ldap/src/main/resources/templates/login.html @@ -21,7 +21,7 @@

You have been logged out

There was an error, please try again

Login with Username and Password

-
+
diff --git a/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..6bd2c422d8 --- /dev/null +++ b/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 3052a5305efc230836481eb036717fce990b7ed7 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 28 Dec 2015 18:23:13 +0200 Subject: [PATCH 039/309] spring batch work --- .../.classpath | 6 +++++- {spring-batch-intro => spring-batch}/.project | 8 +++++++- {spring-batch-intro => spring-batch}/pom.xml | 7 +++---- .../org/baeldung/spring_batch_intro/App.java | 18 +++++++----------- .../spring_batch_intro/SpringBatchConfig.java | 0 .../spring_batch_intro/SpringConfig.java | 0 .../spring_batch_intro/model/Transaction.java | 0 .../service/CustomItemProcessor.java | 0 .../service/RecordFieldSetMapper.java | 0 .../src/main/resources/input/record.csv | 0 .../src/main/resources/spring-batch-intro.xml | 0 .../src/main/resources/spring.xml | 0 .../xml/output.xml | 0 13 files changed, 22 insertions(+), 17 deletions(-) rename {spring-batch-intro => spring-batch}/.classpath (83%) rename {spring-batch-intro => spring-batch}/.project (69%) rename {spring-batch-intro => spring-batch}/pom.xml (85%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/App.java (60%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java (100%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java (100%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java (100%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java (100%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java (100%) rename {spring-batch-intro => spring-batch}/src/main/resources/input/record.csv (100%) rename {spring-batch-intro => spring-batch}/src/main/resources/spring-batch-intro.xml (100%) rename {spring-batch-intro => spring-batch}/src/main/resources/spring.xml (100%) rename {spring-batch-intro => spring-batch}/xml/output.xml (100%) diff --git a/spring-batch-intro/.classpath b/spring-batch/.classpath similarity index 83% rename from spring-batch-intro/.classpath rename to spring-batch/.classpath index 395dbde027..e7ac9faf11 100644 --- a/spring-batch-intro/.classpath +++ b/spring-batch/.classpath @@ -12,7 +12,11 @@ - + + + + + diff --git a/spring-batch-intro/.project b/spring-batch/.project similarity index 69% rename from spring-batch-intro/.project rename to spring-batch/.project index 032f8a9541..0159a7237c 100644 --- a/spring-batch-intro/.project +++ b/spring-batch/.project @@ -1,6 +1,6 @@ - spring-batch-intro + spring-batch @@ -15,8 +15,14 @@ + + org.springframework.ide.eclipse.core.springbuilder + + + + org.springframework.ide.eclipse.core.springnature org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature diff --git a/spring-batch-intro/pom.xml b/spring-batch/pom.xml similarity index 85% rename from spring-batch-intro/pom.xml rename to spring-batch/pom.xml index 28d48c594e..c85aeff6f3 100644 --- a/spring-batch-intro/pom.xml +++ b/spring-batch/pom.xml @@ -1,13 +1,12 @@ - + 4.0.0 org.baeldung - spring-batch-intro + spring-batch 0.1-SNAPSHOT jar - spring-batch-intro + spring-batch http://maven.apache.org diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java similarity index 60% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java index d6af37595c..2ce4dae6e6 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java @@ -4,31 +4,27 @@ import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - public class App { - public static void main(String[] args) { + public static void main(final String[] args) { // Spring Java config - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(SpringConfig.class); context.register(SpringBatchConfig.class); context.refresh(); // Spring xml config - // ApplicationContext context = new ClassPathXmlApplicationContext( - // "spring-batch-intro.xml"); + // ApplicationContext context = new ClassPathXmlApplicationContext("spring-batch.xml"); - JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); - Job job = (Job) context.getBean("firstBatchJob"); + final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); + final Job job = (Job) context.getBean("firstBatchJob"); System.out.println("Starting the batch job"); try { - JobExecution execution = jobLauncher.run(job, new JobParameters()); + final JobExecution execution = jobLauncher.run(job, new JobParameters()); System.out.println("Job Status : " + execution.getStatus()); System.out.println("Job succeeded"); - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); System.out.println("Job failed"); } diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java similarity index 100% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java similarity index 100% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java similarity index 100% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java similarity index 100% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java similarity index 100% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java diff --git a/spring-batch-intro/src/main/resources/input/record.csv b/spring-batch/src/main/resources/input/record.csv similarity index 100% rename from spring-batch-intro/src/main/resources/input/record.csv rename to spring-batch/src/main/resources/input/record.csv diff --git a/spring-batch-intro/src/main/resources/spring-batch-intro.xml b/spring-batch/src/main/resources/spring-batch-intro.xml similarity index 100% rename from spring-batch-intro/src/main/resources/spring-batch-intro.xml rename to spring-batch/src/main/resources/spring-batch-intro.xml diff --git a/spring-batch-intro/src/main/resources/spring.xml b/spring-batch/src/main/resources/spring.xml similarity index 100% rename from spring-batch-intro/src/main/resources/spring.xml rename to spring-batch/src/main/resources/spring.xml diff --git a/spring-batch-intro/xml/output.xml b/spring-batch/xml/output.xml similarity index 100% rename from spring-batch-intro/xml/output.xml rename to spring-batch/xml/output.xml From a19854cceb9353a5eafcff737ef1b25a3c021648 Mon Sep 17 00:00:00 2001 From: Alexander Odinets Date: Wed, 30 Dec 2015 16:56:51 +0300 Subject: [PATCH 040/309] Audit with JPA callbacks, Hibernate Envers and Spring Data JPA --- spring-hibernate4/pom.xml | 80 ++++++++-- .../persistence/dao/IBarAuditableDao.java | 8 + .../persistence/dao/IBarCrudRepository.java | 10 ++ .../org/baeldung/persistence/dao/IBarDao.java | 8 + .../persistence/dao/IFooAuditableDao.java | 8 + .../persistence/dao/common/AbstractDao.java | 14 ++ .../common/AbstractHibernateAuditableDao.java | 37 +++++ .../dao/common/AbstractHibernateDao.java | 24 ++- .../dao/common/AbstractJpaDao.java | 56 +++++++ .../dao/common/IAuditOperations.java | 14 ++ .../persistence/dao/impl/BarAuditableDao.java | 28 ++++ .../baeldung/persistence/dao/impl/BarDao.java | 19 +++ .../persistence/dao/impl/BarJpaDao.java | 19 +++ .../persistence/dao/impl/FooAuditableDao.java | 17 +++ .../baeldung/persistence/dao/impl/FooDao.java | 2 +- .../org/baeldung/persistence/model/Bar.java | 138 ++++++++++++++++- .../org/baeldung/persistence/model/Foo.java | 4 + .../service/IBarAuditableService.java | 8 + .../persistence/service/IBarService.java | 8 + .../service/IFooAuditableService.java | 8 + .../AbstractHibernateAuditableService.java | 30 ++++ .../common/AbstractHibernateService.java | 42 ++++++ .../service/common/AbstractJpaService.java | 42 ++++++ .../service/common/AbstractService.java | 2 - .../common/AbstractSpringDataJpaService.java | 46 ++++++ .../service/impl/BarAuditableService.java | 41 +++++ .../service/impl/BarJpaService.java | 30 ++++ .../persistence/service/impl/BarService.java | 30 ++++ .../service/impl/BarSpringDataJpaService.java | 26 ++++ .../service/impl/ChildService.java | 4 +- .../service/impl/FooAuditableService.java | 41 +++++ .../persistence/service/impl/FooService.java | 6 +- .../service/impl/ParentService.java | 4 +- .../baeldung/spring/PersistenceConfig.java | 111 +++++++++++++- .../resources/persistence-mysql.properties | 3 + .../src/main/resources/webSecurityConfig.xml | 3 +- .../persistence/audit/AuditTestSuite.java | 14 ++ .../audit/EnversFooBarAuditTest.java | 142 ++++++++++++++++++ .../persistence/audit/JPABarAuditTest.java | 106 +++++++++++++ .../audit/SpringDataJPABarAuditTest.java | 76 ++++++++++ .../FooServicePersistenceIntegrationTest.java | 2 + 41 files changed, 1263 insertions(+), 48 deletions(-) create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarAuditableDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarCrudRepository.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IFooAuditableDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractJpaDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/IAuditOperations.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarAuditableDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarJpaDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooAuditableDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarAuditableService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/IFooAuditableService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateAuditableService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractJpaService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractSpringDataJpaService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarAuditableService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarJpaService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarSpringDataJpaService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooAuditableService.java create mode 100644 spring-hibernate4/src/test/java/org/baeldung/persistence/audit/AuditTestSuite.java create mode 100644 spring-hibernate4/src/test/java/org/baeldung/persistence/audit/EnversFooBarAuditTest.java create mode 100644 spring-hibernate4/src/test/java/org/baeldung/persistence/audit/JPABarAuditTest.java create mode 100644 spring-hibernate4/src/test/java/org/baeldung/persistence/audit/SpringDataJPABarAuditTest.java diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml index 3b0e3b6a00..711f9b3533 100644 --- a/spring-hibernate4/pom.xml +++ b/spring-hibernate4/pom.xml @@ -15,6 +15,16 @@ spring-context ${org.springframework.version} + + org.springframework + spring-aspects + ${org.springframework.version} + + + org.springframework.security + spring-security-core + ${org.springframework.security.version} + @@ -23,21 +33,35 @@ spring-orm ${org.springframework.version} + + org.springframework.data + spring-data-jpa + ${org.springframework.data.version} + org.hibernate hibernate-core ${hibernate.version} - org.javassist - javassist - ${javassist.version} + org.hibernate + hibernate-envers + ${hibernate-envers.version} + + + javax.transaction + jta + ${jta.version} + + + javax.el + javax.el-api + ${el-api.version} mysql mysql-connector-java ${mysql-connector-java.version} - runtime @@ -77,6 +101,13 @@ ${org.springframework.version} test + + + org.springframework.security + spring-security-test + ${org.springframework.security.version} + test + junit @@ -85,12 +116,6 @@ test - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - org.hamcrest hamcrest-library @@ -162,7 +187,28 @@ - + @@ -171,19 +217,22 @@ 4.2.2.RELEASE 4.0.2.RELEASE - 3.20.0-GA - + 1.9.2.RELEASE + 4.3.11.Final + ${hibernate.version} 5.1.36 7.0.42 + 1.1 + 2.2.4 1.7.12 1.1.3 - + - 5.2.1.Final + 4.3.2.Final 18.0 @@ -204,6 +253,7 @@ 2.18.1 2.7 1.4.15 + diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarAuditableDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarAuditableDao.java new file mode 100644 index 0000000000..060922942b --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarAuditableDao.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.model.Bar; + +public interface IBarAuditableDao extends IBarDao, IAuditOperations { + // +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarCrudRepository.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarCrudRepository.java new file mode 100644 index 0000000000..70fffd9d80 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarCrudRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.persistence.dao; + +import java.io.Serializable; + +import org.baeldung.persistence.model.Bar; +import org.springframework.data.repository.CrudRepository; + +public interface IBarCrudRepository extends CrudRepository { + // +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarDao.java new file mode 100644 index 0000000000..02814b39b8 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarDao.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Bar; + +public interface IBarDao extends IOperations { + // +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IFooAuditableDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IFooAuditableDao.java new file mode 100644 index 0000000000..ee0cc1fb8a --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IFooAuditableDao.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.model.Foo; + +public interface IFooAuditableDao extends IFooDao, IAuditOperations { + // +} \ No newline at end of file diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractDao.java new file mode 100644 index 0000000000..6a1790ad3e --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractDao.java @@ -0,0 +1,14 @@ +package org.baeldung.persistence.dao.common; + +import java.io.Serializable; + +import com.google.common.base.Preconditions; + +public abstract class AbstractDao implements IOperations { + + protected Class clazz; + + protected final void setClazz(final Class clazzToSet) { + clazz = Preconditions.checkNotNull(clazzToSet); + } +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java new file mode 100644 index 0000000000..f0886c612e --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java @@ -0,0 +1,37 @@ +package org.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +import org.hibernate.envers.AuditReader; +import org.hibernate.envers.AuditReaderFactory; +import org.hibernate.envers.query.AuditQuery; + +@SuppressWarnings("unchecked") +public class AbstractHibernateAuditableDao extends AbstractHibernateDao implements IAuditOperations { + + @Override + public List getEntitiesAtRevision(final Number revision) { + final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); + final AuditQuery query = auditReader.createQuery().forEntitiesAtRevision(clazz, revision); + final List resultList = query.getResultList(); + return resultList; + } + + @Override + public List getEntitiesModifiedAtRevision(final Number revision) { + final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); + final AuditQuery query = auditReader.createQuery().forEntitiesModifiedAtRevision(clazz, revision); + final List resultList = query.getResultList(); + return resultList; + } + + @Override + public List getRevisions() { + final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); + final AuditQuery query = auditReader.createQuery().forRevisionsOfEntity(clazz, true, true); + final List resultList = query.getResultList(); + return resultList; + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateDao.java index 65e57afcb3..dd22d94503 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateDao.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateDao.java @@ -10,55 +10,49 @@ import org.springframework.beans.factory.annotation.Autowired; import com.google.common.base.Preconditions; @SuppressWarnings("unchecked") -public abstract class AbstractHibernateDao implements IOperations { - private Class clazz; +public abstract class AbstractHibernateDao extends AbstractDao implements IOperations { @Autowired - private SessionFactory sessionFactory; + protected SessionFactory sessionFactory; // API - protected final void setClazz(final Class clazzToSet) { - clazz = Preconditions.checkNotNull(clazzToSet); - } - @Override - public final T findOne(final long id) { + public T findOne(final long id) { return (T) getCurrentSession().get(clazz, id); } @Override - public final List findAll() { + public List findAll() { return getCurrentSession().createQuery("from " + clazz.getName()).list(); } @Override - public final void create(final T entity) { + public void create(final T entity) { Preconditions.checkNotNull(entity); - // getCurrentSession().persist(entity); getCurrentSession().saveOrUpdate(entity); } @Override - public final T update(final T entity) { + public T update(final T entity) { Preconditions.checkNotNull(entity); return (T) getCurrentSession().merge(entity); } @Override - public final void delete(final T entity) { + public void delete(final T entity) { Preconditions.checkNotNull(entity); getCurrentSession().delete(entity); } @Override - public final void deleteById(final long entityId) { + public void deleteById(final long entityId) { final T entity = findOne(entityId); Preconditions.checkState(entity != null); delete(entity); } - protected final Session getCurrentSession() { + protected Session getCurrentSession() { return sessionFactory.getCurrentSession(); } diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractJpaDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractJpaDao.java new file mode 100644 index 0000000000..7e08151bea --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractJpaDao.java @@ -0,0 +1,56 @@ +package org.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +public class AbstractJpaDao extends AbstractDao implements IOperations { + + @PersistenceContext + private EntityManager em; + + // API + + @Override + public T findOne(final long id) { + return em.find(clazz, Long.valueOf(id).intValue()); + } + + @Override + public List findAll() { + final CriteriaBuilder cb = em.getCriteriaBuilder(); + final CriteriaQuery cq = cb.createQuery(clazz); + final Root rootEntry = cq.from(clazz); + final CriteriaQuery all = cq.select(rootEntry); + final TypedQuery allQuery = em.createQuery(all); + return allQuery.getResultList(); + } + + @Override + public void create(final T entity) { + em.persist(entity); + } + + @Override + public T update(final T entity) { + em.merge(entity); + return entity; + } + + @Override + public void delete(final T entity) { + em.remove(entity); + } + + @Override + public void deleteById(final long entityId) { + delete(findOne(entityId)); + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/IAuditOperations.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/IAuditOperations.java new file mode 100644 index 0000000000..bcc1059dbe --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/IAuditOperations.java @@ -0,0 +1,14 @@ +package org.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +public interface IAuditOperations { + + List getEntitiesAtRevision(Number revision); + + List getEntitiesModifiedAtRevision(Number revision); + + List getRevisions(); + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarAuditableDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarAuditableDao.java new file mode 100644 index 0000000000..bddd98bcfb --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarAuditableDao.java @@ -0,0 +1,28 @@ +package org.baeldung.persistence.dao.impl; + +import java.util.List; + +import org.baeldung.persistence.dao.IBarAuditableDao; +import org.baeldung.persistence.dao.common.AbstractHibernateAuditableDao; +import org.baeldung.persistence.model.Bar; + +public class BarAuditableDao extends AbstractHibernateAuditableDao implements IBarAuditableDao { + + public BarAuditableDao() { + super(); + + setClazz(Bar.class); + } + + // API + + @Override + public List getRevisions() { + final List resultList = super.getRevisions(); + for (final Bar bar : resultList) { + bar.getFooSet().size(); // force FooSet initialization + } + return resultList; + } + +} \ No newline at end of file diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarDao.java new file mode 100644 index 0000000000..ba48581edb --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarDao.java @@ -0,0 +1,19 @@ +package org.baeldung.persistence.dao.impl; + +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.common.AbstractHibernateDao; +import org.baeldung.persistence.model.Bar; +import org.springframework.stereotype.Repository; + +@Repository +public class BarDao extends AbstractHibernateDao implements IBarDao { + + public BarDao() { + super(); + + setClazz(Bar.class); + } + + // API + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarJpaDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarJpaDao.java new file mode 100644 index 0000000000..cd167dd64f --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarJpaDao.java @@ -0,0 +1,19 @@ +package org.baeldung.persistence.dao.impl; + +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.common.AbstractJpaDao; +import org.baeldung.persistence.model.Bar; +import org.springframework.stereotype.Repository; + +@Repository +public class BarJpaDao extends AbstractJpaDao implements IBarDao { + + public BarJpaDao() { + super(); + + setClazz(Bar.class); + } + + // API + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooAuditableDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooAuditableDao.java new file mode 100644 index 0000000000..ee9cc639b5 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooAuditableDao.java @@ -0,0 +1,17 @@ +package org.baeldung.persistence.dao.impl; + +import org.baeldung.persistence.dao.IFooAuditableDao; +import org.baeldung.persistence.dao.common.AbstractHibernateAuditableDao; +import org.baeldung.persistence.model.Foo; + +public class FooAuditableDao extends AbstractHibernateAuditableDao implements IFooAuditableDao { + + public FooAuditableDao() { + super(); + + setClazz(Foo.class); + } + + // API + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java index eb3a66126c..b8360160da 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java @@ -6,7 +6,7 @@ import org.baeldung.persistence.model.Foo; import org.springframework.stereotype.Repository; @Repository -public class FooDao extends AbstractHibernateDaoimplements IFooDao { +public class FooDao extends AbstractHibernateDao implements IFooDao { public FooDao() { super(); diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Bar.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Bar.java index 410ad79b02..1d4ec69741 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Bar.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Bar.java @@ -1,26 +1,66 @@ package org.baeldung.persistence.model; import java.io.Serializable; +import java.util.Date; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.EntityListeners; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; +import javax.persistence.PrePersist; +import javax.persistence.PreRemove; +import javax.persistence.PreUpdate; import org.hibernate.annotations.OrderBy; +import org.hibernate.envers.Audited; +import org.jboss.logging.Logger; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; import com.google.common.collect.Sets; @Entity @NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") +@Audited +@EntityListeners(AuditingEntityListener.class) public class Bar implements Serializable { + private static Logger logger = Logger.getLogger(Bar.class); + + public enum OPERATION { + INSERT, UPDATE, DELETE; + private String value; + + OPERATION() { + value = toString(); + } + + public String getValue() { + return value; + } + + public static OPERATION parse(final String value) { + OPERATION operation = null; + for (final OPERATION op : OPERATION.values()) { + if (op.getValue().equals(value)) { + operation = op; + break; + } + } + return operation; + } + }; + @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") @@ -31,8 +71,31 @@ public class Bar implements Serializable { @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @OrderBy(clause = "NAME DESC") + // @NotAudited private Set fooSet = Sets.newHashSet(); + @Column(name = "operation") + private String operation; + + @Column(name = "timestamp") + private long timestamp; + + @Column(name = "created_date") + @CreatedDate + private long createdDate; + + @Column(name = "modified_date") + @LastModifiedDate + private long modifiedDate; + + @Column(name = "created_by") + @CreatedBy + private String createdBy; + + @Column(name = "modified_by") + @LastModifiedBy + private String modifiedBy; + public Bar() { super(); } @@ -69,7 +132,57 @@ public class Bar implements Serializable { this.name = name; } - // + public OPERATION getOperation() { + return OPERATION.parse(operation); + } + + public void setOperation(final OPERATION operation) { + this.operation = operation.getValue(); + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(final long timestamp) { + this.timestamp = timestamp; + } + + public long getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(final long createdDate) { + this.createdDate = createdDate; + } + + public long getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(final long modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(final String createdBy) { + this.createdBy = createdBy; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(final String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + public void setOperation(final String operation) { + this.operation = operation; + } @Override public int hashCode() { @@ -103,4 +216,27 @@ public class Bar implements Serializable { return builder.toString(); } + @PrePersist + public void onPrePersist() { + logger.info("@PrePersist"); + audit(OPERATION.INSERT); + } + + @PreUpdate + public void onPreUpdate() { + logger.info("@PreUpdate"); + audit(OPERATION.UPDATE); + } + + @PreRemove + public void onPreRemove() { + logger.info("@PreRemove"); + audit(OPERATION.DELETE); + } + + private void audit(final OPERATION operation) { + setOperation(operation); + setTimestamp((new Date()).getTime()); + } + } diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Foo.java index 974535e058..9a96594cfe 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Foo.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Foo.java @@ -12,7 +12,11 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import org.hibernate.envers.Audited; + @Entity +@Audited +// @Proxy(lazy = false) public class Foo implements Serializable { @Id diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarAuditableService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarAuditableService.java new file mode 100644 index 0000000000..b481dfefeb --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarAuditableService.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.service; + +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.model.Bar; + +public interface IBarAuditableService extends IBarService, IAuditOperations { + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarService.java new file mode 100644 index 0000000000..145a0d54db --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarService.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.service; + +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Bar; + +public interface IBarService extends IOperations { + // +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IFooAuditableService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IFooAuditableService.java new file mode 100644 index 0000000000..2bd9ccb208 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IFooAuditableService.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.service; + +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.model.Foo; + +public interface IFooAuditableService extends IFooService, IAuditOperations { + // +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateAuditableService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateAuditableService.java new file mode 100644 index 0000000000..f9b6703607 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateAuditableService.java @@ -0,0 +1,30 @@ +package org.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.dao.common.IOperations; +import org.springframework.transaction.annotation.Transactional; + +@Transactional(value = "hibernateTransactionManager") +public abstract class AbstractHibernateAuditableService extends AbstractHibernateService implements IOperations, IAuditOperations { + + @Override + public List getEntitiesAtRevision(final Number revision) { + return getAuditableDao().getEntitiesAtRevision(revision); + } + + @Override + public List getEntitiesModifiedAtRevision(final Number revision) { + return getAuditableDao().getEntitiesModifiedAtRevision(revision); + } + + @Override + public List getRevisions() { + return getAuditableDao().getRevisions(); + } + + abstract protected IAuditOperations getAuditableDao(); + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateService.java new file mode 100644 index 0000000000..3539a56896 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateService.java @@ -0,0 +1,42 @@ +package org.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import org.baeldung.persistence.dao.common.IOperations; +import org.springframework.transaction.annotation.Transactional; + +@Transactional(value = "hibernateTransactionManager") +public abstract class AbstractHibernateService extends AbstractService implements IOperations { + + @Override + public T findOne(final long id) { + return super.findOne(id); + } + + @Override + public List findAll() { + return super.findAll(); + } + + @Override + public void create(final T entity) { + super.create(entity); + } + + @Override + public T update(final T entity) { + return super.update(entity); + } + + @Override + public void delete(final T entity) { + super.delete(entity); + } + + @Override + public void deleteById(final long entityId) { + super.deleteById(entityId); + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractJpaService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractJpaService.java new file mode 100644 index 0000000000..2b41edda12 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractJpaService.java @@ -0,0 +1,42 @@ +package org.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import org.baeldung.persistence.dao.common.IOperations; +import org.springframework.transaction.annotation.Transactional; + +@Transactional(value = "jpaTransactionManager") +public abstract class AbstractJpaService extends AbstractService implements IOperations { + + @Override + public T findOne(final long id) { + return super.findOne(id); + } + + @Override + public List findAll() { + return super.findAll(); + } + + @Override + public void create(final T entity) { + super.create(entity); + } + + @Override + public T update(final T entity) { + return super.update(entity); + } + + @Override + public void delete(final T entity) { + super.delete(entity); + } + + @Override + public void deleteById(final long entityId) { + super.deleteById(entityId); + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractService.java index 3b32bc3ebb..530bc5e956 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractService.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractService.java @@ -4,9 +4,7 @@ import java.io.Serializable; import java.util.List; import org.baeldung.persistence.dao.common.IOperations; -import org.springframework.transaction.annotation.Transactional; -@Transactional public abstract class AbstractService implements IOperations { @Override diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractSpringDataJpaService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractSpringDataJpaService.java new file mode 100644 index 0000000000..dfb73204c2 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractSpringDataJpaService.java @@ -0,0 +1,46 @@ +package org.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import org.baeldung.persistence.dao.common.IOperations; +import org.springframework.data.repository.CrudRepository; +import org.springframework.transaction.annotation.Transactional; + +import com.google.common.collect.Lists; + +@Transactional(value = "jpaTransactionManager") +public abstract class AbstractSpringDataJpaService implements IOperations { + + @Override + public T findOne(final long id) { + return getDao().findOne(Long.valueOf(id)); + } + + @Override + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public void create(final T entity) { + getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().delete(Long.valueOf(entityId)); + } + + protected abstract CrudRepository getDao(); +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarAuditableService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarAuditableService.java new file mode 100644 index 0000000000..9124a41a56 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarAuditableService.java @@ -0,0 +1,41 @@ +package org.baeldung.persistence.service.impl; + +import org.baeldung.persistence.dao.IBarAuditableDao; +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.service.IBarAuditableService; +import org.baeldung.persistence.service.common.AbstractHibernateAuditableService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class BarAuditableService extends AbstractHibernateAuditableService implements IBarAuditableService { + + @Autowired + @Qualifier("barHibernateDao") + private IBarDao dao; + + @Autowired + @Qualifier("barHibernateAuditableDao") + private IBarAuditableDao auditDao; + + public BarAuditableService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + + @Override + protected IAuditOperations getAuditableDao() { + return auditDao; + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarJpaService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarJpaService.java new file mode 100644 index 0000000000..d78fbdd7c4 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarJpaService.java @@ -0,0 +1,30 @@ +package org.baeldung.persistence.service.impl; + +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.persistence.service.common.AbstractJpaService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class BarJpaService extends AbstractJpaService implements IBarService { + + @Autowired + @Qualifier("barJpaDao") + private IBarDao dao; + + public BarJpaService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} \ No newline at end of file diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarService.java new file mode 100644 index 0000000000..7fdd1b026d --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarService.java @@ -0,0 +1,30 @@ +package org.baeldung.persistence.service.impl; + +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.persistence.service.common.AbstractHibernateService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class BarService extends AbstractHibernateService implements IBarService { + + @Autowired + @Qualifier("barHibernateDao") + private IBarDao dao; + + public BarService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarSpringDataJpaService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarSpringDataJpaService.java new file mode 100644 index 0000000000..65f665495a --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarSpringDataJpaService.java @@ -0,0 +1,26 @@ +package org.baeldung.persistence.service.impl; + +import java.io.Serializable; + +import org.baeldung.persistence.dao.IBarCrudRepository; +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.persistence.service.common.AbstractSpringDataJpaService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.repository.CrudRepository; + +public class BarSpringDataJpaService extends AbstractSpringDataJpaService implements IBarService { + + @Autowired + private IBarCrudRepository dao; + + public BarSpringDataJpaService() { + super(); + } + + @Override + protected CrudRepository getDao() { + return dao; + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ChildService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ChildService.java index 71b1bc697e..17f5c36e48 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ChildService.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ChildService.java @@ -4,12 +4,12 @@ import org.baeldung.persistence.dao.IChildDao; import org.baeldung.persistence.dao.common.IOperations; import org.baeldung.persistence.model.Child; import org.baeldung.persistence.service.IChildService; -import org.baeldung.persistence.service.common.AbstractService; +import org.baeldung.persistence.service.common.AbstractHibernateService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class ChildService extends AbstractServiceimplements IChildService { +public class ChildService extends AbstractHibernateServiceimplements IChildService { @Autowired private IChildDao dao; diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooAuditableService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooAuditableService.java new file mode 100644 index 0000000000..bef9ba5fad --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooAuditableService.java @@ -0,0 +1,41 @@ +package org.baeldung.persistence.service.impl; + +import org.baeldung.persistence.dao.IFooAuditableDao; +import org.baeldung.persistence.dao.IFooDao; +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Foo; +import org.baeldung.persistence.service.IFooAuditableService; +import org.baeldung.persistence.service.common.AbstractHibernateAuditableService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class FooAuditableService extends AbstractHibernateAuditableService implements IFooAuditableService { + + @Autowired + @Qualifier("fooHibernateDao") + private IFooDao dao; + + @Autowired + @Qualifier("fooHibernateAuditableDao") + private IFooAuditableDao auditDao; + + public FooAuditableService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + + @Override + protected IAuditOperations getAuditableDao() { + return auditDao; + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooService.java index 8a89153dd0..65b5cdec5c 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooService.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooService.java @@ -4,14 +4,16 @@ import org.baeldung.persistence.dao.IFooDao; import org.baeldung.persistence.dao.common.IOperations; import org.baeldung.persistence.model.Foo; import org.baeldung.persistence.service.IFooService; -import org.baeldung.persistence.service.common.AbstractService; +import org.baeldung.persistence.service.common.AbstractHibernateService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service -public class FooService extends AbstractServiceimplements IFooService { +public class FooService extends AbstractHibernateServiceimplements IFooService { @Autowired + @Qualifier("fooHibernateDao") private IFooDao dao; public FooService() { diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ParentService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ParentService.java index 1f9b602350..b78ae53264 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ParentService.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ParentService.java @@ -4,12 +4,12 @@ import org.baeldung.persistence.dao.IParentDao; import org.baeldung.persistence.dao.common.IOperations; import org.baeldung.persistence.model.Parent; import org.baeldung.persistence.service.IParentService; -import org.baeldung.persistence.service.common.AbstractService; +import org.baeldung.persistence.service.common.AbstractHibernateService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class ParentService extends AbstractServiceimplements IParentService { +public class ParentService extends AbstractHibernateServiceimplements IParentService { @Autowired private IParentDao dao; diff --git a/spring-hibernate4/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-hibernate4/src/main/java/org/baeldung/spring/PersistenceConfig.java index 000c67d625..ae7ecf3439 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ b/spring-hibernate4/src/main/java/org/baeldung/spring/PersistenceConfig.java @@ -5,7 +5,24 @@ import java.util.Properties; import javax.sql.DataSource; import org.apache.tomcat.dbcp.dbcp.BasicDataSource; -import org.hibernate.SessionFactory; +import org.baeldung.persistence.dao.IBarAuditableDao; +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.IFooAuditableDao; +import org.baeldung.persistence.dao.IFooDao; +import org.baeldung.persistence.dao.impl.BarAuditableDao; +import org.baeldung.persistence.dao.impl.BarDao; +import org.baeldung.persistence.dao.impl.BarJpaDao; +import org.baeldung.persistence.dao.impl.FooAuditableDao; +import org.baeldung.persistence.dao.impl.FooDao; +import org.baeldung.persistence.service.IBarAuditableService; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.persistence.service.IFooAuditableService; +import org.baeldung.persistence.service.IFooService; +import org.baeldung.persistence.service.impl.BarAuditableService; +import org.baeldung.persistence.service.impl.BarJpaService; +import org.baeldung.persistence.service.impl.BarSpringDataJpaService; +import org.baeldung.persistence.service.impl.FooAuditableService; +import org.baeldung.persistence.service.impl.FooService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -13,14 +30,23 @@ 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.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement +@EnableJpaRepositories(basePackages = { "org.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") +@EnableJpaAuditing @PropertySource({ "classpath:persistence-mysql.properties" }) @ComponentScan({ "org.baeldung.persistence" }) public class PersistenceConfig { @@ -42,6 +68,19 @@ public class PersistenceConfig { return sessionFactory; } + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(restDataSource()); + emf.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + emf.setJpaVendorAdapter(vendorAdapter); + emf.setJpaProperties(hibernateProperties()); + + return emf; + } + @Bean public DataSource restDataSource() { final BasicDataSource dataSource = new BasicDataSource(); @@ -54,12 +93,17 @@ public class PersistenceConfig { } @Bean - @Autowired - public HibernateTransactionManager transactionManager(final SessionFactory sessionFactory) { - final HibernateTransactionManager txManager = new HibernateTransactionManager(); - txManager.setSessionFactory(sessionFactory); + public PlatformTransactionManager hibernateTransactionManager() { + final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory().getObject()); + return transactionManager; + } - return txManager; + @Bean + public PlatformTransactionManager jpaTransactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); + return transactionManager; } @Bean @@ -67,7 +111,57 @@ public class PersistenceConfig { return new PersistenceExceptionTranslationPostProcessor(); } - final Properties hibernateProperties() { + @Bean + public IBarService barJpaService() { + return new BarJpaService(); + } + + @Bean + public IBarService barSpringDataJpaService() { + return new BarSpringDataJpaService(); + } + + @Bean + public IFooService fooHibernateService() { + return new FooService(); + } + + @Bean + public IBarAuditableService barHibernateAuditableService() { + return new BarAuditableService(); + } + + @Bean + public IFooAuditableService fooHibernateAuditableService() { + return new FooAuditableService(); + } + + @Bean + public IBarDao barJpaDao() { + return new BarJpaDao(); + } + + @Bean + public IBarDao barHibernateDao() { + return new BarDao(); + } + + @Bean + public IBarAuditableDao barHibernateAuditableDao() { + return new BarAuditableDao(); + } + + @Bean + public IFooDao fooHibernateDao() { + return new FooDao(); + } + + @Bean + public IFooAuditableDao fooHibernateAuditableDao() { + return new FooAuditableDao(); + } + + private 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")); @@ -76,6 +170,9 @@ public class PersistenceConfig { // hibernateProperties.setProperty("hibernate.format_sql", "true"); // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + // Envers properties + hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); + return hibernateProperties; } diff --git a/spring-hibernate4/src/main/resources/persistence-mysql.properties b/spring-hibernate4/src/main/resources/persistence-mysql.properties index 8263b0d9ac..f6b6ab6fca 100644 --- a/spring-hibernate4/src/main/resources/persistence-mysql.properties +++ b/spring-hibernate4/src/main/resources/persistence-mysql.properties @@ -8,3 +8,6 @@ jdbc.pass=tutorialmy5ql hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop + +# envers.X +envers.audit_table_suffix=_audit_log diff --git a/spring-hibernate4/src/main/resources/webSecurityConfig.xml b/spring-hibernate4/src/main/resources/webSecurityConfig.xml index 88af78dabc..d9423d31e7 100644 --- a/spring-hibernate4/src/main/resources/webSecurityConfig.xml +++ b/spring-hibernate4/src/main/resources/webSecurityConfig.xml @@ -5,7 +5,8 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" > - + + diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/AuditTestSuite.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/AuditTestSuite.java new file mode 100644 index 0000000000..d3a0ab9cb6 --- /dev/null +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/AuditTestSuite.java @@ -0,0 +1,14 @@ +package org.baeldung.persistence.audit; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ // @formatter:off + EnversFooBarAuditTest.class, + JPABarAuditTest.class, + SpringDataJPABarAuditTest.class +}) // @formatter:on +public class AuditTestSuite { + // +} \ No newline at end of file diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/EnversFooBarAuditTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/EnversFooBarAuditTest.java new file mode 100644 index 0000000000..7720253237 --- /dev/null +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/EnversFooBarAuditTest.java @@ -0,0 +1,142 @@ +package org.baeldung.persistence.audit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.List; + +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.model.Foo; +import org.baeldung.persistence.service.IBarAuditableService; +import org.baeldung.persistence.service.IFooAuditableService; +import org.baeldung.spring.PersistenceConfig; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +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 = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class EnversFooBarAuditTest { + + private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + @Autowired + @Qualifier("fooHibernateAuditableService") + private IFooAuditableService fooService; + + @Autowired + @Qualifier("barHibernateAuditableService") + private IBarAuditableService barService; + + @Autowired + private SessionFactory sessionFactory; + + private Session session; + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + makeRevisions(); + session = sessionFactory.openSession(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + session.close(); + } + + private void makeRevisions() { + final Bar bar = rev1(); + rev2(bar); + rev3(bar); + rev4(bar); + } + + // REV #1: insert BAR & FOO1 + private Bar rev1() { + final Bar bar = new Bar("BAR"); + final Foo foo1 = new Foo("FOO1"); + foo1.setBar(bar); + fooService.create(foo1); + return bar; + } + + // REV #2: insert FOO2 & update BAR + private void rev2(final Bar bar) { + final Foo foo2 = new Foo("FOO2"); + foo2.setBar(bar); + fooService.create(foo2); + } + + // REV #3: update BAR + private void rev3(final Bar bar) { + + bar.setName("BAR1"); + barService.update(bar); + } + + // REV #4: insert FOO3 & update BAR + private void rev4(final Bar bar) { + + final Foo foo3 = new Foo("FOO3"); + foo3.setBar(bar); + fooService.create(foo3); + } + + @Test + public final void whenFooBarsModified_thenFooBarsAudited() { + + List barRevisionList; + List fooRevisionList; + + // test Bar revisions + + barRevisionList = barService.getRevisions(); + + assertNotNull(barRevisionList); + assertEquals(4, barRevisionList.size()); + + assertEquals("BAR", barRevisionList.get(0).getName()); + assertEquals("BAR", barRevisionList.get(1).getName()); + assertEquals("BAR1", barRevisionList.get(2).getName()); + assertEquals("BAR1", barRevisionList.get(3).getName()); + + assertEquals(1, barRevisionList.get(0).getFooSet().size()); + assertEquals(2, barRevisionList.get(1).getFooSet().size()); + assertEquals(2, barRevisionList.get(2).getFooSet().size()); + assertEquals(3, barRevisionList.get(3).getFooSet().size()); + + // test Foo revisions + + fooRevisionList = fooService.getRevisions(); + assertNotNull(fooRevisionList); + assertEquals(3, fooRevisionList.size()); + assertEquals("FOO1", fooRevisionList.get(0).getName()); + assertEquals("FOO2", fooRevisionList.get(1).getName()); + assertEquals("FOO3", fooRevisionList.get(2).getName()); + } + +} diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/JPABarAuditTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/JPABarAuditTest.java new file mode 100644 index 0000000000..3f1353ba8c --- /dev/null +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/JPABarAuditTest.java @@ -0,0 +1,106 @@ +package org.baeldung.persistence.audit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.model.Bar.OPERATION; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.spring.PersistenceConfig; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +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 = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class JPABarAuditTest { + + private static Logger logger = LoggerFactory.getLogger(JPABarAuditTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + + @Autowired + @Qualifier("barJpaService") + private IBarService barService; + + @Autowired + private EntityManagerFactory entityManagerFactory; + + private EntityManager em; + + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + em = entityManagerFactory.createEntityManager(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + em.close(); + } + + + @Test + public final void whenBarsModified_thenBarsAudited() { + + // insert BAR1 + Bar bar1 = new Bar("BAR1"); + barService.create(bar1); + + // update BAR1 + bar1.setName("BAR1a"); + barService.update(bar1); + + // insert BAR2 + Bar bar2 = new Bar("BAR2"); + barService.create(bar2); + + // update BAR1 + bar1.setName("BAR1b"); + barService.update(bar1); + + + // get BAR1 and BAR2 from the DB and check the audit values + // detach instances from persistence context to make sure we fire db + em.detach(bar1); + em.detach(bar2); + bar1 = barService.findOne(bar1.getId()); + bar2 = barService.findOne(bar2.getId()); + + assertNotNull(bar1); + assertNotNull(bar2); + assertEquals(OPERATION.UPDATE, bar1.getOperation()); + assertEquals(OPERATION.INSERT, bar2.getOperation()); + assertTrue(bar1.getTimestamp() > bar2.getTimestamp()); + + barService.deleteById(bar1.getId()); + barService.deleteById(bar2.getId()); + + } + +} \ No newline at end of file diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/SpringDataJPABarAuditTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/SpringDataJPABarAuditTest.java new file mode 100644 index 0000000000..bddaac4011 --- /dev/null +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/SpringDataJPABarAuditTest.java @@ -0,0 +1,76 @@ +package org.baeldung.persistence.audit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.spring.PersistenceConfig; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.test.context.support.WithMockUser; +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 = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringDataJPABarAuditTest { + + private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + @Autowired + @Qualifier("barSpringDataJpaService") + private IBarService barService; + + @Autowired + private EntityManagerFactory entityManagerFactory; + + private EntityManager em; + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + em = entityManagerFactory.createEntityManager(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + em.close(); + } + + @Test + @WithMockUser(username = "tutorialuser") + public final void whenBarsModified_thenBarsAudited() { + Bar bar = new Bar("BAR1"); + barService.create(bar); + assertEquals(bar.getCreatedDate(), bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + bar.setName("BAR2"); + bar = barService.update(bar); + assertTrue(bar.getCreatedDate() < bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + } +} diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java index 07c6ba3382..37781aeb22 100644 --- a/spring-hibernate4/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java @@ -8,6 +8,7 @@ import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.InvalidDataAccessApiUsageException; @@ -20,6 +21,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; public class FooServicePersistenceIntegrationTest { @Autowired + @Qualifier("fooHibernateService") private IFooService service; // tests From b6ba166e723a7ec888d19059c433b487c082d8e1 Mon Sep 17 00:00:00 2001 From: gmaipady Date: Wed, 30 Dec 2015 21:17:31 +0530 Subject: [PATCH 041/309] Moved from XML config to Java config --- spring-thymeleaf/.classpath | 12 ++--- spring-thymeleaf/pom.xml | 3 ++ .../WEB-INF/appServlet/servlet-context.xml | 53 ------------------- .../src/main/webapp/WEB-INF/root-context.xml | 8 --- .../src/main/webapp/WEB-INF/web.xml | 34 ------------ 5 files changed, 9 insertions(+), 101 deletions(-) delete mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml delete mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml delete mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/web.xml diff --git a/spring-thymeleaf/.classpath b/spring-thymeleaf/.classpath index 28e4a52cd4..81999ab717 100644 --- a/spring-thymeleaf/.classpath +++ b/spring-thymeleaf/.classpath @@ -11,12 +11,6 @@ - - - - - - @@ -28,5 +22,11 @@ + + + + + + diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 1a8dff671e..ae7451a74e 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -112,6 +112,9 @@ org.apache.maven.plugins maven-war-plugin ${maven-war-plugin.version} + + false + org.apache.maven.plugins diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml deleted file mode 100644 index ef42557429..0000000000 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml deleted file mode 100644 index 5cb2a94d73..0000000000 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 275a482c6f..0000000000 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - contextConfigLocation - /WEB-INF/root-context.xml - - - - - org.springframework.web.context.ContextLoaderListener - - - - - appServlet - org.springframework.web.servlet.DispatcherServlet - - contextConfigLocation - /WEB-INF/appServlet/servlet-context.xml - - 1 - - - - appServlet - / - - \ No newline at end of file From 02740211b07ecaadc6428ee5d9e29b8bdb14df9b Mon Sep 17 00:00:00 2001 From: gmaipady Date: Wed, 30 Dec 2015 21:21:21 +0530 Subject: [PATCH 042/309] Moved from XML config to Java config --- .../org/baeldung/thymeleaf/config/WebApp.java | 36 +++++++++ .../thymeleaf/config/WebMVCConfig.java | 73 +++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java new file mode 100644 index 0000000000..45752a6269 --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java @@ -0,0 +1,36 @@ +package org.baeldung.thymeleaf.config; + +import javax.servlet.ServletRegistration.Dynamic; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +/** + * Java configuration file that is used for web application initialization + */ +public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer { + + public WebApp() { + super(); + } + + @Override + protected Class[] getRootConfigClasses() { + return null; + } + + @Override + protected Class[] getServletConfigClasses() { + return new Class[] { WebMVCConfig.class }; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + + @Override + protected void customizeRegistration(final Dynamic registration) { + super.customizeRegistration(registration); + } + +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java new file mode 100644 index 0000000000..c5bd460eee --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java @@ -0,0 +1,73 @@ +package org.baeldung.thymeleaf.config; + +import org.baeldung.thymeleaf.formatter.NameFormatter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Description; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.format.FormatterRegistry; +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.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; + +@Configuration +@EnableWebMvc +@ComponentScan({ "org.baeldung.thymeleaf" }) +/** + * Java configuration file that is used for Spring MVC and Thymeleaf + * configurations + */ +public class WebMVCConfig extends WebMvcConfigurerAdapter { + + @Bean + @Description("Thymeleaf Template Resolver") + public ServletContextTemplateResolver templateResolver() { + ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/views/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + + return templateResolver; + } + + @Bean + @Description("Thymeleaf Template Engine") + public SpringTemplateEngine templateEngine() { + SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + + return templateEngine; + } + + @Bean + @Description("Thymeleaf View Resolver") + public ThymeleafViewResolver viewResolver() { + ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } + + @Bean + @Description("Spring Message Resolver") + public ResourceBundleMessageSource messageSource() { + ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); + } + + @Override + @Description("Custom Conversion Service") + public void addFormatters(FormatterRegistry registry) { + registry.addFormatter(new NameFormatter()); + } +} From 4a6c23cac65b50769c4f7a289aa1e456f23eb510 Mon Sep 17 00:00:00 2001 From: Alex V Date: Thu, 31 Dec 2015 05:14:39 +0200 Subject: [PATCH 043/309] Code for "Lambda Expressions and Functional Interfaces. Best Practices and Tips" article --- .../src/main/java/org/baeldung/Adder.java | 12 +++ .../src/main/java/org/baeldung/AdderImpl.java | 16 +++ .../src/main/java/org/baeldung/Bar.java | 12 +++ .../src/main/java/org/baeldung/Baz.java | 11 ++ .../src/main/java/org/baeldung/Foo.java | 9 ++ .../main/java/org/baeldung/FooExtended.java | 11 ++ .../src/main/java/org/baeldung/UseFoo.java | 39 +++++++ .../Java8FunctionalInteracesLambdasTest.java | 101 ++++++++++++++++++ .../baeldung/java8/JavaFolderSizeTest.java | 21 ++-- 9 files changed, 226 insertions(+), 6 deletions(-) create mode 100644 core-java-8/src/main/java/org/baeldung/Adder.java create mode 100644 core-java-8/src/main/java/org/baeldung/AdderImpl.java create mode 100644 core-java-8/src/main/java/org/baeldung/Bar.java create mode 100644 core-java-8/src/main/java/org/baeldung/Baz.java create mode 100644 core-java-8/src/main/java/org/baeldung/Foo.java create mode 100644 core-java-8/src/main/java/org/baeldung/FooExtended.java create mode 100644 core-java-8/src/main/java/org/baeldung/UseFoo.java create mode 100644 core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java diff --git a/core-java-8/src/main/java/org/baeldung/Adder.java b/core-java-8/src/main/java/org/baeldung/Adder.java new file mode 100644 index 0000000000..4578990de7 --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/Adder.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import java.util.function.Consumer; +import java.util.function.Function; + +public interface Adder { + + String addWithFunction(Function f); + + void addWithConsumer(Consumer f); + +} diff --git a/core-java-8/src/main/java/org/baeldung/AdderImpl.java b/core-java-8/src/main/java/org/baeldung/AdderImpl.java new file mode 100644 index 0000000000..a62c0cd4fb --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/AdderImpl.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import java.util.function.Consumer; +import java.util.function.Function; + +public class AdderImpl implements Adder { + + @Override + public String addWithFunction(Function f) { + return f.apply("Something "); + } + + @Override + public void addWithConsumer(Consumer f) {} + +} diff --git a/core-java-8/src/main/java/org/baeldung/Bar.java b/core-java-8/src/main/java/org/baeldung/Bar.java new file mode 100644 index 0000000000..0dd7df6be2 --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/Bar.java @@ -0,0 +1,12 @@ +package org.baeldung; + +@FunctionalInterface +public interface Bar { + + String method(String string); + + default String defaultMethod() { + return "String from Bar"; + } + +} diff --git a/core-java-8/src/main/java/org/baeldung/Baz.java b/core-java-8/src/main/java/org/baeldung/Baz.java new file mode 100644 index 0000000000..bcc46af6e7 --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/Baz.java @@ -0,0 +1,11 @@ +package org.baeldung; + +@FunctionalInterface +public interface Baz { + + String method(String string); + + default String defaultMethod() { + return "String from Baz"; + } +} diff --git a/core-java-8/src/main/java/org/baeldung/Foo.java b/core-java-8/src/main/java/org/baeldung/Foo.java new file mode 100644 index 0000000000..a10e45a8f5 --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/Foo.java @@ -0,0 +1,9 @@ +package org.baeldung; + +@FunctionalInterface +public interface Foo { + + String method(String string); + + default void defaultMethod() {} +} diff --git a/core-java-8/src/main/java/org/baeldung/FooExtended.java b/core-java-8/src/main/java/org/baeldung/FooExtended.java new file mode 100644 index 0000000000..39c3a0765f --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/FooExtended.java @@ -0,0 +1,11 @@ +package org.baeldung; + +@FunctionalInterface +public interface FooExtended extends Baz, Bar { + + @Override + default String defaultMethod() { + return Bar.super.defaultMethod(); + } + +} diff --git a/core-java-8/src/main/java/org/baeldung/UseFoo.java b/core-java-8/src/main/java/org/baeldung/UseFoo.java new file mode 100644 index 0000000000..a29c5631ac --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/UseFoo.java @@ -0,0 +1,39 @@ +package org.baeldung; + +import java.util.function.Function; + +public class UseFoo { + + private String value = "Enclosing scope value"; + + public String add(String string, Foo foo) { + return foo.method(string); + } + + public String addWithStandardFI(String string, Function fn) { + return fn.apply(string); + } + + public String scopeExperiment() { + Foo fooIC = new Foo() { + String value = "Inner class value"; + + @Override + public String method(String string) { + return this.value; + } + }; + String resultIC = fooIC.method(""); + + Foo fooLambda = parameter -> { + String value = "Lambda value"; + return this.value; + }; + String resultLambda = fooLambda.method(""); + + return "Results: resultIC = " + resultIC + + ", resultLambda = " + resultLambda; + } + + +} diff --git a/core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java b/core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java new file mode 100644 index 0000000000..3845d6ba84 --- /dev/null +++ b/core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java @@ -0,0 +1,101 @@ +package org.baeldung.java8; + +import org.baeldung.Foo; +import org.baeldung.FooExtended; +import org.baeldung.UseFoo; +import org.junit.Before; +import org.junit.Test; + +import java.util.function.Function; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class Java8FunctionalInteracesLambdasTest { + + private UseFoo useFoo; + + @Before + public void init() { + useFoo = new UseFoo(); + } + + @Test + public void functionalInterfaceInstantiation_whenReturnDefiniteString_thenCorrect() { + + Foo foo = parameter -> parameter + "from lambda"; + String result = useFoo.add("Message ", foo); + + assertEquals("Message from lambda", result); + } + + @Test + public void standardFIParameter_whenReturnDefiniteString_thenCorrect() { + + Function fn = parameter -> parameter + "from lambda"; + String result = useFoo.addWithStandardFI("Message ", fn); + + assertEquals("Message from lambda", result); + } + + @Test + public void defaultMethodFromExtendedInterface_whenReturnDefiniteString_thenCorrect() { + + FooExtended fooExtended = string -> string; + String result = fooExtended.defaultMethod(); + + assertEquals("String from Bar", result); + } + + @Test + public void lambdaAndInnerClassInstantiation_whenReturnSameString_thenCorrect() { + + Foo foo = parameter -> parameter + "from Foo"; + + Foo fooByIC = new Foo() { + @Override + public String method(String string) { + return string + "from Foo"; + } + }; + + assertEquals(foo.method("Something "), fooByIC.method("Something ")); + } + + @Test + public void accessVariablesFromDifferentScopes_whenReturnPredefinedString_thenCorrect() { + + assertEquals("Results: resultIC = Inner class value, resultLambda = Enclosing scope value", + useFoo.scopeExperiment()); + } + + @Test + public void shorteningLambdas_whenReturnEqualsResults_thenCorrect() { + + Foo foo = parameter -> buildString(parameter); + + Foo fooHuge = parameter -> { String result = "Something " + parameter; + //many lines of code + return result; + }; + + assertEquals(foo.method("Something"), fooHuge.method("Something")); + } + + private String buildString(String parameter) { + String result = "Something " + parameter; + //many lines of code + return result; + } + + @Test + public void mutatingOfEffectivelyFinalVariable_whenNotEquals_thenCorrect() { + + int[] total = new int[1]; + Runnable r = () -> total[0]++; + r.run(); + + assertNotEquals(0, total[0]); + } + +} diff --git a/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java b/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java index baa41511de..a65971bb91 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java +++ b/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java @@ -15,15 +15,24 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.stream.StreamSupport; import org.apache.commons.io.FileUtils; +import org.junit.Before; import org.junit.Test; public class JavaFolderSizeTest { + private String path; + + @Before + public void init() { + final String separator = File.separator; + path = "src" + separator + "test" + separator + "resources"; + } + @Test public void whenGetFolderSizeRecursive_thenCorrect() { final long expectedSize = 136; - final File folder = new File("src/test/resources"); + final File folder = new File(path); final long size = getFolderSize(folder); assertEquals(expectedSize, size); @@ -34,7 +43,7 @@ public class JavaFolderSizeTest { final long expectedSize = 136; final AtomicLong size = new AtomicLong(0); - final Path folder = Paths.get("src/test/resources"); + final Path folder = Paths.get(path); Files.walkFileTree(folder, new SimpleFileVisitor() { @Override @@ -51,7 +60,7 @@ public class JavaFolderSizeTest { public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException { final long expectedSize = 136; - final Path folder = Paths.get("src/test/resources"); + final Path folder = Paths.get(path); final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum(); assertEquals(expectedSize, size); @@ -61,7 +70,7 @@ public class JavaFolderSizeTest { public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() { final long expectedSize = 136; - final File folder = new File("src/test/resources"); + final File folder = new File(path); final long size = FileUtils.sizeOfDirectory(folder); assertEquals(expectedSize, size); @@ -71,7 +80,7 @@ public class JavaFolderSizeTest { public void whenGetFolderSizeUsingGuava_thenCorrect() { final long expectedSize = 136; - final File folder = new File("src/test/resources"); + final File folder = new File(path); final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); final long size = StreamSupport.stream(files.spliterator(), false).filter(f -> f.isFile()).mapToLong(File::length).sum(); @@ -81,7 +90,7 @@ public class JavaFolderSizeTest { @Test public void whenGetReadableSize_thenCorrect() { - final File folder = new File("src/test/resources"); + final File folder = new File(path); final long size = getFolderSize(folder); final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" }; From f921036f4f5d4d18fd93917b59a7cc54eeffbe7d Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 31 Dec 2015 13:02:15 +0200 Subject: [PATCH 044/309] Handling accessDenied --- .../baeldung/spring/SecSecurityConfig.java | 48 +++++++++++++++++-- .../web/controller/RootController.java | 15 ++++-- .../web/error/CustomAccessDeniedHandler.java | 22 +++++++++ .../RestResponseEntityExceptionHandler.java | 7 +++ .../src/main/resources/webSecurityConfig.xml | 7 ++- 5 files changed, 92 insertions(+), 7 deletions(-) create mode 100644 spring-security-rest-full/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/SecSecurityConfig.java index acf5ff6be5..75daacbb04 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,16 +1,58 @@ package org.baeldung.spring; +import org.baeldung.web.error.CustomAccessDeniedHandler; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableAutoConfiguration -@ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecSecurityConfig { +// +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +// @ImportResource({ "classpath:webSecurityConfig.xml" }) +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private CustomAccessDeniedHandler accessDeniedHandler; public SecSecurityConfig() { super(); } + // java config + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN"); + } + + @Override + public void configure(final WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN") + .anyRequest().authenticated() + .and() + .httpBasic() + .and() + // .exceptionHandling().accessDeniedPage("/my-error-page") + .exceptionHandling().accessDeniedHandler(accessDeniedHandler) + ; + // @formatter:on + } + } 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 42fc78f611..e83b8cf5ba 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 @@ -11,6 +11,7 @@ import org.baeldung.web.metric.IMetricService; import org.baeldung.web.util.LinkUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -51,6 +52,7 @@ public class RootController { return metricService.getFullMetric(); } + @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping(value = "/status-metric", method = RequestMethod.GET) @ResponseBody public Map getStatusMetric() { @@ -67,9 +69,16 @@ public class RootController { return result; } - @RequestMapping(value = "/metric-graph-data", method = RequestMethod.GET) + @RequestMapping(value = "/admin/x", method = RequestMethod.GET) @ResponseBody - public Object[][] getActuatorMetricData() { - return actMetricService.getGraphData(); + public String sampleAdminPage() { + return "Hello"; } + + @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/error/CustomAccessDeniedHandler.java b/spring-security-rest-full/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java new file mode 100644 index 0000000000..ae7340ef88 --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java @@ -0,0 +1,22 @@ +package org.baeldung.web.error; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +@Component +public class CustomAccessDeniedHandler implements AccessDeniedHandler { + + @Override + public void handle(final HttpServletRequest request, final HttpServletResponse response, final AccessDeniedException ex) throws IOException, ServletException { + response.getOutputStream().print("Error Message Goes Here"); + // response.sendRedirect("/my-error-page"); + } + +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java b/spring-security-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java index a465a82d75..e9d34aa9cf 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java @@ -11,11 +11,13 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.security.access.AccessDeniedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +//import org.springframework.security.access.AccessDeniedException; @ControllerAdvice public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @@ -54,6 +56,11 @@ public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionH } // 403 + @ExceptionHandler({ AccessDeniedException.class }) + public ResponseEntity handleAccessDeniedException(final Exception ex, final WebRequest request) { + System.out.println("request" + request.getUserPrincipal()); + return new ResponseEntity("Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN); + } // 404 diff --git a/spring-security-rest-full/src/main/resources/webSecurityConfig.xml b/spring-security-rest-full/src/main/resources/webSecurityConfig.xml index 915460bd44..a60033b71a 100644 --- a/spring-security-rest-full/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest-full/src/main/resources/webSecurityConfig.xml @@ -9,19 +9,24 @@ - + + + + + + From bfdcb18a3a083b4ee39d435e9c9a6993a9ab39e8 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 4 Jan 2016 00:55:58 +0200 Subject: [PATCH 045/309] cleanup work --- .../.settings/org.eclipse.wst.common.project.facet.core.xml | 2 +- .../src/main/resources/webSecurityConfig.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml index f5888c1411..8a1c189419 100644 --- a/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml +++ b/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -1,5 +1,5 @@ - + diff --git a/spring-security-rest-digest-auth/src/main/resources/webSecurityConfig.xml b/spring-security-rest-digest-auth/src/main/resources/webSecurityConfig.xml index 695efa8047..42a59abff0 100644 --- a/spring-security-rest-digest-auth/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest-digest-auth/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ From 4a029959af84de55bdee134b40fa164bab94c5a9 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 4 Jan 2016 01:01:27 +0200 Subject: [PATCH 046/309] minor cleanup --- .../main/java/org/baeldung/web/metric/MetricFilter.java | 2 +- .../src/main/resources/springDataPersistenceConfig.xml | 7 +++++-- .../src/main/resources/webSecurityConfig.xml | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java index d77aec7919..6c2fb0cb39 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java @@ -26,7 +26,7 @@ public class MetricFilter implements Filter { public void init(final FilterConfig config) throws ServletException { if (metricService == null || actMetricService == null) { metricService = (IMetricService) WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean("metricService"); - actMetricService = (ICustomActuatorMetricService) WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean("actuatorMetricService"); + actMetricService = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean(CustomActuatorMetricService.class); } } diff --git a/spring-security-rest-full/src/main/resources/springDataPersistenceConfig.xml b/spring-security-rest-full/src/main/resources/springDataPersistenceConfig.xml index 5c971d975d..d6d0ec6e47 100644 --- a/spring-security-rest-full/src/main/resources/springDataPersistenceConfig.xml +++ b/spring-security-rest-full/src/main/resources/springDataPersistenceConfig.xml @@ -1,7 +1,10 @@ diff --git a/spring-security-rest-full/src/main/resources/webSecurityConfig.xml b/spring-security-rest-full/src/main/resources/webSecurityConfig.xml index a60033b71a..d6ba952dfd 100644 --- a/spring-security-rest-full/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest-full/src/main/resources/webSecurityConfig.xml @@ -4,7 +4,7 @@ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" + http://www.springframework.org/schema/beans/spring-beans.xsd" > From 6b10b326a2b39737a4ffd5daa40fa884d1db9cac Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 5 Jan 2016 19:55:11 +0200 Subject: [PATCH 047/309] cleanup and upgrade --- spring-all/pom.xml | 4 -- spring-katharsis/pom.xml | 6 ++- spring-security-mvc-ldap/pom.xml | 42 ++----------------- .../org/baeldung/security/SecurityConfig.java | 4 +- .../src/main/resources/templates/login.html | 2 +- .../src/main/resources/webSecurityConfig.xml | 5 +-- spring-security-rest-full/pom.xml | 26 ++++++------ spring-security-rest/pom.xml | 18 ++++---- .../baeldung/spring/SecurityJavaConfig.java | 7 +--- .../src/main/resources/webSecurityConfig.xml | 4 +- 10 files changed, 42 insertions(+), 76 deletions(-) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 16ff340d81..6ce8ad7196 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -128,7 +128,6 @@ junit junit - ${junit.version} test @@ -164,7 +163,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} 1.8 1.8 @@ -174,7 +172,6 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} false @@ -183,7 +180,6 @@ org.apache.maven.plugins maven-surefire-plugin - ${maven-surefire-plugin.version} diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 554ff4e656..892aaf24f1 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -31,7 +31,7 @@ io.katharsis katharsis-servlet - 1.0.0 + ${katharsis.version} @@ -45,7 +45,7 @@ com.jayway.restassured rest-assured - 2.4.0 + ${restassured.version} test @@ -60,6 +60,8 @@ 1.8 + 1.0.0 + 2.4.0 diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index 5282f76a7e..3f9b9ad1ed 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.4.RELEASE + 1.3.1.RELEASE @@ -39,7 +39,7 @@ org.apache.directory.server apacheds-server-jndi - 1.5.5 + ${apacheds.version} @@ -68,42 +68,8 @@ - - - 4.2.4.RELEASE - 4.0.3.RELEASE - - - 4.3.11.Final - 5.1.37 - - - 1.7.13 - 1.1.3 - - - 5.2.2.Final - - - 19.0 - 3.4 - - - 1.3 - 4.12 - 1.10.19 - - 4.4.1 - 4.5 - - 2.4.1 - - - 3.3 - 2.6 - 2.18.1 - 1.4.15 - + + 1.5.5 diff --git a/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java b/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java index ee72ee7891..0d444e36ff 100644 --- a/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java +++ b/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java @@ -9,7 +9,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur * Security Configuration - LDAP and HTTP Authorizations. */ @Configuration -// @ImportResource({ "classpath:webSecurityConfig.xml" }) +// @ImportResource({ "classpath:webSecurityConfig.xml" }) //=> uncomment to use equivalent xml config public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override @@ -20,7 +20,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/", "/home").permitAll().anyRequest().authenticated(); - http.formLogin().loginPage("/login").permitAll().loginProcessingUrl("/j_spring_security_check").and().logout().logoutSuccessUrl("/"); + http.formLogin().loginPage("/login").permitAll().and().logout().logoutSuccessUrl("/"); } } diff --git a/spring-security-mvc-ldap/src/main/resources/templates/login.html b/spring-security-mvc-ldap/src/main/resources/templates/login.html index 81f62fde13..e21ea21e69 100644 --- a/spring-security-mvc-ldap/src/main/resources/templates/login.html +++ b/spring-security-mvc-ldap/src/main/resources/templates/login.html @@ -21,7 +21,7 @@

You have been logged out

There was an error, please try again

Login with Username and Password

- +
diff --git a/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml index 6bd2c422d8..c13f65de5e 100644 --- a/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml @@ -13,10 +13,7 @@ - + diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index bed716897b..cbcc3fca64 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.0.RELEASE + 1.3.1.RELEASE @@ -113,12 +113,12 @@ com.mysema.querydsl querydsl-apt - 3.6.2 + ${querydsl.version} com.mysema.querydsl querydsl-jpa - 3.6.2 + ${querydsl.version} @@ -126,7 +126,7 @@ cz.jirutka.rsql rsql-parser - 2.0.0 + ${rsql.version} @@ -144,7 +144,6 @@ org.apache.httpcomponents httpcore - ${httpcore.version} @@ -164,7 +163,7 @@ xml-apis xml-apis - 1.4.01 + ${xml-apis.version} org.javassist @@ -200,7 +199,7 @@ com.thoughtworks.xstream xstream - 1.4.8 + ${xstream.version} @@ -243,7 +242,6 @@ junit junit - ${junit.version} test @@ -267,7 +265,7 @@ com.jayway.restassured rest-assured - 2.4.0 + ${rest-assured.version} test @@ -344,7 +342,7 @@ com.mysema.maven apt-maven-plugin - 1.1.3 + ${apt-maven-plugin.version} @@ -434,9 +432,12 @@ 5.1.37 1.7.2.RELEASE + 2.0.0 + 3.6.2 + - 2.5.5 + 1.4.01 1.7.13 @@ -444,6 +445,7 @@ 5.2.2.Final + 1.4.8 19.0 @@ -464,7 +466,7 @@ 2.6 2.18.1 1.4.15 - + 1.1.3 \ No newline at end of file diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 42381bf607..2046b38810 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -82,14 +82,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet-api.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -98,7 +98,7 @@ com.fasterxml.jackson.core jackson-databind - 2.2.2 + ${jackson.version} @@ -111,7 +111,7 @@ org.apache.commons commons-lang3 - 3.1 + ${commons-lang3.version} @@ -171,13 +171,13 @@ io.springfox springfox-swagger2 - 2.2.2 + ${springfox.version} io.springfox springfox-swagger-ui - 2.2.2 + ${springfox.version} @@ -263,7 +263,11 @@ 5.2.2.Final - + 3.0.1 + 1.2 + 2.2.2 + 2.2.2 + 19.0 3.4 diff --git a/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java b/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java index ca882909f0..5b88fefdb2 100644 --- a/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java +++ b/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java @@ -35,19 +35,16 @@ public class SecurityJavaConfig extends WebSecurityConfigurerAdapter { } @Override - protected void configure(final HttpSecurity http) throws Exception { // @formatter:off + protected void configure(final HttpSecurity http) throws Exception {// @formatter:off http .csrf().disable() .exceptionHandling() .authenticationEntryPoint(restAuthenticationEntryPoint) .and() .authorizeRequests() - .antMatchers("/api/foos").authenticated() + .antMatchers("/api/**").authenticated() .and() .formLogin() - .loginProcessingUrl("/j_spring_security_check") - .usernameParameter("j_username") - .passwordParameter("j_password") .successHandler(authenticationSuccessHandler) .failureHandler(new SimpleUrlAuthenticationFailureHandler()) .and() diff --git a/spring-security-rest/src/main/resources/webSecurityConfig.xml b/spring-security-rest/src/main/resources/webSecurityConfig.xml index 20651c458c..619b53fb7e 100644 --- a/spring-security-rest/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest/src/main/resources/webSecurityConfig.xml @@ -11,7 +11,9 @@ - + + + From d0a80fc0c431da4569de65fc7473748c969b9bb9 Mon Sep 17 00:00:00 2001 From: David Morley Date: Tue, 5 Jan 2016 21:37:15 -0600 Subject: [PATCH 048/309] Remove Eclipse-specific metadata files --- spring-thymeleaf/.classpath | 32 ---------------------------- spring-thymeleaf/.project | 42 ------------------------------------- 2 files changed, 74 deletions(-) delete mode 100644 spring-thymeleaf/.classpath delete mode 100644 spring-thymeleaf/.project diff --git a/spring-thymeleaf/.classpath b/spring-thymeleaf/.classpath deleted file mode 100644 index 81999ab717..0000000000 --- a/spring-thymeleaf/.classpath +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-thymeleaf/.project b/spring-thymeleaf/.project deleted file mode 100644 index 3c898c7e84..0000000000 --- a/spring-thymeleaf/.project +++ /dev/null @@ -1,42 +0,0 @@ - - - spring-thymeleaf - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - From a937aef25e991a25650caf63c8d4f7c668a20804 Mon Sep 17 00:00:00 2001 From: David Morley Date: Tue, 5 Jan 2016 21:37:48 -0600 Subject: [PATCH 049/309] Rename package to conform with site name --- spring-thymeleaf/pom.xml | 2 +- .../baeldung/thymeleaf/config/WebApp.java | 72 ++++----- .../thymeleaf/config/WebMVCConfig.java | 146 +++++++++--------- .../thymeleaf/controller/HomeController.java | 2 +- .../controller/StudentController.java | 139 +++++++++-------- .../thymeleaf/formatter/NameFormatter.java | 60 +++---- .../baeldung/thymeleaf/model/Student.java | 120 +++++++------- 7 files changed, 270 insertions(+), 271 deletions(-) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/config/WebApp.java (91%) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/config/WebMVCConfig.java (92%) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/controller/HomeController.java (94%) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/controller/StudentController.java (92%) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/formatter/NameFormatter.java (91%) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/model/Student.java (91%) diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index ae7451a74e..16e6849f93 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -1,7 +1,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-thymeleaf 0.1-SNAPSHOT war diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java similarity index 91% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java index 45752a6269..89ad7e601e 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java @@ -1,36 +1,36 @@ -package org.baeldung.thymeleaf.config; - -import javax.servlet.ServletRegistration.Dynamic; - -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; - -/** - * Java configuration file that is used for web application initialization - */ -public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer { - - public WebApp() { - super(); - } - - @Override - protected Class[] getRootConfigClasses() { - return null; - } - - @Override - protected Class[] getServletConfigClasses() { - return new Class[] { WebMVCConfig.class }; - } - - @Override - protected String[] getServletMappings() { - return new String[] { "/" }; - } - - @Override - protected void customizeRegistration(final Dynamic registration) { - super.customizeRegistration(registration); - } - -} +package com.baeldung.thymeleaf.config; + +import javax.servlet.ServletRegistration.Dynamic; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +/** + * Java configuration file that is used for web application initialization + */ +public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer { + + public WebApp() { + super(); + } + + @Override + protected Class[] getRootConfigClasses() { + return null; + } + + @Override + protected Class[] getServletConfigClasses() { + return new Class[] { WebMVCConfig.class }; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + + @Override + protected void customizeRegistration(final Dynamic registration) { + super.customizeRegistration(registration); + } + +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java similarity index 92% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java index c5bd460eee..51c60247a1 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java @@ -1,73 +1,73 @@ -package org.baeldung.thymeleaf.config; - -import org.baeldung.thymeleaf.formatter.NameFormatter; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Description; -import org.springframework.context.support.ResourceBundleMessageSource; -import org.springframework.format.FormatterRegistry; -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.thymeleaf.spring4.SpringTemplateEngine; -import org.thymeleaf.spring4.view.ThymeleafViewResolver; -import org.thymeleaf.templateresolver.ServletContextTemplateResolver; - -@Configuration -@EnableWebMvc -@ComponentScan({ "org.baeldung.thymeleaf" }) -/** - * Java configuration file that is used for Spring MVC and Thymeleaf - * configurations - */ -public class WebMVCConfig extends WebMvcConfigurerAdapter { - - @Bean - @Description("Thymeleaf Template Resolver") - public ServletContextTemplateResolver templateResolver() { - ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); - templateResolver.setPrefix("/WEB-INF/views/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); - - return templateResolver; - } - - @Bean - @Description("Thymeleaf Template Engine") - public SpringTemplateEngine templateEngine() { - SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - - return templateEngine; - } - - @Bean - @Description("Thymeleaf View Resolver") - public ThymeleafViewResolver viewResolver() { - ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } - - @Bean - @Description("Spring Message Resolver") - public ResourceBundleMessageSource messageSource() { - ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); - messageSource.setBasename("messages"); - return messageSource; - } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); - } - - @Override - @Description("Custom Conversion Service") - public void addFormatters(FormatterRegistry registry) { - registry.addFormatter(new NameFormatter()); - } -} +package com.baeldung.thymeleaf.config; + +import com.baeldung.thymeleaf.formatter.NameFormatter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Description; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.format.FormatterRegistry; +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.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; + +@Configuration +@EnableWebMvc +@ComponentScan({ "com.baeldung.thymeleaf" }) +/** + * Java configuration file that is used for Spring MVC and Thymeleaf + * configurations + */ +public class WebMVCConfig extends WebMvcConfigurerAdapter { + + @Bean + @Description("Thymeleaf Template Resolver") + public ServletContextTemplateResolver templateResolver() { + ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/views/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + + return templateResolver; + } + + @Bean + @Description("Thymeleaf Template Engine") + public SpringTemplateEngine templateEngine() { + SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + + return templateEngine; + } + + @Bean + @Description("Thymeleaf View Resolver") + public ThymeleafViewResolver viewResolver() { + ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } + + @Bean + @Description("Spring Message Resolver") + public ResourceBundleMessageSource messageSource() { + ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); + } + + @Override + @Description("Custom Conversion Service") + public void addFormatters(FormatterRegistry registry) { + registry.addFormatter(new NameFormatter()); + } +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java similarity index 94% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java index 505dc8303b..a28d059acc 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java @@ -1,4 +1,4 @@ -package org.baeldung.thymeleaf.controller; +package com.baeldung.thymeleaf.controller; import java.text.DateFormat; import java.util.Date; diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java similarity index 92% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java index 3bef22cdae..912eb521f4 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java @@ -1,70 +1,69 @@ -package org.baeldung.thymeleaf.controller; - -import java.util.ArrayList; -import java.util.List; - -import javax.validation.Valid; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import org.baeldung.thymeleaf.model.Student; - -/** - * Handles requests for the student model. - * - */ -@Controller -public class StudentController { - - @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) - public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { - if (!errors.hasErrors()) { - // get mock objects - List students = buildStudents(); - // add current student - students.add(student); - model.addAttribute("students", students); - } - return ((errors.hasErrors()) ? "addStudent" : "listStudents"); - } - - @RequestMapping(value = "/addStudent", method = RequestMethod.GET) - public String addStudent(Model model) { - model.addAttribute("student", new Student()); - return "addStudent"; - } - - @RequestMapping(value = "/listStudents", method = RequestMethod.GET) - public String listStudent(Model model) { - - model.addAttribute("students", buildStudents()); - - return "listStudents"; - } - - private List buildStudents() { - List students = new ArrayList(); - - Student student1 = new Student(); - student1.setId(1001); - student1.setName("John Smith"); - student1.setGender('M'); - student1.setPercentage(Float.valueOf("80.45")); - - students.add(student1); - - Student student2 = new Student(); - student2.setId(1002); - student2.setName("Jane Williams"); - student2.setGender('F'); - student2.setPercentage(Float.valueOf("60.25")); - - students.add(student2); - return students; - } -} +package com.baeldung.thymeleaf.controller; + +import java.util.ArrayList; +import java.util.List; + +import javax.validation.Valid; + +import com.baeldung.thymeleaf.model.Student; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * Handles requests for the student model. + * + */ +@Controller +public class StudentController { + + @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) + public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { + if (!errors.hasErrors()) { + // get mock objects + List students = buildStudents(); + // add current student + students.add(student); + model.addAttribute("students", students); + } + return ((errors.hasErrors()) ? "addStudent" : "listStudents"); + } + + @RequestMapping(value = "/addStudent", method = RequestMethod.GET) + public String addStudent(Model model) { + model.addAttribute("student", new Student()); + return "addStudent"; + } + + @RequestMapping(value = "/listStudents", method = RequestMethod.GET) + public String listStudent(Model model) { + + model.addAttribute("students", buildStudents()); + + return "listStudents"; + } + + private List buildStudents() { + List students = new ArrayList(); + + Student student1 = new Student(); + student1.setId(1001); + student1.setName("John Smith"); + student1.setGender('M'); + student1.setPercentage(Float.valueOf("80.45")); + + students.add(student1); + + Student student2 = new Student(); + student2.setId(1002); + student2.setName("Jane Williams"); + student2.setGender('F'); + student2.setPercentage(Float.valueOf("60.25")); + + students.add(student2); + return students; + } +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java similarity index 91% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java index 9c07ef8d14..a5d2366390 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java @@ -1,30 +1,30 @@ -package org.baeldung.thymeleaf.formatter; - -import java.text.ParseException; -import java.util.Locale; - -import org.springframework.format.Formatter; -import org.thymeleaf.util.StringUtils; - -/** - * - * Name formatter class that implements the Spring Formatter interface. - * Formats a name(String) and return the value with spaces replaced by commas. - * - */ -public class NameFormatter implements Formatter { - - @Override - public String print(String input, Locale locale) { - return formatName(input, locale); - } - - @Override - public String parse(String input, Locale locale) throws ParseException { - return formatName(input, locale); - } - - private String formatName(String input, Locale locale) { - return StringUtils.replace(input, " ", ","); - } -} +package com.baeldung.thymeleaf.formatter; + +import java.text.ParseException; +import java.util.Locale; + +import org.springframework.format.Formatter; +import org.thymeleaf.util.StringUtils; + +/** + * + * Name formatter class that implements the Spring Formatter interface. + * Formats a name(String) and return the value with spaces replaced by commas. + * + */ +public class NameFormatter implements Formatter { + + @Override + public String print(String input, Locale locale) { + return formatName(input, locale); + } + + @Override + public String parse(String input, Locale locale) throws ParseException { + return formatName(input, locale); + } + + private String formatName(String input, Locale locale) { + return StringUtils.replace(input, " ", ","); + } +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java similarity index 91% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java index f21169dbcf..bce99f286c 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java @@ -1,60 +1,60 @@ -package org.baeldung.thymeleaf.model; - -import java.io.Serializable; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotNull; - -/** - * - * Simple student POJO with few fields - * - */ -public class Student implements Serializable { - - private static final long serialVersionUID = -8582553475226281591L; - - @NotNull(message = "Student ID is required.") - @Min(value = 1000, message = "Student ID must be at least 4 digits.") - private Integer id; - - @NotNull(message = "Student name is required.") - private String name; - - @NotNull(message = "Student gender is required.") - private Character gender; - - private Float percentage; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Character getGender() { - return gender; - } - - public void setGender(Character gender) { - this.gender = gender; - } - - public Float getPercentage() { - return percentage; - } - - public void setPercentage(Float percentage) { - this.percentage = percentage; - } -} +package com.baeldung.thymeleaf.model; + +import java.io.Serializable; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +/** + * + * Simple student POJO with few fields + * + */ +public class Student implements Serializable { + + private static final long serialVersionUID = -8582553475226281591L; + + @NotNull(message = "Student ID is required.") + @Min(value = 1000, message = "Student ID must be at least 4 digits.") + private Integer id; + + @NotNull(message = "Student name is required.") + private String name; + + @NotNull(message = "Student gender is required.") + private Character gender; + + private Float percentage; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Character getGender() { + return gender; + } + + public void setGender(Character gender) { + this.gender = gender; + } + + public Float getPercentage() { + return percentage; + } + + public void setPercentage(Float percentage) { + this.percentage = percentage; + } +} From 671bfc1635419937d3ea4cf3d11ce65600e586f0 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 6 Jan 2016 13:26:07 +0200 Subject: [PATCH 050/309] cleanup and upgrade --- spring-security-basic-auth/pom.xml | 10 ++++++---- spring-security-mvc-custom/pom.xml | 8 +++++--- .../src/main/resources/webSecurityConfig.xml | 2 ++ .../src/main/webapp/WEB-INF/view/console.jsp | 2 +- .../src/main/webapp/WEB-INF/view/homepage.jsp | 2 +- .../src/main/webapp/WEB-INF/view/login.jsp | 8 ++++---- spring-security-mvc-digest-auth/pom.xml | 8 +++++--- 7 files changed, 24 insertions(+), 16 deletions(-) diff --git a/spring-security-basic-auth/pom.xml b/spring-security-basic-auth/pom.xml index 6abefbd7ec..1e15cd5b53 100644 --- a/spring-security-basic-auth/pom.xml +++ b/spring-security-basic-auth/pom.xml @@ -82,14 +82,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -98,7 +98,7 @@ com.google.guava guava - 14.0.1 + ${guava.version} @@ -238,7 +238,9 @@ 5.2.2.Final - + 1.2 + 3.0.1 + 19.0 3.4 diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index 2e2d434fb2..b5f71847f5 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -87,14 +87,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -243,7 +243,9 @@ 5.2.2.Final - + 3.0.1 + 1.2 + 19.0 3.4 diff --git a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml index bbb22c11cb..603ded74fe 100644 --- a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml @@ -12,6 +12,8 @@ + + diff --git a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/console.jsp index d18b59a10c..5a58d8892f 100644 --- a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/console.jsp +++ b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/console.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/homepage.jsp index afd2c6da59..2568adec66 100644 --- a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/homepage.jsp +++ b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/homepage.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp index 0eb857c62a..762218e40f 100644 --- a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp @@ -4,20 +4,20 @@

Login

- + - + - + - + diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index 2dce2835f5..dc2c4d80a5 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -82,14 +82,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -238,7 +238,9 @@ 5.2.2.Final - + 1.2 + 3.0.1 + 19.03.4 From cb45b176f59d7e94be6a46b05b72d1836d3ded16 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 6 Jan 2016 19:38:25 +0200 Subject: [PATCH 051/309] cleanup and upgrade --- spring-security-mvc-login/pom.xml | 6 ++++-- .../src/main/resources/webSecurityConfig.xml | 2 ++ .../src/main/webapp/WEB-INF/view/login.jsp | 4 ++-- spring-security-rest-basic-auth/pom.xml | 11 +++++++---- spring-security-rest-custom/pom.xml | 6 +----- spring-security-rest-digest-auth/pom.xml | 6 ++++-- 6 files changed, 20 insertions(+), 15 deletions(-) diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index 3d76fcb22f..ee6b37743b 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -87,14 +87,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -235,6 +235,8 @@ 5.2.2.Final + 3.0.1 + 1.2 19.0 diff --git a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml index 2bac3024c7..ec4cf60eb5 100644 --- a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml @@ -12,6 +12,8 @@ + + diff --git a/spring-security-mvc-login/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/login.jsp index 013ceccb4e..95930c139d 100644 --- a/spring-security-mvc-login/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/login.jsp @@ -9,11 +9,11 @@
User:
Password:
Remember Me:
- + - + diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index 1fbeeaa9a9..767edb7778 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -88,7 +88,7 @@ com.fasterxml.jackson.core jackson-databind - 2.2.3 + ${jackson.version} @@ -134,14 +134,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -304,7 +304,10 @@ 5.2.2.Final - + 1.2 + 3.0.1 + 2.2.3 + 19.03.4 diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index 20984ba6dd..a112fdcd43 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.4.RELEASE + 1.3.1.RELEASE @@ -141,7 +141,6 @@ junit junit - ${junit.version} test @@ -199,7 +198,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} 1.8 1.8 @@ -211,7 +209,6 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} false @@ -220,7 +217,6 @@ org.apache.maven.plugins maven-surefire-plugin - ${maven-surefire-plugin.version} diff --git a/spring-security-rest-digest-auth/pom.xml b/spring-security-rest-digest-auth/pom.xml index d20220ac36..88e760458b 100644 --- a/spring-security-rest-digest-auth/pom.xml +++ b/spring-security-rest-digest-auth/pom.xml @@ -122,14 +122,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -294,6 +294,8 @@ 5.2.2.Final + 3.0.1 + 1.2 19.0 From 6fd951d7959294eae940df8e8cf6c5f275fc7a11 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 6 Jan 2016 20:01:17 +0200 Subject: [PATCH 052/309] cleanup and upgrade --- spring-security-mvc-session/pom.xml | 11 +++++++---- .../src/main/resources/webSecurityConfig.xml | 3 ++- .../src/main/webapp/WEB-INF/view/console.jsp | 2 +- .../src/main/webapp/WEB-INF/view/homepage.jsp | 2 +- .../src/main/webapp/WEB-INF/view/login.jsp | 8 ++++---- 5 files changed, 15 insertions(+), 11 deletions(-) diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index c9a919e684..fd90be6cc8 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -87,14 +87,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -103,7 +103,7 @@ com.codahale.metrics metrics-core - 3.0.1 + ${codahale.metrics.version} @@ -243,7 +243,10 @@ 5.2.2.Final - + 3.0.1 + 1.2 + 3.0.1 + 19.0 3.4 diff --git a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml index a9b0019fbd..02b74b0933 100644 --- a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml @@ -12,10 +12,11 @@ + + - diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp index d18b59a10c..5a58d8892f 100644 --- a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp +++ b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp index afd2c6da59..2568adec66 100644 --- a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp +++ b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp index 0eb857c62a..762218e40f 100644 --- a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp @@ -4,20 +4,20 @@

Login

- +
User:
Password:
- + - + - + From 70be232c5a58672138138583ccb78bc3ccc626f4 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 7 Jan 2016 15:17:26 +0200 Subject: [PATCH 053/309] cleanup and upgrade --- .../src/main/webapp/WEB-INF/view/login.jsp | 2 +- .../pom.xml | 23 +++++++++++-------- .../src/main/resources/webSecurityConfig.xml | 14 +++++------ .../src/main/webapp/WEB-INF/view/console.jsp | 2 +- .../src/main/webapp/WEB-INF/view/homepage.jsp | 2 +- .../src/main/webapp/WEB-INF/view/login.jsp | 8 +++---- .../src/main/webapp/WEB-INF/view/login.jsp | 2 +- spring-security-oauth/pom.xml | 2 +- 8 files changed, 30 insertions(+), 25 deletions(-) diff --git a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp index 762218e40f..eb41cc79a8 100644 --- a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp @@ -17,7 +17,7 @@ - + diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml index 37f271f66d..1691f10f43 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -93,14 +93,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -109,13 +109,13 @@ com.h2database h2 - 1.4.178 + ${h2.version} postgresql postgresql - 9.1-901.jdbc4 + ${postgresql.version} runtime @@ -260,12 +260,15 @@ - 4.1.4.RELEASE - 3.2.5.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.37 + 1.4.190 + 9.1-901.jdbc4 + 1.7.12 @@ -273,9 +276,11 @@ 5.1.3.Final + 3.0.1 + 1.2 - 18.0 + 19.0 3.4 diff --git a/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml index 0fa077db00..a11f13c9ab 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml @@ -7,11 +7,11 @@ xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation=" - http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd - http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd + http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd - http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd - http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd"> + http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd + http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd"> @@ -35,9 +35,9 @@ - - - + + + diff --git a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/console.jsp index d18b59a10c..5a58d8892f 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/console.jsp +++ b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/console.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/homepage.jsp index afd2c6da59..2568adec66 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/homepage.jsp +++ b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/homepage.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/login.jsp index 5697d1544a..7636cd5e61 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/login.jsp @@ -17,20 +17,20 @@

Login

- +
User:
Password:
Remember Me:
Remember Me:
- + - + - + diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp index 762218e40f..eb41cc79a8 100644 --- a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp @@ -17,7 +17,7 @@ - + diff --git a/spring-security-oauth/pom.xml b/spring-security-oauth/pom.xml index 473a4e5c35..7bb7aa86c8 100644 --- a/spring-security-oauth/pom.xml +++ b/spring-security-oauth/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.7.RELEASE + 1.3.1.RELEASE From a10967217275f62614ffeb3f7f0f8eb2e8ae8e0f Mon Sep 17 00:00:00 2001 From: David Morley Date: Thu, 7 Jan 2016 20:28:55 -0600 Subject: [PATCH 054/309] Rename package org.baeldung -> com.baeldung --- .../src/main/java/{org => com}/baeldung/Adder.java | 2 +- .../src/main/java/{org => com}/baeldung/AdderImpl.java | 2 +- core-java-8/src/main/java/{org => com}/baeldung/Bar.java | 2 +- core-java-8/src/main/java/{org => com}/baeldung/Baz.java | 2 +- core-java-8/src/main/java/{org => com}/baeldung/Foo.java | 2 +- .../src/main/java/{org => com}/baeldung/FooExtended.java | 2 +- .../src/main/java/{org => com}/baeldung/UseFoo.java | 2 +- .../baeldung/java8/Java8CollectionCleanupUnitTest.java | 2 +- .../java8/Java8FunctionalInteracesLambdasTest.java | 8 ++++---- .../{org => com}/baeldung/java8/Java8SortUnitTest.java | 4 ++-- .../{org => com}/baeldung/java8/JavaFolderSizeTest.java | 2 +- .../baeldung/java8/JavaTryWithResourcesTest.java | 2 +- .../java8/base64/ApacheCommonsEncodeDecodeTest.java | 2 +- .../baeldung/java8/base64/Java8EncodeDecodeTest.java | 2 +- .../java/{org => com}/baeldung/java8/entity/Human.java | 2 +- 15 files changed, 19 insertions(+), 19 deletions(-) rename core-java-8/src/main/java/{org => com}/baeldung/Adder.java (90%) rename core-java-8/src/main/java/{org => com}/baeldung/AdderImpl.java (93%) rename core-java-8/src/main/java/{org => com}/baeldung/Bar.java (87%) rename core-java-8/src/main/java/{org => com}/baeldung/Baz.java (87%) rename core-java-8/src/main/java/{org => com}/baeldung/Foo.java (84%) rename core-java-8/src/main/java/{org => com}/baeldung/FooExtended.java (88%) rename core-java-8/src/main/java/{org => com}/baeldung/UseFoo.java (97%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/Java8CollectionCleanupUnitTest.java (97%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/Java8FunctionalInteracesLambdasTest.java (95%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/Java8SortUnitTest.java (98%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/JavaFolderSizeTest.java (99%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/JavaTryWithResourcesTest.java (99%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java (98%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/base64/Java8EncodeDecodeTest.java (99%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/entity/Human.java (98%) diff --git a/core-java-8/src/main/java/org/baeldung/Adder.java b/core-java-8/src/main/java/com/baeldung/Adder.java similarity index 90% rename from core-java-8/src/main/java/org/baeldung/Adder.java rename to core-java-8/src/main/java/com/baeldung/Adder.java index 4578990de7..e3e100f121 100644 --- a/core-java-8/src/main/java/org/baeldung/Adder.java +++ b/core-java-8/src/main/java/com/baeldung/Adder.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import java.util.function.Consumer; import java.util.function.Function; diff --git a/core-java-8/src/main/java/org/baeldung/AdderImpl.java b/core-java-8/src/main/java/com/baeldung/AdderImpl.java similarity index 93% rename from core-java-8/src/main/java/org/baeldung/AdderImpl.java rename to core-java-8/src/main/java/com/baeldung/AdderImpl.java index a62c0cd4fb..55cf84c378 100644 --- a/core-java-8/src/main/java/org/baeldung/AdderImpl.java +++ b/core-java-8/src/main/java/com/baeldung/AdderImpl.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import java.util.function.Consumer; import java.util.function.Function; diff --git a/core-java-8/src/main/java/org/baeldung/Bar.java b/core-java-8/src/main/java/com/baeldung/Bar.java similarity index 87% rename from core-java-8/src/main/java/org/baeldung/Bar.java rename to core-java-8/src/main/java/com/baeldung/Bar.java index 0dd7df6be2..f9b6f2773e 100644 --- a/core-java-8/src/main/java/org/baeldung/Bar.java +++ b/core-java-8/src/main/java/com/baeldung/Bar.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; @FunctionalInterface public interface Bar { diff --git a/core-java-8/src/main/java/org/baeldung/Baz.java b/core-java-8/src/main/java/com/baeldung/Baz.java similarity index 87% rename from core-java-8/src/main/java/org/baeldung/Baz.java rename to core-java-8/src/main/java/com/baeldung/Baz.java index bcc46af6e7..6d03f74198 100644 --- a/core-java-8/src/main/java/org/baeldung/Baz.java +++ b/core-java-8/src/main/java/com/baeldung/Baz.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; @FunctionalInterface public interface Baz { diff --git a/core-java-8/src/main/java/org/baeldung/Foo.java b/core-java-8/src/main/java/com/baeldung/Foo.java similarity index 84% rename from core-java-8/src/main/java/org/baeldung/Foo.java rename to core-java-8/src/main/java/com/baeldung/Foo.java index a10e45a8f5..c42ec86f8b 100644 --- a/core-java-8/src/main/java/org/baeldung/Foo.java +++ b/core-java-8/src/main/java/com/baeldung/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; @FunctionalInterface public interface Foo { diff --git a/core-java-8/src/main/java/org/baeldung/FooExtended.java b/core-java-8/src/main/java/com/baeldung/FooExtended.java similarity index 88% rename from core-java-8/src/main/java/org/baeldung/FooExtended.java rename to core-java-8/src/main/java/com/baeldung/FooExtended.java index 39c3a0765f..c8ed0c35dd 100644 --- a/core-java-8/src/main/java/org/baeldung/FooExtended.java +++ b/core-java-8/src/main/java/com/baeldung/FooExtended.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; @FunctionalInterface public interface FooExtended extends Baz, Bar { diff --git a/core-java-8/src/main/java/org/baeldung/UseFoo.java b/core-java-8/src/main/java/com/baeldung/UseFoo.java similarity index 97% rename from core-java-8/src/main/java/org/baeldung/UseFoo.java rename to core-java-8/src/main/java/com/baeldung/UseFoo.java index a29c5631ac..bfa7a2f2c0 100644 --- a/core-java-8/src/main/java/org/baeldung/UseFoo.java +++ b/core-java-8/src/main/java/com/baeldung/UseFoo.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import java.util.function.Function; diff --git a/core-java-8/src/test/java/org/baeldung/java8/Java8CollectionCleanupUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java similarity index 97% rename from core-java-8/src/test/java/org/baeldung/java8/Java8CollectionCleanupUnitTest.java rename to core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java index acca829b78..7329a2dc97 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/Java8CollectionCleanupUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8; +package com.baeldung.java8; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; diff --git a/core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java similarity index 95% rename from core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java rename to core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java index 3845d6ba84..0620ebd35a 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java @@ -1,8 +1,8 @@ -package org.baeldung.java8; +package com.baeldung.java8; -import org.baeldung.Foo; -import org.baeldung.FooExtended; -import org.baeldung.UseFoo; +import com.baeldung.Foo; +import com.baeldung.FooExtended; +import com.baeldung.UseFoo; import org.junit.Before; import org.junit.Test; diff --git a/core-java-8/src/test/java/org/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java similarity index 98% rename from core-java-8/src/test/java/org/baeldung/java8/Java8SortUnitTest.java rename to core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index 8ed7828de0..e0e10b293e 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8; +package com.baeldung.java8; import static org.hamcrest.Matchers.equalTo; @@ -6,7 +6,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; -import org.baeldung.java8.entity.Human; +import com.baeldung.java8.entity.Human; import org.junit.Assert; import org.junit.Test; diff --git a/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java similarity index 99% rename from core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java rename to core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java index a65971bb91..2ac16b5d1d 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8; +package com.baeldung.java8; import static org.junit.Assert.assertEquals; diff --git a/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java similarity index 99% rename from core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java rename to core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java index a59682c535..18110b181d 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8; +package com.baeldung.java8; import java.io.PrintWriter; import java.io.StringWriter; diff --git a/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java b/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java similarity index 98% rename from core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java rename to core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java index 9745655d8a..07380cdd01 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8.base64; +package com.baeldung.java8.base64; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; diff --git a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java b/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java similarity index 99% rename from core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java rename to core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java index 7b7a0be26a..3c504edbf3 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8.base64; +package com.baeldung.java8.base64; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; diff --git a/core-java-8/src/test/java/org/baeldung/java8/entity/Human.java b/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java similarity index 98% rename from core-java-8/src/test/java/org/baeldung/java8/entity/Human.java rename to core-java-8/src/test/java/com/baeldung/java8/entity/Human.java index ac58b301b7..cab8546129 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/entity/Human.java +++ b/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java @@ -1,4 +1,4 @@ -package org.baeldung.java8.entity; +package com.baeldung.java8.entity; public class Human { private String name; From 959eb4320f908414497b647e183fd0499bf6b2ef Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 9 Jan 2016 01:34:39 +0200 Subject: [PATCH 055/309] minor cleanup work --- .../.settings/org.eclipse.jdt.core.prefs | 9 ++- .../src/main/java/com/baeldung/AdderImpl.java | 5 +- .../src/main/java/com/baeldung/Foo.java | 3 +- .../src/main/java/com/baeldung/UseFoo.java | 22 ++++--- .../Java8FunctionalInteracesLambdasTest.java | 60 +++++++++---------- .../com/baeldung/java8/Java8SortUnitTest.java | 2 +- 6 files changed, 50 insertions(+), 51 deletions(-) diff --git a/core-java-8/.settings/org.eclipse.jdt.core.prefs b/core-java-8/.settings/org.eclipse.jdt.core.prefs index c57289fc09..c38ccc1294 100644 --- a/core-java-8/.settings/org.eclipse.jdt.core.prefs +++ b/core-java-8/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,5 @@ eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled 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 @@ -26,7 +27,7 @@ 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.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning @@ -35,7 +36,7 @@ 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.localVariableHiding=warning org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore @@ -48,6 +49,7 @@ org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignor 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.nonnullParameterAnnotationDropped=warning org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error org.eclipse.jdt.core.compiler.problem.nullReference=warning org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error @@ -68,6 +70,7 @@ 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.syntacticNullAnalysisForFields=disabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled @@ -82,6 +85,7 @@ 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.unusedExceptionParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedImport=warning org.eclipse.jdt.core.compiler.problem.unusedLabel=warning org.eclipse.jdt.core.compiler.problem.unusedLocal=warning @@ -91,6 +95,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference= 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.unusedTypeParameter=ignore 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/core-java-8/src/main/java/com/baeldung/AdderImpl.java b/core-java-8/src/main/java/com/baeldung/AdderImpl.java index 55cf84c378..5109f3aaba 100644 --- a/core-java-8/src/main/java/com/baeldung/AdderImpl.java +++ b/core-java-8/src/main/java/com/baeldung/AdderImpl.java @@ -6,11 +6,12 @@ import java.util.function.Function; public class AdderImpl implements Adder { @Override - public String addWithFunction(Function f) { + public String addWithFunction(Function f) { return f.apply("Something "); } @Override - public void addWithConsumer(Consumer f) {} + public void addWithConsumer(Consumer f) { + } } diff --git a/core-java-8/src/main/java/com/baeldung/Foo.java b/core-java-8/src/main/java/com/baeldung/Foo.java index c42ec86f8b..90ebdfeed3 100644 --- a/core-java-8/src/main/java/com/baeldung/Foo.java +++ b/core-java-8/src/main/java/com/baeldung/Foo.java @@ -5,5 +5,6 @@ public interface Foo { String method(String string); - default void defaultMethod() {} + default void defaultMethod() { + } } diff --git a/core-java-8/src/main/java/com/baeldung/UseFoo.java b/core-java-8/src/main/java/com/baeldung/UseFoo.java index bfa7a2f2c0..a91404ebaf 100644 --- a/core-java-8/src/main/java/com/baeldung/UseFoo.java +++ b/core-java-8/src/main/java/com/baeldung/UseFoo.java @@ -6,34 +6,32 @@ public class UseFoo { private String value = "Enclosing scope value"; - public String add(String string, Foo foo) { + public String add(final String string, final Foo foo) { return foo.method(string); } - public String addWithStandardFI(String string, Function fn) { + public String addWithStandardFI(final String string, final Function fn) { return fn.apply(string); } public String scopeExperiment() { - Foo fooIC = new Foo() { + final Foo fooIC = new Foo() { String value = "Inner class value"; @Override - public String method(String string) { - return this.value; + public String method(final String string) { + return value; } }; - String resultIC = fooIC.method(""); + final String resultIC = fooIC.method(""); - Foo fooLambda = parameter -> { - String value = "Lambda value"; + final Foo fooLambda = parameter -> { + final String value = "Lambda value"; return this.value; }; - String resultLambda = fooLambda.method(""); + final String resultLambda = fooLambda.method(""); - return "Results: resultIC = " + resultIC + - ", resultLambda = " + resultLambda; + return "Results: resultIC = " + resultIC + ", resultLambda = " + resultLambda; } - } diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java index 0620ebd35a..94448fcc83 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java @@ -1,15 +1,16 @@ package com.baeldung.java8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.util.function.Function; + +import org.junit.Before; +import org.junit.Test; + import com.baeldung.Foo; import com.baeldung.FooExtended; import com.baeldung.UseFoo; -import org.junit.Before; -import org.junit.Test; - -import java.util.function.Function; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; public class Java8FunctionalInteracesLambdasTest { @@ -22,39 +23,35 @@ public class Java8FunctionalInteracesLambdasTest { @Test public void functionalInterfaceInstantiation_whenReturnDefiniteString_thenCorrect() { - - Foo foo = parameter -> parameter + "from lambda"; - String result = useFoo.add("Message ", foo); + final Foo foo = parameter -> parameter + "from lambda"; + final String result = useFoo.add("Message ", foo); assertEquals("Message from lambda", result); } @Test public void standardFIParameter_whenReturnDefiniteString_thenCorrect() { - - Function fn = parameter -> parameter + "from lambda"; - String result = useFoo.addWithStandardFI("Message ", fn); + final Function fn = parameter -> parameter + "from lambda"; + final String result = useFoo.addWithStandardFI("Message ", fn); assertEquals("Message from lambda", result); } @Test public void defaultMethodFromExtendedInterface_whenReturnDefiniteString_thenCorrect() { - - FooExtended fooExtended = string -> string; - String result = fooExtended.defaultMethod(); + final FooExtended fooExtended = string -> string; + final String result = fooExtended.defaultMethod(); assertEquals("String from Bar", result); } @Test public void lambdaAndInnerClassInstantiation_whenReturnSameString_thenCorrect() { + final Foo foo = parameter -> parameter + "from Foo"; - Foo foo = parameter -> parameter + "from Foo"; - - Foo fooByIC = new Foo() { + final Foo fooByIC = new Foo() { @Override - public String method(String string) { + public String method(final String string) { return string + "from Foo"; } }; @@ -64,35 +61,32 @@ public class Java8FunctionalInteracesLambdasTest { @Test public void accessVariablesFromDifferentScopes_whenReturnPredefinedString_thenCorrect() { - - assertEquals("Results: resultIC = Inner class value, resultLambda = Enclosing scope value", - useFoo.scopeExperiment()); + assertEquals("Results: resultIC = Inner class value, resultLambda = Enclosing scope value", useFoo.scopeExperiment()); } @Test public void shorteningLambdas_whenReturnEqualsResults_thenCorrect() { + final Foo foo = parameter -> buildString(parameter); - Foo foo = parameter -> buildString(parameter); - - Foo fooHuge = parameter -> { String result = "Something " + parameter; - //many lines of code + final Foo fooHuge = parameter -> { + final String result = "Something " + parameter; + // many lines of code return result; }; assertEquals(foo.method("Something"), fooHuge.method("Something")); } - private String buildString(String parameter) { - String result = "Something " + parameter; - //many lines of code + private String buildString(final String parameter) { + final String result = "Something " + parameter; + // many lines of code return result; } @Test public void mutatingOfEffectivelyFinalVariable_whenNotEquals_thenCorrect() { - - int[] total = new int[1]; - Runnable r = () -> total[0]++; + final int[] total = new int[1]; + final Runnable r = () -> total[0]++; r.run(); assertNotEquals(0, total[0]); diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index e0e10b293e..2ba9e417d6 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -6,10 +6,10 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; -import com.baeldung.java8.entity.Human; import org.junit.Assert; import org.junit.Test; +import com.baeldung.java8.entity.Human; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; From 5154c5ba888d3708b1b905915ba0aa969ccc85d7 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 9 Jan 2016 13:01:30 +0200 Subject: [PATCH 056/309] cleanup and upgrade --- handling-spring-static-resources/.classpath | 4 +- handling-spring-static-resources/pom.xml | 20 +- .../src/main/resources/webSecurityConfig.xml | 8 +- .../src/main/webapp/WEB-INF/view/login.jsp | 6 +- .../.classpath | 2 +- .../pom.xml | 221 ++++++++++++------ .../CustomAuthenticationFailureHandler.java | 2 +- .../java/org/baeldung/spring/MvcConfig.java | 2 +- .../baeldung/spring/SecSecurityConfig.java | 10 +- .../src/main/resources/webSecurityConfig.xml | 17 +- .../src/main/webapp/WEB-INF/view/admin.jsp | 2 +- .../webapp/WEB-INF/view/changePassword.jsp | 2 +- .../src/main/webapp/WEB-INF/view/console.jsp | 2 +- .../src/main/webapp/WEB-INF/view/home.jsp | 2 +- .../src/main/webapp/WEB-INF/view/homepage.jsp | 2 +- .../src/main/webapp/WEB-INF/view/login.jsp | 11 +- .../src/main/webapp/WEB-INF/view/logout.jsp | 2 +- .../baeldung/test/ChangePasswordLiveTest.java | 2 +- 18 files changed, 202 insertions(+), 115 deletions(-) diff --git a/handling-spring-static-resources/.classpath b/handling-spring-static-resources/.classpath index 88536687a5..71a1c1e0b5 100644 --- a/handling-spring-static-resources/.classpath +++ b/handling-spring-static-resources/.classpath @@ -19,9 +19,9 @@ - + - + diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml index 677d705932..8efacc4b28 100644 --- a/handling-spring-static-resources/pom.xml +++ b/handling-spring-static-resources/pom.xml @@ -171,33 +171,29 @@ - 1.7 + 1.8 - 4.1.5.RELEASE - 3.2.5.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 1.8.1 2.3.2-b01 - - 4.1.5.RELEASE - 3.2.5.RELEASE - - 4.3.10.Final - 5.1.35 - 1.7.2.RELEASE + 4.3.11.Final + 5.1.37 + 1.9.2.RELEASE - 2.5.5 + 2.6.4 1.7.13 1.1.3 - 5.1.3.Final + 5.2.2.Final 19.0 diff --git a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml b/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml index 56d7f9c113..76b5015e7b 100644 --- a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml +++ b/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml @@ -2,10 +2,10 @@ @@ -21,7 +21,7 @@ - + diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp b/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp index 1b09f7c634..8c9f46c027 100644 --- a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp +++ b/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp @@ -41,15 +41,15 @@

- +
User:
Password:
Remember Me:
Remember Me:
- + - + diff --git a/spring-security-login-and-registration/.classpath b/spring-security-login-and-registration/.classpath index 91f27076be..26981b6dd7 100644 --- a/spring-security-login-and-registration/.classpath +++ b/spring-security-login-and-registration/.classpath @@ -23,7 +23,7 @@ - + diff --git a/spring-security-login-and-registration/pom.xml b/spring-security-login-and-registration/pom.xml index ffa8be484b..9e0f15688f 100644 --- a/spring-security-login-and-registration/pom.xml +++ b/spring-security-login-and-registration/pom.xml @@ -9,67 +9,108 @@ spring-security-login-and-registration war - - org.springframework.boot - spring-boot-starter-parent - 1.2.6.RELEASE - + - + + - org.springframework.boot - spring-boot-starter-web - - - org.springframework - spring-context-support + org.springframework.security + spring-security-web + ${org.springframework.security.version} org.springframework.security spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} - + + - org.springframework.boot - spring-boot-starter-tomcat - provided + org.springframework + spring-core + ${org.springframework.version} + + + commons-logging + commons-logging + + - org.apache.tomcat.embed - tomcat-embed-websocket - provided + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-context-support + ${org.springframework.version} + + + org.springframework + spring-jdbc + ${org.springframework.version} + + + org.springframework + spring-beans + ${org.springframework.version} + + + org.springframework + spring-aop + ${org.springframework.version} + + + org.springframework + spring-tx + ${org.springframework.version} + + + org.springframework + spring-expression + ${org.springframework.version} + + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} javax.servlet javax.servlet-api + ${javax.servlet.version} + provided - - javax.servlet.jsp - javax.servlet.jsp-api - ${javax.servlet.jsp-api.version} - + javax.servlet jstl + ${jstl.version} + runtime - - org.springframework.security - spring-security-taglibs - - - javax.el - el-api - 2.2 - + org.springframework spring-test + ${org.springframework.version} test @@ -77,17 +118,19 @@ org.passay passay - 1.0 + ${passay.version} org.springframework.data spring-data-jpa + ${spring-data-jpa.version} org.hibernate hibernate-entitymanager + ${hibernate.version} @@ -98,25 +141,29 @@ org.hibernate hibernate-validator + ${hibernate-validator.version} mysql mysql-connector-java + ${mysql-connector-java.version} commons-dbcp commons-dbcp + ${commons-dbcp.version} com.fasterxml.jackson.core jackson-databind + ${jackson.version} javax.mail mail - 1.4.7 + ${javax.mail.version} com.google.guava @@ -128,32 +175,51 @@ org.slf4j slf4j-api + ${org.slf4j.version} ch.qos.logback logback-classic + ${logback.version} + org.slf4j jcl-over-slf4j + ${org.slf4j.version} org.slf4j log4j-over-slf4j + ${org.slf4j.version} junit junit + ${junit.version} test - + + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + com.jayway.restassured rest-assured - 2.4.0 + ${rest-assured.version} test @@ -163,6 +229,11 @@ + + javax.el + el-api + 2.2 + @@ -181,8 +252,8 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - ${java-version} - ${java-version} + 1.8 + 1.8 @@ -192,36 +263,13 @@ ${maven-war-plugin.version} - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - tomcat8x - embedded - - - - - - - 8081 - - - - - org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} - true - **/*IntegrationTest.java - **/*LiveTest.java + @@ -229,21 +277,54 @@ + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + + - 1.7 - 4.1.6.RELEASE + 1.8 + + + 4.2.4.RELEASE 4.0.3.RELEASE + + 4.3.11.Final + 5.2.2.Final + 5.1.37 + 1.9.2.RELEASE + + 1.7.13 1.1.3 2.3.2-b01 - + 3.0.1 + 1.2 + 1 @@ -253,6 +334,14 @@ 19.0 + 1.3 + 4.12 + 1.0 + 2.4.0 + 1.4.7 + 2.6.4 + 1.4 + 1.4.17 3.3 diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java index e8d995e781..94440f8a89 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java @@ -15,7 +15,7 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa import org.springframework.stereotype.Component; import org.springframework.web.servlet.LocaleResolver; -@Component +@Component("authenticationFailureHandler") public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Autowired diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java index 56141d8f33..1234cde0d0 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java @@ -35,7 +35,7 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { super.addViewControllers(registry); - registry.addViewController("/login.html"); + registry.addViewController("/login"); registry.addViewController("/registration.html"); registry.addViewController("/logout.html"); registry.addViewController("/homepage.html"); diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 677ad514e5..9ae8f6e78b 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -51,7 +51,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { http .csrf().disable() .authorizeRequests() - .antMatchers("/j_spring_security_check*","/login*", "/logout*", "/signin/**", "/signup/**", + .antMatchers("/login*","/login*", "/logout*", "/signin/**", "/signup/**", "/user/registration*", "/regitrationConfirm*", "/expiredAccount*", "/registration*", "/badUser*", "/user/resendRegistrationToken*" ,"/forgetPassword*", "/user/resetPassword*", "/user/changePassword*", "/emailError*", "/resources/**","/old/user/registration*","/successRegister*").permitAll() @@ -59,14 +59,11 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .anyRequest().authenticated() .and() .formLogin() - .loginPage("/login.html") - .loginProcessingUrl("/j_spring_security_check") + .loginPage("/login") .defaultSuccessUrl("/homepage.html") - .failureUrl("/login.html?error=true") + .failureUrl("/login?error=true") .successHandler(myAuthenticationSuccessHandler) .failureHandler(authenticationFailureHandler) - .usernameParameter("j_username") - .passwordParameter("j_password") .permitAll() .and() .sessionManagement() @@ -75,7 +72,6 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .and() .logout() .invalidateHttpSession(false) - .logoutUrl("/j_spring_security_logout") .logoutSuccessUrl("/logout.html?logSucc=true") .deleteCookies("JSESSIONID") .permitAll(); diff --git a/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml b/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml index 3141b19142..4e67a1200f 100644 --- a/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml +++ b/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml @@ -2,7 +2,7 @@ @@ -28,10 +28,17 @@ - - - + + + + + + + + diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp index db3d8f20ba..ad0a8231ad 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp @@ -15,7 +15,7 @@ "> diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/changePassword.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/changePassword.jsp index c5ff23287d..88836e96f5 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/changePassword.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/changePassword.jsp @@ -17,7 +17,7 @@ diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/console.jsp index 1cf661af87..e06cdd39f0 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/console.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/console.jsp @@ -13,7 +13,7 @@ "> diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/home.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/home.jsp index f8db1632f6..027f583d61 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/home.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/home.jsp @@ -14,7 +14,7 @@ diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/homepage.jsp index 86cac0152f..af931ac66f 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/homepage.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/homepage.jsp @@ -15,7 +15,7 @@ "> diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp index 949b8164de..c22c3241cd 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp @@ -58,18 +58,17 @@ ${SPRING_SECURITY_LAST_EXCEPTION} - | + |

- + + - +

- +

- ">"> diff --git a/spring-security-login-and-registration/src/test/java/org/baeldung/test/ChangePasswordLiveTest.java b/spring-security-login-and-registration/src/test/java/org/baeldung/test/ChangePasswordLiveTest.java index 05377d5578..3939b5685c 100644 --- a/spring-security-login-and-registration/src/test/java/org/baeldung/test/ChangePasswordLiveTest.java +++ b/spring-security-login-and-registration/src/test/java/org/baeldung/test/ChangePasswordLiveTest.java @@ -38,7 +38,7 @@ public class ChangePasswordLiveTest { @Autowired private PasswordEncoder passwordEncoder; - private final FormAuthConfig formConfig = new FormAuthConfig(URL_PREFIX + "/j_spring_security_check", "j_username", "j_password"); + private final FormAuthConfig formConfig = new FormAuthConfig(URL_PREFIX + "/login", "username", "password"); @Before public void init() { From f060700ceca344930cfabdf08e7698a905d6b56d Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 9 Jan 2016 22:22:58 +0200 Subject: [PATCH 057/309] cleanup and upgrade --- .../src/main/webapp/WEB-INF/view/login.jsp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp index c22c3241cd..a71fe9dc3a 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp @@ -15,20 +15,20 @@ <spring:message code="label.pages.home.title"></spring:message> + + + + + +
+

Foo Details

+
+ + {{foo.id}} +
+ +
+ + {{foo.name}} +
+ +
+ New Foo +
+

+ +

User Details

+
+ + {{user.id}} +
+ +
+ + {{user.username}} +
+ +
+ + {{user.age}} +
+ +
+ New User +
+ +
+ + \ No newline at end of file diff --git a/spring-zuul/spring-zuul-ui/src/main/webapp/resources/angular-utf8-base64.min.js b/spring-zuul/spring-zuul-ui/src/main/webapp/resources/angular-utf8-base64.min.js new file mode 100644 index 0000000000..24af57d020 --- /dev/null +++ b/spring-zuul/spring-zuul-ui/src/main/webapp/resources/angular-utf8-base64.min.js @@ -0,0 +1 @@ +"use strict";angular.module("ab-base64",[]).constant("base64",function(){var a={alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",lookup:null,ie:/MSIE /.test(navigator.userAgent),ieo:/MSIE [67]/.test(navigator.userAgent),encode:function(b){var c,d,e,f,g=a.toUtf8(b),h=-1,i=g.length,j=[,,,];if(a.ie){for(c=[];++h>2,j[1]=(3&d)<<4|e>>4,isNaN(e)?j[2]=j[3]=64:(f=g[++h],j[2]=(15&e)<<2|f>>6,j[3]=isNaN(f)?64:63&f),c.push(a.alphabet.charAt(j[0]),a.alphabet.charAt(j[1]),a.alphabet.charAt(j[2]),a.alphabet.charAt(j[3]));return c.join("")}for(c="";++h>2,j[1]=(3&d)<<4|e>>4,isNaN(e)?j[2]=j[3]=64:(f=g[++h],j[2]=(15&e)<<2|f>>6,j[3]=isNaN(f)?64:63&f),c+=a.alphabet[j[0]]+a.alphabet[j[1]]+a.alphabet[j[2]]+a.alphabet[j[3]];return c},decode:function(b){if(b=b.replace(/\s/g,""),b.length%4)throw new Error("InvalidLengthError: decode failed: The string to be decoded is not the correct length for a base64 encoded string.");if(/[^A-Za-z0-9+\/=\s]/g.test(b))throw new Error("InvalidCharacterError: decode failed: The string contains characters invalid in a base64 encoded string.");var c,d=a.fromUtf8(b),e=0,f=d.length;if(a.ieo){for(c=[];f>e;)c.push(d[e]<128?String.fromCharCode(d[e++]):d[e]>191&&d[e]<224?String.fromCharCode((31&d[e++])<<6|63&d[e++]):String.fromCharCode((15&d[e++])<<12|(63&d[e++])<<6|63&d[e++]));return c.join("")}for(c="";f>e;)c+=String.fromCharCode(d[e]<128?d[e++]:d[e]>191&&d[e]<224?(31&d[e++])<<6|63&d[e++]:(15&d[e++])<<12|(63&d[e++])<<6|63&d[e++]);return c},toUtf8:function(a){var b,c=-1,d=a.length,e=[];if(/^[\x00-\x7f]*$/.test(a))for(;++cb?e.push(b):2048>b?e.push(b>>6|192,63&b|128):e.push(b>>12|224,b>>6&63|128,63&b|128);return e},fromUtf8:function(b){var c,d=-1,e=[],f=[,,,];if(!a.lookup){for(c=a.alphabet.length,a.lookup={};++d>4),f[2]=a.lookup[b.charAt(++d)],64!==f[2])&&(e.push((15&f[1])<<4|f[2]>>2),f[3]=a.lookup[b.charAt(++d)],64!==f[3]);)e.push((3&f[2])<<6|f[3]);return e}},b={decode:function(b){b=b.replace(/-/g,"+").replace(/_/g,"/");var c=b.length%4;if(c){if(1===c)throw new Error("InvalidLengthError: Input base64url string is the wrong length to determine padding");b+=new Array(5-c).join("=")}return a.decode(b)},encode:function(b){var c=a.encode(b);return c.replace(/\+/g,"-").replace(/\//g,"_").split("=",1)[0]}};return{decode:a.decode,encode:a.encode,urldecode:b.decode,urlencode:b.encode}}()); \ No newline at end of file diff --git a/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/web/LiveTest.java b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/web/LiveTest.java new file mode 100644 index 0000000000..094d3250c7 --- /dev/null +++ b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/web/LiveTest.java @@ -0,0 +1,30 @@ +package org.baeldung.web; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.jayway.restassured.RestAssured; +import com.jayway.restassured.response.Response; + +public class LiveTest { + + @Test + public void whenSendRequestToFooResource_thenOK() { + final Response response = RestAssured.get("http://localhost:8080/foos/1"); + assertEquals(200, response.getStatusCode()); + } + + @Test + public void whenSendRequestToUserResource_thenHeaderAdded() { + final Response response = RestAssured.get("http://localhost:8080/users/1"); + assertEquals(200, response.getStatusCode()); + } + + @Test + public void whenSendRequest_thenHeaderAdded() { + final Response response = RestAssured.get("http://localhost:8080/foos/1"); + assertEquals(200, response.getStatusCode()); + assertEquals("TestSample", response.getHeader("Test")); + } +} diff --git a/spring-zuul/spring-zuul-ui/src/test/resources/.gitignore b/spring-zuul/spring-zuul-ui/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-zuul/spring-zuul-ui/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-zuul/spring-zuul-ui/src/test/resources/persistence-mysql.properties b/spring-zuul/spring-zuul-ui/src/test/resources/persistence-mysql.properties new file mode 100644 index 0000000000..8263b0d9ac --- /dev/null +++ b/spring-zuul/spring-zuul-ui/src/test/resources/persistence-mysql.properties @@ -0,0 +1,10 @@ +# jdbc.X +jdbc.driverClassName=com.mysql.jdbc.Driver +jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true +jdbc.user=tutorialuser +jdbc.pass=tutorialmy5ql + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop diff --git a/spring-zuul/spring-zuul-users-resource/.classpath b/spring-zuul/spring-zuul-users-resource/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-zuul/spring-zuul-users-resource/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-zuul/spring-zuul-users-resource/.project b/spring-zuul/spring-zuul-users-resource/.project new file mode 100644 index 0000000000..2fedf43db4 --- /dev/null +++ b/spring-zuul/spring-zuul-users-resource/.project @@ -0,0 +1,48 @@ + + + spring-zuul-users-resource + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-zuul/spring-zuul-users-resource/pom.xml b/spring-zuul/spring-zuul-users-resource/pom.xml new file mode 100644 index 0000000000..653c6b9d15 --- /dev/null +++ b/spring-zuul/spring-zuul-users-resource/pom.xml @@ -0,0 +1,38 @@ + + 4.0.0 + spring-zuul-users-resource + spring-zuul-users-resource + war + + + org.baeldung + spring-zuul + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + + spring-zuul-users-resource + + + src/main/resources + true + + + + + \ No newline at end of file diff --git a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java new file mode 100644 index 0000000000..1e35eff551 --- /dev/null +++ b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java @@ -0,0 +1,14 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.web.SpringBootServletInitializer; + +@SpringBootApplication +public class ResourceServerApplication extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(ResourceServerApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java new file mode 100644 index 0000000000..c040c8ac42 --- /dev/null +++ b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java @@ -0,0 +1,13 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +@ComponentScan({ "org.baeldung.web.controller" }) +public class ResourceServerWebConfig extends WebMvcConfigurerAdapter { + +} diff --git a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/controller/UserController.java b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/controller/UserController.java new file mode 100644 index 0000000000..b1db89179a --- /dev/null +++ b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/controller/UserController.java @@ -0,0 +1,30 @@ +package org.baeldung.web.controller; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.baeldung.web.dto.User; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class UserController { + + public UserController() { + super(); + } + + // API - read + @RequestMapping(method = RequestMethod.GET, value = "/users/{id}") + @ResponseBody + public User findById(@PathVariable final long id, HttpServletRequest req, HttpServletResponse res) { + return new User(Long.parseLong(randomNumeric(2)), randomAlphabetic(4), Integer.parseInt(randomNumeric(2))); + } + +} diff --git a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/dto/User.java b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/dto/User.java new file mode 100644 index 0000000000..f5e4124f93 --- /dev/null +++ b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/dto/User.java @@ -0,0 +1,46 @@ +package org.baeldung.web.dto; + +public class User { + private long id; + private String username; + private int age; + + public User() { + super(); + } + + public User(final long id, final String name, int age) { + super(); + + this.id = id; + this.username = name; + this.age = age; + } + + // + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} \ No newline at end of file diff --git a/spring-zuul/spring-zuul-users-resource/src/main/resources/application.properties b/spring-zuul/spring-zuul-users-resource/src/main/resources/application.properties new file mode 100644 index 0000000000..81284546ce --- /dev/null +++ b/spring-zuul/spring-zuul-users-resource/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.contextPath=/spring-zuul-users-resource +server.port=8081 \ No newline at end of file From 89651d72f7275ae61ca2642ebd0278c591925539 Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 29 Jan 2016 17:44:11 +0200 Subject: [PATCH 154/309] minor fix --- spring-zuul/pom.xml | 1 - .../spring-zuul-foos-resource/.project | 10 ++-- spring-zuul/spring-zuul-ui/.classpath | 10 ++-- spring-zuul/spring-zuul-ui/.project | 10 ++-- .../src/main/resources/application.yml | 4 -- .../src/main/resources/templates/index.html | 32 ------------- .../test/java/org/baeldung/web/LiveTest.java | 6 --- .../spring-zuul-users-resource/.classpath | 32 ------------- .../spring-zuul-users-resource/.project | 48 ------------------- .../spring-zuul-users-resource/pom.xml | 38 --------------- .../config/ResourceServerApplication.java | 14 ------ .../config/ResourceServerWebConfig.java | 13 ----- .../web/controller/UserController.java | 30 ------------ .../main/java/org/baeldung/web/dto/User.java | 46 ------------------ .../src/main/resources/application.properties | 2 - 15 files changed, 15 insertions(+), 281 deletions(-) delete mode 100644 spring-zuul/spring-zuul-users-resource/.classpath delete mode 100644 spring-zuul/spring-zuul-users-resource/.project delete mode 100644 spring-zuul/spring-zuul-users-resource/pom.xml delete mode 100644 spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java delete mode 100644 spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java delete mode 100644 spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/controller/UserController.java delete mode 100644 spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/dto/User.java delete mode 100644 spring-zuul/spring-zuul-users-resource/src/main/resources/application.properties diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml index 57ad3dfd30..6ad1d0be34 100644 --- a/spring-zuul/pom.xml +++ b/spring-zuul/pom.xml @@ -15,7 +15,6 @@ spring-zuul-foos-resource - spring-zuul-users-resource spring-zuul-ui diff --git a/spring-zuul/spring-zuul-foos-resource/.project b/spring-zuul/spring-zuul-foos-resource/.project index de3fc55423..8d04c873fb 100644 --- a/spring-zuul/spring-zuul-foos-resource/.project +++ b/spring-zuul/spring-zuul-foos-resource/.project @@ -20,11 +20,6 @@ - - org.eclipse.m2e.core.maven2Builder - - - org.springframework.ide.eclipse.core.springbuilder @@ -35,6 +30,11 @@ + + org.eclipse.m2e.core.maven2Builder + + + org.eclipse.jem.workbench.JavaEMFNature diff --git a/spring-zuul/spring-zuul-ui/.classpath b/spring-zuul/spring-zuul-ui/.classpath index 1e75b7bbbb..5c3ac53820 100644 --- a/spring-zuul/spring-zuul-ui/.classpath +++ b/spring-zuul/spring-zuul-ui/.classpath @@ -17,6 +17,11 @@
+ + + + + @@ -28,10 +33,5 @@ - - - - - diff --git a/spring-zuul/spring-zuul-ui/.project b/spring-zuul/spring-zuul-ui/.project index d87aec6bec..ec0f2cde81 100644 --- a/spring-zuul/spring-zuul-ui/.project +++ b/spring-zuul/spring-zuul-ui/.project @@ -20,6 +20,11 @@ + + org.eclipse.m2e.core.maven2Builder + + + org.springframework.ide.eclipse.core.springbuilder @@ -30,11 +35,6 @@ - - org.eclipse.m2e.core.maven2Builder - - - org.eclipse.jem.workbench.JavaEMFNature diff --git a/spring-zuul/spring-zuul-ui/src/main/resources/application.yml b/spring-zuul/spring-zuul-ui/src/main/resources/application.yml index 14660c497b..855020a40e 100644 --- a/spring-zuul/spring-zuul-ui/src/main/resources/application.yml +++ b/spring-zuul/spring-zuul-ui/src/main/resources/application.yml @@ -3,7 +3,3 @@ zuul: foos: path: /foos/** url: http://localhost:8081/spring-zuul-foos-resource/foos - users: - path: /users/** - url: http://localhost:8081/spring-zuul-users-resource/users - \ No newline at end of file diff --git a/spring-zuul/spring-zuul-ui/src/main/resources/templates/index.html b/spring-zuul/spring-zuul-ui/src/main/resources/templates/index.html index 07d2b77f7f..d279f9eaf9 100755 --- a/spring-zuul/spring-zuul-ui/src/main/resources/templates/index.html +++ b/spring-zuul/spring-zuul-ui/src/main/resources/templates/index.html @@ -33,17 +33,6 @@ app.controller('mainCtrl', function($scope,$resource,$http) { $scope.foo = $scope.foos.get({fooId:$scope.foo.id}); } - $scope.user = {id:0 , username:"john", age:11}; - $scope.users = $resource("/users/:userId",{userId:'@id'}); - - $scope.getUser = function(){ - $scope.user = $scope.users.get({userId:$scope.user.id}); - } - - - - - }); /*]]>*/ @@ -63,27 +52,6 @@ app.controller('mainCtrl', function($scope,$resource,$http) { -

- -

User Details

-
- - {{user.id}} -
- -
- - {{user.username}} -
- -
- - {{user.age}} -
- -
- New User -
diff --git a/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/web/LiveTest.java b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/web/LiveTest.java index 094d3250c7..7ced527778 100644 --- a/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/web/LiveTest.java +++ b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/web/LiveTest.java @@ -15,12 +15,6 @@ public class LiveTest { assertEquals(200, response.getStatusCode()); } - @Test - public void whenSendRequestToUserResource_thenHeaderAdded() { - final Response response = RestAssured.get("http://localhost:8080/users/1"); - assertEquals(200, response.getStatusCode()); - } - @Test public void whenSendRequest_thenHeaderAdded() { final Response response = RestAssured.get("http://localhost:8080/foos/1"); diff --git a/spring-zuul/spring-zuul-users-resource/.classpath b/spring-zuul/spring-zuul-users-resource/.classpath deleted file mode 100644 index 0cad5db2d0..0000000000 --- a/spring-zuul/spring-zuul-users-resource/.classpath +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-zuul/spring-zuul-users-resource/.project b/spring-zuul/spring-zuul-users-resource/.project deleted file mode 100644 index 2fedf43db4..0000000000 --- a/spring-zuul/spring-zuul-users-resource/.project +++ /dev/null @@ -1,48 +0,0 @@ - - - spring-zuul-users-resource - - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.springframework.ide.eclipse.core.springnature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - diff --git a/spring-zuul/spring-zuul-users-resource/pom.xml b/spring-zuul/spring-zuul-users-resource/pom.xml deleted file mode 100644 index 653c6b9d15..0000000000 --- a/spring-zuul/spring-zuul-users-resource/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - 4.0.0 - spring-zuul-users-resource - spring-zuul-users-resource - war - - - org.baeldung - spring-zuul - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - - - spring-zuul-users-resource - - - src/main/resources - true - - - - - \ No newline at end of file diff --git a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java deleted file mode 100644 index 1e35eff551..0000000000 --- a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.web.SpringBootServletInitializer; - -@SpringBootApplication -public class ResourceServerApplication extends SpringBootServletInitializer { - - public static void main(String[] args) { - SpringApplication.run(ResourceServerApplication.class, args); - } - -} \ No newline at end of file diff --git a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java deleted file mode 100644 index c040c8ac42..0000000000 --- a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@EnableWebMvc -@ComponentScan({ "org.baeldung.web.controller" }) -public class ResourceServerWebConfig extends WebMvcConfigurerAdapter { - -} diff --git a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/controller/UserController.java b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/controller/UserController.java deleted file mode 100644 index b1db89179a..0000000000 --- a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/controller/UserController.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.baeldung.web.controller; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.baeldung.web.dto.User; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -@Controller -public class UserController { - - public UserController() { - super(); - } - - // API - read - @RequestMapping(method = RequestMethod.GET, value = "/users/{id}") - @ResponseBody - public User findById(@PathVariable final long id, HttpServletRequest req, HttpServletResponse res) { - return new User(Long.parseLong(randomNumeric(2)), randomAlphabetic(4), Integer.parseInt(randomNumeric(2))); - } - -} diff --git a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/dto/User.java b/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/dto/User.java deleted file mode 100644 index f5e4124f93..0000000000 --- a/spring-zuul/spring-zuul-users-resource/src/main/java/org/baeldung/web/dto/User.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.baeldung.web.dto; - -public class User { - private long id; - private String username; - private int age; - - public User() { - super(); - } - - public User(final long id, final String name, int age) { - super(); - - this.id = id; - this.username = name; - this.age = age; - } - - // - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(final String username) { - this.username = username; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - -} \ No newline at end of file diff --git a/spring-zuul/spring-zuul-users-resource/src/main/resources/application.properties b/spring-zuul/spring-zuul-users-resource/src/main/resources/application.properties deleted file mode 100644 index 81284546ce..0000000000 --- a/spring-zuul/spring-zuul-users-resource/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -server.contextPath=/spring-zuul-users-resource -server.port=8081 \ No newline at end of file From 796d3668e7ca1e43951a313753922dee6983578b Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 30 Jan 2016 12:00:06 +0200 Subject: [PATCH 155/309] minor maven upgrades --- spring-data-cassandra/pom.xml | 5 ++++- spring-data-mongodb/.project | 4 ++-- spring-data-mongodb/pom.xml | 4 +++- spring-jpa/pom.xml | 2 +- .../pom.xml | 2 +- spring-security-mvc-ldap/pom.xml | 2 +- spring-security-rest-custom/pom.xml | 2 +- spring-security-rest-full/pom.xml | 20 +++++++++---------- 8 files changed, 22 insertions(+), 19 deletions(-) diff --git a/spring-data-cassandra/pom.xml b/spring-data-cassandra/pom.xml index b2b649a422..7e21859b5d 100644 --- a/spring-data-cassandra/pom.xml +++ b/spring-data-cassandra/pom.xml @@ -11,8 +11,11 @@ UTF-8 + + 4.2.3.RELEASE + 1.3.2.RELEASE - 4.2.2.RELEASE + 4.11 1.7.12 1.1.3 diff --git a/spring-data-mongodb/.project b/spring-data-mongodb/.project index e3d7687573..2e5a0d4bac 100644 --- a/spring-data-mongodb/.project +++ b/spring-data-mongodb/.project @@ -11,12 +11,12 @@ - org.eclipse.m2e.core.maven2Builder + org.springframework.ide.eclipse.core.springbuilder - org.springframework.ide.eclipse.core.springbuilder + org.eclipse.m2e.core.maven2Builder diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 23ac353350..558af930b3 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -117,9 +117,11 @@ UTF-8 + + 4.2.4.RELEASE 1.7.1.RELEASE - 4.2.2.RELEASE + 1.3 4.11 2.4.1 diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index 20be07ca5b..2e8f818776 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -186,7 +186,7 @@ 4.3.11.Final 5.1.37 - 1.7.2.RELEASE + 1.8.2.RELEASE 1.7.13 diff --git a/spring-security-login-and-registration/pom.xml b/spring-security-login-and-registration/pom.xml index 9e0f15688f..f5b62be553 100644 --- a/spring-security-login-and-registration/pom.xml +++ b/spring-security-login-and-registration/pom.xml @@ -329,7 +329,7 @@ 1 - 1.8.0.RELEASE + 1.8.2.RELEASE 19.0 diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index 3f9b9ad1ed..317c8dfb73 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.1.RELEASE + 1.3.2.RELEASE diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index a112fdcd43..df936353d9 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.1.RELEASE + 1.3.2.RELEASE diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index b48d87473b..270774ee13 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.1.RELEASE + 1.3.2.RELEASE @@ -92,13 +92,11 @@ org.springframework spring-webmvc - - - org.springframework.data - spring-data-commons - - - + + + org.springframework.data + spring-data-commons + @@ -238,7 +236,7 @@ spring-test test - + org.springframework.security spring-security-test @@ -435,11 +433,11 @@ 4.3.11.Final 5.1.37 - 1.7.2.RELEASE + 1.8.2.RELEASE 2.0.0 3.6.2 - + 2.5.5 1.4.01 From 95e2d063f4e28486d8765e5063d7e3488e335d35 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 30 Jan 2016 12:01:41 +0200 Subject: [PATCH 156/309] general formatting work --- .../java/CollectionJavaPartitionUnitTest.java | 4 ---- .../baeldung/customannotation/DataAccess.java | 2 +- .../DataAccessAnnotationProcessor.java | 6 ++--- .../DataAccessFieldCallback.java | 22 ++++++------------- .../customannotation/BeanWithGenericDAO.java | 5 +++-- .../DataAccessFieldCallbackTest.java | 4 +--- .../spring_batch_intro/SpringBatchConfig.java | 13 ++++------- .../spring_batch_intro/SpringConfig.java | 3 +-- .../spring_batch_intro/model/Transaction.java | 4 +--- .../service/CustomItemProcessor.java | 3 +-- .../persistence/dao/impl/ChildDao.java | 2 +- .../baeldung/persistence/dao/impl/FooDao.java | 2 +- .../persistence/dao/impl/ParentDao.java | 2 +- .../service/impl/ChildService.java | 2 +- .../persistence/service/impl/FooService.java | 2 +- .../service/impl/ParentService.java | 2 +- .../org/baeldung/persistence/dao/FooDao.java | 2 +- .../dao/common/GenericHibernateDao.java | 2 +- .../service/impl/ChildService.java | 2 +- .../persistence/service/impl/FooService.java | 2 +- .../service/impl/ParentService.java | 2 +- .../persistence/audit/JPABarAuditTest.java | 4 ---- .../org/baeldung/persistence/dao/FooDao.java | 2 +- .../org/baeldung/persistence/model/User.java | 2 +- .../java/org/baeldung/aop/LoggingAspect.java | 9 +++++--- .../org/baeldung/aop/PerformanceAspect.java | 3 ++- .../org/baeldung/aop/PublishingAspect.java | 9 +++++--- .../src/main/java/org/baeldung/model/Foo.java | 5 +---- .../web/controller/UserController.java | 21 +++++++++--------- .../java/org/baeldung/aop/AopLoggingTest.java | 4 ++-- .../org/baeldung/aop/AopPerformanceTest.java | 2 +- .../org/baeldung/aop/AopPublishingTest.java | 5 ++--- .../java/org/baeldung/config/TestConfig.java | 2 +- .../baeldung/validation/PasswordMatches.java | 4 ++-- .../org/baeldung/validation/ValidEmail.java | 4 ++-- .../baeldung/validation/ValidPassword.java | 4 ++-- 36 files changed, 71 insertions(+), 97 deletions(-) diff --git a/guava/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java b/guava/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java index 639aea58f6..63583987ea 100644 --- a/guava/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java +++ b/guava/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java @@ -67,8 +67,4 @@ public class CollectionJavaPartitionUnitTest { assertThat(lastPartition, equalTo(expectedLastPartition)); } - - - - } diff --git a/spring-all/src/main/java/org/baeldung/customannotation/DataAccess.java b/spring-all/src/main/java/org/baeldung/customannotation/DataAccess.java index 11bc30a84a..9a8a493a6d 100644 --- a/spring-all/src/main/java/org/baeldung/customannotation/DataAccess.java +++ b/spring-all/src/main/java/org/baeldung/customannotation/DataAccess.java @@ -10,5 +10,5 @@ import java.lang.annotation.Target; @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Documented public @interface DataAccess { - Classentity(); + Class entity(); } diff --git a/spring-all/src/main/java/org/baeldung/customannotation/DataAccessAnnotationProcessor.java b/spring-all/src/main/java/org/baeldung/customannotation/DataAccessAnnotationProcessor.java index 7902da746e..c792073745 100644 --- a/spring-all/src/main/java/org/baeldung/customannotation/DataAccessAnnotationProcessor.java +++ b/spring-all/src/main/java/org/baeldung/customannotation/DataAccessAnnotationProcessor.java @@ -19,15 +19,13 @@ public class DataAccessAnnotationProcessor implements BeanPostProcessor { } @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { scanDataAccessAnnotation(bean, beanName); return bean; } @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } diff --git a/spring-all/src/main/java/org/baeldung/customannotation/DataAccessFieldCallback.java b/spring-all/src/main/java/org/baeldung/customannotation/DataAccessFieldCallback.java index 16526fa56f..8cb62affc4 100644 --- a/spring-all/src/main/java/org/baeldung/customannotation/DataAccessFieldCallback.java +++ b/spring-all/src/main/java/org/baeldung/customannotation/DataAccessFieldCallback.java @@ -12,18 +12,14 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils.FieldCallback; - public final class DataAccessFieldCallback implements FieldCallback { private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class); private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; - private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " - + "value should have same type with injected generic type."; - private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " - + "to raw (non-generic) declaration. This will make your code less type-safe."; - private static String ERROR_CREATE_INSTANCE = "Cannot create instance of " - + "type '{}' or instance creation is failed because: {}"; + private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " + "value should have same type with injected generic type."; + private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " + "to raw (non-generic) declaration. This will make your code less type-safe."; + private static String ERROR_CREATE_INSTANCE = "Cannot create instance of " + "type '{}' or instance creation is failed because: {}"; private ConfigurableListableBeanFactory configurableListableBeanFactory; private Object bean; @@ -34,15 +30,14 @@ public final class DataAccessFieldCallback implements FieldCallback { } @Override - public void doWith(final Field field) - throws IllegalArgumentException, IllegalAccessException { + public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { if (!field.isAnnotationPresent(DataAccess.class)) { return; } ReflectionUtils.makeAccessible(field); final Type fieldGenericType = field.getGenericType(); - // In this example, get actual "GenericDAO' type. - final Class generic = field.getType(); + // In this example, get actual "GenericDAO' type. + final Class generic = field.getType(); final Class classValue = field.getDeclaredAnnotation(DataAccess.class).entity(); if (genericTypeIsValid(classValue, fieldGenericType)) { @@ -54,7 +49,6 @@ public final class DataAccessFieldCallback implements FieldCallback { } } - /** * For example, if user write: *
@@ -75,8 +69,6 @@ public final class DataAccessFieldCallback implements FieldCallback {
         }
     }
 
-
-
     public final Object getBeanInstance(final String beanName, final Class genericClass, final Class paramClass) {
         Object daoInstance = null;
         if (!configurableListableBeanFactory.containsBean(beanName)) {
@@ -90,7 +82,7 @@ public final class DataAccessFieldCallback implements FieldCallback {
                 logger.error(ERROR_CREATE_INSTANCE, genericClass.getTypeName(), e);
                 throw new RuntimeException(e);
             }
-            
+
             daoInstance = configurableListableBeanFactory.initializeBean(toRegister, beanName);
             configurableListableBeanFactory.autowireBeanProperties(daoInstance, AUTOWIRE_MODE, true);
             configurableListableBeanFactory.registerSingleton(beanName, daoInstance);
diff --git a/spring-all/src/test/java/org/baeldung/customannotation/BeanWithGenericDAO.java b/spring-all/src/test/java/org/baeldung/customannotation/BeanWithGenericDAO.java
index 32d4660f41..9ba915f296 100644
--- a/spring-all/src/test/java/org/baeldung/customannotation/BeanWithGenericDAO.java
+++ b/spring-all/src/test/java/org/baeldung/customannotation/BeanWithGenericDAO.java
@@ -5,10 +5,11 @@ import org.springframework.stereotype.Repository;
 @Repository
 public class BeanWithGenericDAO {
 
-    @DataAccess(entity=Person.class)
+    @DataAccess(entity = Person.class)
     private GenericDAO personGenericDAO;
 
-    public BeanWithGenericDAO() {}
+    public BeanWithGenericDAO() {
+    }
 
     public GenericDAO getPersonGenericDAO() {
         return personGenericDAO;
diff --git a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java
index f025a3e00a..e47d03c961 100644
--- a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java
+++ b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java
@@ -15,7 +15,6 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
 import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
-
 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
 public class DataAccessFieldCallbackTest {
@@ -36,8 +35,7 @@ public class DataAccessFieldCallbackTest {
     }
 
     @Test
-    public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue()
-            throws NoSuchFieldException, SecurityException {
+    public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue() throws NoSuchFieldException, SecurityException {
         final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO);
         final Type fieldType = BeanWithGenericDAO.class.getDeclaredField("personGenericDAO").getGenericType();
         final boolean result = callback.genericTypeIsValid(Person.class, fieldType);
diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java
index a024cbc04e..9973005c7c 100644
--- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java
+++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java
@@ -40,8 +40,7 @@ public class SpringBatchConfig {
     private Resource outputXml;
 
     @Bean
-    public ItemReader itemReader()
-        throws UnexpectedInputException, ParseException {
+    public ItemReader itemReader() throws UnexpectedInputException, ParseException {
         FlatFileItemReader reader = new FlatFileItemReader();
         DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
         String[] tokens = { "username", "userid", "transactiondate", "amount" };
@@ -61,8 +60,7 @@ public class SpringBatchConfig {
     }
 
     @Bean
-    public ItemWriter itemWriter(Marshaller marshaller)
-        throws MalformedURLException {
+    public ItemWriter itemWriter(Marshaller marshaller) throws MalformedURLException {
         StaxEventItemWriter itemWriter = new StaxEventItemWriter();
         itemWriter.setMarshaller(marshaller);
         itemWriter.setRootTagName("transactionRecord");
@@ -78,11 +76,8 @@ public class SpringBatchConfig {
     }
 
     @Bean
-    protected Step step1(ItemReader reader,
-        ItemProcessor processor,
-        ItemWriter writer) {
-        return steps.get("step1"). chunk(10)
-            .reader(reader).processor(processor).writer(writer).build();
+    protected Step step1(ItemReader reader, ItemProcessor processor, ItemWriter writer) {
+        return steps.get("step1"). chunk(10).reader(reader).processor(processor).writer(writer).build();
     }
 
     @Bean(name = "firstBatchJob")
diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java
index 91366d8721..ed7d302047 100644
--- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java
+++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java
@@ -38,8 +38,7 @@ public class SpringConfig {
     }
 
     @Bean
-    public DataSourceInitializer dataSourceInitializer(DataSource dataSource)
-        throws MalformedURLException {
+    public DataSourceInitializer dataSourceInitializer(DataSource dataSource) throws MalformedURLException {
         ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
 
         databasePopulator.addScript(dropReopsitoryTables);
diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java
index 6e80298ff0..3b2b9610f2 100644
--- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java
+++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java
@@ -48,9 +48,7 @@ public class Transaction {
 
     @Override
     public String toString() {
-        return "Transaction [username=" + username + ", userId=" + userId
-            + ", transactionDate=" + transactionDate + ", amount=" + amount
-            + "]";
+        return "Transaction [username=" + username + ", userId=" + userId + ", transactionDate=" + transactionDate + ", amount=" + amount + "]";
     }
 
 }
diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java
index baabe79409..ebee1d2802 100644
--- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java
+++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java
@@ -3,8 +3,7 @@ package org.baeldung.spring_batch_intro.service;
 import org.baeldung.spring_batch_intro.model.Transaction;
 import org.springframework.batch.item.ItemProcessor;
 
-public class CustomItemProcessor implements
-    ItemProcessor {
+public class CustomItemProcessor implements ItemProcessor {
 
     public Transaction process(Transaction item) {
         System.out.println("Processing..." + item);
diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ChildDao.java b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ChildDao.java
index 771da435c6..e068573c5c 100644
--- a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ChildDao.java
+++ b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ChildDao.java
@@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Repository;
 
 @Repository
-public class ChildDao extends AbstractHibernateDaoimplements IChildDao {
+public class ChildDao extends AbstractHibernateDao implements IChildDao {
 
     @Autowired
     private SessionFactory sessionFactory;
diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java
index a5d995cec0..baf29c9ecd 100644
--- a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java
+++ b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java
@@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Repository;
 
 @Repository
-public class FooDao extends AbstractHibernateDaoimplements IFooDao {
+public class FooDao extends AbstractHibernateDao implements IFooDao {
 
     @Autowired
     private SessionFactory sessionFactory;
diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ParentDao.java b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ParentDao.java
index 207e01de58..5634137b63 100644
--- a/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ParentDao.java
+++ b/spring-exceptions/src/main/java/org/baeldung/persistence/dao/impl/ParentDao.java
@@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Repository;
 
 @Repository
-public class ParentDao extends AbstractHibernateDaoimplements IParentDao {
+public class ParentDao extends AbstractHibernateDao implements IParentDao {
 
     @Autowired
     private SessionFactory sessionFactory;
diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ChildService.java b/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ChildService.java
index 987466643b..89597313ea 100644
--- a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ChildService.java
+++ b/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ChildService.java
@@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 @Service
-public class ChildService extends AbstractServiceimplements IChildService {
+public class ChildService extends AbstractService implements IChildService {
 
     @Autowired
     private IChildDao dao;
diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/FooService.java b/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/FooService.java
index 382368bbd4..f0a4d7a649 100644
--- a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/FooService.java
+++ b/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/FooService.java
@@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 @Service
-public class FooService extends AbstractServiceimplements IFooService {
+public class FooService extends AbstractService implements IFooService {
 
     @Autowired
     private IFooDao dao;
diff --git a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ParentService.java b/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ParentService.java
index e40ccfd2f8..97c44f4a2f 100644
--- a/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ParentService.java
+++ b/spring-exceptions/src/main/java/org/baeldung/persistence/service/impl/ParentService.java
@@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 @Service
-public class ParentService extends AbstractServiceimplements IParentService {
+public class ParentService extends AbstractService implements IParentService {
 
     @Autowired
     private IParentDao dao;
diff --git a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/FooDao.java b/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/FooDao.java
index cb8d7488ea..23de04169e 100644
--- a/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/FooDao.java
+++ b/spring-hibernate3/src/main/java/org/baeldung/persistence/dao/FooDao.java
@@ -4,7 +4,7 @@ import org.baeldung.persistence.model.Foo;
 import org.springframework.stereotype.Repository;
 
 @Repository
-public class FooDao extends AbstractHibernateDaoimplements IFooDao {
+public class FooDao extends AbstractHibernateDao implements IFooDao {
 
     public FooDao() {
         super();
diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java
index d45fea5a73..18b16fa033 100644
--- a/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java
+++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java
@@ -8,6 +8,6 @@ import org.springframework.stereotype.Repository;
 
 @Repository
 @Scope(BeanDefinition.SCOPE_PROTOTYPE)
-public class GenericHibernateDao extends AbstractHibernateDaoimplements IGenericDao {
+public class GenericHibernateDao extends AbstractHibernateDao implements IGenericDao {
     //
 }
\ No newline at end of file
diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ChildService.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ChildService.java
index 6fd8c27803..417fe2c49a 100644
--- a/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ChildService.java
+++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ChildService.java
@@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 @Service
-public class ChildService extends AbstractHibernateServiceimplements IChildService {
+public class ChildService extends AbstractHibernateService implements IChildService {
 
     @Autowired
     private IChildDao dao;
diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooService.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooService.java
index 008763c00d..84cf018fee 100644
--- a/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooService.java
+++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/FooService.java
@@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.stereotype.Service;
 
 @Service
-public class FooService extends AbstractHibernateServiceimplements IFooService {
+public class FooService extends AbstractHibernateService implements IFooService {
 
     @Autowired
     @Qualifier("fooHibernateDao")
diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ParentService.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ParentService.java
index cbcd5da3d4..078acfc369 100644
--- a/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ParentService.java
+++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/service/impl/ParentService.java
@@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 @Service
-public class ParentService extends AbstractHibernateServiceimplements IParentService {
+public class ParentService extends AbstractHibernateService implements IParentService {
 
     @Autowired
     private IParentDao dao;
diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditTest.java
index 73fa04969e..1e4a10f61c 100644
--- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditTest.java
+++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditTest.java
@@ -41,7 +41,6 @@ public class JPABarAuditTest {
         logger.info("tearDownAfterClass()");
     }
 
-
     @Autowired
     @Qualifier("barJpaService")
     private IBarService barService;
@@ -51,7 +50,6 @@ public class JPABarAuditTest {
 
     private EntityManager em;
 
-
     @Before
     public void setUp() throws Exception {
         logger.info("setUp()");
@@ -64,7 +62,6 @@ public class JPABarAuditTest {
         em.close();
     }
 
-
     @Test
     public final void whenBarsModified_thenBarsAudited() {
 
@@ -84,7 +81,6 @@ public class JPABarAuditTest {
         bar1.setName("BAR1b");
         barService.update(bar1);
 
-
         // get BAR1 and BAR2 from the DB and check the audit values
         // detach instances from persistence context to make sure we fire db
         em.detach(bar1);
diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/dao/FooDao.java b/spring-jpa/src/main/java/org/baeldung/persistence/dao/FooDao.java
index becd8d5f67..77978c5cf2 100644
--- a/spring-jpa/src/main/java/org/baeldung/persistence/dao/FooDao.java
+++ b/spring-jpa/src/main/java/org/baeldung/persistence/dao/FooDao.java
@@ -4,7 +4,7 @@ import org.baeldung.persistence.model.Foo;
 import org.springframework.stereotype.Repository;
 
 @Repository
-public class FooDao extends AbstractJpaDAOimplements IFooDao {
+public class FooDao extends AbstractJpaDAO implements IFooDao {
 
     public FooDao() {
         super();
diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java
index 58a92002c8..67e4c6ae1d 100644
--- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java
+++ b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java
@@ -30,7 +30,7 @@ public class User {
     private String email;
 
     @ManyToMany(fetch = FetchType.EAGER)
-    @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
+    @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") )
     @JsonApiToMany
     @JsonApiIncludeByDefault
     private Set roles;
diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java b/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java
index 72ac610abd..c59c4f060a 100644
--- a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java
+++ b/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java
@@ -24,13 +24,16 @@ public class LoggingAspect {
     };
 
     @Pointcut("@target(org.springframework.stereotype.Repository)")
-    public void repositoryMethods() {}
+    public void repositoryMethods() {
+    }
 
     @Pointcut("@annotation(org.baeldung.aop.annotations.Loggable)")
-    public void loggableMethods() {}
+    public void loggableMethods() {
+    }
 
     @Pointcut("@args(org.baeldung.aop.annotations.Entity)")
-    public void methodsAcceptingEntities() {}
+    public void methodsAcceptingEntities() {
+    }
 
     @Before("repositoryMethods()")
     public void logMethodCall(JoinPoint jp) {
diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java b/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java
index 57f5bc5edd..2d07e5a5f3 100644
--- a/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java
+++ b/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java
@@ -16,7 +16,8 @@ public class PerformanceAspect {
     private static Logger logger = Logger.getLogger(PerformanceAspect.class.getName());
 
     @Pointcut("within(@org.springframework.stereotype.Repository *)")
-    public void repositoryClassMethods() {}
+    public void repositoryClassMethods() {
+    }
 
     @Around("repositoryClassMethods()")
     public Object measureMethodExecutionTime(ProceedingJoinPoint pjp) throws Throwable {
diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java b/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java
index 20a10f4f6a..324605dab1 100644
--- a/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java
+++ b/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java
@@ -21,13 +21,16 @@ public class PublishingAspect {
     }
 
     @Pointcut("@target(org.springframework.stereotype.Repository)")
-    public void repositoryMethods() {}
+    public void repositoryMethods() {
+    }
 
     @Pointcut("execution(* *..create*(Long,..))")
-    public void firstLongParamMethods() {}
+    public void firstLongParamMethods() {
+    }
 
     @Pointcut("repositoryMethods() && firstLongParamMethods()")
-    public void entityCreationMethods() {}
+    public void entityCreationMethods() {
+    }
 
     @AfterReturning(value = "entityCreationMethods()", returning = "entity")
     public void logMethodCall(JoinPoint jp, Object entity) throws Throwable {
diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java b/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java
index 0b1a553afc..87bd7132e6 100644
--- a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java
+++ b/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java
@@ -14,9 +14,6 @@ public class Foo {
 
     @Override
     public String toString() {
-        return "Foo{" +
-                "id=" + id +
-                ", name='" + name + '\'' +
-                '}';
+        return "Foo{" + "id=" + id + ", name='" + name + '\'' + '}';
     }
 }
diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java b/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java
index 731424c336..da39a36adf 100644
--- a/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java
+++ b/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java
@@ -13,20 +13,19 @@ public class UserController {
 
     @RequestMapping(value = "/", method = RequestMethod.GET)
     public String showForm(final Model model) {
-	final User user = new User();
-	user.setFirstname("John");
-	user.setLastname("Roy");
-	user.setEmailId("John.Roy@gmail.com");
-	model.addAttribute("user", user);
-	return "index";
+        final User user = new User();
+        user.setFirstname("John");
+        user.setLastname("Roy");
+        user.setEmailId("John.Roy@gmail.com");
+        model.addAttribute("user", user);
+        return "index";
     }
 
     @RequestMapping(value = "/processForm", method = RequestMethod.POST)
-    public String processForm(@ModelAttribute(value = "user") final User user,
-	    final Model model) {
-	// Insert User into DB
-	model.addAttribute("name", user.getFirstname() + " " + user.getLastname());
-	return "hello";
+    public String processForm(@ModelAttribute(value = "user") final User user, final Model model) {
+        // Insert User into DB
+        model.addAttribute("name", user.getFirstname() + " " + user.getLastname());
+        return "hello";
     }
 
 }
diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java b/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java
index 4c8fcd50a8..b1c9867e41 100644
--- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java
+++ b/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java
@@ -24,12 +24,12 @@ import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 
 @RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
 public class AopLoggingTest {
 
     @Before
     public void setUp() {
-        messages =  new ArrayList<>();
+        messages = new ArrayList<>();
 
         logEventHandler = new Handler() {
             @Override
diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPerformanceTest.java b/spring-mvc-java/src/test/java/org/baeldung/aop/AopPerformanceTest.java
index 82af95957a..69083c60a2 100644
--- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPerformanceTest.java
+++ b/spring-mvc-java/src/test/java/org/baeldung/aop/AopPerformanceTest.java
@@ -23,7 +23,7 @@ import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 
 @RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
 public class AopPerformanceTest {
 
     @Before
diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java b/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java
index 561eec06ec..e691dbd32e 100644
--- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java
+++ b/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java
@@ -22,7 +22,7 @@ import java.util.regex.Pattern;
 import static org.junit.Assert.assertTrue;
 
 @RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
 public class AopPublishingTest {
 
     @Before
@@ -60,8 +60,7 @@ public class AopPublishingTest {
         dao.create(1L, "Bar");
 
         String logMessage = messages.get(0);
-        Pattern pattern = Pattern.compile("Created foo instance: " +
-                Pattern.quote(new Foo(1L, "Bar").toString()));
+        Pattern pattern = Pattern.compile("Created foo instance: " + Pattern.quote(new Foo(1L, "Bar").toString()));
         assertTrue(pattern.matcher(logMessage).matches());
     }
 }
diff --git a/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java b/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java
index 0d103f1029..f9573b2add 100644
--- a/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java
+++ b/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java
@@ -5,7 +5,7 @@ import org.springframework.context.annotation.Configuration;
 import org.springframework.context.annotation.EnableAspectJAutoProxy;
 
 @Configuration
-@ComponentScan(basePackages = {"org.baeldung.dao", "org.baeldung.aop", "org.baeldung.events"})
+@ComponentScan(basePackages = { "org.baeldung.dao", "org.baeldung.aop", "org.baeldung.events" })
 @EnableAspectJAutoProxy
 public class TestConfig {
 }
diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatches.java b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatches.java
index 1e3193b7b5..fcc7e228a7 100644
--- a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatches.java
+++ b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/PasswordMatches.java
@@ -19,8 +19,8 @@ public @interface PasswordMatches {
 
     String message() default "Passwords don't match";
 
-    Class[]groups() default {};
+    Class[] groups() default {};
 
-    Class[]payload() default {};
+    Class[] payload() default {};
 
 }
diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidEmail.java b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidEmail.java
index b5dc4f0f46..a520a45b0c 100644
--- a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidEmail.java
+++ b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidEmail.java
@@ -20,7 +20,7 @@ public @interface ValidEmail {
 
     String message() default "Invalid Email";
 
-    Class[]groups() default {};
+    Class[] groups() default {};
 
-    Class[]payload() default {};
+    Class[] payload() default {};
 }
diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidPassword.java b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidPassword.java
index 5b92f4d133..37b217213a 100644
--- a/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidPassword.java
+++ b/spring-security-login-and-registration/src/main/java/org/baeldung/validation/ValidPassword.java
@@ -20,8 +20,8 @@ public @interface ValidPassword {
 
     String message() default "Invalid Password";
 
-    Class[]groups() default {};
+    Class[] groups() default {};
 
-    Class[]payload() default {};
+    Class[] payload() default {};
 
 }

From c14e7ad1a17b34a60b74a4a4b63e8850567365d6 Mon Sep 17 00:00:00 2001
From: "giuseppe.bueti" 
Date: Sat, 30 Jan 2016 17:48:56 +0100
Subject: [PATCH 157/309] RestEasy Tutorial, CRUD Services example

---
 RestEasy Example/pom.xml                      |  91 +++
 .../src/main/java/com/baeldung/Movie.java     | 535 ++++++++++++++++++
 .../baeldung/client/ServicesInterface.java    |  44 ++
 .../server/service/MovieCrudService.java      |  94 +++
 .../server/service/RestEasyServices.java      |  40 ++
 .../src/main/resources/schema1.xsd            |  29 +
 .../main/webapp/WEB-INF/classes/logback.xml   |   3 +
 .../WEB-INF/jboss-deployment-structure.xml    |  16 +
 .../src/main/webapp/WEB-INF/jboss-web.xml     |   4 +
 .../src/main/webapp/WEB-INF/web.xml           |  51 ++
 .../com/baeldung/server/RestEasyClient.java   |  50 ++
 .../resources/server/movies/transformer.json  |  22 +
 12 files changed, 979 insertions(+)
 create mode 100644 RestEasy Example/pom.xml
 create mode 100644 RestEasy Example/src/main/java/com/baeldung/Movie.java
 create mode 100644 RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java
 create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java
 create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java
 create mode 100644 RestEasy Example/src/main/resources/schema1.xsd
 create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml
 create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml
 create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml
 create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/web.xml
 create mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java
 create mode 100644 RestEasy Example/src/test/resources/server/movies/transformer.json

diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml
new file mode 100644
index 0000000000..b16c5e8267
--- /dev/null
+++ b/RestEasy Example/pom.xml	
@@ -0,0 +1,91 @@
+
+
+    4.0.0
+
+    com.baeldung
+    resteasy-tutorial
+    1.0
+    war
+
+    
+        
+            jboss
+            http://repository.jboss.org/nexus/content/groups/public/
+        
+    
+
+    
+        3.0.14.Final
+        runtime
+    
+
+    
+        RestEasyTutorial
+        
+            
+                org.apache.maven.plugins
+                maven-compiler-plugin
+                
+                    1.8
+                    1.8
+                
+            
+        
+    
+
+    
+        
+        
+            org.jboss.resteasy
+            jaxrs-api
+            3.0.12.Final
+            ${resteasy.scope}
+        
+
+        
+            org.jboss.resteasy
+            resteasy-servlet-initializer
+            ${resteasy.version}
+            ${resteasy.scope}
+            
+                
+                    jboss-jaxrs-api_2.0_spec
+                    org.jboss.spec.javax.ws.rs
+                
+            
+        
+
+        
+            org.jboss.resteasy
+            resteasy-client
+            ${resteasy.version}
+            ${resteasy.scope}
+        
+
+
+        
+            javax.ws.rs
+            javax.ws.rs-api
+            2.0.1
+        
+
+        
+            org.jboss.resteasy
+            resteasy-jackson-provider
+            ${resteasy.version}
+            ${resteasy.scope}
+        
+
+        
+            org.jboss.resteasy
+            resteasy-jaxb-provider
+            ${resteasy.version}
+            ${resteasy.scope}
+        
+
+    
+
+
+
\ No newline at end of file
diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/Movie.java
new file mode 100644
index 0000000000..c0041d2e95
--- /dev/null
+++ b/RestEasy Example/src/main/java/com/baeldung/Movie.java	
@@ -0,0 +1,535 @@
+
+package com.baeldung;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "movie", propOrder = {
+    "actors",
+    "awards",
+    "country",
+    "director",
+    "genre",
+    "imdbID",
+    "imdbRating",
+    "imdbVotes",
+    "language",
+    "metascore",
+    "plot",
+    "poster",
+    "rated",
+    "released",
+    "response",
+    "runtime",
+    "title",
+    "type",
+    "writer",
+    "year"
+})
+public class Movie {
+
+    protected String actors;
+    protected String awards;
+    protected String country;
+    protected String director;
+    protected String genre;
+    protected String imdbID;
+    protected String imdbRating;
+    protected String imdbVotes;
+    protected String language;
+    protected String metascore;
+    protected String plot;
+    protected String poster;
+    protected String rated;
+    protected String released;
+    protected String response;
+    protected String runtime;
+    protected String title;
+    protected String type;
+    protected String writer;
+    protected String year;
+
+    /**
+     * Recupera il valore della propriet� actors.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getActors() {
+        return actors;
+    }
+
+    /**
+     * Imposta il valore della propriet� actors.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setActors(String value) {
+        this.actors = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� awards.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getAwards() {
+        return awards;
+    }
+
+    /**
+     * Imposta il valore della propriet� awards.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setAwards(String value) {
+        this.awards = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� country.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getCountry() {
+        return country;
+    }
+
+    /**
+     * Imposta il valore della propriet� country.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setCountry(String value) {
+        this.country = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� director.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getDirector() {
+        return director;
+    }
+
+    /**
+     * Imposta il valore della propriet� director.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setDirector(String value) {
+        this.director = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� genre.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getGenre() {
+        return genre;
+    }
+
+    /**
+     * Imposta il valore della propriet� genre.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setGenre(String value) {
+        this.genre = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� imdbID.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getImdbID() {
+        return imdbID;
+    }
+
+    /**
+     * Imposta il valore della propriet� imdbID.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setImdbID(String value) {
+        this.imdbID = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� imdbRating.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getImdbRating() {
+        return imdbRating;
+    }
+
+    /**
+     * Imposta il valore della propriet� imdbRating.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setImdbRating(String value) {
+        this.imdbRating = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� imdbVotes.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getImdbVotes() {
+        return imdbVotes;
+    }
+
+    /**
+     * Imposta il valore della propriet� imdbVotes.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setImdbVotes(String value) {
+        this.imdbVotes = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� language.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getLanguage() {
+        return language;
+    }
+
+    /**
+     * Imposta il valore della propriet� language.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setLanguage(String value) {
+        this.language = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� metascore.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getMetascore() {
+        return metascore;
+    }
+
+    /**
+     * Imposta il valore della propriet� metascore.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setMetascore(String value) {
+        this.metascore = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� plot.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getPlot() {
+        return plot;
+    }
+
+    /**
+     * Imposta il valore della propriet� plot.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setPlot(String value) {
+        this.plot = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� poster.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getPoster() {
+        return poster;
+    }
+
+    /**
+     * Imposta il valore della propriet� poster.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setPoster(String value) {
+        this.poster = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� rated.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getRated() {
+        return rated;
+    }
+
+    /**
+     * Imposta il valore della propriet� rated.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setRated(String value) {
+        this.rated = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� released.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getReleased() {
+        return released;
+    }
+
+    /**
+     * Imposta il valore della propriet� released.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setReleased(String value) {
+        this.released = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� response.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getResponse() {
+        return response;
+    }
+
+    /**
+     * Imposta il valore della propriet� response.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setResponse(String value) {
+        this.response = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� runtime.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getRuntime() {
+        return runtime;
+    }
+
+    /**
+     * Imposta il valore della propriet� runtime.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setRuntime(String value) {
+        this.runtime = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� title.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getTitle() {
+        return title;
+    }
+
+    /**
+     * Imposta il valore della propriet� title.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setTitle(String value) {
+        this.title = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� type.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getType() {
+        return type;
+    }
+
+    /**
+     * Imposta il valore della propriet� type.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setType(String value) {
+        this.type = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� writer.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getWriter() {
+        return writer;
+    }
+
+    /**
+     * Imposta il valore della propriet� writer.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setWriter(String value) {
+        this.writer = value;
+    }
+
+    /**
+     * Recupera il valore della propriet� year.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getYear() {
+        return year;
+    }
+
+    /**
+     * Imposta il valore della propriet� year.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setYear(String value) {
+        this.year = value;
+    }
+
+}
diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java
new file mode 100644
index 0000000000..53e88961be
--- /dev/null
+++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java	
@@ -0,0 +1,44 @@
+package com.baeldung.client;
+
+import com.baeldung.Movie;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+
+public interface ServicesInterface {
+
+
+    @GET
+    @Path("/getinfo")
+    @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
+    Movie movieByImdbID(@QueryParam("imdbID") String imdbID);
+
+
+    @POST
+    @Path("/addmovie")
+    @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
+    Response addMovie(Movie movie);
+
+
+    @PUT
+    @Path("/updatemovie")
+    @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
+    Response updateMovie(Movie movie);
+
+
+    @DELETE
+    @Path("/deletemovie")
+    Response deleteMovie(@QueryParam("imdbID") String imdbID);
+
+
+    @GET
+    @Path("/listmovies")
+    @Produces({"application/json"})
+    List listMovies();
+
+}
diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java
new file mode 100644
index 0000000000..d1973e7037
--- /dev/null
+++ b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java	
@@ -0,0 +1,94 @@
+package com.baeldung.server.service;
+
+import com.baeldung.Movie;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.Provider;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+
+@Path("/movies")
+public class MovieCrudService {
+
+
+    private Map inventory = new HashMap();
+
+    @GET
+    @Path("/getinfo")
+    @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
+    public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){
+
+        System.out.println("*** Calling  getinfo ***");
+
+        Movie movie=new Movie();
+        movie.setImdbID(imdbID);
+        return movie;
+    }
+
+    @POST
+    @Path("/addmovie")
+    @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
+    public Response addMovie(Movie movie){
+
+        System.out.println("*** Calling  addMovie ***");
+
+        if (null!=inventory.get(movie.getImdbID())){
+            return Response.status(Response.Status.NOT_MODIFIED)
+                    .entity("Movie is Already in the database.").build();
+        }
+        inventory.put(movie.getImdbID(),movie);
+
+        return Response.status(Response.Status.CREATED).build();
+    }
+
+
+    @PUT
+    @Path("/updatemovie")
+    @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
+    public Response updateMovie(Movie movie){
+
+        System.out.println("*** Calling  updateMovie ***");
+
+        if (null!=inventory.get(movie.getImdbID())){
+            return Response.status(Response.Status.NOT_MODIFIED)
+                    .entity("Movie is not in the database.\nUnable to Update").build();
+        }
+        inventory.put(movie.getImdbID(),movie);
+        return Response.status(Response.Status.OK).build();
+
+    }
+
+
+    @DELETE
+    @Path("/deletemovie")
+    public Response deleteMovie(@QueryParam("imdbID") String imdbID){
+
+        System.out.println("*** Calling  deleteMovie ***");
+
+        if (null==inventory.get(imdbID)){
+            return Response.status(Response.Status.NOT_FOUND)
+                    .entity("Movie is not in the database.\nUnable to Delete").build();
+        }
+
+        inventory.remove(imdbID);
+        return Response.status(Response.Status.OK).build();
+    }
+
+    @GET
+    @Path("/listmovies")
+    @Produces({"application/json"})
+    public List  listMovies(){
+
+        return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new));
+
+    }
+
+
+
+}
diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java
new file mode 100644
index 0000000000..16b6200ad1
--- /dev/null
+++ b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java	
@@ -0,0 +1,40 @@
+package com.baeldung.server.service;
+
+
+import javax.ws.rs.ApplicationPath;
+import javax.ws.rs.core.Application;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Created by Admin on 29/01/2016.
+ */
+
+
+
+@ApplicationPath("/rest")
+public class RestEasyServices extends Application {
+
+    private Set singletons = new HashSet();
+
+    public RestEasyServices() {
+        singletons.add(new MovieCrudService());
+    }
+
+    @Override
+    public Set getSingletons() {
+        return singletons;
+    }
+
+    @Override
+    public Set> getClasses() {
+        return super.getClasses();
+    }
+
+    @Override
+    public Map getProperties() {
+        return super.getProperties();
+    }
+}
diff --git a/RestEasy Example/src/main/resources/schema1.xsd b/RestEasy Example/src/main/resources/schema1.xsd
new file mode 100644
index 0000000000..0d74b7c366
--- /dev/null
+++ b/RestEasy Example/src/main/resources/schema1.xsd	
@@ -0,0 +1,29 @@
+
+
+
+  
+    
+      
+      
+      
+      
+      
+      
+      
+      
+      
+      
+      
+      
+      
+      
+      
+      
+      
+      
+      
+      
+    
+  
+
+
diff --git a/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml b/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml
new file mode 100644
index 0000000000..d94e9f71ab
--- /dev/null
+++ b/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml	
@@ -0,0 +1,3 @@
+
+
+
\ No newline at end of file
diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml
new file mode 100644
index 0000000000..84d75934a7
--- /dev/null
+++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml	
@@ -0,0 +1,16 @@
+
+    
+        
+            
+        
+
+        
+            
+            
+            
+        
+
+        
+    
+
+
\ No newline at end of file
diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml
new file mode 100644
index 0000000000..694bb71332
--- /dev/null
+++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml	
@@ -0,0 +1,4 @@
+
+
+
+
\ No newline at end of file
diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..c66d3b56ae
--- /dev/null
+++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml	
@@ -0,0 +1,51 @@
+
+
+
+    RestEasy Example
+
+    
+        
+            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
+        
+    
+
+    RestEasy Example
+
+    
+        webAppRootKey
+        RestEasyExample
+    
+
+
+    
+    
+        resteasy.servlet.mapping.prefix
+        /rest
+    
+
+
+    
+        resteasy-servlet
+        
+            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
+        
+        
+            javax.ws.rs.Application
+            com.baeldung.server.service.RestEasyServices
+        
+    
+
+    
+        resteasy-servlet
+        /rest/*
+    
+
+
+    
+        index.html
+    
+
+
+
\ No newline at end of file
diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java
new file mode 100644
index 0000000000..e711233979
--- /dev/null
+++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java	
@@ -0,0 +1,50 @@
+package com.baeldung.server;
+
+import com.baeldung.Movie;
+import com.baeldung.client.ServicesInterface;
+import org.jboss.resteasy.client.jaxrs.ResteasyClient;
+import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
+import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
+
+import java.util.List;
+
+public class RestEasyClient {
+
+    public static void main(String[] args) {
+
+        Movie st = new Movie();
+        st.setImdbID("12345");
+
+		/*
+		 *  Alternatively you can use this simple String to send
+		 *  instead of using a Student instance
+		 *
+		 *  String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}";
+		 */
+
+        try {
+            ResteasyClient client = new ResteasyClientBuilder().build();
+            ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies");
+
+            ServicesInterface simple = target.proxy(ServicesInterface.class);
+            final List movies = simple.listMovies();
+
+            /*
+            if (response.getStatus() != 200) {
+                throw new RuntimeException("Failed : HTTP error code : "
+                        + response.getStatus());
+            }
+
+            System.out.println("Server response : \n");
+            System.out.println(response.readEntity(String.class));
+
+            response.close();
+*/
+        } catch (Exception e) {
+
+            e.printStackTrace();
+
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/server/movies/transformer.json
new file mode 100644
index 0000000000..2154868265
--- /dev/null
+++ b/RestEasy Example/src/test/resources/server/movies/transformer.json	
@@ -0,0 +1,22 @@
+{
+  "title": "Transformers",
+  "year": "2007",
+  "rated": "PG-13",
+  "released": "03 Jul 2007",
+  "runtime": "144 min",
+  "genre": "Action, Adventure, Sci-Fi",
+  "director": "Michael Bay",
+  "writer": "Roberto Orci (screenplay), Alex Kurtzman (screenplay), John Rogers (story), Roberto Orci (story), Alex Kurtzman (story)",
+  "actors": "Shia LaBeouf, Megan Fox, Josh Duhamel, Tyrese Gibson",
+  "plot": "A long time ago, far away on the planet of Cybertron, a war is being waged between the noble Autobots (led by the wise Optimus Prime) and the devious Decepticons (commanded by the dreaded Megatron) for control over the Allspark, a mystical talisman that would grant unlimited power to whoever possesses it. The Autobots managed to smuggle the Allspark off the planet, but Megatron blasts off in search of it. He eventually tracks it to the planet of Earth (circa 1850), but his reckless desire for power sends him right into the Arctic Ocean, and the sheer cold forces him into a paralyzed state. His body is later found by Captain Archibald Witwicky, but before going into a comatose state Megatron uses the last of his energy to engrave into the Captain's glasses a map showing the location of the Allspark, and to send a transmission to Cybertron. Megatron is then carried away aboard the Captain's ship. A century later, Captain Witwicky's grandson Sam Witwicky (nicknamed Spike by his friends) buys his first car. To his shock, he discovers it to be Bumblebee, an Autobot in disguise who is to protect Spike, who possesses the Captain's glasses and the map engraved on them. But Bumblebee is not the only Transformer to have arrived on Earth - in the desert of Qatar, the Decepticons Blackout and Scorponok attack a U.S. military base, causing the Pentagon to send their special Sector Seven agents to capture all \"specimens of this alien race.\" Spike and his girlfriend Mikaela find themselves in the midst of a grand battle between the Autobots and the Decepticons, stretching from Hoover Dam all the way to Los Angeles. Meanwhile, deep inside Hoover Dam, the cryogenically stored body of Megatron awakens.",
+  "language": "English, Spanish",
+  "country": "USA",
+  "awards": "Nominated for 3 Oscars. Another 18 wins & 40 nominations.",
+  "poster": "http://ia.media-imdb.com/images/M/MV5BMTQwNjU5MzUzNl5BMl5BanBnXkFtZTYwMzc1MTI3._V1_SX300.jpg",
+  "metascore": "61",
+  "imdbRating": "7.1",
+  "imdbVotes": "492,225",
+  "imdbID": "tt0418279",
+  "Type": "movie",
+  "response": "True"
+}
\ No newline at end of file

From a85c9cbda573fc25ac4d0f133eaf6ed779611ad6 Mon Sep 17 00:00:00 2001
From: Giuseppe Bueti 
Date: Sat, 30 Jan 2016 20:39:28 +0100
Subject: [PATCH 158/309] Added testCase for List All Movies and Add a Movie

---
 RestEasy Example/pom.xml                      |  29 +++++
 .../baeldung/client/ServicesInterface.java    |   6 +-
 .../java/com/baeldung/{ => model}/Movie.java  |  45 +++++++-
 .../{service => }/MovieCrudService.java       |   5 +-
 .../{service => }/RestEasyServices.java       |   2 +-
 .../com/baeldung/server/RestEasyClient.java   | 104 ++++++++++++++----
 .../com/baeldung/server/movies/batman.json    |  22 ++++
 .../baeldung}/server/movies/transformer.json  |   2 +-
 8 files changed, 184 insertions(+), 31 deletions(-)
 rename RestEasy Example/src/main/java/com/baeldung/{ => model}/Movie.java (86%)
 rename RestEasy Example/src/main/java/com/baeldung/server/{service => }/MovieCrudService.java (96%)
 rename RestEasy Example/src/main/java/com/baeldung/server/{service => }/RestEasyServices.java (95%)
 create mode 100644 RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json
 rename RestEasy Example/src/test/resources/{ => com/baeldung}/server/movies/transformer.json (99%)

diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml
index b16c5e8267..8dabfc863b 100644
--- a/RestEasy Example/pom.xml	
+++ b/RestEasy Example/pom.xml	
@@ -85,6 +85,35 @@
             ${resteasy.scope}
         
 
+        
+
+        
+            junit
+            junit
+            4.4
+        
+
+        
+            commons-io
+            commons-io
+            2.4
+        
+
+        
+            com.fasterxml.jackson.core
+            jackson-core
+            2.7.0
+        
+
+        
+            com.fasterxml.jackson.core
+            jackson-annotations
+            2.7.0
+        
+
+
+
+
     
 
 
diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java
index 53e88961be..2585c32438 100644
--- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java	
+++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java	
@@ -1,15 +1,13 @@
 package com.baeldung.client;
 
-import com.baeldung.Movie;
+import com.baeldung.model.Movie;
 
 import javax.ws.rs.*;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-import java.util.ArrayList;
 import java.util.List;
-import java.util.stream.Collectors;
-
 
+@Path("/movies")
 public interface ServicesInterface {
 
 
diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java
similarity index 86%
rename from RestEasy Example/src/main/java/com/baeldung/Movie.java
rename to RestEasy Example/src/main/java/com/baeldung/model/Movie.java
index c0041d2e95..052ba081c1 100644
--- a/RestEasy Example/src/main/java/com/baeldung/Movie.java	
+++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java	
@@ -1,5 +1,5 @@
 
-package com.baeldung;
+package com.baeldung.model;
 
 import javax.xml.bind.annotation.XmlAccessType;
 import javax.xml.bind.annotation.XmlAccessorType;
@@ -532,4 +532,47 @@ public class Movie {
         this.year = value;
     }
 
+    @Override
+    public String toString() {
+        return "Movie{" +
+                "actors='" + actors + '\'' +
+                ", awards='" + awards + '\'' +
+                ", country='" + country + '\'' +
+                ", director='" + director + '\'' +
+                ", genre='" + genre + '\'' +
+                ", imdbID='" + imdbID + '\'' +
+                ", imdbRating='" + imdbRating + '\'' +
+                ", imdbVotes='" + imdbVotes + '\'' +
+                ", language='" + language + '\'' +
+                ", metascore='" + metascore + '\'' +
+                ", poster='" + poster + '\'' +
+                ", rated='" + rated + '\'' +
+                ", released='" + released + '\'' +
+                ", response='" + response + '\'' +
+                ", runtime='" + runtime + '\'' +
+                ", title='" + title + '\'' +
+                ", type='" + type + '\'' +
+                ", writer='" + writer + '\'' +
+                ", year='" + year + '\'' +
+                '}';
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        Movie movie = (Movie) o;
+
+        if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false;
+        return title != null ? title.equals(movie.title) : movie.title == null;
+
+    }
+
+    @Override
+    public int hashCode() {
+        int result = imdbID != null ? imdbID.hashCode() : 0;
+        result = 31 * result + (title != null ? title.hashCode() : 0);
+        return result;
+    }
 }
diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java
similarity index 96%
rename from RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java
rename to RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java
index d1973e7037..60e0121966 100644
--- a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java	
+++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java	
@@ -1,11 +1,10 @@
-package com.baeldung.server.service;
+package com.baeldung.server;
 
-import com.baeldung.Movie;
+import com.baeldung.model.Movie;
 
 import javax.ws.rs.*;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.Provider;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java
similarity index 95%
rename from RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java
rename to RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java
index 16b6200ad1..8c57d2c9b4 100644
--- a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java	
+++ b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java	
@@ -1,4 +1,4 @@
-package com.baeldung.server.service;
+package com.baeldung.server;
 
 
 import javax.ws.rs.ApplicationPath;
diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java
index e711233979..c77f494862 100644
--- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java	
+++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java	
@@ -1,49 +1,111 @@
 package com.baeldung.server;
 
-import com.baeldung.Movie;
+import com.baeldung.model.Movie;
 import com.baeldung.client.ServicesInterface;
+import org.apache.commons.io.IOUtils;
+import org.codehaus.jackson.map.DeserializationConfig;
+import org.codehaus.jackson.map.ObjectMapper;
 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
 
+import javax.naming.NamingException;
+import javax.ws.rs.core.Link;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileReader;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
 import java.util.List;
+import java.util.Locale;
 
 public class RestEasyClient {
 
-    public static void main(String[] args) {
 
-        Movie st = new Movie();
-        st.setImdbID("12345");
+    Movie  transformerMovie=null;
+    Movie   batmanMovie=null;
+    ObjectMapper jsonMapper=null;
 
-		/*
-		 *  Alternatively you can use this simple String to send
-		 *  instead of using a Student instance
-		 *
-		 *  String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}";
-		 */
+    @BeforeClass
+    public static void loadMovieInventory(){
+
+
+
+    }
+
+    @Before
+    public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException {
+
+
+        jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+        jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
+        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
+        jsonMapper.setDateFormat(sdf);
+
+        try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) {
+            String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
+            transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class);
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new RuntimeException("Test is going to die ...", e);
+        }
+
+        try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) {
+            String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
+            batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new RuntimeException("Test is going to die ...", e);
+        }
+
+    }
+
+    @Test
+    public void testListAllMovies() {
 
         try {
             ResteasyClient client = new ResteasyClientBuilder().build();
-            ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies");
+            ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest"));
+            ServicesInterface simple = target.proxy(ServicesInterface.class);
+
+            final List movies = simple.listMovies();
+            System.out.println(movies);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+
+    @Test
+    public void testAddMovie() {
+
+        try {
+            ResteasyClient client = new ResteasyClientBuilder().build();
+            ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest"));
 
             ServicesInterface simple = target.proxy(ServicesInterface.class);
-            final List movies = simple.listMovies();
+            final Response moviesResponse = simple.addMovie(batmanMovie);
 
-            /*
-            if (response.getStatus() != 200) {
+            if (moviesResponse.getStatus() != 201) {
+                System.out.println(moviesResponse.readEntity(String.class));
                 throw new RuntimeException("Failed : HTTP error code : "
-                        + response.getStatus());
+                        + moviesResponse.getStatus());
             }
 
-            System.out.println("Server response : \n");
-            System.out.println(response.readEntity(String.class));
+            moviesResponse.close();
 
-            response.close();
-*/
         } catch (Exception e) {
-
             e.printStackTrace();
-
         }
     }
 
diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json
new file mode 100644
index 0000000000..28061d5bf9
--- /dev/null
+++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json	
@@ -0,0 +1,22 @@
+{
+  "title": "Batman",
+  "year": "1989",
+  "rated": "PG-13",
+  "released": "23 Jun 1989",
+  "runtime": "126 min",
+  "genre": "Action, Adventure",
+  "director": "Tim Burton",
+  "writer": "Bob Kane (Batman characters), Sam Hamm (story), Sam Hamm (screenplay), Warren Skaaren (screenplay)",
+  "actors": "Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl",
+  "plot": "The Dark Knight of Gotham City begins his war on crime with his first major enemy being the clownishly homicidal Joker.",
+  "language": "English, French",
+  "country": "USA, UK",
+  "awards": "Won 1 Oscar. Another 9 wins & 22 nominations.",
+  "poster": "http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg",
+  "metascore": "66",
+  "imdbRating": "7.6",
+  "imdbVotes": "256,000",
+  "imdbID": "tt0096895",
+  "type": "movie",
+  "response": "True"
+}
\ No newline at end of file
diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json
similarity index 99%
rename from RestEasy Example/src/test/resources/server/movies/transformer.json
rename to RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json
index 2154868265..a3b033a8ba 100644
--- a/RestEasy Example/src/test/resources/server/movies/transformer.json	
+++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json	
@@ -17,6 +17,6 @@
   "imdbRating": "7.1",
   "imdbVotes": "492,225",
   "imdbID": "tt0418279",
-  "Type": "movie",
+  "type": "movie",
   "response": "True"
 }
\ No newline at end of file

From 453d9953858aa8ef9b5c0e54a3c7887e6fd36f9d Mon Sep 17 00:00:00 2001
From: amedviediev 
Date: Sat, 30 Jan 2016 23:05:06 +0200
Subject: [PATCH 159/309] - Updated source code for the article "Returning
 Custom Status Codes from Spring MVC Controllers" to be included in the
 spring-rest project

---
 spring-mvc-custom-status-codes/.gitignore     | 13 ------
 spring-mvc-custom-status-codes/pom.xml        | 44 -------------------
 .../CustomStatusCodesApplication.java         | 11 -----
 .../src/main/resources/application.properties |  0
 .../controller/status}/ExampleController.java |  2 +-
 .../status}/ForbiddenException.java           |  2 +-
 6 files changed, 2 insertions(+), 70 deletions(-)
 delete mode 100644 spring-mvc-custom-status-codes/.gitignore
 delete mode 100644 spring-mvc-custom-status-codes/pom.xml
 delete mode 100644 spring-mvc-custom-status-codes/src/main/java/com/baeldung/CustomStatusCodesApplication.java
 delete mode 100644 spring-mvc-custom-status-codes/src/main/resources/application.properties
 rename {spring-mvc-custom-status-codes/src/main/java/com/baeldung => spring-rest/src/main/java/org/baeldung/web/controller/status}/ExampleController.java (94%)
 rename {spring-mvc-custom-status-codes/src/main/java/com/baeldung => spring-rest/src/main/java/org/baeldung/web/controller/status}/ForbiddenException.java (85%)

diff --git a/spring-mvc-custom-status-codes/.gitignore b/spring-mvc-custom-status-codes/.gitignore
deleted file mode 100644
index 83c05e60c8..0000000000
--- a/spring-mvc-custom-status-codes/.gitignore
+++ /dev/null
@@ -1,13 +0,0 @@
-*.class
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-
-# Packaged files #
-*.jar
-*.war
-*.ear
\ No newline at end of file
diff --git a/spring-mvc-custom-status-codes/pom.xml b/spring-mvc-custom-status-codes/pom.xml
deleted file mode 100644
index 3fce332645..0000000000
--- a/spring-mvc-custom-status-codes/pom.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-
-
-	4.0.0
-
-	com.baeldung
-	custom-status-codes
-	0.0.1-SNAPSHOT
-	jar
-
-	spring-mvc-custom-status-codes
-	Returning Custom Status Codes from Spring MVC Controllers
-
-	
-		org.springframework.boot
-		spring-boot-starter-parent
-		1.3.2.RELEASE
-		 
-	
-
-	
-		UTF-8
-		1.8
-	
-
-	
-        
-            org.springframework.boot
-            spring-boot-starter-web
-            1.3.2.RELEASE
-        
-	
-	
-	
-		
-			
-				org.springframework.boot
-				spring-boot-maven-plugin
-			
-		
-	
-	
-
-
diff --git a/spring-mvc-custom-status-codes/src/main/java/com/baeldung/CustomStatusCodesApplication.java b/spring-mvc-custom-status-codes/src/main/java/com/baeldung/CustomStatusCodesApplication.java
deleted file mode 100644
index 2baf4b122f..0000000000
--- a/spring-mvc-custom-status-codes/src/main/java/com/baeldung/CustomStatusCodesApplication.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.baeldung;
-
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-
-@SpringBootApplication
-public class CustomStatusCodesApplication {
-	public static void main(String[] args) {
-		SpringApplication.run(CustomStatusCodesApplication.class, args);
-	}
-}
diff --git a/spring-mvc-custom-status-codes/src/main/resources/application.properties b/spring-mvc-custom-status-codes/src/main/resources/application.properties
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/spring-mvc-custom-status-codes/src/main/java/com/baeldung/ExampleController.java b/spring-rest/src/main/java/org/baeldung/web/controller/status/ExampleController.java
similarity index 94%
rename from spring-mvc-custom-status-codes/src/main/java/com/baeldung/ExampleController.java
rename to spring-rest/src/main/java/org/baeldung/web/controller/status/ExampleController.java
index 2d8f699776..ceda138768 100644
--- a/spring-mvc-custom-status-codes/src/main/java/com/baeldung/ExampleController.java
+++ b/spring-rest/src/main/java/org/baeldung/web/controller/status/ExampleController.java
@@ -1,4 +1,4 @@
-package com.baeldung;
+package org.baeldung.web.controller.status;
 
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
diff --git a/spring-mvc-custom-status-codes/src/main/java/com/baeldung/ForbiddenException.java b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java
similarity index 85%
rename from spring-mvc-custom-status-codes/src/main/java/com/baeldung/ForbiddenException.java
rename to spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java
index 858d428681..1d4aff2ebf 100644
--- a/spring-mvc-custom-status-codes/src/main/java/com/baeldung/ForbiddenException.java
+++ b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java
@@ -1,4 +1,4 @@
-package com.baeldung;
+package org.baeldung.web.controller.status;
 
 import org.springframework.http.HttpStatus;
 import org.springframework.web.bind.annotation.ResponseStatus;

From cc8d42c58bfa5dc671a9fb670cae5b196f9e2e53 Mon Sep 17 00:00:00 2001
From: David Morley 
Date: Sat, 30 Jan 2016 15:41:48 -0600
Subject: [PATCH 160/309] Clean up Spring Data Redis example

---
 .../main/java/org/baeldung/spring/data/redis/model/Student.java | 2 --
 1 file changed, 2 deletions(-)

diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/model/Student.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/model/Student.java
index 825248f183..acc96899ce 100644
--- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/model/Student.java
+++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/model/Student.java
@@ -4,8 +4,6 @@ import java.io.Serializable;
 
 public class Student implements Serializable {
 
-    private static final long serialVersionUID = -1907106213598514113L;
-
     public enum Gender {
         MALE, FEMALE
     }

From a2a026a503167a5e3a0fb2f3e8856686ce1428cc Mon Sep 17 00:00:00 2001
From: Giuseppe Bueti 
Date: Sun, 31 Jan 2016 11:05:11 +0100
Subject: [PATCH 161/309] Added testCase for all Services

---
 RestEasy Example/pom.xml                      |  15 --
 .../baeldung/client/ServicesInterface.java    |  10 +-
 .../com/baeldung/server/MovieCrudService.java |  15 +-
 .../src/main/webapp/WEB-INF/web.xml           |   2 +-
 .../com/baeldung/server/RestEasyClient.java   | 112 -----------
 .../baeldung/server/RestEasyClientTest.java   | 189 ++++++++++++++++++
 6 files changed, 206 insertions(+), 137 deletions(-)
 delete mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java
 create mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java

diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml
index 8dabfc863b..6935238d91 100644
--- a/RestEasy Example/pom.xml	
+++ b/RestEasy Example/pom.xml	
@@ -99,21 +99,6 @@
             2.4
         
 
-        
-            com.fasterxml.jackson.core
-            jackson-core
-            2.7.0
-        
-
-        
-            com.fasterxml.jackson.core
-            jackson-annotations
-            2.7.0
-        
-
-
-
-
     
 
 
diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java
index 2585c32438..7efed546d8 100644
--- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java	
+++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java	
@@ -17,6 +17,12 @@ public interface ServicesInterface {
     Movie movieByImdbID(@QueryParam("imdbID") String imdbID);
 
 
+    @GET
+    @Path("/listmovies")
+    @Produces({"application/json"})
+    List listMovies();
+
+
     @POST
     @Path("/addmovie")
     @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
@@ -34,9 +40,5 @@ public interface ServicesInterface {
     Response deleteMovie(@QueryParam("imdbID") String imdbID);
 
 
-    @GET
-    @Path("/listmovies")
-    @Produces({"application/json"})
-    List listMovies();
 
 }
diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java
index 60e0121966..18366e2faa 100644
--- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java	
+++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java	
@@ -18,18 +18,21 @@ public class MovieCrudService {
 
     private Map inventory = new HashMap();
 
+
     @GET
     @Path("/getinfo")
     @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
     public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){
 
-        System.out.println("*** Calling  getinfo ***");
+        System.out.println("*** Calling  getinfo for a given ImdbID***");
+
+        if(inventory.containsKey(imdbID)){
+            return inventory.get(imdbID);
+        }else return null;
 
-        Movie movie=new Movie();
-        movie.setImdbID(imdbID);
-        return movie;
     }
 
+
     @POST
     @Path("/addmovie")
     @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
@@ -41,6 +44,7 @@ public class MovieCrudService {
             return Response.status(Response.Status.NOT_MODIFIED)
                     .entity("Movie is Already in the database.").build();
         }
+
         inventory.put(movie.getImdbID(),movie);
 
         return Response.status(Response.Status.CREATED).build();
@@ -54,7 +58,7 @@ public class MovieCrudService {
 
         System.out.println("*** Calling  updateMovie ***");
 
-        if (null!=inventory.get(movie.getImdbID())){
+        if (null==inventory.get(movie.getImdbID())){
             return Response.status(Response.Status.NOT_MODIFIED)
                     .entity("Movie is not in the database.\nUnable to Update").build();
         }
@@ -79,6 +83,7 @@ public class MovieCrudService {
         return Response.status(Response.Status.OK).build();
     }
 
+
     @GET
     @Path("/listmovies")
     @Produces({"application/json"})
diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml
index c66d3b56ae..ab3bc1aa83 100644
--- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml	
+++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml	
@@ -33,7 +33,7 @@
         
         
             javax.ws.rs.Application
-            com.baeldung.server.service.RestEasyServices
+            com.baeldung.server.RestEasyServices
         
     
 
diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java
deleted file mode 100644
index c77f494862..0000000000
--- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java	
+++ /dev/null
@@ -1,112 +0,0 @@
-package com.baeldung.server;
-
-import com.baeldung.model.Movie;
-import com.baeldung.client.ServicesInterface;
-import org.apache.commons.io.IOUtils;
-import org.codehaus.jackson.map.DeserializationConfig;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.jboss.resteasy.client.jaxrs.ResteasyClient;
-import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
-import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import javax.naming.NamingException;
-import javax.ws.rs.core.Link;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileReader;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Locale;
-
-public class RestEasyClient {
-
-
-    Movie  transformerMovie=null;
-    Movie   batmanMovie=null;
-    ObjectMapper jsonMapper=null;
-
-    @BeforeClass
-    public static void loadMovieInventory(){
-
-
-
-    }
-
-    @Before
-    public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException {
-
-
-        jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-        jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
-        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
-        jsonMapper.setDateFormat(sdf);
-
-        try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) {
-            String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
-            transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class);
-        } catch (Exception e) {
-            e.printStackTrace();
-            throw new RuntimeException("Test is going to die ...", e);
-        }
-
-        try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) {
-            String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
-            batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class);
-
-        } catch (Exception e) {
-            e.printStackTrace();
-            throw new RuntimeException("Test is going to die ...", e);
-        }
-
-    }
-
-    @Test
-    public void testListAllMovies() {
-
-        try {
-            ResteasyClient client = new ResteasyClientBuilder().build();
-            ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest"));
-            ServicesInterface simple = target.proxy(ServicesInterface.class);
-
-            final List movies = simple.listMovies();
-            System.out.println(movies);
-
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
-
-
-    @Test
-    public void testAddMovie() {
-
-        try {
-            ResteasyClient client = new ResteasyClientBuilder().build();
-            ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest"));
-
-            ServicesInterface simple = target.proxy(ServicesInterface.class);
-            final Response moviesResponse = simple.addMovie(batmanMovie);
-
-            if (moviesResponse.getStatus() != 201) {
-                System.out.println(moviesResponse.readEntity(String.class));
-                throw new RuntimeException("Failed : HTTP error code : "
-                        + moviesResponse.getStatus());
-            }
-
-            moviesResponse.close();
-
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
-}
\ No newline at end of file
diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java
new file mode 100644
index 0000000000..fb4205bcd7
--- /dev/null
+++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java	
@@ -0,0 +1,189 @@
+package com.baeldung.server;
+
+import com.baeldung.model.Movie;
+import com.baeldung.client.ServicesInterface;
+import org.apache.commons.io.IOUtils;
+import org.codehaus.jackson.map.DeserializationConfig;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.jboss.resteasy.client.jaxrs.ResteasyClient;
+import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
+import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import javax.naming.NamingException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.text.SimpleDateFormat;
+import java.util.List;
+import java.util.Locale;
+
+public class RestEasyClientTest {
+
+
+    Movie  transformerMovie=null;
+    Movie   batmanMovie=null;
+    ObjectMapper jsonMapper=null;
+
+    @BeforeClass
+    public static void loadMovieInventory(){
+
+
+
+    }
+
+    @Before
+    public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException {
+
+
+        jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+        jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
+        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
+        jsonMapper.setDateFormat(sdf);
+
+        try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/transformer.json")) {
+            String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
+            transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class);
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new RuntimeException("Test is going to die ...", e);
+        }
+
+        try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/batman.json")) {
+            String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
+            batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new RuntimeException("Test is going to die ...", e);
+        }
+
+    }
+
+
+    @Test
+    public void testListAllMovies() {
+
+        try {
+            ResteasyClient client = new ResteasyClientBuilder().build();
+            ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest"));
+            ServicesInterface simple = target.proxy(ServicesInterface.class);
+
+            Response moviesResponse = simple.addMovie(transformerMovie);
+            moviesResponse.close();
+            moviesResponse = simple.addMovie(batmanMovie);
+            moviesResponse.close();
+
+            final List movies = simple.listMovies();
+            System.out.println(movies);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    @Test
+    public void testMovieByImdbID() {
+
+        String transformerImdbId="tt0418279";
+
+        try {
+            ResteasyClient client = new ResteasyClientBuilder().build();
+            ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest"));
+            ServicesInterface simple = target.proxy(ServicesInterface.class);
+
+            Response moviesResponse = simple.addMovie(transformerMovie);
+            moviesResponse.close();
+
+            final Movie movies = simple.movieByImdbID(transformerImdbId);
+            System.out.println(movies);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    @Test
+    public void testAddMovie() {
+
+        try {
+            ResteasyClient client = new ResteasyClientBuilder().build();
+            ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest"));
+            ServicesInterface simple = target.proxy(ServicesInterface.class);
+
+            Response moviesResponse = simple.addMovie(batmanMovie);
+            moviesResponse.close();
+            moviesResponse = simple.addMovie(transformerMovie);
+
+            if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
+                //System.out.println(moviesResponse.readEntity(String.class));
+                System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus());
+            }
+            moviesResponse.close();
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    @Test
+    public void testDeleteMovie() {
+
+        String transformerImdbId="tt0418279";
+
+        try {
+            ResteasyClient client = new ResteasyClientBuilder().build();
+            ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest"));
+            ServicesInterface simple = target.proxy(ServicesInterface.class);
+
+            Response moviesResponse = simple.addMovie(batmanMovie);
+            moviesResponse.close();
+            moviesResponse = simple.deleteMovie(transformerImdbId);
+            moviesResponse.close();
+
+            if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) {
+                System.out.println(moviesResponse.readEntity(String.class));
+                throw new RuntimeException("Failed : HTTP error code : "  + moviesResponse.getStatus());
+            }
+
+            moviesResponse.close();
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    @Test
+    public void testUpdateMovie() {
+
+        try {
+
+            ResteasyClient client = new ResteasyClientBuilder().build();
+            ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest"));
+            ServicesInterface simple = target.proxy(ServicesInterface.class);
+
+            Response moviesResponse = simple.addMovie(batmanMovie);
+            moviesResponse.close();
+            batmanMovie.setImdbVotes("300,000");
+            moviesResponse = simple.updateMovie(batmanMovie);
+
+            if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) {
+                //System.out.println(moviesResponse.readEntity(String.class));
+                System.out.println("Failed : HTTP error code : "  + moviesResponse.getStatus());
+            }
+
+            moviesResponse.close();
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+}
\ No newline at end of file

From e2527695e6f873a44d2b41c147e444fc60bfa7e3 Mon Sep 17 00:00:00 2001
From: DOHA 
Date: Sun, 31 Jan 2016 19:08:02 +0200
Subject: [PATCH 162/309] upgrade to tomcat 8.0.30

---
 spring-hibernate4/pom.xml                     |  2 +-
 .../baeldung/spring/PersistenceConfig.java    | 38 +++++++++----------
 2 files changed, 20 insertions(+), 20 deletions(-)

diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml
index 33eee53c78..652636b7cc 100644
--- a/spring-hibernate4/pom.xml
+++ b/spring-hibernate4/pom.xml
@@ -222,7 +222,7 @@
         4.3.11.Final
         ${hibernate.version}
         5.1.37
-        7.0.42
+        8.0.30
         1.1
         2.2.4
 
diff --git a/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java b/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java
index 05efc7a4ff..35e80b81a5 100644
--- a/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java
+++ b/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java
@@ -4,25 +4,7 @@ import java.util.Properties;
 
 import javax.sql.DataSource;
 
-import com.baeldung.persistence.dao.impl.BarDao;
-import com.baeldung.persistence.dao.impl.FooDao;
-import com.baeldung.persistence.service.IBarAuditableService;
-import com.baeldung.persistence.service.IFooAuditableService;
-import com.baeldung.persistence.service.IFooService;
-import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
-import com.baeldung.persistence.dao.IBarAuditableDao;
-import com.baeldung.persistence.dao.IBarDao;
-import com.baeldung.persistence.dao.IFooAuditableDao;
-import com.baeldung.persistence.dao.IFooDao;
-import com.baeldung.persistence.dao.impl.BarAuditableDao;
-import com.baeldung.persistence.dao.impl.BarJpaDao;
-import com.baeldung.persistence.dao.impl.FooAuditableDao;
-import com.baeldung.persistence.service.IBarService;
-import com.baeldung.persistence.service.impl.BarAuditableService;
-import com.baeldung.persistence.service.impl.BarJpaService;
-import com.baeldung.persistence.service.impl.BarSpringDataJpaService;
-import com.baeldung.persistence.service.impl.FooAuditableService;
-import com.baeldung.persistence.service.impl.FooService;
+import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
@@ -41,6 +23,24 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
 import org.springframework.transaction.PlatformTransactionManager;
 import org.springframework.transaction.annotation.EnableTransactionManagement;
 
+import com.baeldung.persistence.dao.IBarAuditableDao;
+import com.baeldung.persistence.dao.IBarDao;
+import com.baeldung.persistence.dao.IFooAuditableDao;
+import com.baeldung.persistence.dao.IFooDao;
+import com.baeldung.persistence.dao.impl.BarAuditableDao;
+import com.baeldung.persistence.dao.impl.BarDao;
+import com.baeldung.persistence.dao.impl.BarJpaDao;
+import com.baeldung.persistence.dao.impl.FooAuditableDao;
+import com.baeldung.persistence.dao.impl.FooDao;
+import com.baeldung.persistence.service.IBarAuditableService;
+import com.baeldung.persistence.service.IBarService;
+import com.baeldung.persistence.service.IFooAuditableService;
+import com.baeldung.persistence.service.IFooService;
+import com.baeldung.persistence.service.impl.BarAuditableService;
+import com.baeldung.persistence.service.impl.BarJpaService;
+import com.baeldung.persistence.service.impl.BarSpringDataJpaService;
+import com.baeldung.persistence.service.impl.FooAuditableService;
+import com.baeldung.persistence.service.impl.FooService;
 import com.google.common.base.Preconditions;
 
 @Configuration

From e6cc0bb7225757ae91994e0549589bc47077d658 Mon Sep 17 00:00:00 2001
From: DOHA 
Date: Sun, 31 Jan 2016 19:36:30 +0200
Subject: [PATCH 163/309] upgrade to tomcat8

---
 spring-hibernate4/src/main/resources/hibernate4Config.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/spring-hibernate4/src/main/resources/hibernate4Config.xml b/spring-hibernate4/src/main/resources/hibernate4Config.xml
index 661cc942d8..ca507802cd 100644
--- a/spring-hibernate4/src/main/resources/hibernate4Config.xml
+++ b/spring-hibernate4/src/main/resources/hibernate4Config.xml
@@ -18,7 +18,7 @@
         
     
 
-    
+    
         
         
         

From ddec979e4d0383161654b79fce48b88f59286735 Mon Sep 17 00:00:00 2001
From: David Morley 
Date: Mon, 1 Feb 2016 05:51:27 -0600
Subject: [PATCH 164/309] Update Spring Data Redis example to use constructor
 injection

---
 .../data/redis/repo/StudentRepository.java    |  3 ++-
 .../redis/repo/StudentRepositoryImpl.java     | 24 ++++++++++++++-----
 2 files changed, 20 insertions(+), 7 deletions(-)

diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java
index 6a909ed137..9e5502f8e0 100644
--- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java
+++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java
@@ -1,12 +1,13 @@
 package org.baeldung.spring.data.redis.repo;
 
 import org.baeldung.spring.data.redis.model.Student;
+import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Component;
 
 import java.util.Map;
 
 public interface StudentRepository {
-    
+
     void saveStudent(Student person);
     
     void updateStudent(Student student);
diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java
index 55e6ad5edc..43294cae58 100644
--- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java
+++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java
@@ -2,9 +2,11 @@ package org.baeldung.spring.data.redis.repo;
 
 import org.baeldung.spring.data.redis.model.Student;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.HashOperations;
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Repository;
 
+import javax.annotation.PostConstruct;
 import java.util.Map;
 
 @Repository
@@ -12,26 +14,36 @@ public class StudentRepositoryImpl implements StudentRepository {
 
     private static final String KEY = "Student";
 
-    @Autowired
     private RedisTemplate redisTemplate;
+    private HashOperations hashOperations;
+
+    @Autowired
+    public StudentRepositoryImpl(RedisTemplate redisTemplate) {
+        this.redisTemplate = redisTemplate;
+    }
+
+    @PostConstruct
+    private void init() {
+        hashOperations = redisTemplate.opsForHash();
+    }
 
     public void saveStudent(final Student student) {
-        redisTemplate.opsForHash().put(KEY, student.getId(), student);
+        hashOperations.put(KEY, student.getId(), student);
     }
 
     public void updateStudent(final Student student) {
-        redisTemplate.opsForHash().put(KEY, student.getId(), student);
+        hashOperations.put(KEY, student.getId(), student);
     }
 
     public Student findStudent(final String id) {
-        return (Student) redisTemplate.opsForHash().get(KEY, id);
+        return (Student) hashOperations.get(KEY, id);
     }
 
     public Map findAllStudents() {
-        return redisTemplate.opsForHash().entries(KEY);
+        return hashOperations.entries(KEY);
     }
 
     public void deleteStudent(final String id) {
-        this.redisTemplate.opsForHash().delete(KEY, id);
+        hashOperations.delete(KEY, id);
     }
 }

From 2fff2739690a712e5d87263c3f1c1c192f51ae9f Mon Sep 17 00:00:00 2001
From: oborkovskyi 
Date: Mon, 1 Feb 2016 16:12:47 +0200
Subject: [PATCH 165/309] Added guava19 test project

---
 guava19/pom.xml                               | 46 +++++++++
 .../java/com/baeldung/guava/entity/User.java  | 36 +++++++
 .../com/baeldung/guava/CharMatcherTest.java   | 33 +++++++
 .../baeldung/guava/GuavaMiscUtilsTest.java    | 95 +++++++++++++++++++
 .../java/com/baeldung/guava/HashingTest.java  | 34 +++++++
 .../com/baeldung/guava/TypeTokenTest.java     | 45 +++++++++
 6 files changed, 289 insertions(+)
 create mode 100644 guava19/pom.xml
 create mode 100644 guava19/src/main/java/com/baeldung/guava/entity/User.java
 create mode 100644 guava19/src/test/java/com/baeldung/guava/CharMatcherTest.java
 create mode 100644 guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java
 create mode 100644 guava19/src/test/java/com/baeldung/guava/HashingTest.java
 create mode 100644 guava19/src/test/java/com/baeldung/guava/TypeTokenTest.java

diff --git a/guava19/pom.xml b/guava19/pom.xml
new file mode 100644
index 0000000000..97c1b0ea4e
--- /dev/null
+++ b/guava19/pom.xml
@@ -0,0 +1,46 @@
+
+
+    4.0.0
+
+    com.baeldung
+    guava
+    1.0-SNAPSHOT
+
+    
+        
+            com.google.guava
+            guava
+            19.0
+        
+        
+            junit
+            junit
+            4.12
+        
+        
+            org.hamcrest
+            hamcrest-all
+            1.3
+        
+    
+    
+        
+            
+                maven-compiler-plugin
+                3.3
+                
+                    true
+                    true
+                    1.8
+                    1.8
+                    UTF-8
+                    true
+                    true
+                
+            
+        
+    
+
+
\ No newline at end of file
diff --git a/guava19/src/main/java/com/baeldung/guava/entity/User.java b/guava19/src/main/java/com/baeldung/guava/entity/User.java
new file mode 100644
index 0000000000..be673edb10
--- /dev/null
+++ b/guava19/src/main/java/com/baeldung/guava/entity/User.java
@@ -0,0 +1,36 @@
+package com.baeldung.guava.entity;
+
+import com.google.common.base.MoreObjects;
+
+public class User{
+    private long id;
+    private String name;
+    private int age;
+
+    public User(long id, String name, int age) {
+        this.id = id;
+        this.name = name;
+        this.age = age;
+    }
+
+    public long getId() {
+        return id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public int getAge() {
+        return age;
+    }
+
+    @Override
+    public String toString() {
+        return MoreObjects.toStringHelper(User.class)
+                .add("id", id)
+                .add("name", name)
+                .add("age", age)
+                .toString();
+    }
+}
\ No newline at end of file
diff --git a/guava19/src/test/java/com/baeldung/guava/CharMatcherTest.java b/guava19/src/test/java/com/baeldung/guava/CharMatcherTest.java
new file mode 100644
index 0000000000..f890d9abc1
--- /dev/null
+++ b/guava19/src/test/java/com/baeldung/guava/CharMatcherTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.guava;
+
+import com.google.common.base.CharMatcher;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class CharMatcherTest {
+    @Test
+    public void whenMatchingLetterOrString_ShouldReturnTrueForCorrectString() throws Exception {
+        String inputString = "someString789";
+        boolean result = CharMatcher.javaLetterOrDigit().matchesAllOf(inputString);
+
+        assertTrue(result);
+    }
+
+    @Test
+    public void whenCollapsingString_ShouldReturnStringWithDashesInsteadOfWhitespaces() throws Exception {
+        String inputPhoneNumber = "8 123 456 123";
+        String result = CharMatcher.whitespace().collapseFrom(inputPhoneNumber, '-');
+
+        assertEquals("8-123-456-123", result);
+    }
+
+    @Test
+    public void whenCountingDigitsInString_ShouldReturnActualCountOfDigits() throws Exception {
+        String inputPhoneNumber = "8 123 456 123";
+        int result = CharMatcher.digit().countIn(inputPhoneNumber);
+
+        assertEquals(10, result);
+    }
+}
diff --git a/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java
new file mode 100644
index 0000000000..4569019e60
--- /dev/null
+++ b/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java
@@ -0,0 +1,95 @@
+package com.baeldung.guava;
+
+import com.baeldung.guava.entity.User;
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Throwables;
+import com.google.common.collect.*;
+import com.google.common.hash.HashCode;
+import com.google.common.hash.HashFunction;
+import com.google.common.hash.Hashing;
+import com.google.common.reflect.TypeToken;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
+import static org.hamcrest.core.AnyOf.anyOf;
+import static org.junit.Assert.*;
+
+public class GuavaMiscUtilsTest {
+
+    @Test
+    public void whenGettingLazyStackTrace_ListShouldBeReturned() throws Exception {
+        IllegalArgumentException e = new IllegalArgumentException("Some argument is incorrect");
+
+        List stackTraceElements = Throwables.lazyStackTrace(e);
+
+        assertEquals(27, stackTraceElements.size());
+    }
+
+    @Test
+    public void multisetShouldCountHitsOfMultipleDuplicateObjects() throws Exception {
+        List userNames = Arrays.asList("David", "Eugene", "Alex", "Alex", "David", "David", "David");
+
+        Multiset userNamesMultiset = HashMultiset.create(userNames);
+
+        assertEquals(7, userNamesMultiset.size());
+        assertEquals(4, userNamesMultiset.count("David"));
+        assertEquals(2, userNamesMultiset.count("Alex"));
+        assertEquals(1, userNamesMultiset.count("Eugene"));
+        assertThat(userNamesMultiset.elementSet(), anyOf(containsInAnyOrder("Alex", "David", "Eugene")));
+    }
+
+    @Test
+    public void whenAddingNewConnectedRange_RangesShouldBeMerged() throws Exception {
+        RangeSet rangeSet = TreeRangeSet.create();
+
+        rangeSet.add(Range.closed(1, 10));
+        rangeSet.add(Range.closed(5, 15));
+        rangeSet.add(Range.closedOpen(10, 17));
+
+        assertTrue(rangeSet.encloses(Range.closedOpen(1, 17)));
+        assertTrue(rangeSet.encloses(Range.closed(2, 3)));
+        assertTrue(rangeSet.contains(15));
+        assertFalse(rangeSet.contains(17));
+        assertEquals(1, rangeSet.asDescendingSetOfRanges().size());
+    }
+
+    @Test
+    public void cartesianProductShouldReturnAllPossibleCombinations() throws Exception {
+        List first = Lists.newArrayList("value1", "value2");
+        List second = Lists.newArrayList("value3", "value4");
+
+        List> cartesianProduct = Lists.cartesianProduct(first, second);
+
+        List pair1 = Lists.newArrayList("value2", "value3");
+        List pair2 = Lists.newArrayList("value2", "value4");
+        List pair3 = Lists.newArrayList("value1", "value3");
+        List pair4 = Lists.newArrayList("value1", "value4");
+
+        assertThat(cartesianProduct, anyOf(containsInAnyOrder(pair1, pair2, pair3, pair4)));
+    }
+
+    @Test
+    public void multisetShouldRemoveOccurrencesOfSpecifiedObjects() throws Exception {
+        Multiset multisetToModify = HashMultiset.create();
+        Multiset occurrencesToRemove = HashMultiset.create();
+
+        multisetToModify.add("John");
+        multisetToModify.add("Max");
+        multisetToModify.add("Alex");
+
+        occurrencesToRemove.add("Alex");
+        occurrencesToRemove.add("John");
+
+        Multisets.removeOccurrences(multisetToModify, occurrencesToRemove);
+
+        assertEquals(1, multisetToModify.size());
+        assertTrue(multisetToModify.contains("Max"));
+        assertFalse(multisetToModify.contains("John"));
+        assertFalse(multisetToModify.contains("Alex"));
+    }
+}
\ No newline at end of file
diff --git a/guava19/src/test/java/com/baeldung/guava/HashingTest.java b/guava19/src/test/java/com/baeldung/guava/HashingTest.java
new file mode 100644
index 0000000000..9b4acde9f7
--- /dev/null
+++ b/guava19/src/test/java/com/baeldung/guava/HashingTest.java
@@ -0,0 +1,34 @@
+package com.baeldung.guava;
+
+import com.google.common.hash.HashCode;
+import com.google.common.hash.HashFunction;
+import com.google.common.hash.Hashing;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class HashingTest {
+    @Test
+    public void whenHashingInSha384_hashFunctionShouldBeReturned() throws Exception {
+        int inputData = 15;
+
+        HashFunction hashFunction = Hashing.sha384();
+        HashCode hashCode = hashFunction.hashInt(inputData);
+
+        assertEquals("0904b6277381dcfbdddd6b6c66e4e3e8f83d4690718d8e6f272c891f24773a12feaf8c449fa6e42240a621b2b5e3cda8",
+                hashCode.toString());
+    }
+
+    @Test
+    public void whenConcatenatingHashFunction_concatenatedHashShouldBeReturned() throws Exception {
+        int inputData = 15;
+
+        HashFunction hashFunction = Hashing.concatenating(Hashing.crc32(), Hashing.crc32());
+        HashFunction crc32Function = Hashing.crc32();
+
+        HashCode hashCode = hashFunction.hashInt(inputData);
+        HashCode crc32HashCode = crc32Function.hashInt(inputData);
+
+        assertEquals(crc32HashCode.toString() + crc32HashCode.toString(), hashCode.toString());
+    }
+}
diff --git a/guava19/src/test/java/com/baeldung/guava/TypeTokenTest.java b/guava19/src/test/java/com/baeldung/guava/TypeTokenTest.java
new file mode 100644
index 0000000000..1923451f20
--- /dev/null
+++ b/guava19/src/test/java/com/baeldung/guava/TypeTokenTest.java
@@ -0,0 +1,45 @@
+package com.baeldung.guava;
+
+import com.google.common.reflect.TypeToken;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class TypeTokenTest {
+    @Test
+    public void whenCheckingIsAssignableFrom_shouldReturnTrueEvenIfGenericIsSpecified() throws Exception {
+        ArrayList stringList = new ArrayList<>();
+        ArrayList intList = new ArrayList<>();
+        boolean isAssignableFrom = stringList.getClass().isAssignableFrom(intList.getClass());
+
+        assertTrue(isAssignableFrom);
+    }
+
+    @Test
+    public void whenCheckingIsSupertypeOf_shouldReturnFalseIfGenericIsSpecified() throws Exception {
+        TypeToken> listString = new TypeToken>() {
+        };
+        TypeToken> integerString = new TypeToken>() {
+        };
+
+        boolean isSupertypeOf = listString.isSupertypeOf(integerString);
+
+        assertFalse(isSupertypeOf);
+    }
+
+    @Test
+    public void whenCheckingIsSubtypeOf_shouldReturnTrueIfClassIsExtendedFrom() throws Exception {
+        TypeToken> stringList = new TypeToken>() {
+        };
+        TypeToken list = new TypeToken() {
+        };
+
+        boolean isSubtypeOf = stringList.isSubtypeOf(list);
+
+        assertTrue(isSubtypeOf);
+    }
+}

From de3b09bfd1d72942b333b73c4ff735d5fcf17f04 Mon Sep 17 00:00:00 2001
From: amedviediev 
Date: Mon, 1 Feb 2016 20:38:01 +0200
Subject: [PATCH 166/309] - Added test code for the article "Returning Custom
 Status Codes from Spring MVC Controllers"

---
 .../status/ExampleControllerTest.java         | 43 +++++++++++++++++++
 1 file changed, 43 insertions(+)
 create mode 100644 spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java

diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java
new file mode 100644
index 0000000000..8d4f583a08
--- /dev/null
+++ b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java
@@ -0,0 +1,43 @@
+package com.baeldung;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.SpringApplicationConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.web.WebAppConfiguration;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = WebConfig.class)
+@WebAppConfiguration
+public class ExampleControllerTest {
+
+    private MockMvc mockMvc;
+
+    @Autowired
+    private WebApplicationContext webApplicationContext;
+
+    @Before
+    public void setUp() {
+        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
+    }
+
+    @Test
+    public void whenGetRequestSentToController_thenReturnsStatusNotAcceptable() throws Exception {
+        mockMvc.perform(get("/controller"))
+            .andExpect(status().isNotAcceptable());
+    }
+
+    @Test
+    public void whenGetRequestSentToException_thenReturnsStatusForbidden() throws Exception {
+        mockMvc.perform(get("/exception"))
+                .andExpect(status().isForbidden());
+    }
+}

From 6a203ae91bcad889998d2ff579b74eefbec90ad9 Mon Sep 17 00:00:00 2001
From: Ivan 
Date: Tue, 2 Feb 2016 17:37:39 +0100
Subject: [PATCH 167/309] Add multiple ViewResolver configuration example

---
 .../baeldung/spring/web/config/WebConfig.java | 49 +++++++++++++++++--
 .../src/main/resources/views.properties       |  3 ++
 spring-mvc-java/src/main/resources/views.xml  | 10 ++++
 3 files changed, 58 insertions(+), 4 deletions(-)
 create mode 100644 spring-mvc-java/src/main/resources/views.properties
 create mode 100644 spring-mvc-java/src/main/resources/views.xml

diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java
index d60bcfe127..58438d2976 100644
--- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java
+++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java
@@ -1,19 +1,60 @@
 package org.baeldung.spring.web.config;
 
+import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Configuration;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.web.servlet.ViewResolver;
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
+import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
+import org.springframework.web.servlet.view.InternalResourceViewResolver;
+import org.springframework.web.servlet.view.JstlView;
+import org.springframework.web.servlet.view.ResourceBundleViewResolver;
+import org.springframework.web.servlet.view.XmlViewResolver;
 
 @Configuration
 @EnableWebMvc
 @ComponentScan("org.baeldung.web")
 public class WebConfig extends WebMvcConfigurerAdapter {
 
-    public WebConfig() {
-        super();
-    }
+	public WebConfig() {
+		super();
+	}
 
-    // API
+	@Override
+	public void addViewControllers(final ViewControllerRegistry registry) {
 
+		super.addViewControllers(registry);
+		registry.addViewController("/sample.html");
+	}
+
+	@Bean
+	public ViewResolver internalResourceViewResolver() {
+
+		final InternalResourceViewResolver bean = new InternalResourceViewResolver();
+		bean.setViewClass(JstlView.class);
+		bean.setPrefix("/WEB-INF/view/");
+		bean.setSuffix(".jsp");
+		bean.setOrder(2);
+		return bean;
+	}
+
+	@Bean
+	public ViewResolver xmlViewResolver() {
+
+		final XmlViewResolver bean = new XmlViewResolver();
+		bean.setLocation(new ClassPathResource("views.xml"));
+		bean.setOrder(1);
+		return bean;
+	}
+
+	@Bean
+	public ViewResolver resourceBundleViewResolver() {
+
+		final ResourceBundleViewResolver bean = new ResourceBundleViewResolver();
+		bean.setBasename("views");
+		bean.setOrder(0);
+		return bean;
+	}
 }
\ No newline at end of file
diff --git a/spring-mvc-java/src/main/resources/views.properties b/spring-mvc-java/src/main/resources/views.properties
new file mode 100644
index 0000000000..95687cb62a
--- /dev/null
+++ b/spring-mvc-java/src/main/resources/views.properties
@@ -0,0 +1,3 @@
+sample.(class)=org.springframework.web.servlet.view.JstlView
+sample.url=/WEB-INF/view/sample.jsp
+
diff --git a/spring-mvc-java/src/main/resources/views.xml b/spring-mvc-java/src/main/resources/views.xml
new file mode 100644
index 0000000000..83bca5293d
--- /dev/null
+++ b/spring-mvc-java/src/main/resources/views.xml
@@ -0,0 +1,10 @@
+
+ 
+    
+        
+    
+    
+
\ No newline at end of file

From dfc96b2dd101a98d214e9b289f05b6a0cc885d25 Mon Sep 17 00:00:00 2001
From: amedviediev 
Date: Tue, 2 Feb 2016 20:15:51 +0200
Subject: [PATCH 168/309] - Fixed tests

---
 spring-rest/pom.xml                                          | 4 ----
 .../web/controller/status/ExampleControllerTest.java         | 5 +++--
 2 files changed, 3 insertions(+), 6 deletions(-)

diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml
index e2cf9d7c3e..54ac868b95 100644
--- a/spring-rest/pom.xml
+++ b/spring-rest/pom.xml
@@ -33,7 +33,6 @@
         
             org.springframework
             spring-web
-            ${org.springframework.version}
             
                 
                     commons-logging
@@ -44,12 +43,10 @@
         
             org.springframework
             spring-webmvc
-            ${org.springframework.version}
         
         
             org.springframework
             spring-oxm
-            ${org.springframework.version}
         
 
         
@@ -229,7 +226,6 @@
 
     
         
-        4.2.4.RELEASE
         4.0.3.RELEASE
 
         
diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java
index 8d4f583a08..1344d2d40e 100644
--- a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java
+++ b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java
@@ -1,13 +1,14 @@
-package com.baeldung;
+package org.baeldung.web.controller.status;
 
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
+import org.baeldung.config.WebConfig;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.SpringApplicationConfiguration;
+import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 import org.springframework.test.context.web.WebAppConfiguration;
 import org.springframework.test.web.servlet.MockMvc;

From dffa1d2504053dccf48d5effe7ff60aa806f35ce Mon Sep 17 00:00:00 2001
From: eugenp 
Date: Wed, 3 Feb 2016 19:28:48 +0200
Subject: [PATCH 169/309] minor cleanup work

---
 .../converter/UserWriterConverter.java        |  2 +
 .../baeldung/spring/web/config/WebConfig.java | 65 +++++++++----------
 2 files changed, 34 insertions(+), 33 deletions(-)

diff --git a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java b/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java
index 54fa78e2d0..2dedda46ec 100644
--- a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java
+++ b/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java
@@ -9,6 +9,7 @@ import com.mongodb.DBObject;
 
 @Component
 public class UserWriterConverter implements Converter {
+
     @Override
     public DBObject convert(final User user) {
         final DBObject dbObject = new BasicDBObject();
@@ -22,4 +23,5 @@ public class UserWriterConverter implements Converter {
         dbObject.removeField("_class");
         return dbObject;
     }
+
 }
diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java
index 58438d2976..09e9cff917 100644
--- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java
+++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java
@@ -18,43 +18,42 @@ import org.springframework.web.servlet.view.XmlViewResolver;
 @ComponentScan("org.baeldung.web")
 public class WebConfig extends WebMvcConfigurerAdapter {
 
-	public WebConfig() {
-		super();
-	}
+    public WebConfig() {
+        super();
+    }
 
-	@Override
-	public void addViewControllers(final ViewControllerRegistry registry) {
+    //
 
-		super.addViewControllers(registry);
-		registry.addViewController("/sample.html");
-	}
+    @Override
+    public void addViewControllers(final ViewControllerRegistry registry) {
+        super.addViewControllers(registry);
+        registry.addViewController("/sample.html");
+    }
 
-	@Bean
-	public ViewResolver internalResourceViewResolver() {
+    @Bean
+    public ViewResolver internalResourceViewResolver() {
+        final InternalResourceViewResolver bean = new InternalResourceViewResolver();
+        bean.setViewClass(JstlView.class);
+        bean.setPrefix("/WEB-INF/view/");
+        bean.setSuffix(".jsp");
+        bean.setOrder(2);
+        return bean;
+    }
 
-		final InternalResourceViewResolver bean = new InternalResourceViewResolver();
-		bean.setViewClass(JstlView.class);
-		bean.setPrefix("/WEB-INF/view/");
-		bean.setSuffix(".jsp");
-		bean.setOrder(2);
-		return bean;
-	}
+    @Bean
+    public ViewResolver xmlViewResolver() {
+        final XmlViewResolver bean = new XmlViewResolver();
+        bean.setLocation(new ClassPathResource("views.xml"));
+        bean.setOrder(1);
+        return bean;
+    }
 
-	@Bean
-	public ViewResolver xmlViewResolver() {
+    @Bean
+    public ViewResolver resourceBundleViewResolver() {
+        final ResourceBundleViewResolver bean = new ResourceBundleViewResolver();
+        bean.setBasename("views");
+        bean.setOrder(0);
+        return bean;
+    }
 
-		final XmlViewResolver bean = new XmlViewResolver();
-		bean.setLocation(new ClassPathResource("views.xml"));
-		bean.setOrder(1);
-		return bean;
-	}
-
-	@Bean
-	public ViewResolver resourceBundleViewResolver() {
-
-		final ResourceBundleViewResolver bean = new ResourceBundleViewResolver();
-		bean.setBasename("views");
-		bean.setOrder(0);
-		return bean;
-	}
 }
\ No newline at end of file

From 032be8319e108f95f0d87d9f020a9f021186ef93 Mon Sep 17 00:00:00 2001
From: Dmitry Zinkevich 
Date: Thu, 14 Jan 2016 08:42:10 +0300
Subject: [PATCH 170/309] Add Elasticsearch Spring Data test cases

---
 spring-data-elasticsearch/.classpath          |  31 +++++
 spring-data-elasticsearch/.project            |  29 ++++
 spring-data-elasticsearch/README.md           |  12 ++
 spring-data-elasticsearch/pom.xml             |  78 +++++++++++
 .../main/java/com/baeldung/config/Config.java |  53 +++++++
 .../com/baeldung/dao/ArticleRepository.java   |  16 +++
 .../main/java/com/baeldung/model/Article.java |  60 ++++++++
 .../main/java/com/baeldung/model/Author.java  |  28 ++++
 .../com/baeldung/service/ArticleService.java  |  15 ++
 .../baeldung/service/ArticleServiceImpl.java  |  54 ++++++++
 .../src/main/resources/logback.xml            |  20 +++
 .../java/com/baeldung/ElasticSearchTest.java  | 130 ++++++++++++++++++
 12 files changed, 526 insertions(+)
 create mode 100644 spring-data-elasticsearch/.classpath
 create mode 100644 spring-data-elasticsearch/.project
 create mode 100644 spring-data-elasticsearch/README.md
 create mode 100644 spring-data-elasticsearch/pom.xml
 create mode 100644 spring-data-elasticsearch/src/main/java/com/baeldung/config/Config.java
 create mode 100644 spring-data-elasticsearch/src/main/java/com/baeldung/dao/ArticleRepository.java
 create mode 100644 spring-data-elasticsearch/src/main/java/com/baeldung/model/Article.java
 create mode 100644 spring-data-elasticsearch/src/main/java/com/baeldung/model/Author.java
 create mode 100644 spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleService.java
 create mode 100644 spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleServiceImpl.java
 create mode 100644 spring-data-elasticsearch/src/main/resources/logback.xml
 create mode 100644 spring-data-elasticsearch/src/test/java/com/baeldung/ElasticSearchTest.java

diff --git a/spring-data-elasticsearch/.classpath b/spring-data-elasticsearch/.classpath
new file mode 100644
index 0000000000..698778fef3
--- /dev/null
+++ b/spring-data-elasticsearch/.classpath
@@ -0,0 +1,31 @@
+
+
+	
+		
+			
+			
+		
+	
+	
+		
+			
+		
+	
+	
+		
+			
+			
+		
+	
+	
+		
+			
+		
+	
+	
+		
+			
+		
+	
+	
+
diff --git a/spring-data-elasticsearch/.project b/spring-data-elasticsearch/.project
new file mode 100644
index 0000000000..09b9a781ed
--- /dev/null
+++ b/spring-data-elasticsearch/.project
@@ -0,0 +1,29 @@
+
+
+	spring-data-elasticsearch
+	
+	
+	
+	
+		
+			org.eclipse.jdt.core.javabuilder
+			
+			
+		
+		
+			org.eclipse.m2e.core.maven2Builder
+			
+			
+		
+		
+			org.springframework.ide.eclipse.core.springbuilder
+			
+			
+		
+	
+	
+		org.springframework.ide.eclipse.core.springnature
+		org.eclipse.jdt.core.javanature
+		org.eclipse.m2e.core.maven2Nature
+	
+
diff --git a/spring-data-elasticsearch/README.md b/spring-data-elasticsearch/README.md
new file mode 100644
index 0000000000..0dae92e0e7
--- /dev/null
+++ b/spring-data-elasticsearch/README.md
@@ -0,0 +1,12 @@
+## Spring Data Elasticsearch
+
+### Build the Project with Tests Running
+```
+mvn clean install
+```
+
+### Run Tests Directly
+```
+mvn test
+```
+
diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml
new file mode 100644
index 0000000000..7ac6dd0fcf
--- /dev/null
+++ b/spring-data-elasticsearch/pom.xml
@@ -0,0 +1,78 @@
+
+	4.0.0
+
+	org.baeldung
+	spring-data-elasticsearch
+	0.0.1-SNAPSHOT
+	jar
+
+	spring-data-elasticsearch
+
+	
+		UTF-8
+		1.3.2.RELEASE
+		4.2.2.RELEASE
+		4.11
+		1.7.12
+		1.1.3
+		1.3.2.RELEASE
+	
+
+	
+		
+			org.springframework
+			spring-core
+			${org.springframework.version}
+		
+		
+			junit
+			junit-dep
+			${junit.version}
+			test
+		
+		
+			org.springframework
+			spring-test
+			${org.springframework.version}
+			test
+		
+		
+			org.springframework.data
+			spring-data-elasticsearch
+			${elasticsearch.version}
+		
+		
+			org.slf4j
+			slf4j-api
+			${org.slf4j.version}
+		
+		
+			ch.qos.logback
+			logback-classic
+			${logback.version}
+		
+		
+			org.slf4j
+			jcl-over-slf4j
+			${org.slf4j.version}
+		
+		
+			org.slf4j
+			log4j-over-slf4j
+			${org.slf4j.version}
+		
+	
+	
+		
+			
+				maven-compiler-plugin
+				2.3.2
+				
+					1.8
+					1.8
+				
+			
+		
+	
+
diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/config/Config.java b/spring-data-elasticsearch/src/main/java/com/baeldung/config/Config.java
new file mode 100644
index 0000000000..eb65e38f65
--- /dev/null
+++ b/spring-data-elasticsearch/src/main/java/com/baeldung/config/Config.java
@@ -0,0 +1,53 @@
+package com.baeldung.config;
+
+import org.elasticsearch.common.settings.ImmutableSettings;
+import org.elasticsearch.node.NodeBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
+import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
+import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+@Configuration
+@EnableElasticsearchRepositories(basePackages = "com.baeldung.dao")
+@ComponentScan(basePackages = {"com.baeldung.service"})
+public class Config {
+
+    private static Logger logger = LoggerFactory.getLogger(Config.class);
+
+    @Bean
+    public NodeBuilder nodeBuilder() {
+        return new NodeBuilder();
+    }
+
+    @Bean
+    public ElasticsearchOperations elasticsearchTemplate() {
+
+        try {
+            Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data");
+
+            ImmutableSettings.Builder elasticsearchSettings = ImmutableSettings.settingsBuilder()
+                    .put("http.enabled", "false")
+                    .put("path.data", tmpDir.toAbsolutePath().toString());
+
+            logger.debug(tmpDir.toAbsolutePath().toString());
+
+            return new ElasticsearchTemplate(nodeBuilder()
+                    .local(true)
+                    .settings(elasticsearchSettings.build())
+                    .node()
+                    .client());
+        } catch (IOException ioex) {
+            logger.error("Cannot create temp dir", ioex);
+            throw new RuntimeException();
+        }
+    }
+}
diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/dao/ArticleRepository.java b/spring-data-elasticsearch/src/main/java/com/baeldung/dao/ArticleRepository.java
new file mode 100644
index 0000000000..6ed86eff9b
--- /dev/null
+++ b/spring-data-elasticsearch/src/main/java/com/baeldung/dao/ArticleRepository.java
@@ -0,0 +1,16 @@
+package com.baeldung.dao;
+
+import com.baeldung.model.Article;
+import com.baeldung.model.Article;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.elasticsearch.annotations.Query;
+import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
+
+public interface ArticleRepository extends ElasticsearchRepository {
+
+    Page
findByAuthorsName(String name, Pageable pageable); + + @Query("{\"bool\": {\"must\": [{\"match\": {\"authors.name\": \"?0\"}}]}}") + Page
findByAuthorsNameUsingCustomQuery(String name, Pageable pageable); +} diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/model/Article.java b/spring-data-elasticsearch/src/main/java/com/baeldung/model/Article.java new file mode 100644 index 0000000000..17580ca0db --- /dev/null +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/model/Article.java @@ -0,0 +1,60 @@ +package com.baeldung.model; + +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.FieldIndex; +import org.springframework.data.elasticsearch.annotations.FieldType; + +import java.util.List; + +@Document(indexName = "article", type = "article") +public class Article { + + @Id + private String id; + @Field(type = FieldType.String, index = FieldIndex.not_analyzed) + private String title; + @Field(type = FieldType.Nested) + private List authors; + + public Article() { + } + + public Article(String title) { + this.title = title; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + @Override + public String toString() { + return "Article{" + + "id='" + id + '\'' + + ", title='" + title + '\'' + + ", authors=" + authors + + '}'; + } +} diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/model/Author.java b/spring-data-elasticsearch/src/main/java/com/baeldung/model/Author.java new file mode 100644 index 0000000000..09239efbe5 --- /dev/null +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/model/Author.java @@ -0,0 +1,28 @@ +package com.baeldung.model; + +public class Author { + + private String name; + + public Author() { + } + + public Author(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Author{" + + "name='" + name + '\'' + + '}'; + } +} diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleService.java b/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleService.java new file mode 100644 index 0000000000..052e22c67d --- /dev/null +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleService.java @@ -0,0 +1,15 @@ +package com.baeldung.service; + +import com.baeldung.model.Article; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +public interface ArticleService { + Article save(Article article); + Article findOne(String id); + Iterable
findAll(); + Page
findByAuthorName(String name, Pageable pageable); + Page
findByAuthorNameUsingCustomQuery(String name, Pageable pageable); + long count(); + void delete(Article article); +} diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleServiceImpl.java b/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleServiceImpl.java new file mode 100644 index 0000000000..4dc100ec22 --- /dev/null +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleServiceImpl.java @@ -0,0 +1,54 @@ +package com.baeldung.service; + +import com.baeldung.dao.ArticleRepository; +import com.baeldung.model.Article; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +public class ArticleServiceImpl implements ArticleService { + + private ArticleRepository articleRepository; + + @Autowired + public void setArticleRepository(ArticleRepository articleRepository) { + this.articleRepository = articleRepository; + } + + @Override + public Article save(Article article) { + return articleRepository.save(article); + } + + @Override + public Article findOne(String id) { + return articleRepository.findOne(id); + } + + @Override + public Iterable
findAll() { + return articleRepository.findAll(); + } + + @Override + public Page
findByAuthorName(String name, Pageable pageable) { + return articleRepository.findByAuthorsName(name, pageable); + } + + @Override + public Page
findByAuthorNameUsingCustomQuery(String name, Pageable pageable) { + return articleRepository.findByAuthorsNameUsingCustomQuery(name, pageable); + } + + @Override + public long count() { + return articleRepository.count(); + } + + @Override + public void delete(Article article) { + articleRepository.delete(article); + } +} diff --git a/spring-data-elasticsearch/src/main/resources/logback.xml b/spring-data-elasticsearch/src/main/resources/logback.xml new file mode 100644 index 0000000000..37a9e2edbf --- /dev/null +++ b/spring-data-elasticsearch/src/main/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + elasticsearch - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/ElasticSearchTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/ElasticSearchTest.java new file mode 100644 index 0000000000..07248149c2 --- /dev/null +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/ElasticSearchTest.java @@ -0,0 +1,130 @@ +package com.baeldung; + +import com.baeldung.config.Config; +import com.baeldung.model.Article; +import com.baeldung.model.Author; +import com.baeldung.service.ArticleService; +import org.elasticsearch.index.query.QueryBuilder; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.data.elasticsearch.core.query.SearchQuery; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import java.util.List; + +import static java.util.Arrays.asList; +import static org.elasticsearch.index.query.FilterBuilders.regexpFilter; +import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {Config.class}, loader = AnnotationConfigContextLoader.class) +public class ElasticSearchTest { + + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private ArticleService articleService; + + private final Author johnSmith = new Author("John Smith"); + private final Author johnDoe = new Author("John Doe"); + + @Before + public void before() { + elasticsearchTemplate.deleteIndex(Article.class); + elasticsearchTemplate.createIndex(Article.class); + + Article article = new Article("Spring Data Elasticsearch"); + article.setAuthors(asList(johnSmith, johnDoe)); + articleService.save(article); + + article = new Article("Search engines"); + article.setAuthors(asList(johnDoe)); + articleService.save(article); + + article = new Article("Second Article About Elasticsearch"); + article.setAuthors(asList(johnSmith)); + articleService.save(article); + } + + @Test + public void givenArticleService_whenSaveArticle_thenIdIsAssigned() { + List authors = asList( + new Author("John Smith"), johnDoe); + + Article article = new Article("Making Search Elastic"); + article.setAuthors(authors); + + article = articleService.save(article); + assertNotNull(article.getId()); + } + + @Test + public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() { + + Page
articleByAuthorName = articleService.findByAuthorName(johnSmith.getName(), new PageRequest(0, 10)); + assertEquals(2L, articleByAuthorName.getTotalElements()); + } + + @Test + public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() { + + Page
articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("John Smith", new PageRequest(0, 10)); + assertEquals(3L, articleByAuthorName.getTotalElements()); + } + + + @Test + public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() { + + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withFilter(regexpFilter("title", ".*data.*")) + .build(); + List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + + assertEquals(1, articles.size()); + } + + @Test + public void givenSavedDoc_whenTitleUpdated_thenCouldFindByUpdatedTitle() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(fuzzyQuery("title", "serch")) + .build(); + List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + + assertEquals(1, articles.size()); + + Article article = articles.get(0); + final String newTitle = "Getting started with Search Engines"; + article.setTitle(newTitle); + articleService.save(article); + + assertEquals(newTitle, articleService.findOne(article.getId()).getTitle()); + } + + @Test + public void givenSavedDoc_whenDelete_thenRemovedFromIndex() { + + final String articleTitle = "Spring Data Elasticsearch"; + + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")) + .build(); + List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + final long count = articleService.count(); + + articleService.delete(articles.get(0)); + + assertEquals(count - 1, articleService.count()); + } +} From 68f33a231298f75ed4d73d86a879491b4a05e4a1 Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Thu, 4 Feb 2016 15:10:06 +0300 Subject: [PATCH 171/309] Change index name to 'blog' and rename package to 'repository' --- .../src/main/java/com/baeldung/config/Config.java | 2 +- .../src/main/java/com/baeldung/model/Article.java | 2 +- .../baeldung/repository/ArticleRepository.java | 15 +++++++++++++++ .../com/baeldung/service/ArticleServiceImpl.java | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) create mode 100644 spring-data-elasticsearch/src/main/java/com/baeldung/repository/ArticleRepository.java diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/config/Config.java b/spring-data-elasticsearch/src/main/java/com/baeldung/config/Config.java index eb65e38f65..a67ec64534 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/config/Config.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/config/Config.java @@ -17,7 +17,7 @@ import java.nio.file.Path; import java.nio.file.Paths; @Configuration -@EnableElasticsearchRepositories(basePackages = "com.baeldung.dao") +@EnableElasticsearchRepositories(basePackages = "com.baeldung.repository") @ComponentScan(basePackages = {"com.baeldung.service"}) public class Config { diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/model/Article.java b/spring-data-elasticsearch/src/main/java/com/baeldung/model/Article.java index 17580ca0db..dee1d0817e 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/model/Article.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/model/Article.java @@ -8,7 +8,7 @@ import org.springframework.data.elasticsearch.annotations.FieldType; import java.util.List; -@Document(indexName = "article", type = "article") +@Document(indexName = "blog", type = "article") public class Article { @Id diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/repository/ArticleRepository.java b/spring-data-elasticsearch/src/main/java/com/baeldung/repository/ArticleRepository.java new file mode 100644 index 0000000000..1cb74889c5 --- /dev/null +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/repository/ArticleRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.repository; + +import com.baeldung.model.Article; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.elasticsearch.annotations.Query; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +public interface ArticleRepository extends ElasticsearchRepository { + + Page
findByAuthorsName(String name, Pageable pageable); + + @Query("{\"bool\": {\"must\": [{\"match\": {\"authors.name\": \"?0\"}}]}}") + Page
findByAuthorsNameUsingCustomQuery(String name, Pageable pageable); +} diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleServiceImpl.java b/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleServiceImpl.java index 4dc100ec22..59feb2816c 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleServiceImpl.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleServiceImpl.java @@ -1,6 +1,6 @@ package com.baeldung.service; -import com.baeldung.dao.ArticleRepository; +import com.baeldung.repository.ArticleRepository; import com.baeldung.model.Article; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; From 65635956703a6473aef19009070118e536c71076 Mon Sep 17 00:00:00 2001 From: Eugen Date: Fri, 5 Feb 2016 10:25:17 +0200 Subject: [PATCH 172/309] Create README.md --- spring-batch/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 spring-batch/README.md diff --git a/spring-batch/README.md b/spring-batch/README.md new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-batch/README.md @@ -0,0 +1 @@ + From 6ab868cef39ac442eba1421b38826aaf9f4b541e Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 6 Feb 2016 12:50:32 +0200 Subject: [PATCH 173/309] cleanup work --- ...pse.wst.jsdt.core.javascriptValidator.launch | 7 +++++++ spring-security-login-and-registration/.project | 17 ++++++----------- 2 files changed, 13 insertions(+), 11 deletions(-) create mode 100644 spring-security-login-and-registration/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch diff --git a/spring-security-login-and-registration/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-security-login-and-registration/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch new file mode 100644 index 0000000000..627021fb96 --- /dev/null +++ b/spring-security-login-and-registration/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch @@ -0,0 +1,7 @@ + + + + + + + diff --git a/spring-security-login-and-registration/.project b/spring-security-login-and-registration/.project index 2c3e86ed06..4a27f224a4 100644 --- a/spring-security-login-and-registration/.project +++ b/spring-security-login-and-registration/.project @@ -6,8 +6,13 @@ - org.eclipse.wst.jsdt.core.javascriptValidator + org.eclipse.ui.externaltools.ExternalToolBuilder + full,incremental, + + LaunchConfigHandle + <project>/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch + @@ -25,16 +30,6 @@ - - org.jboss.tools.jst.web.kb.kbbuilder - - - - - org.hibernate.eclipse.console.hibernateBuilder - - - org.eclipse.wst.validation.validationbuilder From 0d45b71098d3dc53b0abe2ae9af500fc1a58c410 Mon Sep 17 00:00:00 2001 From: Kevin Gilmore Date: Sat, 6 Feb 2016 11:32:12 -0600 Subject: [PATCH 174/309] API for RAML modularization article --- .../api-before-modularization.raml | 119 ++++++++++++++++++ raml/modularization/api-with-libraries.raml | 50 ++++++++ .../api-with-typed-fragments.raml | 74 +++++++++++ raml/modularization/api.raml | 47 +++++++ raml/modularization/examples/Bar.json | 6 + raml/modularization/examples/Bars.json | 19 +++ raml/modularization/examples/Error.json | 4 + raml/modularization/examples/Foo.json | 4 + raml/modularization/examples/Foos.json | 16 +++ .../extensions/en_US/additionalResources.raml | 16 +++ raml/modularization/libraries/dataTypes.raml | 19 +++ .../libraries/resourceTypes.raml | 32 +++++ .../libraries/securitySchemes.raml | 20 +++ raml/modularization/libraries/traits.raml | 33 +++++ .../overlays/es_ES/additionalResources.raml | 13 ++ .../overlays/es_ES/documentationItems.raml | 23 ++++ .../resourceTypes/collection.raml | 12 ++ raml/modularization/resourceTypes/item.raml | 14 +++ raml/modularization/traits/hasNotFound.raml | 8 ++ .../modularization/traits/hasRequestItem.raml | 5 + .../traits/hasResponseCollection.raml | 8 ++ .../traits/hasResponseItem.raml | 8 ++ raml/modularization/types/Bar.raml | 7 ++ raml/modularization/types/Error.raml | 5 + raml/modularization/types/Foo.raml | 6 + 25 files changed, 568 insertions(+) create mode 100644 raml/modularization/api-before-modularization.raml create mode 100644 raml/modularization/api-with-libraries.raml create mode 100644 raml/modularization/api-with-typed-fragments.raml create mode 100644 raml/modularization/api.raml create mode 100644 raml/modularization/examples/Bar.json create mode 100644 raml/modularization/examples/Bars.json create mode 100644 raml/modularization/examples/Error.json create mode 100644 raml/modularization/examples/Foo.json create mode 100644 raml/modularization/examples/Foos.json create mode 100644 raml/modularization/extensions/en_US/additionalResources.raml create mode 100644 raml/modularization/libraries/dataTypes.raml create mode 100644 raml/modularization/libraries/resourceTypes.raml create mode 100644 raml/modularization/libraries/securitySchemes.raml create mode 100644 raml/modularization/libraries/traits.raml create mode 100644 raml/modularization/overlays/es_ES/additionalResources.raml create mode 100644 raml/modularization/overlays/es_ES/documentationItems.raml create mode 100644 raml/modularization/resourceTypes/collection.raml create mode 100644 raml/modularization/resourceTypes/item.raml create mode 100644 raml/modularization/traits/hasNotFound.raml create mode 100644 raml/modularization/traits/hasRequestItem.raml create mode 100644 raml/modularization/traits/hasResponseCollection.raml create mode 100644 raml/modularization/traits/hasResponseItem.raml create mode 100644 raml/modularization/types/Bar.raml create mode 100644 raml/modularization/types/Error.raml create mode 100644 raml/modularization/types/Foo.raml diff --git a/raml/modularization/api-before-modularization.raml b/raml/modularization/api-before-modularization.raml new file mode 100644 index 0000000000..b580c33983 --- /dev/null +++ b/raml/modularization/api-before-modularization.raml @@ -0,0 +1,119 @@ +#%RAML 1.0 +title: API for REST Services used in the RAML tutorials on Baeldung.com +documentation: + - title: Overview + - content: | + This document defines the interface for the REST services + used in the popular RAML Tutorial series at Baeldung.com. + - title: Disclaimer: + - content: | + All names used in this definition are purely fictional. + Any similarities between the names used in this tutorial and those of real persons, whether living or dead, are merely coincidental. + - title: Copyright + - content: Copyright 2016 by Baeldung.com. All rights reserved. +version: v1 +protocols: [ HTTPS ] +baseUri: http://rest-api.baeldung.com/api/{version} +mediaType: application/json +securedBy: basicAuth +securitySchemes: + - basicAuth: + description: Each request must contain the headers necessary for + basic authentication + type: Basic Authentication + describedBy: + headers: + Authorization: + description: | + Used to send the Base64 encoded "username:password" + credentials + type: string + responses: + 401: + description: | + Unauthorized. Either the provided username and password + combination is invalid, or the user is not allowed to + access the content provided by the requested URL. +types: + Foo: !include types/Foo.raml + Bar: !include types/Bar.raml + Error: !include types/Error.raml +resourceTypes: + - collection: + usage: Use this resourceType to represent a collection of items + description: A collection of <> + get: + description: | + Get all <>, + optionally filtered + is: [ hasResponseCollection ] + post: + description: | + Create a new <> + is: [ hasRequestItem ] + - item: + usage: Use this resourceType to represent any single item + description: A single <> + get: + description: Get a <> by <> + is: [ hasResponseItem, hasNotFound ] + put: + description: Update a <> by <> + is: [ hasRequestItem, hasResponseItem, hasNotFound ] + delete: + description: Delete a <> by <> + is: [ hasNotFound ] + responses: + 204: +traits: + - hasRequestItem: + body: + application/json: + type: <> + - hasResponseItem: + responses: + 200: + body: + application/json: + type: <> + example: !include examples/<>.json + - hasResponseCollection: + responses: + 200: + body: + application/json: + type: <>[] + example: !include examples/<>.json + - hasNotFound: + responses: + 404: + body: + application/json: + type: Error + example: !include examples/Error.json +/foos: + type: collection + typeName: Foo + get: + queryParameters: + name?: string + ownerName?: string + /{fooId}: + type: item + typeName: Foo + /name/{name}: + get: + description: List all foos with a certain name + typeName: Foo + is: [ hasResponseCollection ] +/bars: + type: collection + typeName: Bar + /{barId}: + type: item + typeName: Bar + /fooId/{fooId}: + get: + description: Get all bars for the matching fooId + typeName: Bar + is: [ hasResponseCollection ] \ No newline at end of file diff --git a/raml/modularization/api-with-libraries.raml b/raml/modularization/api-with-libraries.raml new file mode 100644 index 0000000000..b3081e843a --- /dev/null +++ b/raml/modularization/api-with-libraries.raml @@ -0,0 +1,50 @@ +#%RAML 1.0 +title: API for REST Services used in the RAML tutorials on Baeldung.com +documentation: + - title: Overview + - content: | + This document defines the interface for the REST services + used in the popular RAML Tutorial series at Baeldung.com. + - title: Disclaimer: + - content: | + All names used in this definition are purely fictional. + Any similarities between the names used in this tutorial and those of real persons, whether living or dead, are merely coincidental. + - title: Copyright + - content: Copyright 2016 by Baeldung.com. All rights reserved. +uses: + mySecuritySchemes: !include libraries/security.raml + myDataTypes: !include libraries/dataTypes.raml + myResourceTypes: !include libraries/resourceTypes.raml + myTraits: !include libraries/traits.raml +version: v1 +protocols: [ HTTPS ] +baseUri: http://rest-api.baeldung.com/api/{version} +mediaType: application/json +securedBy: [ mySecuritySchemes.basicAuth ] +/foos: + type: myResourceTypes.collection + typeName: myDataTypes.Foo + get: + queryParameters: + name?: string + ownerName?: string + /{fooId}: + type: myResourceTypes.item + typeName: myDataTypes.Foo + /name/{name}: + get: + description: List all foos with a certain name + typeName: myDataTypes.Foo + is: [ myTraits.hasResponseCollection ] +/bars: + type: myResourceTypes.collection + typeName: myDataTypes.Bar + /{barId}: + type: myResourceTypes.item + typeName: myDataTypes.Bar + /fooId/{fooId}: + get: + description: Get all bars for the matching fooId + type: myResourceTypes.item + typeName: myDataTypes.Bar + is: [ myTraits.hasResponseCollection ] \ No newline at end of file diff --git a/raml/modularization/api-with-typed-fragments.raml b/raml/modularization/api-with-typed-fragments.raml new file mode 100644 index 0000000000..2bb4e317c1 --- /dev/null +++ b/raml/modularization/api-with-typed-fragments.raml @@ -0,0 +1,74 @@ +#%RAML 1.0 +title: API for REST Services used in the RAML tutorials on Baeldung.com +documentation: + - title: Overview + - content: | + This document defines the interface for the REST services + used in the popular RAML Tutorial series at Baeldung.com. + - title: Disclaimer: + - content: | + All names used in this definition are purely fictional. + Any similarities between the names used in this tutorial and those of real persons, whether living or dead, are merely coincidental. + - title: Copyright + - content: Copyright 2016 by Baeldung.com. All rights reserved. +version: v1 +protocols: [ HTTPS ] +baseUri: http://rest-api.baeldung.com/api/{version} +mediaType: application/json +securedBy: [ basicAuth ] +securitySchemes: + - basicAuth: + description: Each request must contain the headers necessary for + basic authentication + type: Basic Authentication + describedBy: + headers: + Authorization: + description: | + Used to send the Base64 encoded "username:password" + credentials + type: string + responses: + 401: + description: | + Unauthorized. Either the provided username and password + combination is invalid, or the user is not allowed to + access the content provided by the requested URL. +types: + Foo: !include types/Foo.raml + Bar: !include types/Bar.raml + Error: !include types/Error.raml +resourceTypes: + - collection: !include resourceTypes/collection.raml + - item: !include resourceTypes/item.raml +traits: + - hasRequestItem: !include traits/hasRequestItem.raml + - hasResponseItem: !include traits/hasResponseItem.raml + - hasResponseCollection: !include traits/hasResponseCollection.raml + - hasNotFound: !include traits/hasNotFound.raml +/foos: + type: collection + typeName: Foo + get: + queryParameters: + name?: string + ownerName?: string + /{fooId}: + type: item + typeName: Foo + /name/{name}: + get: + description: List all foos with a certain name + typeName: Foo + is: [ hasResponseCollection ] +/bars: + type: collection + typeName: Bar + /{barId}: + type: item + typeName: Bar + /fooId/{fooId}: + get: + description: Get all bars for the matching fooId + typeName: Bar + is: [ hasResponseCollection ] \ No newline at end of file diff --git a/raml/modularization/api.raml b/raml/modularization/api.raml new file mode 100644 index 0000000000..184027cd26 --- /dev/null +++ b/raml/modularization/api.raml @@ -0,0 +1,47 @@ +#%RAML 1.0 +title: Baeldung Foo REST Services API +uses: + security: !include libraries/security.raml +version: v1 +protocols: [ HTTPS ] +baseUri: http://rest-api.baeldung.com/api/{version} +mediaType: application/json +securedBy: [ security.basicAuth ] +types: + Foo: !include types/Foo.raml + Bar: !include types/Bar.raml + Error: !include types/Error.raml +resourceTypes: + - collection: !include resourceTypes/collection.raml + - item: !include resourceTypes/item.raml +traits: + - hasRequestItem: !include traits/hasRequestItem.raml + - hasResponseItem: !include traits/hasResponseItem.raml + - hasResponseCollection: !include traits/hasResponseCollection.raml + - hasNotFound: !include traits/hasNotFound.raml +/foos: + type: collection + typeName: Foo + get: + queryParameters: + name?: string + ownerName?: string + /{fooId}: + type: item + typeName: Foo + /name/{name}: + get: + description: List all foos with a certain name + typeName: Foo + is: [ hasResponseCollection ] +/bars: + type: collection + typeName: Bar + /{barId}: + type: item + typeName: Bar + /fooId/{fooId}: + get: + description: Get all bars for the matching fooId + typeName: Bar + is: [ hasResponseCollection ] \ No newline at end of file diff --git a/raml/modularization/examples/Bar.json b/raml/modularization/examples/Bar.json new file mode 100644 index 0000000000..0ee1b34edb --- /dev/null +++ b/raml/modularization/examples/Bar.json @@ -0,0 +1,6 @@ +{ + "id" : 1, + "name" : "First Bar", + "city" : "Austin", + "fooId" : 2 +} \ No newline at end of file diff --git a/raml/modularization/examples/Bars.json b/raml/modularization/examples/Bars.json new file mode 100644 index 0000000000..89ea875432 --- /dev/null +++ b/raml/modularization/examples/Bars.json @@ -0,0 +1,19 @@ +[ + { + "id" : 1, + "name" : "First Bar", + "city" : "Austin", + "fooId" : 2 + }, + { + "id" : 2, + "name" : "Second Bar", + "city" : "Dallas", + "fooId" : 1 + }, + { + "id" : 3, + "name" : "Third Bar", + "fooId" : 2 + } +] \ No newline at end of file diff --git a/raml/modularization/examples/Error.json b/raml/modularization/examples/Error.json new file mode 100644 index 0000000000..dca56da7c2 --- /dev/null +++ b/raml/modularization/examples/Error.json @@ -0,0 +1,4 @@ +{ + "message" : "Not found", + "code" : 1001 +} \ No newline at end of file diff --git a/raml/modularization/examples/Foo.json b/raml/modularization/examples/Foo.json new file mode 100644 index 0000000000..1b1b8c891e --- /dev/null +++ b/raml/modularization/examples/Foo.json @@ -0,0 +1,4 @@ +{ + "id" : 1, + "name" : "First Foo" +} \ No newline at end of file diff --git a/raml/modularization/examples/Foos.json b/raml/modularization/examples/Foos.json new file mode 100644 index 0000000000..74f64689f0 --- /dev/null +++ b/raml/modularization/examples/Foos.json @@ -0,0 +1,16 @@ +[ + { + "id" : 1, + "name" : "First Foo", + "ownerName" : "Jack Robinson" + }, + { + "id" : 2, + "name" : "Second Foo" + }, + { + "id" : 3, + "name" : "Third Foo", + "ownerName" : "Chuck Norris" + } +] \ No newline at end of file diff --git a/raml/modularization/extensions/en_US/additionalResources.raml b/raml/modularization/extensions/en_US/additionalResources.raml new file mode 100644 index 0000000000..20c6851f23 --- /dev/null +++ b/raml/modularization/extensions/en_US/additionalResources.raml @@ -0,0 +1,16 @@ +#%RAML 1.0 Extension +# File located at: +# /extensions/en_US/additionalResources.raml +masterRef: /api.raml +usage: This extension defines additional resources for version 2 of the API. +version: v2 +/foos: + /bar/{barId}: + get: + description: | + Get the foo that is related to the bar having barId = {barId} + typeName: Foo + queryParameters: + barId?: integer + typeName: Foo + is: [ hasResponseItem ] diff --git a/raml/modularization/libraries/dataTypes.raml b/raml/modularization/libraries/dataTypes.raml new file mode 100644 index 0000000000..8a240e62dc --- /dev/null +++ b/raml/modularization/libraries/dataTypes.raml @@ -0,0 +1,19 @@ +#%RAML 1.0 Library +# This is the file /libraries/dataTypes.raml +usage: This library defines the data types for the API +types: + Foo: + properties: + id: integer + name: string + ownerName?: string + Bar: + properties: + id: integer + name: string + city?: string + fooId: integer + Error: + properties: + code: integer + message: string diff --git a/raml/modularization/libraries/resourceTypes.raml b/raml/modularization/libraries/resourceTypes.raml new file mode 100644 index 0000000000..681ff710d6 --- /dev/null +++ b/raml/modularization/libraries/resourceTypes.raml @@ -0,0 +1,32 @@ +#%RAML 1.0 Library +# This is the file /libraries/resourceTypes.raml +usage: This library defines the resource types for the API +uses: + myTraits: !include traits.raml +resourceTypes: + collection: + usage: Use this resourceType to represent a collection of items + description: A collection of <> + get: + description: | + Get all <>, + optionally filtered + is: [ myTraits.hasResponseCollection ] + post: + description: | + Create a new <> + is: [ myTraits.hasRequestItem ] + item: + usage: Use this resourceType to represent any single item + description: A single <> + get: + description: Get a <> by <> + is: [ myTraits.hasResponseItem, myTraits.hasNotFound ] + put: + description: Update a <> by <> + is: [ myTraits.hasRequestItem, myTraits.hasResponseItem, myTraits.hasNotFound ] + delete: + description: Delete a <> by <> + is: [ myTraits.hasNotFound ] + responses: + 204: diff --git a/raml/modularization/libraries/securitySchemes.raml b/raml/modularization/libraries/securitySchemes.raml new file mode 100644 index 0000000000..621c6ac975 --- /dev/null +++ b/raml/modularization/libraries/securitySchemes.raml @@ -0,0 +1,20 @@ +#%RAML 1.0 Library +# This is the file /libraries/securitySchemes.raml +securitySchemes: + - basicAuth: + description: Each request must contain the headers necessary for + basic authentication + type: Basic Authentication + describedBy: + headers: + Authorization: + description: | + Used to send the Base64 encoded "username:password" + credentials + type: string + responses: + 401: + description: | + Unauthorized. Either the provided username and password + combination is invalid, or the user is not allowed to + access the content provided by the requested URL. diff --git a/raml/modularization/libraries/traits.raml b/raml/modularization/libraries/traits.raml new file mode 100644 index 0000000000..c101d94c02 --- /dev/null +++ b/raml/modularization/libraries/traits.raml @@ -0,0 +1,33 @@ +#%RAML 1.0 Library +# This is the file /libraries/traits.raml +usage: This library defines some basic traits +traits: + hasRequestItem: + usage: Use this trait for resources whose request body is a single item + body: + application/json: + type: <> + hasResponseItem: + usage: Use this trait for resources whose response body is a single item + responses: + 200: + body: + application/json: + type: <> + example: !include /examples/<>.json + hasResponseCollection: + usage: Use this trait for resources whose response body is a collection of items + responses: + 200: + body: + application/json: + type: <>[] + example: !include /examples/<>.json + hasNotFound: + usage: Use this trait for resources that could respond with a 404 status + responses: + 404: + body: + application/json: + type: Error + example: !include /examples/Error.json diff --git a/raml/modularization/overlays/es_ES/additionalResources.raml b/raml/modularization/overlays/es_ES/additionalResources.raml new file mode 100644 index 0000000000..e8748fd726 --- /dev/null +++ b/raml/modularization/overlays/es_ES/additionalResources.raml @@ -0,0 +1,13 @@ +#%RAML 1.0 Overlay +# Archivo situado en: +# /overlays/es_ES/additionalResources.raml +masterRef: /api.raml +usage: | + Se trata de un español demasiado que describe los recursos adicionales + para la versión 2 del API. +version: v2 +/foos: + /bar/{barId}: + get: + description: | + Obtener el foo que se relaciona con el bar tomando barId = {barId} diff --git a/raml/modularization/overlays/es_ES/documentationItems.raml b/raml/modularization/overlays/es_ES/documentationItems.raml new file mode 100644 index 0000000000..dc6ca3eaef --- /dev/null +++ b/raml/modularization/overlays/es_ES/documentationItems.raml @@ -0,0 +1,23 @@ +#%RAML 1.0 Overlay +# File located at (archivo situado en): +# /overlays/es_ES/documentationItems.raml +masterRef: /api.raml +usage: | + To provide user documentation and other descriptive text in Spanish + (Para proporcionar la documentación del usuario y otro texto descriptivo en español) +title: API para servicios REST utilizados en los tutoriales RAML en Baeldung.com +documentation: + - title: Descripción general + - content: | + Este documento define la interfaz para los servicios REST + utilizados en la popular serie de RAML Tutorial en Baeldung.com + - title: Renuncia + - content: | + Todos los nombres usados ​​en esta definición son pura ficción. + Cualquier similitud entre los nombres utilizados en este tutorial + y los de las personas reales, ya sea vivo o muerto, + no son más que coincidenta. + + - title: Derechos de autor + - content: | + Derechos de autor 2016 por Baeldung.com. Todos los derechos reservados. diff --git a/raml/modularization/resourceTypes/collection.raml b/raml/modularization/resourceTypes/collection.raml new file mode 100644 index 0000000000..0cab417f14 --- /dev/null +++ b/raml/modularization/resourceTypes/collection.raml @@ -0,0 +1,12 @@ +#%RAML 1.0 ResourceType +usage: Use this resourceType to represent a collection of items +description: A collection of <> +get: + description: | + Get all <>, + optionally filtered + is: [ hasResponseCollection ] +post: + description: | + Create a new <> + is: [ hasRequestItem ] diff --git a/raml/modularization/resourceTypes/item.raml b/raml/modularization/resourceTypes/item.raml new file mode 100644 index 0000000000..59f057ca98 --- /dev/null +++ b/raml/modularization/resourceTypes/item.raml @@ -0,0 +1,14 @@ +#%RAML 1.0 ResourceType +usage: Use this resourceType to represent any single item +description: A single <> +get: + description: Get a <> by <> + is: [ hasResponseItem, hasNotFound ] +put: + description: Update a <> by <> + is: [ hasRequestItem, hasResponseItem, hasNotFound ] +delete: + description: Delete a <> by <> + is: [ hasNotFound ] + responses: + 204: diff --git a/raml/modularization/traits/hasNotFound.raml b/raml/modularization/traits/hasNotFound.raml new file mode 100644 index 0000000000..8d2d940c03 --- /dev/null +++ b/raml/modularization/traits/hasNotFound.raml @@ -0,0 +1,8 @@ +#%RAML 1.0 Trait +usage: Use this trait for resources that could respond with a 404 status +responses: + 404: + body: + application/json: + type: Error + example: !include /examples/Error.json diff --git a/raml/modularization/traits/hasRequestItem.raml b/raml/modularization/traits/hasRequestItem.raml new file mode 100644 index 0000000000..06281781c0 --- /dev/null +++ b/raml/modularization/traits/hasRequestItem.raml @@ -0,0 +1,5 @@ +#%RAML 1.0 Trait +usage: Use this trait for resources whose request body is a single item +body: + application/json: + type: <> diff --git a/raml/modularization/traits/hasResponseCollection.raml b/raml/modularization/traits/hasResponseCollection.raml new file mode 100644 index 0000000000..47dc1c2d5f --- /dev/null +++ b/raml/modularization/traits/hasResponseCollection.raml @@ -0,0 +1,8 @@ +#%RAML 1.0 Trait +usage: Use this trait for resources whose response body is a collection of items +responses: + 200: + body: + application/json: + type: <>[] + example: !include /examples/<>.json diff --git a/raml/modularization/traits/hasResponseItem.raml b/raml/modularization/traits/hasResponseItem.raml new file mode 100644 index 0000000000..94d3ba0756 --- /dev/null +++ b/raml/modularization/traits/hasResponseItem.raml @@ -0,0 +1,8 @@ +#%RAML 1.0 Trait +usage: Use this trait for resources whose response body is a single item +responses: + 200: + body: + application/json: + type: <> + example: !include /examples/<>.json diff --git a/raml/modularization/types/Bar.raml b/raml/modularization/types/Bar.raml new file mode 100644 index 0000000000..92255a75fe --- /dev/null +++ b/raml/modularization/types/Bar.raml @@ -0,0 +1,7 @@ +#%RAML 1.0 DataType + +properties: + id: integer + name: string + city?: string + fooId: integer diff --git a/raml/modularization/types/Error.raml b/raml/modularization/types/Error.raml new file mode 100644 index 0000000000..8d54b5f181 --- /dev/null +++ b/raml/modularization/types/Error.raml @@ -0,0 +1,5 @@ +#%RAML 1.0 DataType + + properties: + code: integer + message: string diff --git a/raml/modularization/types/Foo.raml b/raml/modularization/types/Foo.raml new file mode 100644 index 0000000000..1702865e05 --- /dev/null +++ b/raml/modularization/types/Foo.raml @@ -0,0 +1,6 @@ +#%RAML 1.0 DataType + +properties: + id: integer + name: string + ownerName?: string From 8506171908e954c3453a3050fce22963d09e127a Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 6 Feb 2016 21:09:04 +0200 Subject: [PATCH 175/309] removing unused file --- .../src/main/resources/webSecurityConfig.xml | 36 ------------------- 1 file changed, 36 deletions(-) delete mode 100644 spring-jpa/src/main/resources/webSecurityConfig.xml diff --git a/spring-jpa/src/main/resources/webSecurityConfig.xml b/spring-jpa/src/main/resources/webSecurityConfig.xml deleted file mode 100644 index 88af78dabc..0000000000 --- a/spring-jpa/src/main/resources/webSecurityConfig.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file From 2be93cd3216df16ced5143fb69e3056e628b80e0 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 6 Feb 2016 21:25:59 +0200 Subject: [PATCH 176/309] minimal cleanup in Eclipse --- .../org.hibernate.eclipse.console.hibernateBuilder.launch | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 spring-security-rest-full/.externalToolBuilders/org.hibernate.eclipse.console.hibernateBuilder.launch diff --git a/spring-security-rest-full/.externalToolBuilders/org.hibernate.eclipse.console.hibernateBuilder.launch b/spring-security-rest-full/.externalToolBuilders/org.hibernate.eclipse.console.hibernateBuilder.launch deleted file mode 100644 index 9bc0284d26..0000000000 --- a/spring-security-rest-full/.externalToolBuilders/org.hibernate.eclipse.console.hibernateBuilder.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - From 8b7e761c00f4a1db8710e8f38a4fdf061fa489bb Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Sat, 6 Feb 2016 23:48:50 +0200 Subject: [PATCH 177/309] Update README.md --- spring-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-jpa/README.md b/spring-jpa/README.md index 11df42ac52..387e3c00eb 100644 --- a/spring-jpa/README.md +++ b/spring-jpa/README.md @@ -7,3 +7,4 @@ - [Spring 3 and JPA with Hibernate](http://www.baeldung.com/2011/12/13/the-persistence-layer-with-spring-3-1-and-jpa/) - [Transactions with Spring 3 and JPA](http://www.baeldung.com/2011/12/26/transaction-configuration-with-jpa-and-spring-3-1/) - [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa) +- [JPA Pagination](http://www.baeldung.com/jpa-pagination) From f09bce94f9e670e48ad8b00030bb967ea2e5326b Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Sat, 6 Feb 2016 23:51:06 +0200 Subject: [PATCH 178/309] Update README.md --- spring-hibernate4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-hibernate4/README.md b/spring-hibernate4/README.md index 0d1ac1600e..96f8074165 100644 --- a/spring-hibernate4/README.md +++ b/spring-hibernate4/README.md @@ -5,6 +5,7 @@ ### Relevant Articles: - [Hibernate 4 with Spring](http://www.baeldung.com/hibernate-4-spring) - [The DAO with Spring 3 and Hibernate](http://www.baeldung.com/2011/12/02/the-persistence-layer-with-spring-3-1-and-hibernate/) +- [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination) ### Quick Start From ab4b2d8a1a51f0c24e455f17f671c503fd4c1928 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Sat, 6 Feb 2016 23:52:34 +0200 Subject: [PATCH 179/309] Update README.md --- spring-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-jpa/README.md b/spring-jpa/README.md index 387e3c00eb..da55ca7b75 100644 --- a/spring-jpa/README.md +++ b/spring-jpa/README.md @@ -8,3 +8,4 @@ - [Transactions with Spring 3 and JPA](http://www.baeldung.com/2011/12/26/transaction-configuration-with-jpa-and-spring-3-1/) - [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa) - [JPA Pagination](http://www.baeldung.com/jpa-pagination) +- [Sorting with JPA](http://www.baeldung.com/jpa-sort) From 1ba1bf2bc5056effb8d718f41885ff30075fd4e0 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sun, 7 Feb 2016 12:49:30 +0200 Subject: [PATCH 180/309] jackson skip conditionally --- .../jackson/dynamicIgnore/Address.java | 41 +++++++ .../jackson/dynamicIgnore/Hidable.java | 9 ++ .../dynamicIgnore/HidableSerializer.java | 29 +++++ .../jackson/dynamicIgnore/Person.java | 41 +++++++ .../test/JacksonDynamicIgnoreTest.java | 100 ++++++++++++++++++ 5 files changed, 220 insertions(+) create mode 100644 jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Address.java create mode 100644 jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Hidable.java create mode 100644 jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/HidableSerializer.java create mode 100644 jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Person.java create mode 100644 jackson/src/test/java/org/baeldung/jackson/test/JacksonDynamicIgnoreTest.java diff --git a/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Address.java b/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Address.java new file mode 100644 index 0000000000..41ea8e7be3 --- /dev/null +++ b/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Address.java @@ -0,0 +1,41 @@ +package org.baeldung.jackson.dynamicIgnore; + + +public class Address implements Hidable { + private String city; + private String country; + private boolean hidden; + + public Address(final String city, final String country, final boolean hidden) { + super(); + this.city = city; + this.country = country; + this.hidden = hidden; + } + + public String getCity() { + return city; + } + + public void setCity(final String city) { + this.city = city; + } + + public String getCountry() { + return country; + } + + public void setCountry(final String country) { + this.country = country; + } + + @Override + public boolean isHidden() { + return hidden; + } + + public void setHidden(final boolean hidden) { + this.hidden = hidden; + } + +} diff --git a/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Hidable.java b/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Hidable.java new file mode 100644 index 0000000000..9eaa0c9619 --- /dev/null +++ b/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Hidable.java @@ -0,0 +1,9 @@ +package org.baeldung.jackson.dynamicIgnore; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + + +@JsonIgnoreProperties("hidden") +public interface Hidable { + boolean isHidden(); +} diff --git a/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/HidableSerializer.java b/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/HidableSerializer.java new file mode 100644 index 0000000000..35bd8fd7f6 --- /dev/null +++ b/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/HidableSerializer.java @@ -0,0 +1,29 @@ +package org.baeldung.jackson.dynamicIgnore; + +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; + +public class HidableSerializer extends JsonSerializer { + + private JsonSerializer defaultSerializer; + + public HidableSerializer(final JsonSerializer serializer) { + defaultSerializer = serializer; + } + + @Override + public void serialize(final Hidable value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { + if (value.isHidden()) + return; + defaultSerializer.serialize(value, jgen, provider); + } + + @Override + public boolean isEmpty(final SerializerProvider provider, final Hidable value) { + return (value == null || value.isHidden()); + } +} diff --git a/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Person.java b/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Person.java new file mode 100644 index 0000000000..5fe294a5e1 --- /dev/null +++ b/jackson/src/test/java/org/baeldung/jackson/dynamicIgnore/Person.java @@ -0,0 +1,41 @@ +package org.baeldung.jackson.dynamicIgnore; + + +public class Person implements Hidable { + private String name; + private Address address; + private boolean hidden; + + public Person(final String name, final Address address, final boolean hidden) { + super(); + this.name = name; + this.address = address; + this.hidden = hidden; + } + + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public Address getAddress() { + return address; + } + + public void setAddress(final Address address) { + this.address = address; + } + @Override + public boolean isHidden() { + return hidden; + } + + public void setHidden(final boolean hidden) { + this.hidden = hidden; + } + +} diff --git a/jackson/src/test/java/org/baeldung/jackson/test/JacksonDynamicIgnoreTest.java b/jackson/src/test/java/org/baeldung/jackson/test/JacksonDynamicIgnoreTest.java new file mode 100644 index 0000000000..d98f948dec --- /dev/null +++ b/jackson/src/test/java/org/baeldung/jackson/test/JacksonDynamicIgnoreTest.java @@ -0,0 +1,100 @@ +package org.baeldung.jackson.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; + +import org.baeldung.jackson.dynamicIgnore.Address; +import org.baeldung.jackson.dynamicIgnore.Hidable; +import org.baeldung.jackson.dynamicIgnore.HidableSerializer; +import org.baeldung.jackson.dynamicIgnore.Person; +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.BeanDescription; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationConfig; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; + +public class JacksonDynamicIgnoreTest { + + private ObjectMapper mapper = new ObjectMapper(); + + @Before + public void setUp() { + mapper.setSerializationInclusion(Include.NON_EMPTY); + mapper.registerModule(new SimpleModule() { + @Override + public void setupModule(final SetupContext context) { + super.setupModule(context); + context.addBeanSerializerModifier(new BeanSerializerModifier() { + @Override + public JsonSerializer modifySerializer(final SerializationConfig config, final BeanDescription beanDesc, final JsonSerializer serializer) { + if (Hidable.class.isAssignableFrom(beanDesc.getBeanClass())) { + return new HidableSerializer((JsonSerializer) serializer); + } + return serializer; + } + }); + } + }); + } + + @Test + public void whenNotHidden_thenCorrect() throws JsonProcessingException { + final Address ad = new Address("ny", "usa", false); + final Person person = new Person("john", ad, false); + final String result = mapper.writeValueAsString(person); + + assertTrue(result.contains("name")); + assertTrue(result.contains("john")); + assertTrue(result.contains("address")); + assertTrue(result.contains("usa")); + + System.out.println("Not Hidden = " + result); + } + + @Test + public void whenAddressHidden_thenCorrect() throws JsonProcessingException { + final Address ad = new Address("ny", "usa", true); + final Person person = new Person("john", ad, false); + final String result = mapper.writeValueAsString(person); + + assertTrue(result.contains("name")); + assertTrue(result.contains("john")); + assertFalse(result.contains("address")); + assertFalse(result.contains("usa")); + + System.out.println("Address Hidden = " + result); + } + + @Test + public void whenAllHidden_thenCorrect() throws JsonProcessingException { + final Address ad = new Address("ny", "usa", false); + final Person person = new Person("john", ad, true); + final String result = mapper.writeValueAsString(person); + + assertTrue(result.length() == 0); + + System.out.println("All Hidden = " + result); + } + + @Test + public void whenSerializeList_thenCorrect() throws JsonProcessingException { + final Address ad1 = new Address("tokyo", "jp", true); + final Address ad2 = new Address("london", "uk", false); + final Address ad3 = new Address("ny", "usa", false); + final Person p1 = new Person("john", ad1, false); + final Person p2 = new Person("tom", ad2, true); + final Person p3 = new Person("adam", ad3, false); + + final String result = mapper.writeValueAsString(Arrays.asList(p1, p2, p3)); + + System.out.println(result); + } +} From 333e8793bd20d4faabce6733e635844d050f5a2a Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 7 Feb 2016 18:15:42 +0200 Subject: [PATCH 181/309] minor upgrade --- jackson/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jackson/pom.xml b/jackson/pom.xml index 9996330361..ed7a5944a5 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -140,7 +140,7 @@ 5.1.35 - 2.5.5 + 2.7.1-1 1.7.13 From 80b3e457f2eb16c2082381cf198c0be7c3b096a3 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:29:30 +0100 Subject: [PATCH 182/309] Minor Bugfix --- .../baeldung/client/ServicesInterface.java | 4 +- .../main/java/com/baeldung/model/Movie.java | 22 +-- .../com/baeldung/server/MovieCrudService.java | 12 +- .../src/main/webapp/WEB-INF/web.xml | 37 +---- .../java/baeldung/client/RestEasyClient.java | 7 + .../baeldung/server/RestEasyClientTest.java | 149 +++++++----------- 6 files changed, 81 insertions(+), 150 deletions(-) create mode 100644 RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 7efed546d8..749cabc757 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -14,7 +14,7 @@ public interface ServicesInterface { @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - Movie movieByImdbID(@QueryParam("imdbID") String imdbID); + Movie movieByImdbId(@QueryParam("imdbId") String imdbId); @GET @@ -37,7 +37,7 @@ public interface ServicesInterface { @DELETE @Path("/deletemovie") - Response deleteMovie(@QueryParam("imdbID") String imdbID); + Response deleteMovie(@QueryParam("imdbId") String imdbID); diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 052ba081c1..a2b2bd5250 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -13,7 +13,7 @@ import javax.xml.bind.annotation.XmlType; "country", "director", "genre", - "imdbID", + "imdbId", "imdbRating", "imdbVotes", "language", @@ -36,7 +36,7 @@ public class Movie { protected String country; protected String director; protected String genre; - protected String imdbID; + protected String imdbId; protected String imdbRating; protected String imdbVotes; protected String language; @@ -173,27 +173,27 @@ public class Movie { } /** - * Recupera il valore della propriet� imdbID. + * Recupera il valore della propriet� imdbId. * * @return * possible object is * {@link String } * */ - public String getImdbID() { - return imdbID; + public String getImdbId() { + return imdbId; } /** - * Imposta il valore della propriet� imdbID. + * Imposta il valore della propriet� imdbId. * * @param value * allowed object is * {@link String } * */ - public void setImdbID(String value) { - this.imdbID = value; + public void setImdbId(String value) { + this.imdbId = value; } /** @@ -540,7 +540,7 @@ public class Movie { ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + - ", imdbID='" + imdbID + '\'' + + ", imdbId='" + imdbId + '\'' + ", imdbRating='" + imdbRating + '\'' + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + @@ -564,14 +564,14 @@ public class Movie { Movie movie = (Movie) o; - if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false; + if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; return title != null ? title.equals(movie.title) : movie.title == null; } @Override public int hashCode() { - int result = imdbID != null ? imdbID.hashCode() : 0; + int result = imdbId != null ? imdbId.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); return result; } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 18366e2faa..29226aa0e0 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -22,7 +22,7 @@ public class MovieCrudService { @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ + public Movie movieByImdbID(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling getinfo for a given ImdbID***"); @@ -40,12 +40,12 @@ public class MovieCrudService { System.out.println("*** Calling addMovie ***"); - if (null!=inventory.get(movie.getImdbID())){ + if (null!=inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.CREATED).build(); } @@ -58,11 +58,11 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null==inventory.get(movie.getImdbID())){ + if (null==inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.OK).build(); } @@ -70,7 +70,7 @@ public class MovieCrudService { @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbID") String imdbID){ + public Response deleteMovie(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling deleteMovie ***"); diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index ab3bc1aa83..f70fdf7975 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -5,47 +5,12 @@ RestEasy Example - - - org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap - - - - RestEasy Example - - - webAppRootKey - RestEasyExample - - - - + resteasy.servlet.mapping.prefix /rest - - resteasy-servlet - - org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher - - - javax.ws.rs.Application - com.baeldung.server.RestEasyServices - - - - - resteasy-servlet - /rest/* - - - - - index.html - - \ No newline at end of file diff --git a/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java b/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java new file mode 100644 index 0000000000..b474b3d4f8 --- /dev/null +++ b/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java @@ -0,0 +1,7 @@ +package baeldung.client; + +/** + * Created by Admin on 29/01/2016. + */ +public class RestEasyClient { +} diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java index fb4205bcd7..b6a2e2a0c1 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -1,7 +1,7 @@ package com.baeldung.server; -import com.baeldung.model.Movie; import com.baeldung.client.ServicesInterface; +import com.baeldung.model.Movie; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; @@ -9,7 +9,6 @@ import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import javax.naming.NamingException; @@ -23,22 +22,13 @@ import java.util.Locale; public class RestEasyClientTest { - Movie transformerMovie=null; Movie batmanMovie=null; ObjectMapper jsonMapper=null; - @BeforeClass - public static void loadMovieInventory(){ - - - - } - @Before public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); @@ -57,133 +47,102 @@ public class RestEasyClientTest { batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); } catch (Exception e) { - e.printStackTrace(); throw new RuntimeException("Test is going to die ...", e); } - } - @Test public void testListAllMovies() { - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(transformerMovie); - moviesResponse.close(); - moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); - final List movies = simple.listMovies(); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } + List movies = simple.listMovies(); + System.out.println(movies); } - @Test - public void testMovieByImdbID() { + public void testMovieByImdbId() { String transformerImdbId="tt0418279"; - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(transformerMovie); - moviesResponse.close(); + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); - final Movie movies = simple.movieByImdbID(transformerImdbId); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } + Movie movies = simple.movieByImdbId(transformerImdbId); + System.out.println(movies); } @Test public void testAddMovie() { - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - moviesResponse = simple.addMovie(transformerMovie); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(transformerMovie); - if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { - //System.out.println(moviesResponse.readEntity(String.class)); - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } @Test - public void testDeleteMovie() { + public void testDeleteMovi1e() { - String transformerImdbId="tt0418279"; + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.deleteMovie(batmanMovie.getImdbId()); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - moviesResponse = simple.deleteMovie(transformerImdbId); - moviesResponse.close(); - - if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println(moviesResponse.readEntity(String.class)); + throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } @Test public void testUpdateMovie() { - try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + batmanMovie.setImdbVotes("300,000"); + moviesResponse = simple.updateMovie(batmanMovie); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - batmanMovie.setImdbVotes("300,000"); - moviesResponse = simple.updateMovie(batmanMovie); - - if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - //System.out.println(moviesResponse.readEntity(String.class)); - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } } \ No newline at end of file From a0c22cc22514d0190d14d51e6bcc06ad5eed8836 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sat, 30 Jan 2016 17:48:56 +0100 Subject: [PATCH 183/309] RestEasy Tutorial, CRUD Services example --- RestEasy Example/pom.xml | 91 +++ .../src/main/java/com/baeldung/Movie.java | 535 ++++++++++++++++++ .../baeldung/client/ServicesInterface.java | 44 ++ .../server/service/MovieCrudService.java | 94 +++ .../server/service/RestEasyServices.java | 40 ++ .../src/main/resources/schema1.xsd | 29 + .../main/webapp/WEB-INF/classes/logback.xml | 3 + .../WEB-INF/jboss-deployment-structure.xml | 16 + .../src/main/webapp/WEB-INF/jboss-web.xml | 4 + .../src/main/webapp/WEB-INF/web.xml | 51 ++ .../com/baeldung/server/RestEasyClient.java | 50 ++ .../resources/server/movies/transformer.json | 22 + 12 files changed, 979 insertions(+) create mode 100644 RestEasy Example/pom.xml create mode 100644 RestEasy Example/src/main/java/com/baeldung/Movie.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java create mode 100644 RestEasy Example/src/main/resources/schema1.xsd create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/web.xml create mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java create mode 100644 RestEasy Example/src/test/resources/server/movies/transformer.json diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml new file mode 100644 index 0000000000..b16c5e8267 --- /dev/null +++ b/RestEasy Example/pom.xml @@ -0,0 +1,91 @@ + + + 4.0.0 + + com.baeldung + resteasy-tutorial + 1.0 + war + + + + jboss + http://repository.jboss.org/nexus/content/groups/public/ + + + + + 3.0.14.Final + runtime + + + + RestEasyTutorial + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + + org.jboss.resteasy + jaxrs-api + 3.0.12.Final + ${resteasy.scope} + + + + org.jboss.resteasy + resteasy-servlet-initializer + ${resteasy.version} + ${resteasy.scope} + + + jboss-jaxrs-api_2.0_spec + org.jboss.spec.javax.ws.rs + + + + + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + ${resteasy.scope} + + + + + javax.ws.rs + javax.ws.rs-api + 2.0.1 + + + + org.jboss.resteasy + resteasy-jackson-provider + ${resteasy.version} + ${resteasy.scope} + + + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy.version} + ${resteasy.scope} + + + + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/Movie.java new file mode 100644 index 0000000000..c0041d2e95 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/Movie.java @@ -0,0 +1,535 @@ + +package com.baeldung; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; + + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "movie", propOrder = { + "actors", + "awards", + "country", + "director", + "genre", + "imdbID", + "imdbRating", + "imdbVotes", + "language", + "metascore", + "plot", + "poster", + "rated", + "released", + "response", + "runtime", + "title", + "type", + "writer", + "year" +}) +public class Movie { + + protected String actors; + protected String awards; + protected String country; + protected String director; + protected String genre; + protected String imdbID; + protected String imdbRating; + protected String imdbVotes; + protected String language; + protected String metascore; + protected String plot; + protected String poster; + protected String rated; + protected String released; + protected String response; + protected String runtime; + protected String title; + protected String type; + protected String writer; + protected String year; + + /** + * Recupera il valore della propriet� actors. + * + * @return + * possible object is + * {@link String } + * + */ + public String getActors() { + return actors; + } + + /** + * Imposta il valore della propriet� actors. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setActors(String value) { + this.actors = value; + } + + /** + * Recupera il valore della propriet� awards. + * + * @return + * possible object is + * {@link String } + * + */ + public String getAwards() { + return awards; + } + + /** + * Imposta il valore della propriet� awards. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setAwards(String value) { + this.awards = value; + } + + /** + * Recupera il valore della propriet� country. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCountry() { + return country; + } + + /** + * Imposta il valore della propriet� country. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCountry(String value) { + this.country = value; + } + + /** + * Recupera il valore della propriet� director. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDirector() { + return director; + } + + /** + * Imposta il valore della propriet� director. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDirector(String value) { + this.director = value; + } + + /** + * Recupera il valore della propriet� genre. + * + * @return + * possible object is + * {@link String } + * + */ + public String getGenre() { + return genre; + } + + /** + * Imposta il valore della propriet� genre. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setGenre(String value) { + this.genre = value; + } + + /** + * Recupera il valore della propriet� imdbID. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbID() { + return imdbID; + } + + /** + * Imposta il valore della propriet� imdbID. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbID(String value) { + this.imdbID = value; + } + + /** + * Recupera il valore della propriet� imdbRating. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbRating() { + return imdbRating; + } + + /** + * Imposta il valore della propriet� imdbRating. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbRating(String value) { + this.imdbRating = value; + } + + /** + * Recupera il valore della propriet� imdbVotes. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbVotes() { + return imdbVotes; + } + + /** + * Imposta il valore della propriet� imdbVotes. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbVotes(String value) { + this.imdbVotes = value; + } + + /** + * Recupera il valore della propriet� language. + * + * @return + * possible object is + * {@link String } + * + */ + public String getLanguage() { + return language; + } + + /** + * Imposta il valore della propriet� language. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setLanguage(String value) { + this.language = value; + } + + /** + * Recupera il valore della propriet� metascore. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMetascore() { + return metascore; + } + + /** + * Imposta il valore della propriet� metascore. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMetascore(String value) { + this.metascore = value; + } + + /** + * Recupera il valore della propriet� plot. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPlot() { + return plot; + } + + /** + * Imposta il valore della propriet� plot. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPlot(String value) { + this.plot = value; + } + + /** + * Recupera il valore della propriet� poster. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPoster() { + return poster; + } + + /** + * Imposta il valore della propriet� poster. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPoster(String value) { + this.poster = value; + } + + /** + * Recupera il valore della propriet� rated. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRated() { + return rated; + } + + /** + * Imposta il valore della propriet� rated. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRated(String value) { + this.rated = value; + } + + /** + * Recupera il valore della propriet� released. + * + * @return + * possible object is + * {@link String } + * + */ + public String getReleased() { + return released; + } + + /** + * Imposta il valore della propriet� released. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setReleased(String value) { + this.released = value; + } + + /** + * Recupera il valore della propriet� response. + * + * @return + * possible object is + * {@link String } + * + */ + public String getResponse() { + return response; + } + + /** + * Imposta il valore della propriet� response. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setResponse(String value) { + this.response = value; + } + + /** + * Recupera il valore della propriet� runtime. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRuntime() { + return runtime; + } + + /** + * Imposta il valore della propriet� runtime. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRuntime(String value) { + this.runtime = value; + } + + /** + * Recupera il valore della propriet� title. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTitle() { + return title; + } + + /** + * Imposta il valore della propriet� title. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTitle(String value) { + this.title = value; + } + + /** + * Recupera il valore della propriet� type. + * + * @return + * possible object is + * {@link String } + * + */ + public String getType() { + return type; + } + + /** + * Imposta il valore della propriet� type. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setType(String value) { + this.type = value; + } + + /** + * Recupera il valore della propriet� writer. + * + * @return + * possible object is + * {@link String } + * + */ + public String getWriter() { + return writer; + } + + /** + * Imposta il valore della propriet� writer. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setWriter(String value) { + this.writer = value; + } + + /** + * Recupera il valore della propriet� year. + * + * @return + * possible object is + * {@link String } + * + */ + public String getYear() { + return year; + } + + /** + * Imposta il valore della propriet� year. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setYear(String value) { + this.year = value; + } + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java new file mode 100644 index 0000000000..53e88961be --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -0,0 +1,44 @@ +package com.baeldung.client; + +import com.baeldung.Movie; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + + +public interface ServicesInterface { + + + @GET + @Path("/getinfo") + @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + Movie movieByImdbID(@QueryParam("imdbID") String imdbID); + + + @POST + @Path("/addmovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + Response addMovie(Movie movie); + + + @PUT + @Path("/updatemovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + Response updateMovie(Movie movie); + + + @DELETE + @Path("/deletemovie") + Response deleteMovie(@QueryParam("imdbID") String imdbID); + + + @GET + @Path("/listmovies") + @Produces({"application/json"}) + List listMovies(); + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java new file mode 100644 index 0000000000..d1973e7037 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java @@ -0,0 +1,94 @@ +package com.baeldung.server.service; + +import com.baeldung.Movie; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + + +@Path("/movies") +public class MovieCrudService { + + + private Map inventory = new HashMap(); + + @GET + @Path("/getinfo") + @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ + + System.out.println("*** Calling getinfo ***"); + + Movie movie=new Movie(); + movie.setImdbID(imdbID); + return movie; + } + + @POST + @Path("/addmovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Response addMovie(Movie movie){ + + System.out.println("*** Calling addMovie ***"); + + if (null!=inventory.get(movie.getImdbID())){ + return Response.status(Response.Status.NOT_MODIFIED) + .entity("Movie is Already in the database.").build(); + } + inventory.put(movie.getImdbID(),movie); + + return Response.status(Response.Status.CREATED).build(); + } + + + @PUT + @Path("/updatemovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Response updateMovie(Movie movie){ + + System.out.println("*** Calling updateMovie ***"); + + if (null!=inventory.get(movie.getImdbID())){ + return Response.status(Response.Status.NOT_MODIFIED) + .entity("Movie is not in the database.\nUnable to Update").build(); + } + inventory.put(movie.getImdbID(),movie); + return Response.status(Response.Status.OK).build(); + + } + + + @DELETE + @Path("/deletemovie") + public Response deleteMovie(@QueryParam("imdbID") String imdbID){ + + System.out.println("*** Calling deleteMovie ***"); + + if (null==inventory.get(imdbID)){ + return Response.status(Response.Status.NOT_FOUND) + .entity("Movie is not in the database.\nUnable to Delete").build(); + } + + inventory.remove(imdbID); + return Response.status(Response.Status.OK).build(); + } + + @GET + @Path("/listmovies") + @Produces({"application/json"}) + public List listMovies(){ + + return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); + + } + + + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java new file mode 100644 index 0000000000..16b6200ad1 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java @@ -0,0 +1,40 @@ +package com.baeldung.server.service; + + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Created by Admin on 29/01/2016. + */ + + + +@ApplicationPath("/rest") +public class RestEasyServices extends Application { + + private Set singletons = new HashSet(); + + public RestEasyServices() { + singletons.add(new MovieCrudService()); + } + + @Override + public Set getSingletons() { + return singletons; + } + + @Override + public Set> getClasses() { + return super.getClasses(); + } + + @Override + public Map getProperties() { + return super.getProperties(); + } +} diff --git a/RestEasy Example/src/main/resources/schema1.xsd b/RestEasy Example/src/main/resources/schema1.xsd new file mode 100644 index 0000000000..0d74b7c366 --- /dev/null +++ b/RestEasy Example/src/main/resources/schema1.xsd @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml b/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml new file mode 100644 index 0000000000..d94e9f71ab --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml new file mode 100644 index 0000000000..84d75934a7 --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml new file mode 100644 index 0000000000..694bb71332 --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..c66d3b56ae --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,51 @@ + + + + RestEasy Example + + + + org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap + + + + RestEasy Example + + + webAppRootKey + RestEasyExample + + + + + + resteasy.servlet.mapping.prefix + /rest + + + + + resteasy-servlet + + org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher + + + javax.ws.rs.Application + com.baeldung.server.service.RestEasyServices + + + + + resteasy-servlet + /rest/* + + + + + index.html + + + + \ No newline at end of file diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java new file mode 100644 index 0000000000..e711233979 --- /dev/null +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java @@ -0,0 +1,50 @@ +package com.baeldung.server; + +import com.baeldung.Movie; +import com.baeldung.client.ServicesInterface; +import org.jboss.resteasy.client.jaxrs.ResteasyClient; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; + +import java.util.List; + +public class RestEasyClient { + + public static void main(String[] args) { + + Movie st = new Movie(); + st.setImdbID("12345"); + + /* + * Alternatively you can use this simple String to send + * instead of using a Student instance + * + * String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}"; + */ + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies"); + + ServicesInterface simple = target.proxy(ServicesInterface.class); + final List movies = simple.listMovies(); + + /* + if (response.getStatus() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + + response.getStatus()); + } + + System.out.println("Server response : \n"); + System.out.println(response.readEntity(String.class)); + + response.close(); +*/ + } catch (Exception e) { + + e.printStackTrace(); + + } + } + +} \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/server/movies/transformer.json new file mode 100644 index 0000000000..2154868265 --- /dev/null +++ b/RestEasy Example/src/test/resources/server/movies/transformer.json @@ -0,0 +1,22 @@ +{ + "title": "Transformers", + "year": "2007", + "rated": "PG-13", + "released": "03 Jul 2007", + "runtime": "144 min", + "genre": "Action, Adventure, Sci-Fi", + "director": "Michael Bay", + "writer": "Roberto Orci (screenplay), Alex Kurtzman (screenplay), John Rogers (story), Roberto Orci (story), Alex Kurtzman (story)", + "actors": "Shia LaBeouf, Megan Fox, Josh Duhamel, Tyrese Gibson", + "plot": "A long time ago, far away on the planet of Cybertron, a war is being waged between the noble Autobots (led by the wise Optimus Prime) and the devious Decepticons (commanded by the dreaded Megatron) for control over the Allspark, a mystical talisman that would grant unlimited power to whoever possesses it. The Autobots managed to smuggle the Allspark off the planet, but Megatron blasts off in search of it. He eventually tracks it to the planet of Earth (circa 1850), but his reckless desire for power sends him right into the Arctic Ocean, and the sheer cold forces him into a paralyzed state. His body is later found by Captain Archibald Witwicky, but before going into a comatose state Megatron uses the last of his energy to engrave into the Captain's glasses a map showing the location of the Allspark, and to send a transmission to Cybertron. Megatron is then carried away aboard the Captain's ship. A century later, Captain Witwicky's grandson Sam Witwicky (nicknamed Spike by his friends) buys his first car. To his shock, he discovers it to be Bumblebee, an Autobot in disguise who is to protect Spike, who possesses the Captain's glasses and the map engraved on them. But Bumblebee is not the only Transformer to have arrived on Earth - in the desert of Qatar, the Decepticons Blackout and Scorponok attack a U.S. military base, causing the Pentagon to send their special Sector Seven agents to capture all \"specimens of this alien race.\" Spike and his girlfriend Mikaela find themselves in the midst of a grand battle between the Autobots and the Decepticons, stretching from Hoover Dam all the way to Los Angeles. Meanwhile, deep inside Hoover Dam, the cryogenically stored body of Megatron awakens.", + "language": "English, Spanish", + "country": "USA", + "awards": "Nominated for 3 Oscars. Another 18 wins & 40 nominations.", + "poster": "http://ia.media-imdb.com/images/M/MV5BMTQwNjU5MzUzNl5BMl5BanBnXkFtZTYwMzc1MTI3._V1_SX300.jpg", + "metascore": "61", + "imdbRating": "7.1", + "imdbVotes": "492,225", + "imdbID": "tt0418279", + "Type": "movie", + "response": "True" +} \ No newline at end of file From 72a74b8096cd535da6ff3c96d7cc05d305c5e1a9 Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sat, 30 Jan 2016 20:39:28 +0100 Subject: [PATCH 184/309] Added testCase for List All Movies and Add a Movie --- RestEasy Example/pom.xml | 29 +++++ .../baeldung/client/ServicesInterface.java | 6 +- .../java/com/baeldung/{ => model}/Movie.java | 45 +++++++- .../{service => }/MovieCrudService.java | 5 +- .../{service => }/RestEasyServices.java | 2 +- .../com/baeldung/server/RestEasyClient.java | 104 ++++++++++++++---- .../com/baeldung/server/movies/batman.json | 22 ++++ .../baeldung}/server/movies/transformer.json | 2 +- 8 files changed, 184 insertions(+), 31 deletions(-) rename RestEasy Example/src/main/java/com/baeldung/{ => model}/Movie.java (86%) rename RestEasy Example/src/main/java/com/baeldung/server/{service => }/MovieCrudService.java (96%) rename RestEasy Example/src/main/java/com/baeldung/server/{service => }/RestEasyServices.java (95%) create mode 100644 RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json rename RestEasy Example/src/test/resources/{ => com/baeldung}/server/movies/transformer.json (99%) diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index b16c5e8267..8dabfc863b 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -85,6 +85,35 @@ ${resteasy.scope} + + + + junit + junit + 4.4 + + + + commons-io + commons-io + 2.4 + + + + com.fasterxml.jackson.core + jackson-core + 2.7.0 + + + + com.fasterxml.jackson.core + jackson-annotations + 2.7.0 + + + + + diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 53e88961be..2585c32438 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -1,15 +1,13 @@ package com.baeldung.client; -import com.baeldung.Movie; +import com.baeldung.model.Movie; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; - +@Path("/movies") public interface ServicesInterface { diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java similarity index 86% rename from RestEasy Example/src/main/java/com/baeldung/Movie.java rename to RestEasy Example/src/main/java/com/baeldung/model/Movie.java index c0041d2e95..052ba081c1 100644 --- a/RestEasy Example/src/main/java/com/baeldung/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -1,5 +1,5 @@ -package com.baeldung; +package com.baeldung.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -532,4 +532,47 @@ public class Movie { this.year = value; } + @Override + public String toString() { + return "Movie{" + + "actors='" + actors + '\'' + + ", awards='" + awards + '\'' + + ", country='" + country + '\'' + + ", director='" + director + '\'' + + ", genre='" + genre + '\'' + + ", imdbID='" + imdbID + '\'' + + ", imdbRating='" + imdbRating + '\'' + + ", imdbVotes='" + imdbVotes + '\'' + + ", language='" + language + '\'' + + ", metascore='" + metascore + '\'' + + ", poster='" + poster + '\'' + + ", rated='" + rated + '\'' + + ", released='" + released + '\'' + + ", response='" + response + '\'' + + ", runtime='" + runtime + '\'' + + ", title='" + title + '\'' + + ", type='" + type + '\'' + + ", writer='" + writer + '\'' + + ", year='" + year + '\'' + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Movie movie = (Movie) o; + + if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false; + return title != null ? title.equals(movie.title) : movie.title == null; + + } + + @Override + public int hashCode() { + int result = imdbID != null ? imdbID.hashCode() : 0; + result = 31 * result + (title != null ? title.hashCode() : 0); + return result; + } } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java similarity index 96% rename from RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java rename to RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index d1973e7037..60e0121966 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -1,11 +1,10 @@ -package com.baeldung.server.service; +package com.baeldung.server; -import com.baeldung.Movie; +import com.baeldung.model.Movie; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java similarity index 95% rename from RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java rename to RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java index 16b6200ad1..8c57d2c9b4 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java @@ -1,4 +1,4 @@ -package com.baeldung.server.service; +package com.baeldung.server; import javax.ws.rs.ApplicationPath; diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java index e711233979..c77f494862 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java @@ -1,49 +1,111 @@ package com.baeldung.server; -import com.baeldung.Movie; +import com.baeldung.model.Movie; import com.baeldung.client.ServicesInterface; +import org.apache.commons.io.IOUtils; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.ObjectMapper; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import javax.naming.NamingException; +import javax.ws.rs.core.Link; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Arrays; import java.util.List; +import java.util.Locale; public class RestEasyClient { - public static void main(String[] args) { - Movie st = new Movie(); - st.setImdbID("12345"); + Movie transformerMovie=null; + Movie batmanMovie=null; + ObjectMapper jsonMapper=null; - /* - * Alternatively you can use this simple String to send - * instead of using a Student instance - * - * String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}"; - */ + @BeforeClass + public static void loadMovieInventory(){ + + + + } + + @Before + public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { + + + jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + jsonMapper.setDateFormat(sdf); + + try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) { + String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) { + String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + } + + @Test + public void testListAllMovies() { try { ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies"); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + final List movies = simple.listMovies(); + System.out.println(movies); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Test + public void testAddMovie() { + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); ServicesInterface simple = target.proxy(ServicesInterface.class); - final List movies = simple.listMovies(); + final Response moviesResponse = simple.addMovie(batmanMovie); - /* - if (response.getStatus() != 200) { + if (moviesResponse.getStatus() != 201) { + System.out.println(moviesResponse.readEntity(String.class)); throw new RuntimeException("Failed : HTTP error code : " - + response.getStatus()); + + moviesResponse.getStatus()); } - System.out.println("Server response : \n"); - System.out.println(response.readEntity(String.class)); + moviesResponse.close(); - response.close(); -*/ } catch (Exception e) { - e.printStackTrace(); - } } diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json new file mode 100644 index 0000000000..28061d5bf9 --- /dev/null +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json @@ -0,0 +1,22 @@ +{ + "title": "Batman", + "year": "1989", + "rated": "PG-13", + "released": "23 Jun 1989", + "runtime": "126 min", + "genre": "Action, Adventure", + "director": "Tim Burton", + "writer": "Bob Kane (Batman characters), Sam Hamm (story), Sam Hamm (screenplay), Warren Skaaren (screenplay)", + "actors": "Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl", + "plot": "The Dark Knight of Gotham City begins his war on crime with his first major enemy being the clownishly homicidal Joker.", + "language": "English, French", + "country": "USA, UK", + "awards": "Won 1 Oscar. Another 9 wins & 22 nominations.", + "poster": "http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg", + "metascore": "66", + "imdbRating": "7.6", + "imdbVotes": "256,000", + "imdbID": "tt0096895", + "type": "movie", + "response": "True" +} \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json similarity index 99% rename from RestEasy Example/src/test/resources/server/movies/transformer.json rename to RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json index 2154868265..a3b033a8ba 100644 --- a/RestEasy Example/src/test/resources/server/movies/transformer.json +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json @@ -17,6 +17,6 @@ "imdbRating": "7.1", "imdbVotes": "492,225", "imdbID": "tt0418279", - "Type": "movie", + "type": "movie", "response": "True" } \ No newline at end of file From 4174ff7dd2a1deb7e023067326e8fa2495385003 Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sun, 31 Jan 2016 11:05:11 +0100 Subject: [PATCH 185/309] Added testCase for all Services --- RestEasy Example/pom.xml | 15 -- .../baeldung/client/ServicesInterface.java | 10 +- .../com/baeldung/server/MovieCrudService.java | 15 +- .../src/main/webapp/WEB-INF/web.xml | 2 +- .../com/baeldung/server/RestEasyClient.java | 112 ----------- .../baeldung/server/RestEasyClientTest.java | 189 ++++++++++++++++++ 6 files changed, 206 insertions(+), 137 deletions(-) delete mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java create mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index 8dabfc863b..6935238d91 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -99,21 +99,6 @@ 2.4 - - com.fasterxml.jackson.core - jackson-core - 2.7.0 - - - - com.fasterxml.jackson.core - jackson-annotations - 2.7.0 - - - - - diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 2585c32438..7efed546d8 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -17,6 +17,12 @@ public interface ServicesInterface { Movie movieByImdbID(@QueryParam("imdbID") String imdbID); + @GET + @Path("/listmovies") + @Produces({"application/json"}) + List listMovies(); + + @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @@ -34,9 +40,5 @@ public interface ServicesInterface { Response deleteMovie(@QueryParam("imdbID") String imdbID); - @GET - @Path("/listmovies") - @Produces({"application/json"}) - List listMovies(); } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 60e0121966..18366e2faa 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -18,18 +18,21 @@ public class MovieCrudService { private Map inventory = new HashMap(); + @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ - System.out.println("*** Calling getinfo ***"); + System.out.println("*** Calling getinfo for a given ImdbID***"); + + if(inventory.containsKey(imdbID)){ + return inventory.get(imdbID); + }else return null; - Movie movie=new Movie(); - movie.setImdbID(imdbID); - return movie; } + @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @@ -41,6 +44,7 @@ public class MovieCrudService { return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } + inventory.put(movie.getImdbID(),movie); return Response.status(Response.Status.CREATED).build(); @@ -54,7 +58,7 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null!=inventory.get(movie.getImdbID())){ + if (null==inventory.get(movie.getImdbID())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } @@ -79,6 +83,7 @@ public class MovieCrudService { return Response.status(Response.Status.OK).build(); } + @GET @Path("/listmovies") @Produces({"application/json"}) diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index c66d3b56ae..ab3bc1aa83 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -33,7 +33,7 @@ javax.ws.rs.Application - com.baeldung.server.service.RestEasyServices + com.baeldung.server.RestEasyServices diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java deleted file mode 100644 index c77f494862..0000000000 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.model.Movie; -import com.baeldung.client.ServicesInterface; -import org.apache.commons.io.IOUtils; -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; -import org.jboss.resteasy.client.jaxrs.ResteasyClient; -import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; -import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import javax.naming.NamingException; -import javax.ws.rs.core.Link; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -public class RestEasyClient { - - - Movie transformerMovie=null; - Movie batmanMovie=null; - ObjectMapper jsonMapper=null; - - @BeforeClass - public static void loadMovieInventory(){ - - - - } - - @Before - public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - - - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); - jsonMapper.setDateFormat(sdf); - - try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) { - String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Test is going to die ...", e); - } - - try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) { - String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); - - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Test is going to die ...", e); - } - - } - - @Test - public void testListAllMovies() { - - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); - - final List movies = simple.listMovies(); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - @Test - public void testAddMovie() { - - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - - ServicesInterface simple = target.proxy(ServicesInterface.class); - final Response moviesResponse = simple.addMovie(batmanMovie); - - if (moviesResponse.getStatus() != 201) { - System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " - + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java new file mode 100644 index 0000000000..fb4205bcd7 --- /dev/null +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -0,0 +1,189 @@ +package com.baeldung.server; + +import com.baeldung.model.Movie; +import com.baeldung.client.ServicesInterface; +import org.apache.commons.io.IOUtils; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.ObjectMapper; +import org.jboss.resteasy.client.jaxrs.ResteasyClient; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.naming.NamingException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Locale; + +public class RestEasyClientTest { + + + Movie transformerMovie=null; + Movie batmanMovie=null; + ObjectMapper jsonMapper=null; + + @BeforeClass + public static void loadMovieInventory(){ + + + + } + + @Before + public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { + + + jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + jsonMapper.setDateFormat(sdf); + + try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/transformer.json")) { + String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/batman.json")) { + String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + } + + + @Test + public void testListAllMovies() { + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + + final List movies = simple.listMovies(); + System.out.println(movies); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testMovieByImdbID() { + + String transformerImdbId="tt0418279"; + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + + final Movie movies = simple.movieByImdbID(transformerImdbId); + System.out.println(movies); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testAddMovie() { + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(transformerMovie); + + if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { + //System.out.println(moviesResponse.readEntity(String.class)); + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + moviesResponse.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testDeleteMovie() { + + String transformerImdbId="tt0418279"; + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.deleteMovie(transformerImdbId); + moviesResponse.close(); + + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println(moviesResponse.readEntity(String.class)); + throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + + moviesResponse.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testUpdateMovie() { + + try { + + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + batmanMovie.setImdbVotes("300,000"); + moviesResponse = simple.updateMovie(batmanMovie); + + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + //System.out.println(moviesResponse.readEntity(String.class)); + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + + moviesResponse.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + +} \ No newline at end of file From 85d299e739fa00317d687fdd2af2ffa43a9dfc1c Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:29:30 +0100 Subject: [PATCH 186/309] Minor Bugfix --- .../baeldung/client/ServicesInterface.java | 4 +- .../main/java/com/baeldung/model/Movie.java | 22 +-- .../com/baeldung/server/MovieCrudService.java | 12 +- .../src/main/webapp/WEB-INF/web.xml | 37 +---- .../java/baeldung/client/RestEasyClient.java | 7 + .../baeldung/server/RestEasyClientTest.java | 149 +++++++----------- 6 files changed, 81 insertions(+), 150 deletions(-) create mode 100644 RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 7efed546d8..749cabc757 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -14,7 +14,7 @@ public interface ServicesInterface { @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - Movie movieByImdbID(@QueryParam("imdbID") String imdbID); + Movie movieByImdbId(@QueryParam("imdbId") String imdbId); @GET @@ -37,7 +37,7 @@ public interface ServicesInterface { @DELETE @Path("/deletemovie") - Response deleteMovie(@QueryParam("imdbID") String imdbID); + Response deleteMovie(@QueryParam("imdbId") String imdbID); diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 052ba081c1..a2b2bd5250 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -13,7 +13,7 @@ import javax.xml.bind.annotation.XmlType; "country", "director", "genre", - "imdbID", + "imdbId", "imdbRating", "imdbVotes", "language", @@ -36,7 +36,7 @@ public class Movie { protected String country; protected String director; protected String genre; - protected String imdbID; + protected String imdbId; protected String imdbRating; protected String imdbVotes; protected String language; @@ -173,27 +173,27 @@ public class Movie { } /** - * Recupera il valore della propriet� imdbID. + * Recupera il valore della propriet� imdbId. * * @return * possible object is * {@link String } * */ - public String getImdbID() { - return imdbID; + public String getImdbId() { + return imdbId; } /** - * Imposta il valore della propriet� imdbID. + * Imposta il valore della propriet� imdbId. * * @param value * allowed object is * {@link String } * */ - public void setImdbID(String value) { - this.imdbID = value; + public void setImdbId(String value) { + this.imdbId = value; } /** @@ -540,7 +540,7 @@ public class Movie { ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + - ", imdbID='" + imdbID + '\'' + + ", imdbId='" + imdbId + '\'' + ", imdbRating='" + imdbRating + '\'' + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + @@ -564,14 +564,14 @@ public class Movie { Movie movie = (Movie) o; - if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false; + if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; return title != null ? title.equals(movie.title) : movie.title == null; } @Override public int hashCode() { - int result = imdbID != null ? imdbID.hashCode() : 0; + int result = imdbId != null ? imdbId.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); return result; } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 18366e2faa..29226aa0e0 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -22,7 +22,7 @@ public class MovieCrudService { @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ + public Movie movieByImdbID(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling getinfo for a given ImdbID***"); @@ -40,12 +40,12 @@ public class MovieCrudService { System.out.println("*** Calling addMovie ***"); - if (null!=inventory.get(movie.getImdbID())){ + if (null!=inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.CREATED).build(); } @@ -58,11 +58,11 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null==inventory.get(movie.getImdbID())){ + if (null==inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.OK).build(); } @@ -70,7 +70,7 @@ public class MovieCrudService { @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbID") String imdbID){ + public Response deleteMovie(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling deleteMovie ***"); diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index ab3bc1aa83..f70fdf7975 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -5,47 +5,12 @@ RestEasy Example - - - org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap - - - - RestEasy Example - - - webAppRootKey - RestEasyExample - - - - + resteasy.servlet.mapping.prefix /rest - - resteasy-servlet - - org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher - - - javax.ws.rs.Application - com.baeldung.server.RestEasyServices - - - - - resteasy-servlet - /rest/* - - - - - index.html - - \ No newline at end of file diff --git a/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java b/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java new file mode 100644 index 0000000000..b474b3d4f8 --- /dev/null +++ b/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java @@ -0,0 +1,7 @@ +package baeldung.client; + +/** + * Created by Admin on 29/01/2016. + */ +public class RestEasyClient { +} diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java index fb4205bcd7..b6a2e2a0c1 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -1,7 +1,7 @@ package com.baeldung.server; -import com.baeldung.model.Movie; import com.baeldung.client.ServicesInterface; +import com.baeldung.model.Movie; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; @@ -9,7 +9,6 @@ import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import javax.naming.NamingException; @@ -23,22 +22,13 @@ import java.util.Locale; public class RestEasyClientTest { - Movie transformerMovie=null; Movie batmanMovie=null; ObjectMapper jsonMapper=null; - @BeforeClass - public static void loadMovieInventory(){ - - - - } - @Before public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); @@ -57,133 +47,102 @@ public class RestEasyClientTest { batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); } catch (Exception e) { - e.printStackTrace(); throw new RuntimeException("Test is going to die ...", e); } - } - @Test public void testListAllMovies() { - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(transformerMovie); - moviesResponse.close(); - moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); - final List movies = simple.listMovies(); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } + List movies = simple.listMovies(); + System.out.println(movies); } - @Test - public void testMovieByImdbID() { + public void testMovieByImdbId() { String transformerImdbId="tt0418279"; - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(transformerMovie); - moviesResponse.close(); + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); - final Movie movies = simple.movieByImdbID(transformerImdbId); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } + Movie movies = simple.movieByImdbId(transformerImdbId); + System.out.println(movies); } @Test public void testAddMovie() { - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - moviesResponse = simple.addMovie(transformerMovie); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(transformerMovie); - if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { - //System.out.println(moviesResponse.readEntity(String.class)); - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } @Test - public void testDeleteMovie() { + public void testDeleteMovi1e() { - String transformerImdbId="tt0418279"; + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.deleteMovie(batmanMovie.getImdbId()); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - moviesResponse = simple.deleteMovie(transformerImdbId); - moviesResponse.close(); - - if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println(moviesResponse.readEntity(String.class)); + throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } @Test public void testUpdateMovie() { - try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + batmanMovie.setImdbVotes("300,000"); + moviesResponse = simple.updateMovie(batmanMovie); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - batmanMovie.setImdbVotes("300,000"); - moviesResponse = simple.updateMovie(batmanMovie); - - if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - //System.out.println(moviesResponse.readEntity(String.class)); - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } } \ No newline at end of file From d4a4d20fa03d9356ee122834846551cd71427c44 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:39:35 +0100 Subject: [PATCH 187/309] Minor Bugfix --- .../main/java/com/baeldung/model/Movie.java | 321 +----------------- 1 file changed, 1 insertion(+), 320 deletions(-) diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index a2b2bd5250..805ba95209 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -52,482 +52,163 @@ public class Movie { protected String writer; protected String year; - /** - * Recupera il valore della propriet� actors. - * - * @return - * possible object is - * {@link String } - * - */ + public String getActors() { return actors; } - /** - * Imposta il valore della propriet� actors. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setActors(String value) { this.actors = value; } - /** - * Recupera il valore della propriet� awards. - * - * @return - * possible object is - * {@link String } - * - */ public String getAwards() { return awards; } - /** - * Imposta il valore della propriet� awards. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setAwards(String value) { this.awards = value; } - /** - * Recupera il valore della propriet� country. - * - * @return - * possible object is - * {@link String } - * - */ public String getCountry() { return country; } - /** - * Imposta il valore della propriet� country. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setCountry(String value) { this.country = value; } - /** - * Recupera il valore della propriet� director. - * - * @return - * possible object is - * {@link String } - * - */ public String getDirector() { return director; } - /** - * Imposta il valore della propriet� director. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setDirector(String value) { this.director = value; } - /** - * Recupera il valore della propriet� genre. - * - * @return - * possible object is - * {@link String } - * - */ public String getGenre() { return genre; } - /** - * Imposta il valore della propriet� genre. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setGenre(String value) { this.genre = value; } - /** - * Recupera il valore della propriet� imdbId. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbId() { return imdbId; } - /** - * Imposta il valore della propriet� imdbId. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setImdbId(String value) { this.imdbId = value; } - /** - * Recupera il valore della propriet� imdbRating. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbRating() { return imdbRating; } - /** - * Imposta il valore della propriet� imdbRating. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setImdbRating(String value) { this.imdbRating = value; } - /** - * Recupera il valore della propriet� imdbVotes. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbVotes() { return imdbVotes; } - /** - * Imposta il valore della propriet� imdbVotes. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setImdbVotes(String value) { this.imdbVotes = value; } - /** - * Recupera il valore della propriet� language. - * - * @return - * possible object is - * {@link String } - * - */ public String getLanguage() { return language; } - /** - * Imposta il valore della propriet� language. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setLanguage(String value) { this.language = value; } - /** - * Recupera il valore della propriet� metascore. - * - * @return - * possible object is - * {@link String } - * - */ public String getMetascore() { return metascore; } - /** - * Imposta il valore della propriet� metascore. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setMetascore(String value) { this.metascore = value; } - /** - * Recupera il valore della propriet� plot. - * - * @return - * possible object is - * {@link String } - * - */ public String getPlot() { return plot; } - /** - * Imposta il valore della propriet� plot. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setPlot(String value) { this.plot = value; } - /** - * Recupera il valore della propriet� poster. - * - * @return - * possible object is - * {@link String } - * - */ public String getPoster() { return poster; } - /** - * Imposta il valore della propriet� poster. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setPoster(String value) { this.poster = value; } - /** - * Recupera il valore della propriet� rated. - * - * @return - * possible object is - * {@link String } - * - */ public String getRated() { return rated; } - /** - * Imposta il valore della propriet� rated. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setRated(String value) { this.rated = value; } - /** - * Recupera il valore della propriet� released. - * - * @return - * possible object is - * {@link String } - * - */ public String getReleased() { return released; } - /** - * Imposta il valore della propriet� released. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setReleased(String value) { this.released = value; } - /** - * Recupera il valore della propriet� response. - * - * @return - * possible object is - * {@link String } - * - */ public String getResponse() { return response; } - /** - * Imposta il valore della propriet� response. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setResponse(String value) { this.response = value; } - /** - * Recupera il valore della propriet� runtime. - * - * @return - * possible object is - * {@link String } - * - */ public String getRuntime() { return runtime; } - /** - * Imposta il valore della propriet� runtime. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setRuntime(String value) { this.runtime = value; } - /** - * Recupera il valore della propriet� title. - * - * @return - * possible object is - * {@link String } - * - */ public String getTitle() { return title; } - /** - * Imposta il valore della propriet� title. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setTitle(String value) { this.title = value; } - /** - * Recupera il valore della propriet� type. - * - * @return - * possible object is - * {@link String } - * - */ public String getType() { return type; } - /** - * Imposta il valore della propriet� type. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setType(String value) { this.type = value; } - /** - * Recupera il valore della propriet� writer. - * - * @return - * possible object is - * {@link String } - * - */ public String getWriter() { return writer; } - /** - * Imposta il valore della propriet� writer. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setWriter(String value) { this.writer = value; } - /** - * Recupera il valore della propriet� year. - * - * @return - * possible object is - * {@link String } - * - */ public String getYear() { return year; } - /** - * Imposta il valore della propriet� year. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setYear(String value) { this.year = value; } From 183ae3d3b9bae2ce9151c4ab0702b74ecb54d1dd Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:47:42 +0100 Subject: [PATCH 188/309] Minor Bugfix --- .../main/java/com/baeldung/model/Movie.java | 260 ------------------ 1 file changed, 260 deletions(-) diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 8eb8283d28..76e84a6378 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -84,390 +84,130 @@ public class Movie { this.director = value; } - public String getGenre() { return genre; } - public void setGenre(String value) { this.genre = value; } - /** - * Recupera il valore della propriet� imdbId. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbId() { return imdbId; } - /** - * Imposta il valore della propriet� imdbId. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setImdbId(String value) { this.imdbId = value; } - /** - * Recupera il valore della propriet� imdbRating. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbRating() { return imdbRating; } - /** - * Imposta il valore della propriet� imdbRating. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setImdbRating(String value) { this.imdbRating = value; } - /** - * Recupera il valore della propriet� imdbVotes. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbVotes() { return imdbVotes; } public void setImdbVotes(String value) { - /** - * Imposta il valore della propriet� imdbVotes. - * - * @param value - * allowed object is - * {@link String } - * - */ this.imdbVotes = value; } public String getLanguage() { - /** - * Recupera il valore della propriet� language. - * - * @return - * possible object is - * {@link String } - * - */ return language; } - /** - * Imposta il valore della propriet� language. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setLanguage(String value) { this.language = value; } - /** - * Recupera il valore della propriet� metascore. - * - * @return - * possible object is - * {@link String } - * - */ public String getMetascore() { return metascore; } - /** - * Imposta il valore della propriet� metascore. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setMetascore(String value) { this.metascore = value; } - /** - * Recupera il valore della propriet� plot. - * - * @return - * possible object is - * {@link String } - * - */ public String getPlot() { return plot; } - /** - * Imposta il valore della propriet� plot. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setPlot(String value) { this.plot = value; } - /** - * Recupera il valore della propriet� poster. - * - * @return - * possible object is - * {@link String } - * - */ public String getPoster() { return poster; } - /** - * Imposta il valore della propriet� poster. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setPoster(String value) { this.poster = value; } - /** - * Recupera il valore della propriet� rated. - * - * @return - * possible object is - * {@link String } - * - */ public String getRated() { return rated; } - /** - * Imposta il valore della propriet� rated. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setRated(String value) { this.rated = value; } - /** - * Recupera il valore della propriet� released. - * - * @return - * possible object is - * {@link String } - * - */ public String getReleased() { return released; } - /** - * Imposta il valore della propriet� released. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setReleased(String value) { this.released = value; } - /** - * Recupera il valore della propriet� response. - * - * @return - * possible object is - * {@link String } - * - */ public String getResponse() { return response; } - /** - * Imposta il valore della propriet� response. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setResponse(String value) { this.response = value; } - /** - * Recupera il valore della propriet� runtime. - * - * @return - * possible object is - * {@link String } - * - */ public String getRuntime() { return runtime; } - /** - * Imposta il valore della propriet� runtime. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setRuntime(String value) { this.runtime = value; } - /** - * Recupera il valore della propriet� title. - * - * @return - * possible object is - * {@link String } - * - */ public String getTitle() { return title; } - /** - * Imposta il valore della propriet� title. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setTitle(String value) { this.title = value; } -<<<<<<< HEAD -======= - /** - * Recupera il valore della propriet� type. - * - * @return - * possible object is - * {@link String } - * - */ ->>>>>>> origin/master public String getType() { return type; } -<<<<<<< HEAD -======= - /** - * Imposta il valore della propriet� type. - * - * @param value - * allowed object is - * {@link String } - * - */ ->>>>>>> origin/master public void setType(String value) { this.type = value; } -<<<<<<< HEAD -======= - /** - * Recupera il valore della propriet� writer. - * - * @return - * possible object is - * {@link String } - * - */ ->>>>>>> origin/master public String getWriter() { return writer; } -<<<<<<< HEAD -======= - /** - * Imposta il valore della propriet� writer. - * - * @param value - * allowed object is - * {@link String } - * - */ ->>>>>>> origin/master public void setWriter(String value) { this.writer = value; } -<<<<<<< HEAD -======= - /** - * Recupera il valore della propriet� year. - * - * @return - * possible object is - * {@link String } - * - */ ->>>>>>> origin/master public String getYear() { return year; } -<<<<<<< HEAD -======= - /** - * Imposta il valore della propriet� year. - * - * @param value - * allowed object is - * {@link String } - * - */ ->>>>>>> origin/master public void setYear(String value) { this.year = value; } From 03b6cbf3e545dcb817abf364f1edea3e2b074a03 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:55:46 +0100 Subject: [PATCH 189/309] CleanUp Code --- RestEasy Example/pom.xml | 3 +- .../baeldung/client/ServicesInterface.java | 1 - .../main/java/com/baeldung/model/Movie.java | 2 -- .../com/baeldung/server/MovieCrudService.java | 17 ++++------- .../com/baeldung/server/RestEasyServices.java | 8 ----- .../src/main/resources/schema1.xsd | 29 ------------------- .../src/main/webapp/WEB-INF/web.xml | 3 -- .../java/baeldung/client/RestEasyClient.java | 7 ----- .../baeldung/server/RestEasyClientTest.java | 1 - 9 files changed, 7 insertions(+), 64 deletions(-) delete mode 100644 RestEasy Example/src/main/resources/schema1.xsd delete mode 100644 RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index 6935238d91..9c890da2b7 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -36,7 +36,7 @@ - + org.jboss.resteasy jaxrs-api @@ -101,5 +101,4 @@ - \ No newline at end of file diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 749cabc757..3c8d6abc00 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -1,7 +1,6 @@ package com.baeldung.client; import com.baeldung.model.Movie; - import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 76e84a6378..7590f10487 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -1,11 +1,9 @@ - package com.baeldung.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; - @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "movie", propOrder = { "actors", diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 29226aa0e0..bbb3b1e953 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -1,7 +1,6 @@ package com.baeldung.server; import com.baeldung.model.Movie; - import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -11,23 +10,21 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; - @Path("/movies") public class MovieCrudService { - private Map inventory = new HashMap(); @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbId") String imdbID){ + public Movie movieByImdbId(@QueryParam("imdbId") String imdbId){ System.out.println("*** Calling getinfo for a given ImdbID***"); - if(inventory.containsKey(imdbID)){ - return inventory.get(imdbID); + if(inventory.containsKey(imdbId)){ + return inventory.get(imdbId); }else return null; } @@ -70,16 +67,16 @@ public class MovieCrudService { @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbId") String imdbID){ + public Response deleteMovie(@QueryParam("imdbId") String imdbId){ System.out.println("*** Calling deleteMovie ***"); - if (null==inventory.get(imdbID)){ + if (null==inventory.get(imdbId)){ return Response.status(Response.Status.NOT_FOUND) .entity("Movie is not in the database.\nUnable to Delete").build(); } - inventory.remove(imdbID); + inventory.remove(imdbId); return Response.status(Response.Status.OK).build(); } @@ -93,6 +90,4 @@ public class MovieCrudService { } - - } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java index 8c57d2c9b4..7726e49f38 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java @@ -1,19 +1,11 @@ package com.baeldung.server; - import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; -import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; -/** - * Created by Admin on 29/01/2016. - */ - - - @ApplicationPath("/rest") public class RestEasyServices extends Application { diff --git a/RestEasy Example/src/main/resources/schema1.xsd b/RestEasy Example/src/main/resources/schema1.xsd deleted file mode 100644 index 0d74b7c366..0000000000 --- a/RestEasy Example/src/main/resources/schema1.xsd +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index f70fdf7975..1e7f64004d 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -5,12 +5,9 @@ RestEasy Example - resteasy.servlet.mapping.prefix /rest - - \ No newline at end of file diff --git a/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java b/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java deleted file mode 100644 index b474b3d4f8..0000000000 --- a/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java +++ /dev/null @@ -1,7 +0,0 @@ -package baeldung.client; - -/** - * Created by Admin on 29/01/2016. - */ -public class RestEasyClient { -} diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java index b6a2e2a0c1..faa39e0199 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -10,7 +10,6 @@ import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.junit.Before; import org.junit.Test; - import javax.naming.NamingException; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; From 9c60f320892dcdfe2d15b5b68332c58e103fa64a Mon Sep 17 00:00:00 2001 From: David Morley Date: Sun, 7 Feb 2016 14:54:04 -0600 Subject: [PATCH 190/309] Clean up examples for Spring Data Elasticsearch --- .../baeldung/{ => spring/data/es}/config/Config.java | 4 ++-- .../data/es/dao}/ArticleRepository.java | 4 ++-- .../baeldung/{ => spring/data/es}/model/Article.java | 2 +- .../baeldung/{ => spring/data/es}/model/Author.java | 2 +- .../data/es/repository}/ArticleRepository.java | 5 ++--- .../{ => spring/data/es}/service/ArticleService.java | 4 ++-- .../data/es}/service/ArticleServiceImpl.java | 6 +++--- .../{ => spring/data/es}/ElasticSearchTest.java | 11 +++++------ 8 files changed, 18 insertions(+), 20 deletions(-) rename spring-data-elasticsearch/src/main/java/com/baeldung/{ => spring/data/es}/config/Config.java (94%) rename spring-data-elasticsearch/src/main/java/com/baeldung/{repository => spring/data/es/dao}/ArticleRepository.java (86%) rename spring-data-elasticsearch/src/main/java/com/baeldung/{ => spring/data/es}/model/Article.java (96%) rename spring-data-elasticsearch/src/main/java/com/baeldung/{ => spring/data/es}/model/Author.java (90%) rename spring-data-elasticsearch/src/main/java/com/baeldung/{dao => spring/data/es/repository}/ArticleRepository.java (85%) rename spring-data-elasticsearch/src/main/java/com/baeldung/{ => spring/data/es}/service/ArticleService.java (82%) rename spring-data-elasticsearch/src/main/java/com/baeldung/{ => spring/data/es}/service/ArticleServiceImpl.java (89%) rename spring-data-elasticsearch/src/test/java/com/baeldung/{ => spring/data/es}/ElasticSearchTest.java (94%) diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/config/Config.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java similarity index 94% rename from spring-data-elasticsearch/src/main/java/com/baeldung/config/Config.java rename to spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java index a67ec64534..78e4083a28 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/config/Config.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java @@ -1,4 +1,4 @@ -package com.baeldung.config; +package com.baeldung.spring.data.es.config; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.node.NodeBuilder; @@ -18,7 +18,7 @@ import java.nio.file.Paths; @Configuration @EnableElasticsearchRepositories(basePackages = "com.baeldung.repository") -@ComponentScan(basePackages = {"com.baeldung.service"}) +@ComponentScan(basePackages = {"com.baeldung.spring.data.es.service"}) public class Config { private static Logger logger = LoggerFactory.getLogger(Config.class); diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/repository/ArticleRepository.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java similarity index 86% rename from spring-data-elasticsearch/src/main/java/com/baeldung/repository/ArticleRepository.java rename to spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java index 1cb74889c5..313eba5b36 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/repository/ArticleRepository.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java @@ -1,6 +1,6 @@ -package com.baeldung.repository; +package com.baeldung.spring.data.es.dao; -import com.baeldung.model.Article; +import com.baeldung.spring.data.es.model.Article; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/model/Article.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java similarity index 96% rename from spring-data-elasticsearch/src/main/java/com/baeldung/model/Article.java rename to spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java index dee1d0817e..dd472982ce 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/model/Article.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java @@ -1,4 +1,4 @@ -package com.baeldung.model; +package com.baeldung.spring.data.es.model; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/model/Author.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Author.java similarity index 90% rename from spring-data-elasticsearch/src/main/java/com/baeldung/model/Author.java rename to spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Author.java index 09239efbe5..c335c4534a 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/model/Author.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Author.java @@ -1,4 +1,4 @@ -package com.baeldung.model; +package com.baeldung.spring.data.es.model; public class Author { diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/dao/ArticleRepository.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java similarity index 85% rename from spring-data-elasticsearch/src/main/java/com/baeldung/dao/ArticleRepository.java rename to spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java index 6ed86eff9b..27628950d7 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/dao/ArticleRepository.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java @@ -1,7 +1,6 @@ -package com.baeldung.dao; +package com.baeldung.spring.data.es.repository; -import com.baeldung.model.Article; -import com.baeldung.model.Article; +import com.baeldung.spring.data.es.model.Article; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleService.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java similarity index 82% rename from spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleService.java rename to spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java index 052e22c67d..760bad4b01 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleService.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java @@ -1,6 +1,6 @@ -package com.baeldung.service; +package com.baeldung.spring.data.es.service; -import com.baeldung.model.Article; +import com.baeldung.spring.data.es.model.Article; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleServiceImpl.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java similarity index 89% rename from spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleServiceImpl.java rename to spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java index 59feb2816c..3bb6e6a0e0 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/service/ArticleServiceImpl.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java @@ -1,7 +1,7 @@ -package com.baeldung.service; +package com.baeldung.spring.data.es.service; -import com.baeldung.repository.ArticleRepository; -import com.baeldung.model.Article; +import com.baeldung.spring.data.es.repository.ArticleRepository; +import com.baeldung.spring.data.es.model.Article; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/ElasticSearchTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java similarity index 94% rename from spring-data-elasticsearch/src/test/java/com/baeldung/ElasticSearchTest.java rename to spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java index 07248149c2..34ccfd788e 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/ElasticSearchTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java @@ -1,10 +1,9 @@ -package com.baeldung; +package com.baeldung.spring.data.es; -import com.baeldung.config.Config; -import com.baeldung.model.Article; -import com.baeldung.model.Author; -import com.baeldung.service.ArticleService; -import org.elasticsearch.index.query.QueryBuilder; +import com.baeldung.spring.data.es.config.Config; +import com.baeldung.spring.data.es.model.Article; +import com.baeldung.spring.data.es.model.Author; +import com.baeldung.spring.data.es.service.ArticleService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; From 58e82f3c1f630af700aa2890a1f01835969b9667 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 11:46:02 +0200 Subject: [PATCH 191/309] Update README.md --- spring-hibernate4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-hibernate4/README.md b/spring-hibernate4/README.md index 96f8074165..acf20632fe 100644 --- a/spring-hibernate4/README.md +++ b/spring-hibernate4/README.md @@ -6,6 +6,7 @@ - [Hibernate 4 with Spring](http://www.baeldung.com/hibernate-4-spring) - [The DAO with Spring 3 and Hibernate](http://www.baeldung.com/2011/12/02/the-persistence-layer-with-spring-3-1-and-hibernate/) - [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination) +- [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort) ### Quick Start From d68375cd6da76a53a8074daf862d659da21f22bb Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 11:57:26 +0200 Subject: [PATCH 192/309] Update README.md --- httpclient/README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/httpclient/README.md b/httpclient/README.md index 529ac754f8..b9dd431500 100644 --- a/httpclient/README.md +++ b/httpclient/README.md @@ -5,12 +5,13 @@ ### Relevant Articles: -- [HttpClient 4 – Send Custom Cookie](http://www.baeldung.com/httpclient-4-cookies) -- [HttpClient 4 – Get the Status Code](http://www.baeldung.com/httpclient-status-code) -- [HttpClient 4 – Cancel / Abort Request](http://www.baeldung.com/httpclient-cancel-request) +- [HttpClient 4 – Send Custom Cookie](http://www.baeldung.com/httpclient-4-cookies) +- [HttpClient 4 – Get the Status Code](http://www.baeldung.com/httpclient-status-code) +- [HttpClient 4 – Cancel / Abort Request](http://www.baeldung.com/httpclient-cancel-request) - [HttpClient 4 Cookbook](http://www.baeldung.com/httpclient4) - [Unshorten URLs with HttpClient](http://www.baeldung.com/unshorten-url-httpclient) - [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl) -- [HttpClient 4 – Follow Redirects for POST](http://www.baeldung.com/httpclient-redirect-on-http-post) -- [HttpClient – Set Custom Header](http://www.baeldung.com/httpclient-custom-http-header) +- [HttpClient 4 – Follow Redirects for POST](http://www.baeldung.com/httpclient-redirect-on-http-post) +- [HttpClient – Set Custom Header](http://www.baeldung.com/httpclient-custom-http-header) - [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication) +- [Multipart Upload with HttpClient 4](http://www.baeldung.com/httpclient-multipart-upload) From e4e5a9e479859468c26a061711beeb3712d421f8 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 11:58:55 +0200 Subject: [PATCH 193/309] Update README.md --- spring-security-rest-full/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index 63ca8c7926..b53435a222 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -11,6 +11,7 @@ - [ETags for REST with Spring](http://www.baeldung.com/2013/01/11/etags-for-rest-with-spring/) - [Error Handling for REST with Spring 3](http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/) - [Integration Testing with the Maven Cargo plugin](http://www.baeldung.com/2011/10/16/how-to-set-up-integration-testing-with-the-maven-cargo-plugin/) +- [Introduction to Spring Data JPA](http://www.baeldung.com/2011/12/22/the-persistence-layer-with-spring-data-jpa/) ### Build the Project From 72bd9c54b9f53a8c01581cb0a6f3fd6f0a8aebe8 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:01:25 +0200 Subject: [PATCH 194/309] Update README.md --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 772681ad57..665a06a3c8 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -6,4 +6,5 @@ - [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list) - [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file) - [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string) +- [Converting between an Array and a List in Java](http://www.baeldung.com/convert-array-to-list-and-list-to-array) From ec551bfe3fc43a6aeb2c3c20adcb0c8bef125149 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:02:58 +0200 Subject: [PATCH 195/309] Update README.md --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 665a06a3c8..6aa04df33f 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -7,4 +7,5 @@ - [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file) - [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string) - [Converting between an Array and a List in Java](http://www.baeldung.com/convert-array-to-list-and-list-to-array) +- [Converting between an Array and a Set in Java](http://www.baeldung.com/convert-array-to-set-and-set-to-array) From 693081d509ac9d9cb1e991ea5e18348f4cfd1c40 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:04:32 +0200 Subject: [PATCH 196/309] Update README.md --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 6aa04df33f..a98e5524ac 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -8,4 +8,5 @@ - [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string) - [Converting between an Array and a List in Java](http://www.baeldung.com/convert-array-to-list-and-list-to-array) - [Converting between an Array and a Set in Java](http://www.baeldung.com/convert-array-to-set-and-set-to-array) +- [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list) From c5cad39354069a1888cc547c2cf5cc165b298bf3 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:07:07 +0200 Subject: [PATCH 197/309] Update README.md --- core-java/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java/README.md b/core-java/README.md index a98e5524ac..b8f63717ed 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -9,4 +9,4 @@ - [Converting between an Array and a List in Java](http://www.baeldung.com/convert-array-to-list-and-list-to-array) - [Converting between an Array and a Set in Java](http://www.baeldung.com/convert-array-to-set-and-set-to-array) - [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list) - +- [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set) From 9f9aee658f21ac127c2b1158832d7311bd1193ee Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:08:35 +0200 Subject: [PATCH 198/309] Update README.md --- spring-security-mvc-persisted-remember-me/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-mvc-persisted-remember-me/README.md b/spring-security-mvc-persisted-remember-me/README.md index 11f5417028..df83fd3d77 100644 --- a/spring-security-mvc-persisted-remember-me/README.md +++ b/spring-security-mvc-persisted-remember-me/README.md @@ -4,7 +4,7 @@ ### Relevant Articles: -- [Spring Security Persisted Remember Me] +- [Spring Security Persisted Remember Me](http://www.baeldung.com/spring-security-persistent-remember-me) - [Spring Security Remember Me](http://www.baeldung.com/spring-security-remember-me) - [Redirect to different pages after Login with Spring Security](http://www.baeldung.com/spring_redirect_after_login) From 7bc00c24b721a406a3434964b803f835335a4e43 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:13:41 +0200 Subject: [PATCH 199/309] Update README.md --- spring-security-rest-full/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index b53435a222..cffbcf40f0 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -12,6 +12,7 @@ - [Error Handling for REST with Spring 3](http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/) - [Integration Testing with the Maven Cargo plugin](http://www.baeldung.com/2011/10/16/how-to-set-up-integration-testing-with-the-maven-cargo-plugin/) - [Introduction to Spring Data JPA](http://www.baeldung.com/2011/12/22/the-persistence-layer-with-spring-data-jpa/) +- [Project Configuration with Spring](http://www.baeldung.com/2012/03/12/project-configuration-with-spring/) ### Build the Project From dfc7b2113d40bf7c5a350027473f88ea6a51245a Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:14:54 +0200 Subject: [PATCH 200/309] Update README.md --- spring-mvc-xml/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 908e21d4bf..2409ec8174 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -7,3 +7,4 @@ ### Relevant Articles: - [Spring MVC Tutorial](http://www.baeldung.com/spring-mvc-tutorial) - [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout) +- [Basic Forms with Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial) From 550068f5a8fb8f0f02a5edeb66edd831f875ad47 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:19:34 +0200 Subject: [PATCH 201/309] Update README.md --- gson/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gson/README.md b/gson/README.md index 559e536d81..47d8ecfb39 100644 --- a/gson/README.md +++ b/gson/README.md @@ -2,5 +2,6 @@ ## GSON Cookbooks and Examples -### Relevant Articles: +### Relevant Articles: +-[Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide) From adc258155690a4d45e0ffd9c238cbf89081c8f29 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:20:01 +0200 Subject: [PATCH 202/309] Update README.md --- gson/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gson/README.md b/gson/README.md index 47d8ecfb39..67651b732e 100644 --- a/gson/README.md +++ b/gson/README.md @@ -4,4 +4,4 @@ ### Relevant Articles: --[Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide) +- [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide) From d33f16a68d762b189c4ea17fc2199ddacb748b81 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:21:29 +0200 Subject: [PATCH 203/309] Update README.md --- spring-security-login-and-registration/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-login-and-registration/README.md b/spring-security-login-and-registration/README.md index 1c5b16d6f6..1638e82756 100644 --- a/spring-security-login-and-registration/README.md +++ b/spring-security-login-and-registration/README.md @@ -5,6 +5,7 @@ ### Relevant Articles: - [Spring Security Registration Tutorial](http://www.baeldung.com/spring-security-registration) +- [The Registration Process With Spring Security](http://www.baeldung.com/registration-with-spring-mvc-and-spring-security) From 28bddf2d8ebde5847c9f7f0cda79b7f9a24db63d Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:22:55 +0200 Subject: [PATCH 204/309] Update README.md --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index b8f63717ed..6db2b370f6 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -10,3 +10,4 @@ - [Converting between an Array and a Set in Java](http://www.baeldung.com/convert-array-to-set-and-set-to-array) - [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list) - [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set) +- [Java – Write to File](http://www.baeldung.com/java-write-to-file) From 1d24669cbb35963cc06791a3156613cb7ada28c4 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:26:06 +0200 Subject: [PATCH 205/309] Update README.md --- guava/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/guava/README.md b/guava/README.md index 8960b4676e..948087ff1e 100644 --- a/guava/README.md +++ b/guava/README.md @@ -7,7 +7,6 @@ - [Guava Collections Cookbook](http://www.baeldung.com/guava-collections) - [Guava Ordering Cookbook](http://www.baeldung.com/guava-order) - [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates) - - [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays) - - [Partition a List in Java](http://www.baeldung.com/java-list-split) +- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection) From 20d79082dd70ddf6118e0e0bf2155ef6821371d4 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:28:15 +0200 Subject: [PATCH 206/309] Update README.md --- guava/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/guava/README.md b/guava/README.md index 948087ff1e..86771a740c 100644 --- a/guava/README.md +++ b/guava/README.md @@ -10,3 +10,4 @@ - [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays) - [Partition a List in Java](http://www.baeldung.com/java-list-split) - [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection) +- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial) From d8bb9affec51c483f021dd8564eb6597e4952b33 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:29:23 +0200 Subject: [PATCH 207/309] Update README.md --- guava/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/guava/README.md b/guava/README.md index 86771a740c..43acf04bd1 100644 --- a/guava/README.md +++ b/guava/README.md @@ -11,3 +11,4 @@ - [Partition a List in Java](http://www.baeldung.com/java-list-split) - [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection) - [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial) +- [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file) From c2a226141b750871e580b8e77f25561e7456b6eb Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:33:13 +0200 Subject: [PATCH 208/309] Update README.md --- guava/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/guava/README.md b/guava/README.md index 43acf04bd1..dfffe8bc07 100644 --- a/guava/README.md +++ b/guava/README.md @@ -12,3 +12,4 @@ - [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection) - [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial) - [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file) +- [Guava – Lists](http://www.baeldung.com/guava-lists) From 30b74f9d04a3614061c4c13748a91fa4fae3c564 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:34:20 +0200 Subject: [PATCH 209/309] Update README.md --- guava/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/guava/README.md b/guava/README.md index dfffe8bc07..7fdf28033d 100644 --- a/guava/README.md +++ b/guava/README.md @@ -13,3 +13,4 @@ - [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial) - [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file) - [Guava – Lists](http://www.baeldung.com/guava-lists) +- [Guava – Sets](http://www.baeldung.com/guava-sets) From 371ebf5db18d1495ba41b0cda5f7cc96b098d496 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:35:14 +0200 Subject: [PATCH 210/309] Update README.md --- guava/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/guava/README.md b/guava/README.md index 7fdf28033d..28bcfeb912 100644 --- a/guava/README.md +++ b/guava/README.md @@ -14,3 +14,4 @@ - [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file) - [Guava – Lists](http://www.baeldung.com/guava-lists) - [Guava – Sets](http://www.baeldung.com/guava-sets) +- [Guava – Maps](http://www.baeldung.com/guava-maps) From 86ca22330b3ee915b44032a0829de436b05ced9c Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:38:54 +0200 Subject: [PATCH 211/309] Update README.md --- mockito/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mockito/README.md b/mockito/README.md index 5ecc5722b0..eb80042c4b 100644 --- a/mockito/README.md +++ b/mockito/README.md @@ -6,4 +6,4 @@ ### Relevant Articles: - [Mockito Verify Cookbook](http://www.baeldung.com/mockito-verify) - [Mockito When/Then Cookbook](http://www.baeldung.com/mockito-behavior) - +- [Mockito – Using Spies](http://www.baeldung.com/mockito-spy) From b3dff4d5de740eab323a390895a66d5c8fb2eb32 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:40:40 +0200 Subject: [PATCH 212/309] Update README.md --- spring-all/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-all/README.md b/spring-all/README.md index 4a3bd25077..baab7ec083 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -6,4 +6,5 @@ This project is used to replicate Spring Exceptions only. ### Relevant articles: -- [Properties with Spring](http://www.baeldung.com/2012/02/06/properties-with-spring) - checkout the `org.baeldung.properties` package for all scenarios of properties injection and usage \ No newline at end of file +- [Properties with Spring](http://www.baeldung.com/2012/02/06/properties-with-spring) - checkout the `org.baeldung.properties` package for all scenarios of properties injection and usage +- [Spring Profiles](http://www.baeldung.com/spring-profiles) From 731c0803c4e5833c619ea40aa1f78e8f1f86f87a Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:42:32 +0200 Subject: [PATCH 213/309] Update README.md --- mockito/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/mockito/README.md b/mockito/README.md index eb80042c4b..5e7cd19f78 100644 --- a/mockito/README.md +++ b/mockito/README.md @@ -7,3 +7,4 @@ - [Mockito Verify Cookbook](http://www.baeldung.com/mockito-verify) - [Mockito When/Then Cookbook](http://www.baeldung.com/mockito-behavior) - [Mockito – Using Spies](http://www.baeldung.com/mockito-spy) +- [Mockito – @Mock, @Spy, @Captor and @InjectMocks](http://www.baeldung.com/mockito-annotations) From cfc4d69a88218b4a44db4a52fb2d1c23963c6641 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:44:18 +0200 Subject: [PATCH 214/309] Update README.md --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 6db2b370f6..9a7c0d3776 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -11,3 +11,4 @@ - [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list) - [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set) - [Java – Write to File](http://www.baeldung.com/java-write-to-file) +- [Java Scanner](http://www.baeldung.com/java-scanner) From 32f6d8ab6c4776853fd3bc29c5a334fd5bd481ca Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:45:35 +0200 Subject: [PATCH 215/309] Update README.md --- httpclient/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/httpclient/README.md b/httpclient/README.md index b9dd431500..1cf788287c 100644 --- a/httpclient/README.md +++ b/httpclient/README.md @@ -15,3 +15,4 @@ - [HttpClient – Set Custom Header](http://www.baeldung.com/httpclient-custom-http-header) - [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication) - [Multipart Upload with HttpClient 4](http://www.baeldung.com/httpclient-multipart-upload) +- [HttpAsyncClient Tutorial](http://www.baeldung.com/httpasyncclient-tutorial) From e2de29e24ba0c8b422d0a4ad9c50658898b10b6e Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:47:00 +0200 Subject: [PATCH 216/309] Update README.md --- core-java-8/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-8/README.md b/core-java-8/README.md index 9bb6bb811c..f957b90799 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -3,4 +3,5 @@ ## Core Java 8 Cookbooks and Examples ### Relevant Articles: -// - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) +// - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) +// - [Java – Directory Size](http://www.baeldung.com/java-folder-size) From 68aa809456ac772c98b0da813400d346926b9fd8 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:47:21 +0200 Subject: [PATCH 217/309] Update README.md --- core-java-8/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-8/README.md b/core-java-8/README.md index f957b90799..e3fa3f9848 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -4,4 +4,4 @@ ### Relevant Articles: // - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) -// - [Java – Directory Size](http://www.baeldung.com/java-folder-size) +- [Java – Directory Size](http://www.baeldung.com/java-folder-size) From a8165f78fece34a7c572208f65497dda37c4473b Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:48:14 +0200 Subject: [PATCH 218/309] Update README.md --- core-java-8/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-8/README.md b/core-java-8/README.md index e3fa3f9848..f957b90799 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -4,4 +4,4 @@ ### Relevant Articles: // - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) -- [Java – Directory Size](http://www.baeldung.com/java-folder-size) +// - [Java – Directory Size](http://www.baeldung.com/java-folder-size) From 06f00f1cb166492332794ce4aabd1fd1a7521b33 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:48:29 +0200 Subject: [PATCH 219/309] Update README.md --- core-java-8/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-8/README.md b/core-java-8/README.md index f957b90799..e3fa3f9848 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -4,4 +4,4 @@ ### Relevant Articles: // - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) -// - [Java – Directory Size](http://www.baeldung.com/java-folder-size) +- [Java – Directory Size](http://www.baeldung.com/java-folder-size) From d9f9436f758683edd57b5d54b9b1605c964fc9b8 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:50:49 +0200 Subject: [PATCH 220/309] Update README.md --- spring-security-login-and-registration/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-login-and-registration/README.md b/spring-security-login-and-registration/README.md index 1638e82756..a5a9701ff8 100644 --- a/spring-security-login-and-registration/README.md +++ b/spring-security-login-and-registration/README.md @@ -6,7 +6,7 @@ ### Relevant Articles: - [Spring Security Registration Tutorial](http://www.baeldung.com/spring-security-registration) - [The Registration Process With Spring Security](http://www.baeldung.com/registration-with-spring-mvc-and-spring-security) - +- [Registration – Activate a New Account by Email](http://www.baeldung.com/registration-verify-user-by-email) ### Build the Project From d12e115d0bf5cf9736f8aef516c42adbe51a0f28 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:53:05 +0200 Subject: [PATCH 221/309] Update README.md --- jackson/README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/jackson/README.md b/jackson/README.md index 539cb34761..bb19fc7f77 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -4,9 +4,8 @@ ### Relevant Articles: - [Jackson Ignore Properties on Marshalling](http://www.baeldung.com/jackson-ignore-properties-on-serialization) -- [Jackson – Unmarshall to Collection/Array](http://www.baeldung.com/jackson-collection-array) +- [Jackson – Unmarshall to Collection/Array](http://www.baeldung.com/jackson-collection-array) - [Jackson Unmarshalling json with Unknown Properties](http://www.baeldung.com/jackson-deserialize-json-unknown-properties) -- [Jackson – Custom Serializer](http://www.baeldung.com/jackson-custom-serialization) -- [Jackson – Custom Deserializer](http://www.baeldung.com/jackson-deserialization) - - +- [Jackson – Custom Serializer](http://www.baeldung.com/jackson-custom-serialization) +- [Jackson – Custom Deserializer](http://www.baeldung.com/jackson-deserialization) +- [Jackson Exceptions – Problems and Solutions](http://www.baeldung.com/jackson-exception) From 9877e0008b0f1b7ea2fea271e9c5f661985e86dd Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Mon, 8 Feb 2016 12:54:36 +0200 Subject: [PATCH 222/309] Update README.md --- jackson/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jackson/README.md b/jackson/README.md index bb19fc7f77..046c6b6cfb 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -9,3 +9,4 @@ - [Jackson – Custom Serializer](http://www.baeldung.com/jackson-custom-serialization) - [Jackson – Custom Deserializer](http://www.baeldung.com/jackson-deserialization) - [Jackson Exceptions – Problems and Solutions](http://www.baeldung.com/jackson-exception) +- [Jackson Date](http://www.baeldung.com/jackson-serialize-dates) From c3ef41a10ddf15cc2e919272334fe666579863da Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Mon, 8 Feb 2016 14:00:11 +0100 Subject: [PATCH 223/309] CleanUp and reformatting Code; dependency fix in pom.xml --- RestEasy Example/pom.xml | 147 +++++++----------- .../baeldung/client/ServicesInterface.java | 15 +- .../main/java/com/baeldung/model/Movie.java | 56 ++----- .../com/baeldung/server/MovieCrudService.java | 49 +++--- .../WEB-INF/jboss-deployment-structure.xml | 22 +-- .../src/main/webapp/WEB-INF/web.xml | 14 +- .../baeldung/server/RestEasyClientTest.java | 23 ++- .../com/baeldung/server/movies/batman.json | 2 +- .../baeldung/server/movies/transformer.json | 2 +- 9 files changed, 125 insertions(+), 205 deletions(-) diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index 9c890da2b7..ec9e87b0d1 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -1,104 +1,77 @@ - - 4.0.0 + + 4.0.0 - com.baeldung - resteasy-tutorial - 1.0 - war + com.baeldung + resteasy-tutorial + 1.0 + war - - - jboss - http://repository.jboss.org/nexus/content/groups/public/ - - + + 3.0.14.Final + - - 3.0.14.Final - runtime - + + RestEasyTutorial + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + - - RestEasyTutorial - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - + - + - - org.jboss.resteasy - jaxrs-api - 3.0.12.Final - ${resteasy.scope} - - - - org.jboss.resteasy - resteasy-servlet-initializer - ${resteasy.version} - ${resteasy.scope} - - - jboss-jaxrs-api_2.0_spec - org.jboss.spec.javax.ws.rs - - - - - - org.jboss.resteasy - resteasy-client - ${resteasy.version} - ${resteasy.scope} - + + org.jboss.resteasy + resteasy-servlet-initializer + ${resteasy.version} + - - javax.ws.rs - javax.ws.rs-api - 2.0.1 - + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + - - org.jboss.resteasy - resteasy-jackson-provider - ${resteasy.version} - ${resteasy.scope} - + - - org.jboss.resteasy - resteasy-jaxb-provider - ${resteasy.version} - ${resteasy.scope} - + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy.version} + - + + org.jboss.resteasy + resteasy-jackson-provider + ${resteasy.version} + - - junit - junit - 4.4 - + - - commons-io - commons-io - 2.4 - + + junit + junit + 4.4 + + + + commons-io + commons-io + 2.4 + + + - \ No newline at end of file diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 3c8d6abc00..3d03c16faf 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -9,35 +9,28 @@ import java.util.List; @Path("/movies") public interface ServicesInterface { - @GET @Path("/getinfo") - @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Movie movieByImdbId(@QueryParam("imdbId") String imdbId); - @GET @Path("/listmovies") - @Produces({"application/json"}) + @Produces({ "application/json" }) List listMovies(); - @POST @Path("/addmovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Response addMovie(Movie movie); - @PUT @Path("/updatemovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Response updateMovie(Movie movie); - @DELETE @Path("/deletemovie") Response deleteMovie(@QueryParam("imdbId") String imdbID); - - } diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 7590f10487..5aade4591a 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -5,28 +5,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "movie", propOrder = { - "actors", - "awards", - "country", - "director", - "genre", - "imdbId", - "imdbRating", - "imdbVotes", - "language", - "metascore", - "plot", - "poster", - "rated", - "released", - "response", - "runtime", - "title", - "type", - "writer", - "year" -}) +@XmlType(name = "movie", propOrder = { "actors", "awards", "country", "director", "genre", "imdbId", "imdbRating", "imdbVotes", "language", "metascore", "plot", "poster", "rated", "released", "response", "runtime", "title", "type", "writer", "year" }) public class Movie { protected String actors; @@ -212,37 +191,22 @@ public class Movie { @Override public String toString() { - return "Movie{" + - "actors='" + actors + '\'' + - ", awards='" + awards + '\'' + - ", country='" + country + '\'' + - ", director='" + director + '\'' + - ", genre='" + genre + '\'' + - ", imdbId='" + imdbId + '\'' + - ", imdbRating='" + imdbRating + '\'' + - ", imdbVotes='" + imdbVotes + '\'' + - ", language='" + language + '\'' + - ", metascore='" + metascore + '\'' + - ", poster='" + poster + '\'' + - ", rated='" + rated + '\'' + - ", released='" + released + '\'' + - ", response='" + response + '\'' + - ", runtime='" + runtime + '\'' + - ", title='" + title + '\'' + - ", type='" + type + '\'' + - ", writer='" + writer + '\'' + - ", year='" + year + '\'' + - '}'; + return "Movie{" + "actors='" + actors + '\'' + ", awards='" + awards + '\'' + ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + ", imdbId='" + imdbId + '\'' + ", imdbRating='" + imdbRating + '\'' + + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + ", metascore='" + metascore + '\'' + ", poster='" + poster + '\'' + ", rated='" + rated + '\'' + ", released='" + released + '\'' + ", response='" + response + '\'' + + ", runtime='" + runtime + '\'' + ", title='" + title + '\'' + ", type='" + type + '\'' + ", writer='" + writer + '\'' + ", year='" + year + '\'' + '}'; } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Movie movie = (Movie) o; - if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; + if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) + return false; return title != null ? title.equals(movie.title) : movie.title == null; } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index bbb3b1e953..6a0699874a 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -13,78 +13,71 @@ import java.util.stream.Collectors; @Path("/movies") public class MovieCrudService { - private Map inventory = new HashMap(); - + private Map inventory = new HashMap(); @GET @Path("/getinfo") - @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbId(@QueryParam("imdbId") String imdbId){ + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Movie movieByImdbId(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling getinfo for a given ImdbID***"); - if(inventory.containsKey(imdbId)){ + if (inventory.containsKey(imdbId)) { return inventory.get(imdbId); - }else return null; + } else + return null; } - @POST @Path("/addmovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Response addMovie(Movie movie){ + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Response addMovie(Movie movie) { System.out.println("*** Calling addMovie ***"); - if (null!=inventory.get(movie.getImdbId())){ - return Response.status(Response.Status.NOT_MODIFIED) - .entity("Movie is Already in the database.").build(); + if (null != inventory.get(movie.getImdbId())) { + return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is Already in the database.").build(); } - inventory.put(movie.getImdbId(),movie); + inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.CREATED).build(); } - @PUT @Path("/updatemovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Response updateMovie(Movie movie){ + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Response updateMovie(Movie movie) { System.out.println("*** Calling updateMovie ***"); - if (null==inventory.get(movie.getImdbId())){ - return Response.status(Response.Status.NOT_MODIFIED) - .entity("Movie is not in the database.\nUnable to Update").build(); + if (null == inventory.get(movie.getImdbId())) { + return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is not in the database.\nUnable to Update").build(); } - inventory.put(movie.getImdbId(),movie); + inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.OK).build(); } - @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbId") String imdbId){ + public Response deleteMovie(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling deleteMovie ***"); - if (null==inventory.get(imdbId)){ - return Response.status(Response.Status.NOT_FOUND) - .entity("Movie is not in the database.\nUnable to Delete").build(); + if (null == inventory.get(imdbId)) { + return Response.status(Response.Status.NOT_FOUND).entity("Movie is not in the database.\nUnable to Delete").build(); } inventory.remove(imdbId); return Response.status(Response.Status.OK).build(); } - @GET @Path("/listmovies") - @Produces({"application/json"}) - public List listMovies(){ + @Produces({ "application/json" }) + public List listMovies() { return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml index 84d75934a7..7879603d19 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -1,16 +1,16 @@ - - - - + + + + - - - - - + + + + + - - + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index 1e7f64004d..d5f00293f4 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -1,13 +1,13 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> - RestEasy Example + RestEasy Example - - resteasy.servlet.mapping.prefix - /rest - + + resteasy.servlet.mapping.prefix + /rest + \ No newline at end of file diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java index faa39e0199..3760ae2415 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -21,14 +21,14 @@ import java.util.Locale; public class RestEasyClientTest { - Movie transformerMovie=null; - Movie batmanMovie=null; - ObjectMapper jsonMapper=null; + Movie transformerMovie = null; + Movie batmanMovie = null; + ObjectMapper jsonMapper = null; @Before public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); jsonMapper.setDateFormat(sdf); @@ -69,7 +69,7 @@ public class RestEasyClientTest { @Test public void testMovieByImdbId() { - String transformerImdbId="tt0418279"; + String transformerImdbId = "tt0418279"; ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); @@ -82,7 +82,6 @@ public class RestEasyClientTest { System.out.println(movies); } - @Test public void testAddMovie() { @@ -99,10 +98,9 @@ public class RestEasyClientTest { } moviesResponse.close(); - System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); } - @Test public void testDeleteMovi1e() { @@ -116,14 +114,13 @@ public class RestEasyClientTest { if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); + throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); - System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); } - @Test public void testUpdateMovie() { @@ -137,11 +134,11 @@ public class RestEasyClientTest { moviesResponse = simple.updateMovie(batmanMovie); if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); - System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); } } \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json index 28061d5bf9..173901c948 100644 --- a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json @@ -16,7 +16,7 @@ "metascore": "66", "imdbRating": "7.6", "imdbVotes": "256,000", - "imdbID": "tt0096895", + "imdbId": "tt0096895", "type": "movie", "response": "True" } \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json index a3b033a8ba..a4fd061a82 100644 --- a/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json @@ -16,7 +16,7 @@ "metascore": "61", "imdbRating": "7.1", "imdbVotes": "492,225", - "imdbID": "tt0418279", + "imdbId": "tt0418279", "type": "movie", "response": "True" } \ No newline at end of file From d362112a31f1c283556f94f2a470eed1053dbdd6 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Mon, 8 Feb 2016 16:08:15 +0100 Subject: [PATCH 224/309] CleanUp and reformatting Code. --- .../src/main/java/com/baeldung/server/MovieCrudService.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 6a0699874a..b7f3215f3f 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -26,7 +26,6 @@ public class MovieCrudService { return inventory.get(imdbId); } else return null; - } @POST @@ -41,7 +40,6 @@ public class MovieCrudService { } inventory.put(movie.getImdbId(), movie); - return Response.status(Response.Status.CREATED).build(); } @@ -55,9 +53,9 @@ public class MovieCrudService { if (null == inventory.get(movie.getImdbId())) { return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is not in the database.\nUnable to Update").build(); } + inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.OK).build(); - } @DELETE @@ -80,7 +78,6 @@ public class MovieCrudService { public List listMovies() { return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); - } } From ae772727ce8e66289c6e883c22335d17fbdbdc43 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sat, 30 Jan 2016 17:48:56 +0100 Subject: [PATCH 225/309] RestEasy Tutorial, CRUD Services example --- RestEasy Example/pom.xml | 91 +++ .../src/main/java/com/baeldung/Movie.java | 535 ++++++++++++++++++ .../baeldung/client/ServicesInterface.java | 44 ++ .../server/service/MovieCrudService.java | 94 +++ .../server/service/RestEasyServices.java | 40 ++ .../src/main/resources/schema1.xsd | 29 + .../main/webapp/WEB-INF/classes/logback.xml | 3 + .../WEB-INF/jboss-deployment-structure.xml | 16 + .../src/main/webapp/WEB-INF/jboss-web.xml | 4 + .../src/main/webapp/WEB-INF/web.xml | 51 ++ .../com/baeldung/server/RestEasyClient.java | 50 ++ .../resources/server/movies/transformer.json | 22 + 12 files changed, 979 insertions(+) create mode 100644 RestEasy Example/pom.xml create mode 100644 RestEasy Example/src/main/java/com/baeldung/Movie.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java create mode 100644 RestEasy Example/src/main/resources/schema1.xsd create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/web.xml create mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java create mode 100644 RestEasy Example/src/test/resources/server/movies/transformer.json diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml new file mode 100644 index 0000000000..b16c5e8267 --- /dev/null +++ b/RestEasy Example/pom.xml @@ -0,0 +1,91 @@ + + + 4.0.0 + + com.baeldung + resteasy-tutorial + 1.0 + war + + + + jboss + http://repository.jboss.org/nexus/content/groups/public/ + + + + + 3.0.14.Final + runtime + + + + RestEasyTutorial + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + + org.jboss.resteasy + jaxrs-api + 3.0.12.Final + ${resteasy.scope} + + + + org.jboss.resteasy + resteasy-servlet-initializer + ${resteasy.version} + ${resteasy.scope} + + + jboss-jaxrs-api_2.0_spec + org.jboss.spec.javax.ws.rs + + + + + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + ${resteasy.scope} + + + + + javax.ws.rs + javax.ws.rs-api + 2.0.1 + + + + org.jboss.resteasy + resteasy-jackson-provider + ${resteasy.version} + ${resteasy.scope} + + + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy.version} + ${resteasy.scope} + + + + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/Movie.java new file mode 100644 index 0000000000..c0041d2e95 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/Movie.java @@ -0,0 +1,535 @@ + +package com.baeldung; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; + + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "movie", propOrder = { + "actors", + "awards", + "country", + "director", + "genre", + "imdbID", + "imdbRating", + "imdbVotes", + "language", + "metascore", + "plot", + "poster", + "rated", + "released", + "response", + "runtime", + "title", + "type", + "writer", + "year" +}) +public class Movie { + + protected String actors; + protected String awards; + protected String country; + protected String director; + protected String genre; + protected String imdbID; + protected String imdbRating; + protected String imdbVotes; + protected String language; + protected String metascore; + protected String plot; + protected String poster; + protected String rated; + protected String released; + protected String response; + protected String runtime; + protected String title; + protected String type; + protected String writer; + protected String year; + + /** + * Recupera il valore della propriet� actors. + * + * @return + * possible object is + * {@link String } + * + */ + public String getActors() { + return actors; + } + + /** + * Imposta il valore della propriet� actors. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setActors(String value) { + this.actors = value; + } + + /** + * Recupera il valore della propriet� awards. + * + * @return + * possible object is + * {@link String } + * + */ + public String getAwards() { + return awards; + } + + /** + * Imposta il valore della propriet� awards. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setAwards(String value) { + this.awards = value; + } + + /** + * Recupera il valore della propriet� country. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCountry() { + return country; + } + + /** + * Imposta il valore della propriet� country. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCountry(String value) { + this.country = value; + } + + /** + * Recupera il valore della propriet� director. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDirector() { + return director; + } + + /** + * Imposta il valore della propriet� director. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDirector(String value) { + this.director = value; + } + + /** + * Recupera il valore della propriet� genre. + * + * @return + * possible object is + * {@link String } + * + */ + public String getGenre() { + return genre; + } + + /** + * Imposta il valore della propriet� genre. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setGenre(String value) { + this.genre = value; + } + + /** + * Recupera il valore della propriet� imdbID. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbID() { + return imdbID; + } + + /** + * Imposta il valore della propriet� imdbID. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbID(String value) { + this.imdbID = value; + } + + /** + * Recupera il valore della propriet� imdbRating. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbRating() { + return imdbRating; + } + + /** + * Imposta il valore della propriet� imdbRating. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbRating(String value) { + this.imdbRating = value; + } + + /** + * Recupera il valore della propriet� imdbVotes. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbVotes() { + return imdbVotes; + } + + /** + * Imposta il valore della propriet� imdbVotes. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbVotes(String value) { + this.imdbVotes = value; + } + + /** + * Recupera il valore della propriet� language. + * + * @return + * possible object is + * {@link String } + * + */ + public String getLanguage() { + return language; + } + + /** + * Imposta il valore della propriet� language. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setLanguage(String value) { + this.language = value; + } + + /** + * Recupera il valore della propriet� metascore. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMetascore() { + return metascore; + } + + /** + * Imposta il valore della propriet� metascore. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMetascore(String value) { + this.metascore = value; + } + + /** + * Recupera il valore della propriet� plot. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPlot() { + return plot; + } + + /** + * Imposta il valore della propriet� plot. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPlot(String value) { + this.plot = value; + } + + /** + * Recupera il valore della propriet� poster. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPoster() { + return poster; + } + + /** + * Imposta il valore della propriet� poster. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPoster(String value) { + this.poster = value; + } + + /** + * Recupera il valore della propriet� rated. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRated() { + return rated; + } + + /** + * Imposta il valore della propriet� rated. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRated(String value) { + this.rated = value; + } + + /** + * Recupera il valore della propriet� released. + * + * @return + * possible object is + * {@link String } + * + */ + public String getReleased() { + return released; + } + + /** + * Imposta il valore della propriet� released. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setReleased(String value) { + this.released = value; + } + + /** + * Recupera il valore della propriet� response. + * + * @return + * possible object is + * {@link String } + * + */ + public String getResponse() { + return response; + } + + /** + * Imposta il valore della propriet� response. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setResponse(String value) { + this.response = value; + } + + /** + * Recupera il valore della propriet� runtime. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRuntime() { + return runtime; + } + + /** + * Imposta il valore della propriet� runtime. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRuntime(String value) { + this.runtime = value; + } + + /** + * Recupera il valore della propriet� title. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTitle() { + return title; + } + + /** + * Imposta il valore della propriet� title. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTitle(String value) { + this.title = value; + } + + /** + * Recupera il valore della propriet� type. + * + * @return + * possible object is + * {@link String } + * + */ + public String getType() { + return type; + } + + /** + * Imposta il valore della propriet� type. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setType(String value) { + this.type = value; + } + + /** + * Recupera il valore della propriet� writer. + * + * @return + * possible object is + * {@link String } + * + */ + public String getWriter() { + return writer; + } + + /** + * Imposta il valore della propriet� writer. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setWriter(String value) { + this.writer = value; + } + + /** + * Recupera il valore della propriet� year. + * + * @return + * possible object is + * {@link String } + * + */ + public String getYear() { + return year; + } + + /** + * Imposta il valore della propriet� year. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setYear(String value) { + this.year = value; + } + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java new file mode 100644 index 0000000000..53e88961be --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -0,0 +1,44 @@ +package com.baeldung.client; + +import com.baeldung.Movie; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + + +public interface ServicesInterface { + + + @GET + @Path("/getinfo") + @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + Movie movieByImdbID(@QueryParam("imdbID") String imdbID); + + + @POST + @Path("/addmovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + Response addMovie(Movie movie); + + + @PUT + @Path("/updatemovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + Response updateMovie(Movie movie); + + + @DELETE + @Path("/deletemovie") + Response deleteMovie(@QueryParam("imdbID") String imdbID); + + + @GET + @Path("/listmovies") + @Produces({"application/json"}) + List listMovies(); + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java new file mode 100644 index 0000000000..d1973e7037 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java @@ -0,0 +1,94 @@ +package com.baeldung.server.service; + +import com.baeldung.Movie; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + + +@Path("/movies") +public class MovieCrudService { + + + private Map inventory = new HashMap(); + + @GET + @Path("/getinfo") + @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ + + System.out.println("*** Calling getinfo ***"); + + Movie movie=new Movie(); + movie.setImdbID(imdbID); + return movie; + } + + @POST + @Path("/addmovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Response addMovie(Movie movie){ + + System.out.println("*** Calling addMovie ***"); + + if (null!=inventory.get(movie.getImdbID())){ + return Response.status(Response.Status.NOT_MODIFIED) + .entity("Movie is Already in the database.").build(); + } + inventory.put(movie.getImdbID(),movie); + + return Response.status(Response.Status.CREATED).build(); + } + + + @PUT + @Path("/updatemovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Response updateMovie(Movie movie){ + + System.out.println("*** Calling updateMovie ***"); + + if (null!=inventory.get(movie.getImdbID())){ + return Response.status(Response.Status.NOT_MODIFIED) + .entity("Movie is not in the database.\nUnable to Update").build(); + } + inventory.put(movie.getImdbID(),movie); + return Response.status(Response.Status.OK).build(); + + } + + + @DELETE + @Path("/deletemovie") + public Response deleteMovie(@QueryParam("imdbID") String imdbID){ + + System.out.println("*** Calling deleteMovie ***"); + + if (null==inventory.get(imdbID)){ + return Response.status(Response.Status.NOT_FOUND) + .entity("Movie is not in the database.\nUnable to Delete").build(); + } + + inventory.remove(imdbID); + return Response.status(Response.Status.OK).build(); + } + + @GET + @Path("/listmovies") + @Produces({"application/json"}) + public List listMovies(){ + + return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); + + } + + + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java new file mode 100644 index 0000000000..16b6200ad1 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java @@ -0,0 +1,40 @@ +package com.baeldung.server.service; + + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Created by Admin on 29/01/2016. + */ + + + +@ApplicationPath("/rest") +public class RestEasyServices extends Application { + + private Set singletons = new HashSet(); + + public RestEasyServices() { + singletons.add(new MovieCrudService()); + } + + @Override + public Set getSingletons() { + return singletons; + } + + @Override + public Set> getClasses() { + return super.getClasses(); + } + + @Override + public Map getProperties() { + return super.getProperties(); + } +} diff --git a/RestEasy Example/src/main/resources/schema1.xsd b/RestEasy Example/src/main/resources/schema1.xsd new file mode 100644 index 0000000000..0d74b7c366 --- /dev/null +++ b/RestEasy Example/src/main/resources/schema1.xsd @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml b/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml new file mode 100644 index 0000000000..d94e9f71ab --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml new file mode 100644 index 0000000000..84d75934a7 --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml new file mode 100644 index 0000000000..694bb71332 --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..c66d3b56ae --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,51 @@ + + + + RestEasy Example + + + + org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap + + + + RestEasy Example + + + webAppRootKey + RestEasyExample + + + + + + resteasy.servlet.mapping.prefix + /rest + + + + + resteasy-servlet + + org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher + + + javax.ws.rs.Application + com.baeldung.server.service.RestEasyServices + + + + + resteasy-servlet + /rest/* + + + + + index.html + + + + \ No newline at end of file diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java new file mode 100644 index 0000000000..e711233979 --- /dev/null +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java @@ -0,0 +1,50 @@ +package com.baeldung.server; + +import com.baeldung.Movie; +import com.baeldung.client.ServicesInterface; +import org.jboss.resteasy.client.jaxrs.ResteasyClient; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; + +import java.util.List; + +public class RestEasyClient { + + public static void main(String[] args) { + + Movie st = new Movie(); + st.setImdbID("12345"); + + /* + * Alternatively you can use this simple String to send + * instead of using a Student instance + * + * String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}"; + */ + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies"); + + ServicesInterface simple = target.proxy(ServicesInterface.class); + final List movies = simple.listMovies(); + + /* + if (response.getStatus() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + + response.getStatus()); + } + + System.out.println("Server response : \n"); + System.out.println(response.readEntity(String.class)); + + response.close(); +*/ + } catch (Exception e) { + + e.printStackTrace(); + + } + } + +} \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/server/movies/transformer.json new file mode 100644 index 0000000000..2154868265 --- /dev/null +++ b/RestEasy Example/src/test/resources/server/movies/transformer.json @@ -0,0 +1,22 @@ +{ + "title": "Transformers", + "year": "2007", + "rated": "PG-13", + "released": "03 Jul 2007", + "runtime": "144 min", + "genre": "Action, Adventure, Sci-Fi", + "director": "Michael Bay", + "writer": "Roberto Orci (screenplay), Alex Kurtzman (screenplay), John Rogers (story), Roberto Orci (story), Alex Kurtzman (story)", + "actors": "Shia LaBeouf, Megan Fox, Josh Duhamel, Tyrese Gibson", + "plot": "A long time ago, far away on the planet of Cybertron, a war is being waged between the noble Autobots (led by the wise Optimus Prime) and the devious Decepticons (commanded by the dreaded Megatron) for control over the Allspark, a mystical talisman that would grant unlimited power to whoever possesses it. The Autobots managed to smuggle the Allspark off the planet, but Megatron blasts off in search of it. He eventually tracks it to the planet of Earth (circa 1850), but his reckless desire for power sends him right into the Arctic Ocean, and the sheer cold forces him into a paralyzed state. His body is later found by Captain Archibald Witwicky, but before going into a comatose state Megatron uses the last of his energy to engrave into the Captain's glasses a map showing the location of the Allspark, and to send a transmission to Cybertron. Megatron is then carried away aboard the Captain's ship. A century later, Captain Witwicky's grandson Sam Witwicky (nicknamed Spike by his friends) buys his first car. To his shock, he discovers it to be Bumblebee, an Autobot in disguise who is to protect Spike, who possesses the Captain's glasses and the map engraved on them. But Bumblebee is not the only Transformer to have arrived on Earth - in the desert of Qatar, the Decepticons Blackout and Scorponok attack a U.S. military base, causing the Pentagon to send their special Sector Seven agents to capture all \"specimens of this alien race.\" Spike and his girlfriend Mikaela find themselves in the midst of a grand battle between the Autobots and the Decepticons, stretching from Hoover Dam all the way to Los Angeles. Meanwhile, deep inside Hoover Dam, the cryogenically stored body of Megatron awakens.", + "language": "English, Spanish", + "country": "USA", + "awards": "Nominated for 3 Oscars. Another 18 wins & 40 nominations.", + "poster": "http://ia.media-imdb.com/images/M/MV5BMTQwNjU5MzUzNl5BMl5BanBnXkFtZTYwMzc1MTI3._V1_SX300.jpg", + "metascore": "61", + "imdbRating": "7.1", + "imdbVotes": "492,225", + "imdbID": "tt0418279", + "Type": "movie", + "response": "True" +} \ No newline at end of file From 09c853477edb3a0cb0f4154b6a8c9077f877ae02 Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sat, 30 Jan 2016 20:39:28 +0100 Subject: [PATCH 226/309] Added testCase for List All Movies and Add a Movie --- RestEasy Example/pom.xml | 29 +++++ .../baeldung/client/ServicesInterface.java | 6 +- .../java/com/baeldung/{ => model}/Movie.java | 45 +++++++- .../{service => }/MovieCrudService.java | 5 +- .../{service => }/RestEasyServices.java | 2 +- .../com/baeldung/server/RestEasyClient.java | 104 ++++++++++++++---- .../com/baeldung/server/movies/batman.json | 22 ++++ .../baeldung}/server/movies/transformer.json | 2 +- 8 files changed, 184 insertions(+), 31 deletions(-) rename RestEasy Example/src/main/java/com/baeldung/{ => model}/Movie.java (86%) rename RestEasy Example/src/main/java/com/baeldung/server/{service => }/MovieCrudService.java (96%) rename RestEasy Example/src/main/java/com/baeldung/server/{service => }/RestEasyServices.java (95%) create mode 100644 RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json rename RestEasy Example/src/test/resources/{ => com/baeldung}/server/movies/transformer.json (99%) diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index b16c5e8267..8dabfc863b 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -85,6 +85,35 @@ ${resteasy.scope} + + + + junit + junit + 4.4 + + + + commons-io + commons-io + 2.4 + + + + com.fasterxml.jackson.core + jackson-core + 2.7.0 + + + + com.fasterxml.jackson.core + jackson-annotations + 2.7.0 + + + + + diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 53e88961be..2585c32438 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -1,15 +1,13 @@ package com.baeldung.client; -import com.baeldung.Movie; +import com.baeldung.model.Movie; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; - +@Path("/movies") public interface ServicesInterface { diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java similarity index 86% rename from RestEasy Example/src/main/java/com/baeldung/Movie.java rename to RestEasy Example/src/main/java/com/baeldung/model/Movie.java index c0041d2e95..052ba081c1 100644 --- a/RestEasy Example/src/main/java/com/baeldung/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -1,5 +1,5 @@ -package com.baeldung; +package com.baeldung.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -532,4 +532,47 @@ public class Movie { this.year = value; } + @Override + public String toString() { + return "Movie{" + + "actors='" + actors + '\'' + + ", awards='" + awards + '\'' + + ", country='" + country + '\'' + + ", director='" + director + '\'' + + ", genre='" + genre + '\'' + + ", imdbID='" + imdbID + '\'' + + ", imdbRating='" + imdbRating + '\'' + + ", imdbVotes='" + imdbVotes + '\'' + + ", language='" + language + '\'' + + ", metascore='" + metascore + '\'' + + ", poster='" + poster + '\'' + + ", rated='" + rated + '\'' + + ", released='" + released + '\'' + + ", response='" + response + '\'' + + ", runtime='" + runtime + '\'' + + ", title='" + title + '\'' + + ", type='" + type + '\'' + + ", writer='" + writer + '\'' + + ", year='" + year + '\'' + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Movie movie = (Movie) o; + + if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false; + return title != null ? title.equals(movie.title) : movie.title == null; + + } + + @Override + public int hashCode() { + int result = imdbID != null ? imdbID.hashCode() : 0; + result = 31 * result + (title != null ? title.hashCode() : 0); + return result; + } } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java similarity index 96% rename from RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java rename to RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index d1973e7037..60e0121966 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -1,11 +1,10 @@ -package com.baeldung.server.service; +package com.baeldung.server; -import com.baeldung.Movie; +import com.baeldung.model.Movie; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java similarity index 95% rename from RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java rename to RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java index 16b6200ad1..8c57d2c9b4 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java @@ -1,4 +1,4 @@ -package com.baeldung.server.service; +package com.baeldung.server; import javax.ws.rs.ApplicationPath; diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java index e711233979..c77f494862 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java @@ -1,49 +1,111 @@ package com.baeldung.server; -import com.baeldung.Movie; +import com.baeldung.model.Movie; import com.baeldung.client.ServicesInterface; +import org.apache.commons.io.IOUtils; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.ObjectMapper; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import javax.naming.NamingException; +import javax.ws.rs.core.Link; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Arrays; import java.util.List; +import java.util.Locale; public class RestEasyClient { - public static void main(String[] args) { - Movie st = new Movie(); - st.setImdbID("12345"); + Movie transformerMovie=null; + Movie batmanMovie=null; + ObjectMapper jsonMapper=null; - /* - * Alternatively you can use this simple String to send - * instead of using a Student instance - * - * String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}"; - */ + @BeforeClass + public static void loadMovieInventory(){ + + + + } + + @Before + public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { + + + jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + jsonMapper.setDateFormat(sdf); + + try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) { + String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) { + String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + } + + @Test + public void testListAllMovies() { try { ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies"); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + final List movies = simple.listMovies(); + System.out.println(movies); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Test + public void testAddMovie() { + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); ServicesInterface simple = target.proxy(ServicesInterface.class); - final List movies = simple.listMovies(); + final Response moviesResponse = simple.addMovie(batmanMovie); - /* - if (response.getStatus() != 200) { + if (moviesResponse.getStatus() != 201) { + System.out.println(moviesResponse.readEntity(String.class)); throw new RuntimeException("Failed : HTTP error code : " - + response.getStatus()); + + moviesResponse.getStatus()); } - System.out.println("Server response : \n"); - System.out.println(response.readEntity(String.class)); + moviesResponse.close(); - response.close(); -*/ } catch (Exception e) { - e.printStackTrace(); - } } diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json new file mode 100644 index 0000000000..28061d5bf9 --- /dev/null +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json @@ -0,0 +1,22 @@ +{ + "title": "Batman", + "year": "1989", + "rated": "PG-13", + "released": "23 Jun 1989", + "runtime": "126 min", + "genre": "Action, Adventure", + "director": "Tim Burton", + "writer": "Bob Kane (Batman characters), Sam Hamm (story), Sam Hamm (screenplay), Warren Skaaren (screenplay)", + "actors": "Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl", + "plot": "The Dark Knight of Gotham City begins his war on crime with his first major enemy being the clownishly homicidal Joker.", + "language": "English, French", + "country": "USA, UK", + "awards": "Won 1 Oscar. Another 9 wins & 22 nominations.", + "poster": "http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg", + "metascore": "66", + "imdbRating": "7.6", + "imdbVotes": "256,000", + "imdbID": "tt0096895", + "type": "movie", + "response": "True" +} \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json similarity index 99% rename from RestEasy Example/src/test/resources/server/movies/transformer.json rename to RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json index 2154868265..a3b033a8ba 100644 --- a/RestEasy Example/src/test/resources/server/movies/transformer.json +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json @@ -17,6 +17,6 @@ "imdbRating": "7.1", "imdbVotes": "492,225", "imdbID": "tt0418279", - "Type": "movie", + "type": "movie", "response": "True" } \ No newline at end of file From 6263054087798e2bf302a2f72f231616b1c5488e Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sun, 31 Jan 2016 11:05:11 +0100 Subject: [PATCH 227/309] Added testCase for all Services --- RestEasy Example/pom.xml | 15 -- .../baeldung/client/ServicesInterface.java | 10 +- .../com/baeldung/server/MovieCrudService.java | 15 +- .../src/main/webapp/WEB-INF/web.xml | 2 +- .../com/baeldung/server/RestEasyClient.java | 112 ----------- .../baeldung/server/RestEasyClientTest.java | 189 ++++++++++++++++++ 6 files changed, 206 insertions(+), 137 deletions(-) delete mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java create mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index 8dabfc863b..6935238d91 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -99,21 +99,6 @@ 2.4 - - com.fasterxml.jackson.core - jackson-core - 2.7.0 - - - - com.fasterxml.jackson.core - jackson-annotations - 2.7.0 - - - - - diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 2585c32438..7efed546d8 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -17,6 +17,12 @@ public interface ServicesInterface { Movie movieByImdbID(@QueryParam("imdbID") String imdbID); + @GET + @Path("/listmovies") + @Produces({"application/json"}) + List listMovies(); + + @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @@ -34,9 +40,5 @@ public interface ServicesInterface { Response deleteMovie(@QueryParam("imdbID") String imdbID); - @GET - @Path("/listmovies") - @Produces({"application/json"}) - List listMovies(); } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 60e0121966..18366e2faa 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -18,18 +18,21 @@ public class MovieCrudService { private Map inventory = new HashMap(); + @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ - System.out.println("*** Calling getinfo ***"); + System.out.println("*** Calling getinfo for a given ImdbID***"); + + if(inventory.containsKey(imdbID)){ + return inventory.get(imdbID); + }else return null; - Movie movie=new Movie(); - movie.setImdbID(imdbID); - return movie; } + @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @@ -41,6 +44,7 @@ public class MovieCrudService { return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } + inventory.put(movie.getImdbID(),movie); return Response.status(Response.Status.CREATED).build(); @@ -54,7 +58,7 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null!=inventory.get(movie.getImdbID())){ + if (null==inventory.get(movie.getImdbID())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } @@ -79,6 +83,7 @@ public class MovieCrudService { return Response.status(Response.Status.OK).build(); } + @GET @Path("/listmovies") @Produces({"application/json"}) diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index c66d3b56ae..ab3bc1aa83 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -33,7 +33,7 @@ javax.ws.rs.Application - com.baeldung.server.service.RestEasyServices + com.baeldung.server.RestEasyServices diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java deleted file mode 100644 index c77f494862..0000000000 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.model.Movie; -import com.baeldung.client.ServicesInterface; -import org.apache.commons.io.IOUtils; -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; -import org.jboss.resteasy.client.jaxrs.ResteasyClient; -import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; -import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import javax.naming.NamingException; -import javax.ws.rs.core.Link; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -public class RestEasyClient { - - - Movie transformerMovie=null; - Movie batmanMovie=null; - ObjectMapper jsonMapper=null; - - @BeforeClass - public static void loadMovieInventory(){ - - - - } - - @Before - public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - - - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); - jsonMapper.setDateFormat(sdf); - - try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) { - String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Test is going to die ...", e); - } - - try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) { - String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); - - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Test is going to die ...", e); - } - - } - - @Test - public void testListAllMovies() { - - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); - - final List movies = simple.listMovies(); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - @Test - public void testAddMovie() { - - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - - ServicesInterface simple = target.proxy(ServicesInterface.class); - final Response moviesResponse = simple.addMovie(batmanMovie); - - if (moviesResponse.getStatus() != 201) { - System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " - + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java new file mode 100644 index 0000000000..fb4205bcd7 --- /dev/null +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -0,0 +1,189 @@ +package com.baeldung.server; + +import com.baeldung.model.Movie; +import com.baeldung.client.ServicesInterface; +import org.apache.commons.io.IOUtils; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.ObjectMapper; +import org.jboss.resteasy.client.jaxrs.ResteasyClient; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.naming.NamingException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Locale; + +public class RestEasyClientTest { + + + Movie transformerMovie=null; + Movie batmanMovie=null; + ObjectMapper jsonMapper=null; + + @BeforeClass + public static void loadMovieInventory(){ + + + + } + + @Before + public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { + + + jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + jsonMapper.setDateFormat(sdf); + + try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/transformer.json")) { + String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/batman.json")) { + String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + } + + + @Test + public void testListAllMovies() { + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + + final List movies = simple.listMovies(); + System.out.println(movies); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testMovieByImdbID() { + + String transformerImdbId="tt0418279"; + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + + final Movie movies = simple.movieByImdbID(transformerImdbId); + System.out.println(movies); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testAddMovie() { + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(transformerMovie); + + if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { + //System.out.println(moviesResponse.readEntity(String.class)); + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + moviesResponse.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testDeleteMovie() { + + String transformerImdbId="tt0418279"; + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.deleteMovie(transformerImdbId); + moviesResponse.close(); + + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println(moviesResponse.readEntity(String.class)); + throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + + moviesResponse.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testUpdateMovie() { + + try { + + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + batmanMovie.setImdbVotes("300,000"); + moviesResponse = simple.updateMovie(batmanMovie); + + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + //System.out.println(moviesResponse.readEntity(String.class)); + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + + moviesResponse.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + +} \ No newline at end of file From c57578dba5d51ed62541518498550b6431b71cf6 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:29:30 +0100 Subject: [PATCH 228/309] Minor Bugfix --- .../baeldung/client/ServicesInterface.java | 4 +- .../main/java/com/baeldung/model/Movie.java | 22 +-- .../com/baeldung/server/MovieCrudService.java | 12 +- .../src/main/webapp/WEB-INF/web.xml | 37 +---- .../java/baeldung/client/RestEasyClient.java | 7 + .../baeldung/server/RestEasyClientTest.java | 149 +++++++----------- 6 files changed, 81 insertions(+), 150 deletions(-) create mode 100644 RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 7efed546d8..749cabc757 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -14,7 +14,7 @@ public interface ServicesInterface { @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - Movie movieByImdbID(@QueryParam("imdbID") String imdbID); + Movie movieByImdbId(@QueryParam("imdbId") String imdbId); @GET @@ -37,7 +37,7 @@ public interface ServicesInterface { @DELETE @Path("/deletemovie") - Response deleteMovie(@QueryParam("imdbID") String imdbID); + Response deleteMovie(@QueryParam("imdbId") String imdbID); diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 052ba081c1..a2b2bd5250 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -13,7 +13,7 @@ import javax.xml.bind.annotation.XmlType; "country", "director", "genre", - "imdbID", + "imdbId", "imdbRating", "imdbVotes", "language", @@ -36,7 +36,7 @@ public class Movie { protected String country; protected String director; protected String genre; - protected String imdbID; + protected String imdbId; protected String imdbRating; protected String imdbVotes; protected String language; @@ -173,27 +173,27 @@ public class Movie { } /** - * Recupera il valore della propriet� imdbID. + * Recupera il valore della propriet� imdbId. * * @return * possible object is * {@link String } * */ - public String getImdbID() { - return imdbID; + public String getImdbId() { + return imdbId; } /** - * Imposta il valore della propriet� imdbID. + * Imposta il valore della propriet� imdbId. * * @param value * allowed object is * {@link String } * */ - public void setImdbID(String value) { - this.imdbID = value; + public void setImdbId(String value) { + this.imdbId = value; } /** @@ -540,7 +540,7 @@ public class Movie { ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + - ", imdbID='" + imdbID + '\'' + + ", imdbId='" + imdbId + '\'' + ", imdbRating='" + imdbRating + '\'' + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + @@ -564,14 +564,14 @@ public class Movie { Movie movie = (Movie) o; - if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false; + if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; return title != null ? title.equals(movie.title) : movie.title == null; } @Override public int hashCode() { - int result = imdbID != null ? imdbID.hashCode() : 0; + int result = imdbId != null ? imdbId.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); return result; } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 18366e2faa..29226aa0e0 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -22,7 +22,7 @@ public class MovieCrudService { @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ + public Movie movieByImdbID(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling getinfo for a given ImdbID***"); @@ -40,12 +40,12 @@ public class MovieCrudService { System.out.println("*** Calling addMovie ***"); - if (null!=inventory.get(movie.getImdbID())){ + if (null!=inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.CREATED).build(); } @@ -58,11 +58,11 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null==inventory.get(movie.getImdbID())){ + if (null==inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.OK).build(); } @@ -70,7 +70,7 @@ public class MovieCrudService { @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbID") String imdbID){ + public Response deleteMovie(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling deleteMovie ***"); diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index ab3bc1aa83..f70fdf7975 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -5,47 +5,12 @@ RestEasy Example - - - org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap - - - - RestEasy Example - - - webAppRootKey - RestEasyExample - - - - + resteasy.servlet.mapping.prefix /rest - - resteasy-servlet - - org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher - - - javax.ws.rs.Application - com.baeldung.server.RestEasyServices - - - - - resteasy-servlet - /rest/* - - - - - index.html - - \ No newline at end of file diff --git a/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java b/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java new file mode 100644 index 0000000000..b474b3d4f8 --- /dev/null +++ b/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java @@ -0,0 +1,7 @@ +package baeldung.client; + +/** + * Created by Admin on 29/01/2016. + */ +public class RestEasyClient { +} diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java index fb4205bcd7..b6a2e2a0c1 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -1,7 +1,7 @@ package com.baeldung.server; -import com.baeldung.model.Movie; import com.baeldung.client.ServicesInterface; +import com.baeldung.model.Movie; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; @@ -9,7 +9,6 @@ import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import javax.naming.NamingException; @@ -23,22 +22,13 @@ import java.util.Locale; public class RestEasyClientTest { - Movie transformerMovie=null; Movie batmanMovie=null; ObjectMapper jsonMapper=null; - @BeforeClass - public static void loadMovieInventory(){ - - - - } - @Before public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); @@ -57,133 +47,102 @@ public class RestEasyClientTest { batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); } catch (Exception e) { - e.printStackTrace(); throw new RuntimeException("Test is going to die ...", e); } - } - @Test public void testListAllMovies() { - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(transformerMovie); - moviesResponse.close(); - moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); - final List movies = simple.listMovies(); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } + List movies = simple.listMovies(); + System.out.println(movies); } - @Test - public void testMovieByImdbID() { + public void testMovieByImdbId() { String transformerImdbId="tt0418279"; - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(transformerMovie); - moviesResponse.close(); + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); - final Movie movies = simple.movieByImdbID(transformerImdbId); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } + Movie movies = simple.movieByImdbId(transformerImdbId); + System.out.println(movies); } @Test public void testAddMovie() { - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - moviesResponse = simple.addMovie(transformerMovie); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(transformerMovie); - if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { - //System.out.println(moviesResponse.readEntity(String.class)); - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } @Test - public void testDeleteMovie() { + public void testDeleteMovi1e() { - String transformerImdbId="tt0418279"; + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.deleteMovie(batmanMovie.getImdbId()); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - moviesResponse = simple.deleteMovie(transformerImdbId); - moviesResponse.close(); - - if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println(moviesResponse.readEntity(String.class)); + throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } @Test public void testUpdateMovie() { - try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + batmanMovie.setImdbVotes("300,000"); + moviesResponse = simple.updateMovie(batmanMovie); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - batmanMovie.setImdbVotes("300,000"); - moviesResponse = simple.updateMovie(batmanMovie); - - if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - //System.out.println(moviesResponse.readEntity(String.class)); - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } } \ No newline at end of file From 9d3f34d6367e623aac467de603eba275f878e580 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sat, 30 Jan 2016 17:48:56 +0100 Subject: [PATCH 229/309] RestEasy Tutorial, CRUD Services example --- .../src/main/java/com/baeldung/Movie.java | 535 ++++++++++++++++++ .../server/service/MovieCrudService.java | 94 +++ .../server/service/RestEasyServices.java | 40 ++ .../com/baeldung/server/RestEasyClient.java | 50 ++ .../resources/server/movies/transformer.json | 22 + 5 files changed, 741 insertions(+) create mode 100644 RestEasy Example/src/main/java/com/baeldung/Movie.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java create mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java create mode 100644 RestEasy Example/src/test/resources/server/movies/transformer.json diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/Movie.java new file mode 100644 index 0000000000..c0041d2e95 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/Movie.java @@ -0,0 +1,535 @@ + +package com.baeldung; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; + + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "movie", propOrder = { + "actors", + "awards", + "country", + "director", + "genre", + "imdbID", + "imdbRating", + "imdbVotes", + "language", + "metascore", + "plot", + "poster", + "rated", + "released", + "response", + "runtime", + "title", + "type", + "writer", + "year" +}) +public class Movie { + + protected String actors; + protected String awards; + protected String country; + protected String director; + protected String genre; + protected String imdbID; + protected String imdbRating; + protected String imdbVotes; + protected String language; + protected String metascore; + protected String plot; + protected String poster; + protected String rated; + protected String released; + protected String response; + protected String runtime; + protected String title; + protected String type; + protected String writer; + protected String year; + + /** + * Recupera il valore della propriet� actors. + * + * @return + * possible object is + * {@link String } + * + */ + public String getActors() { + return actors; + } + + /** + * Imposta il valore della propriet� actors. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setActors(String value) { + this.actors = value; + } + + /** + * Recupera il valore della propriet� awards. + * + * @return + * possible object is + * {@link String } + * + */ + public String getAwards() { + return awards; + } + + /** + * Imposta il valore della propriet� awards. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setAwards(String value) { + this.awards = value; + } + + /** + * Recupera il valore della propriet� country. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCountry() { + return country; + } + + /** + * Imposta il valore della propriet� country. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCountry(String value) { + this.country = value; + } + + /** + * Recupera il valore della propriet� director. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDirector() { + return director; + } + + /** + * Imposta il valore della propriet� director. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDirector(String value) { + this.director = value; + } + + /** + * Recupera il valore della propriet� genre. + * + * @return + * possible object is + * {@link String } + * + */ + public String getGenre() { + return genre; + } + + /** + * Imposta il valore della propriet� genre. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setGenre(String value) { + this.genre = value; + } + + /** + * Recupera il valore della propriet� imdbID. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbID() { + return imdbID; + } + + /** + * Imposta il valore della propriet� imdbID. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbID(String value) { + this.imdbID = value; + } + + /** + * Recupera il valore della propriet� imdbRating. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbRating() { + return imdbRating; + } + + /** + * Imposta il valore della propriet� imdbRating. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbRating(String value) { + this.imdbRating = value; + } + + /** + * Recupera il valore della propriet� imdbVotes. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbVotes() { + return imdbVotes; + } + + /** + * Imposta il valore della propriet� imdbVotes. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbVotes(String value) { + this.imdbVotes = value; + } + + /** + * Recupera il valore della propriet� language. + * + * @return + * possible object is + * {@link String } + * + */ + public String getLanguage() { + return language; + } + + /** + * Imposta il valore della propriet� language. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setLanguage(String value) { + this.language = value; + } + + /** + * Recupera il valore della propriet� metascore. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMetascore() { + return metascore; + } + + /** + * Imposta il valore della propriet� metascore. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMetascore(String value) { + this.metascore = value; + } + + /** + * Recupera il valore della propriet� plot. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPlot() { + return plot; + } + + /** + * Imposta il valore della propriet� plot. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPlot(String value) { + this.plot = value; + } + + /** + * Recupera il valore della propriet� poster. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPoster() { + return poster; + } + + /** + * Imposta il valore della propriet� poster. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPoster(String value) { + this.poster = value; + } + + /** + * Recupera il valore della propriet� rated. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRated() { + return rated; + } + + /** + * Imposta il valore della propriet� rated. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRated(String value) { + this.rated = value; + } + + /** + * Recupera il valore della propriet� released. + * + * @return + * possible object is + * {@link String } + * + */ + public String getReleased() { + return released; + } + + /** + * Imposta il valore della propriet� released. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setReleased(String value) { + this.released = value; + } + + /** + * Recupera il valore della propriet� response. + * + * @return + * possible object is + * {@link String } + * + */ + public String getResponse() { + return response; + } + + /** + * Imposta il valore della propriet� response. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setResponse(String value) { + this.response = value; + } + + /** + * Recupera il valore della propriet� runtime. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRuntime() { + return runtime; + } + + /** + * Imposta il valore della propriet� runtime. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRuntime(String value) { + this.runtime = value; + } + + /** + * Recupera il valore della propriet� title. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTitle() { + return title; + } + + /** + * Imposta il valore della propriet� title. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTitle(String value) { + this.title = value; + } + + /** + * Recupera il valore della propriet� type. + * + * @return + * possible object is + * {@link String } + * + */ + public String getType() { + return type; + } + + /** + * Imposta il valore della propriet� type. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setType(String value) { + this.type = value; + } + + /** + * Recupera il valore della propriet� writer. + * + * @return + * possible object is + * {@link String } + * + */ + public String getWriter() { + return writer; + } + + /** + * Imposta il valore della propriet� writer. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setWriter(String value) { + this.writer = value; + } + + /** + * Recupera il valore della propriet� year. + * + * @return + * possible object is + * {@link String } + * + */ + public String getYear() { + return year; + } + + /** + * Imposta il valore della propriet� year. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setYear(String value) { + this.year = value; + } + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java new file mode 100644 index 0000000000..d1973e7037 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java @@ -0,0 +1,94 @@ +package com.baeldung.server.service; + +import com.baeldung.Movie; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + + +@Path("/movies") +public class MovieCrudService { + + + private Map inventory = new HashMap(); + + @GET + @Path("/getinfo") + @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ + + System.out.println("*** Calling getinfo ***"); + + Movie movie=new Movie(); + movie.setImdbID(imdbID); + return movie; + } + + @POST + @Path("/addmovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Response addMovie(Movie movie){ + + System.out.println("*** Calling addMovie ***"); + + if (null!=inventory.get(movie.getImdbID())){ + return Response.status(Response.Status.NOT_MODIFIED) + .entity("Movie is Already in the database.").build(); + } + inventory.put(movie.getImdbID(),movie); + + return Response.status(Response.Status.CREATED).build(); + } + + + @PUT + @Path("/updatemovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Response updateMovie(Movie movie){ + + System.out.println("*** Calling updateMovie ***"); + + if (null!=inventory.get(movie.getImdbID())){ + return Response.status(Response.Status.NOT_MODIFIED) + .entity("Movie is not in the database.\nUnable to Update").build(); + } + inventory.put(movie.getImdbID(),movie); + return Response.status(Response.Status.OK).build(); + + } + + + @DELETE + @Path("/deletemovie") + public Response deleteMovie(@QueryParam("imdbID") String imdbID){ + + System.out.println("*** Calling deleteMovie ***"); + + if (null==inventory.get(imdbID)){ + return Response.status(Response.Status.NOT_FOUND) + .entity("Movie is not in the database.\nUnable to Delete").build(); + } + + inventory.remove(imdbID); + return Response.status(Response.Status.OK).build(); + } + + @GET + @Path("/listmovies") + @Produces({"application/json"}) + public List listMovies(){ + + return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); + + } + + + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java new file mode 100644 index 0000000000..16b6200ad1 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java @@ -0,0 +1,40 @@ +package com.baeldung.server.service; + + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Created by Admin on 29/01/2016. + */ + + + +@ApplicationPath("/rest") +public class RestEasyServices extends Application { + + private Set singletons = new HashSet(); + + public RestEasyServices() { + singletons.add(new MovieCrudService()); + } + + @Override + public Set getSingletons() { + return singletons; + } + + @Override + public Set> getClasses() { + return super.getClasses(); + } + + @Override + public Map getProperties() { + return super.getProperties(); + } +} diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java new file mode 100644 index 0000000000..e711233979 --- /dev/null +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java @@ -0,0 +1,50 @@ +package com.baeldung.server; + +import com.baeldung.Movie; +import com.baeldung.client.ServicesInterface; +import org.jboss.resteasy.client.jaxrs.ResteasyClient; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; + +import java.util.List; + +public class RestEasyClient { + + public static void main(String[] args) { + + Movie st = new Movie(); + st.setImdbID("12345"); + + /* + * Alternatively you can use this simple String to send + * instead of using a Student instance + * + * String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}"; + */ + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies"); + + ServicesInterface simple = target.proxy(ServicesInterface.class); + final List movies = simple.listMovies(); + + /* + if (response.getStatus() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + + response.getStatus()); + } + + System.out.println("Server response : \n"); + System.out.println(response.readEntity(String.class)); + + response.close(); +*/ + } catch (Exception e) { + + e.printStackTrace(); + + } + } + +} \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/server/movies/transformer.json new file mode 100644 index 0000000000..2154868265 --- /dev/null +++ b/RestEasy Example/src/test/resources/server/movies/transformer.json @@ -0,0 +1,22 @@ +{ + "title": "Transformers", + "year": "2007", + "rated": "PG-13", + "released": "03 Jul 2007", + "runtime": "144 min", + "genre": "Action, Adventure, Sci-Fi", + "director": "Michael Bay", + "writer": "Roberto Orci (screenplay), Alex Kurtzman (screenplay), John Rogers (story), Roberto Orci (story), Alex Kurtzman (story)", + "actors": "Shia LaBeouf, Megan Fox, Josh Duhamel, Tyrese Gibson", + "plot": "A long time ago, far away on the planet of Cybertron, a war is being waged between the noble Autobots (led by the wise Optimus Prime) and the devious Decepticons (commanded by the dreaded Megatron) for control over the Allspark, a mystical talisman that would grant unlimited power to whoever possesses it. The Autobots managed to smuggle the Allspark off the planet, but Megatron blasts off in search of it. He eventually tracks it to the planet of Earth (circa 1850), but his reckless desire for power sends him right into the Arctic Ocean, and the sheer cold forces him into a paralyzed state. His body is later found by Captain Archibald Witwicky, but before going into a comatose state Megatron uses the last of his energy to engrave into the Captain's glasses a map showing the location of the Allspark, and to send a transmission to Cybertron. Megatron is then carried away aboard the Captain's ship. A century later, Captain Witwicky's grandson Sam Witwicky (nicknamed Spike by his friends) buys his first car. To his shock, he discovers it to be Bumblebee, an Autobot in disguise who is to protect Spike, who possesses the Captain's glasses and the map engraved on them. But Bumblebee is not the only Transformer to have arrived on Earth - in the desert of Qatar, the Decepticons Blackout and Scorponok attack a U.S. military base, causing the Pentagon to send their special Sector Seven agents to capture all \"specimens of this alien race.\" Spike and his girlfriend Mikaela find themselves in the midst of a grand battle between the Autobots and the Decepticons, stretching from Hoover Dam all the way to Los Angeles. Meanwhile, deep inside Hoover Dam, the cryogenically stored body of Megatron awakens.", + "language": "English, Spanish", + "country": "USA", + "awards": "Nominated for 3 Oscars. Another 18 wins & 40 nominations.", + "poster": "http://ia.media-imdb.com/images/M/MV5BMTQwNjU5MzUzNl5BMl5BanBnXkFtZTYwMzc1MTI3._V1_SX300.jpg", + "metascore": "61", + "imdbRating": "7.1", + "imdbVotes": "492,225", + "imdbID": "tt0418279", + "Type": "movie", + "response": "True" +} \ No newline at end of file From fa973988fb4b4d6357eac6bcadf1f3ac4143605a Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sat, 30 Jan 2016 20:39:28 +0100 Subject: [PATCH 230/309] Added testCase for List All Movies and Add a Movie --- .../src/main/java/com/baeldung/Movie.java | 535 ------------------ .../main/java/com/baeldung/model/Movie.java | 22 +- .../com/baeldung/server/MovieCrudService.java | 25 +- .../server/service/MovieCrudService.java | 94 --- .../server/service/RestEasyServices.java | 40 -- .../com/baeldung/server/RestEasyClient.java | 104 +++- .../resources/server/movies/transformer.json | 22 - 7 files changed, 104 insertions(+), 738 deletions(-) delete mode 100644 RestEasy Example/src/main/java/com/baeldung/Movie.java delete mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java delete mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java delete mode 100644 RestEasy Example/src/test/resources/server/movies/transformer.json diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/Movie.java deleted file mode 100644 index c0041d2e95..0000000000 --- a/RestEasy Example/src/main/java/com/baeldung/Movie.java +++ /dev/null @@ -1,535 +0,0 @@ - -package com.baeldung; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "movie", propOrder = { - "actors", - "awards", - "country", - "director", - "genre", - "imdbID", - "imdbRating", - "imdbVotes", - "language", - "metascore", - "plot", - "poster", - "rated", - "released", - "response", - "runtime", - "title", - "type", - "writer", - "year" -}) -public class Movie { - - protected String actors; - protected String awards; - protected String country; - protected String director; - protected String genre; - protected String imdbID; - protected String imdbRating; - protected String imdbVotes; - protected String language; - protected String metascore; - protected String plot; - protected String poster; - protected String rated; - protected String released; - protected String response; - protected String runtime; - protected String title; - protected String type; - protected String writer; - protected String year; - - /** - * Recupera il valore della propriet� actors. - * - * @return - * possible object is - * {@link String } - * - */ - public String getActors() { - return actors; - } - - /** - * Imposta il valore della propriet� actors. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setActors(String value) { - this.actors = value; - } - - /** - * Recupera il valore della propriet� awards. - * - * @return - * possible object is - * {@link String } - * - */ - public String getAwards() { - return awards; - } - - /** - * Imposta il valore della propriet� awards. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setAwards(String value) { - this.awards = value; - } - - /** - * Recupera il valore della propriet� country. - * - * @return - * possible object is - * {@link String } - * - */ - public String getCountry() { - return country; - } - - /** - * Imposta il valore della propriet� country. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setCountry(String value) { - this.country = value; - } - - /** - * Recupera il valore della propriet� director. - * - * @return - * possible object is - * {@link String } - * - */ - public String getDirector() { - return director; - } - - /** - * Imposta il valore della propriet� director. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setDirector(String value) { - this.director = value; - } - - /** - * Recupera il valore della propriet� genre. - * - * @return - * possible object is - * {@link String } - * - */ - public String getGenre() { - return genre; - } - - /** - * Imposta il valore della propriet� genre. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setGenre(String value) { - this.genre = value; - } - - /** - * Recupera il valore della propriet� imdbID. - * - * @return - * possible object is - * {@link String } - * - */ - public String getImdbID() { - return imdbID; - } - - /** - * Imposta il valore della propriet� imdbID. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setImdbID(String value) { - this.imdbID = value; - } - - /** - * Recupera il valore della propriet� imdbRating. - * - * @return - * possible object is - * {@link String } - * - */ - public String getImdbRating() { - return imdbRating; - } - - /** - * Imposta il valore della propriet� imdbRating. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setImdbRating(String value) { - this.imdbRating = value; - } - - /** - * Recupera il valore della propriet� imdbVotes. - * - * @return - * possible object is - * {@link String } - * - */ - public String getImdbVotes() { - return imdbVotes; - } - - /** - * Imposta il valore della propriet� imdbVotes. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setImdbVotes(String value) { - this.imdbVotes = value; - } - - /** - * Recupera il valore della propriet� language. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLanguage() { - return language; - } - - /** - * Imposta il valore della propriet� language. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLanguage(String value) { - this.language = value; - } - - /** - * Recupera il valore della propriet� metascore. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMetascore() { - return metascore; - } - - /** - * Imposta il valore della propriet� metascore. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMetascore(String value) { - this.metascore = value; - } - - /** - * Recupera il valore della propriet� plot. - * - * @return - * possible object is - * {@link String } - * - */ - public String getPlot() { - return plot; - } - - /** - * Imposta il valore della propriet� plot. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setPlot(String value) { - this.plot = value; - } - - /** - * Recupera il valore della propriet� poster. - * - * @return - * possible object is - * {@link String } - * - */ - public String getPoster() { - return poster; - } - - /** - * Imposta il valore della propriet� poster. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setPoster(String value) { - this.poster = value; - } - - /** - * Recupera il valore della propriet� rated. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRated() { - return rated; - } - - /** - * Imposta il valore della propriet� rated. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRated(String value) { - this.rated = value; - } - - /** - * Recupera il valore della propriet� released. - * - * @return - * possible object is - * {@link String } - * - */ - public String getReleased() { - return released; - } - - /** - * Imposta il valore della propriet� released. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setReleased(String value) { - this.released = value; - } - - /** - * Recupera il valore della propriet� response. - * - * @return - * possible object is - * {@link String } - * - */ - public String getResponse() { - return response; - } - - /** - * Imposta il valore della propriet� response. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setResponse(String value) { - this.response = value; - } - - /** - * Recupera il valore della propriet� runtime. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRuntime() { - return runtime; - } - - /** - * Imposta il valore della propriet� runtime. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRuntime(String value) { - this.runtime = value; - } - - /** - * Recupera il valore della propriet� title. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTitle() { - return title; - } - - /** - * Imposta il valore della propriet� title. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTitle(String value) { - this.title = value; - } - - /** - * Recupera il valore della propriet� type. - * - * @return - * possible object is - * {@link String } - * - */ - public String getType() { - return type; - } - - /** - * Imposta il valore della propriet� type. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setType(String value) { - this.type = value; - } - - /** - * Recupera il valore della propriet� writer. - * - * @return - * possible object is - * {@link String } - * - */ - public String getWriter() { - return writer; - } - - /** - * Imposta il valore della propriet� writer. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setWriter(String value) { - this.writer = value; - } - - /** - * Recupera il valore della propriet� year. - * - * @return - * possible object is - * {@link String } - * - */ - public String getYear() { - return year; - } - - /** - * Imposta il valore della propriet� year. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setYear(String value) { - this.year = value; - } - -} diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index a2b2bd5250..052ba081c1 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -13,7 +13,7 @@ import javax.xml.bind.annotation.XmlType; "country", "director", "genre", - "imdbId", + "imdbID", "imdbRating", "imdbVotes", "language", @@ -36,7 +36,7 @@ public class Movie { protected String country; protected String director; protected String genre; - protected String imdbId; + protected String imdbID; protected String imdbRating; protected String imdbVotes; protected String language; @@ -173,27 +173,27 @@ public class Movie { } /** - * Recupera il valore della propriet� imdbId. + * Recupera il valore della propriet� imdbID. * * @return * possible object is * {@link String } * */ - public String getImdbId() { - return imdbId; + public String getImdbID() { + return imdbID; } /** - * Imposta il valore della propriet� imdbId. + * Imposta il valore della propriet� imdbID. * * @param value * allowed object is * {@link String } * */ - public void setImdbId(String value) { - this.imdbId = value; + public void setImdbID(String value) { + this.imdbID = value; } /** @@ -540,7 +540,7 @@ public class Movie { ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + - ", imdbId='" + imdbId + '\'' + + ", imdbID='" + imdbID + '\'' + ", imdbRating='" + imdbRating + '\'' + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + @@ -564,14 +564,14 @@ public class Movie { Movie movie = (Movie) o; - if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; + if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false; return title != null ? title.equals(movie.title) : movie.title == null; } @Override public int hashCode() { - int result = imdbId != null ? imdbId.hashCode() : 0; + int result = imdbID != null ? imdbID.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); return result; } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 29226aa0e0..60e0121966 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -18,21 +18,18 @@ public class MovieCrudService { private Map inventory = new HashMap(); - @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbId") String imdbID){ + public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ - System.out.println("*** Calling getinfo for a given ImdbID***"); - - if(inventory.containsKey(imdbID)){ - return inventory.get(imdbID); - }else return null; + System.out.println("*** Calling getinfo ***"); + Movie movie=new Movie(); + movie.setImdbID(imdbID); + return movie; } - @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @@ -40,12 +37,11 @@ public class MovieCrudService { System.out.println("*** Calling addMovie ***"); - if (null!=inventory.get(movie.getImdbId())){ + if (null!=inventory.get(movie.getImdbID())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } - - inventory.put(movie.getImdbId(),movie); + inventory.put(movie.getImdbID(),movie); return Response.status(Response.Status.CREATED).build(); } @@ -58,11 +54,11 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null==inventory.get(movie.getImdbId())){ + if (null!=inventory.get(movie.getImdbID())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } - inventory.put(movie.getImdbId(),movie); + inventory.put(movie.getImdbID(),movie); return Response.status(Response.Status.OK).build(); } @@ -70,7 +66,7 @@ public class MovieCrudService { @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbId") String imdbID){ + public Response deleteMovie(@QueryParam("imdbID") String imdbID){ System.out.println("*** Calling deleteMovie ***"); @@ -83,7 +79,6 @@ public class MovieCrudService { return Response.status(Response.Status.OK).build(); } - @GET @Path("/listmovies") @Produces({"application/json"}) diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java deleted file mode 100644 index d1973e7037..0000000000 --- a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.baeldung.server.service; - -import com.baeldung.Movie; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - - -@Path("/movies") -public class MovieCrudService { - - - private Map inventory = new HashMap(); - - @GET - @Path("/getinfo") - @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ - - System.out.println("*** Calling getinfo ***"); - - Movie movie=new Movie(); - movie.setImdbID(imdbID); - return movie; - } - - @POST - @Path("/addmovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Response addMovie(Movie movie){ - - System.out.println("*** Calling addMovie ***"); - - if (null!=inventory.get(movie.getImdbID())){ - return Response.status(Response.Status.NOT_MODIFIED) - .entity("Movie is Already in the database.").build(); - } - inventory.put(movie.getImdbID(),movie); - - return Response.status(Response.Status.CREATED).build(); - } - - - @PUT - @Path("/updatemovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Response updateMovie(Movie movie){ - - System.out.println("*** Calling updateMovie ***"); - - if (null!=inventory.get(movie.getImdbID())){ - return Response.status(Response.Status.NOT_MODIFIED) - .entity("Movie is not in the database.\nUnable to Update").build(); - } - inventory.put(movie.getImdbID(),movie); - return Response.status(Response.Status.OK).build(); - - } - - - @DELETE - @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbID") String imdbID){ - - System.out.println("*** Calling deleteMovie ***"); - - if (null==inventory.get(imdbID)){ - return Response.status(Response.Status.NOT_FOUND) - .entity("Movie is not in the database.\nUnable to Delete").build(); - } - - inventory.remove(imdbID); - return Response.status(Response.Status.OK).build(); - } - - @GET - @Path("/listmovies") - @Produces({"application/json"}) - public List listMovies(){ - - return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); - - } - - - -} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java deleted file mode 100644 index 16b6200ad1..0000000000 --- a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.server.service; - - -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * Created by Admin on 29/01/2016. - */ - - - -@ApplicationPath("/rest") -public class RestEasyServices extends Application { - - private Set singletons = new HashSet(); - - public RestEasyServices() { - singletons.add(new MovieCrudService()); - } - - @Override - public Set getSingletons() { - return singletons; - } - - @Override - public Set> getClasses() { - return super.getClasses(); - } - - @Override - public Map getProperties() { - return super.getProperties(); - } -} diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java index e711233979..c77f494862 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java @@ -1,49 +1,111 @@ package com.baeldung.server; -import com.baeldung.Movie; +import com.baeldung.model.Movie; import com.baeldung.client.ServicesInterface; +import org.apache.commons.io.IOUtils; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.ObjectMapper; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import javax.naming.NamingException; +import javax.ws.rs.core.Link; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Arrays; import java.util.List; +import java.util.Locale; public class RestEasyClient { - public static void main(String[] args) { - Movie st = new Movie(); - st.setImdbID("12345"); + Movie transformerMovie=null; + Movie batmanMovie=null; + ObjectMapper jsonMapper=null; - /* - * Alternatively you can use this simple String to send - * instead of using a Student instance - * - * String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}"; - */ + @BeforeClass + public static void loadMovieInventory(){ + + + + } + + @Before + public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { + + + jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + jsonMapper.setDateFormat(sdf); + + try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) { + String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) { + String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + } + + @Test + public void testListAllMovies() { try { ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies"); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + final List movies = simple.listMovies(); + System.out.println(movies); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Test + public void testAddMovie() { + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); ServicesInterface simple = target.proxy(ServicesInterface.class); - final List movies = simple.listMovies(); + final Response moviesResponse = simple.addMovie(batmanMovie); - /* - if (response.getStatus() != 200) { + if (moviesResponse.getStatus() != 201) { + System.out.println(moviesResponse.readEntity(String.class)); throw new RuntimeException("Failed : HTTP error code : " - + response.getStatus()); + + moviesResponse.getStatus()); } - System.out.println("Server response : \n"); - System.out.println(response.readEntity(String.class)); + moviesResponse.close(); - response.close(); -*/ } catch (Exception e) { - e.printStackTrace(); - } } diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/server/movies/transformer.json deleted file mode 100644 index 2154868265..0000000000 --- a/RestEasy Example/src/test/resources/server/movies/transformer.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "title": "Transformers", - "year": "2007", - "rated": "PG-13", - "released": "03 Jul 2007", - "runtime": "144 min", - "genre": "Action, Adventure, Sci-Fi", - "director": "Michael Bay", - "writer": "Roberto Orci (screenplay), Alex Kurtzman (screenplay), John Rogers (story), Roberto Orci (story), Alex Kurtzman (story)", - "actors": "Shia LaBeouf, Megan Fox, Josh Duhamel, Tyrese Gibson", - "plot": "A long time ago, far away on the planet of Cybertron, a war is being waged between the noble Autobots (led by the wise Optimus Prime) and the devious Decepticons (commanded by the dreaded Megatron) for control over the Allspark, a mystical talisman that would grant unlimited power to whoever possesses it. The Autobots managed to smuggle the Allspark off the planet, but Megatron blasts off in search of it. He eventually tracks it to the planet of Earth (circa 1850), but his reckless desire for power sends him right into the Arctic Ocean, and the sheer cold forces him into a paralyzed state. His body is later found by Captain Archibald Witwicky, but before going into a comatose state Megatron uses the last of his energy to engrave into the Captain's glasses a map showing the location of the Allspark, and to send a transmission to Cybertron. Megatron is then carried away aboard the Captain's ship. A century later, Captain Witwicky's grandson Sam Witwicky (nicknamed Spike by his friends) buys his first car. To his shock, he discovers it to be Bumblebee, an Autobot in disguise who is to protect Spike, who possesses the Captain's glasses and the map engraved on them. But Bumblebee is not the only Transformer to have arrived on Earth - in the desert of Qatar, the Decepticons Blackout and Scorponok attack a U.S. military base, causing the Pentagon to send their special Sector Seven agents to capture all \"specimens of this alien race.\" Spike and his girlfriend Mikaela find themselves in the midst of a grand battle between the Autobots and the Decepticons, stretching from Hoover Dam all the way to Los Angeles. Meanwhile, deep inside Hoover Dam, the cryogenically stored body of Megatron awakens.", - "language": "English, Spanish", - "country": "USA", - "awards": "Nominated for 3 Oscars. Another 18 wins & 40 nominations.", - "poster": "http://ia.media-imdb.com/images/M/MV5BMTQwNjU5MzUzNl5BMl5BanBnXkFtZTYwMzc1MTI3._V1_SX300.jpg", - "metascore": "61", - "imdbRating": "7.1", - "imdbVotes": "492,225", - "imdbID": "tt0418279", - "Type": "movie", - "response": "True" -} \ No newline at end of file From 913f2908e0468550647ac32d61db4da23d7093a3 Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sun, 31 Jan 2016 11:05:11 +0100 Subject: [PATCH 231/309] Added testCase for all Services --- .../baeldung/client/ServicesInterface.java | 6 + .../com/baeldung/server/MovieCrudService.java | 15 ++- .../com/baeldung/server/RestEasyClient.java | 112 ------------------ 3 files changed, 16 insertions(+), 117 deletions(-) delete mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 749cabc757..8898b83483 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -23,6 +23,12 @@ public interface ServicesInterface { List listMovies(); + @GET + @Path("/listmovies") + @Produces({"application/json"}) + List listMovies(); + + @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 60e0121966..18366e2faa 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -18,18 +18,21 @@ public class MovieCrudService { private Map inventory = new HashMap(); + @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ - System.out.println("*** Calling getinfo ***"); + System.out.println("*** Calling getinfo for a given ImdbID***"); + + if(inventory.containsKey(imdbID)){ + return inventory.get(imdbID); + }else return null; - Movie movie=new Movie(); - movie.setImdbID(imdbID); - return movie; } + @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @@ -41,6 +44,7 @@ public class MovieCrudService { return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } + inventory.put(movie.getImdbID(),movie); return Response.status(Response.Status.CREATED).build(); @@ -54,7 +58,7 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null!=inventory.get(movie.getImdbID())){ + if (null==inventory.get(movie.getImdbID())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } @@ -79,6 +83,7 @@ public class MovieCrudService { return Response.status(Response.Status.OK).build(); } + @GET @Path("/listmovies") @Produces({"application/json"}) diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java deleted file mode 100644 index c77f494862..0000000000 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.model.Movie; -import com.baeldung.client.ServicesInterface; -import org.apache.commons.io.IOUtils; -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; -import org.jboss.resteasy.client.jaxrs.ResteasyClient; -import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; -import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import javax.naming.NamingException; -import javax.ws.rs.core.Link; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -public class RestEasyClient { - - - Movie transformerMovie=null; - Movie batmanMovie=null; - ObjectMapper jsonMapper=null; - - @BeforeClass - public static void loadMovieInventory(){ - - - - } - - @Before - public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - - - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); - jsonMapper.setDateFormat(sdf); - - try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) { - String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Test is going to die ...", e); - } - - try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) { - String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); - - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Test is going to die ...", e); - } - - } - - @Test - public void testListAllMovies() { - - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); - - final List movies = simple.listMovies(); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - @Test - public void testAddMovie() { - - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - - ServicesInterface simple = target.proxy(ServicesInterface.class); - final Response moviesResponse = simple.addMovie(batmanMovie); - - if (moviesResponse.getStatus() != 201) { - System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " - + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file From 929a7d7483b6361f28ec19e8513ed7468f2686e8 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:29:30 +0100 Subject: [PATCH 232/309] Minor Bugfix --- .../baeldung/client/ServicesInterface.java | 6 ----- .../main/java/com/baeldung/model/Movie.java | 22 +++++++++---------- .../com/baeldung/server/MovieCrudService.java | 12 +++++----- 3 files changed, 17 insertions(+), 23 deletions(-) diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 8898b83483..749cabc757 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -23,12 +23,6 @@ public interface ServicesInterface { List listMovies(); - @GET - @Path("/listmovies") - @Produces({"application/json"}) - List listMovies(); - - @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 052ba081c1..a2b2bd5250 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -13,7 +13,7 @@ import javax.xml.bind.annotation.XmlType; "country", "director", "genre", - "imdbID", + "imdbId", "imdbRating", "imdbVotes", "language", @@ -36,7 +36,7 @@ public class Movie { protected String country; protected String director; protected String genre; - protected String imdbID; + protected String imdbId; protected String imdbRating; protected String imdbVotes; protected String language; @@ -173,27 +173,27 @@ public class Movie { } /** - * Recupera il valore della propriet� imdbID. + * Recupera il valore della propriet� imdbId. * * @return * possible object is * {@link String } * */ - public String getImdbID() { - return imdbID; + public String getImdbId() { + return imdbId; } /** - * Imposta il valore della propriet� imdbID. + * Imposta il valore della propriet� imdbId. * * @param value * allowed object is * {@link String } * */ - public void setImdbID(String value) { - this.imdbID = value; + public void setImdbId(String value) { + this.imdbId = value; } /** @@ -540,7 +540,7 @@ public class Movie { ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + - ", imdbID='" + imdbID + '\'' + + ", imdbId='" + imdbId + '\'' + ", imdbRating='" + imdbRating + '\'' + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + @@ -564,14 +564,14 @@ public class Movie { Movie movie = (Movie) o; - if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false; + if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; return title != null ? title.equals(movie.title) : movie.title == null; } @Override public int hashCode() { - int result = imdbID != null ? imdbID.hashCode() : 0; + int result = imdbId != null ? imdbId.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); return result; } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 18366e2faa..29226aa0e0 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -22,7 +22,7 @@ public class MovieCrudService { @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ + public Movie movieByImdbID(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling getinfo for a given ImdbID***"); @@ -40,12 +40,12 @@ public class MovieCrudService { System.out.println("*** Calling addMovie ***"); - if (null!=inventory.get(movie.getImdbID())){ + if (null!=inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.CREATED).build(); } @@ -58,11 +58,11 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null==inventory.get(movie.getImdbID())){ + if (null==inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.OK).build(); } @@ -70,7 +70,7 @@ public class MovieCrudService { @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbID") String imdbID){ + public Response deleteMovie(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling deleteMovie ***"); From bcad6811a346b82cb38c1a6cbe5d8fc7408450b8 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:39:35 +0100 Subject: [PATCH 233/309] Minor Bugfix --- .../main/java/com/baeldung/model/Movie.java | 321 +----------------- 1 file changed, 1 insertion(+), 320 deletions(-) diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index a2b2bd5250..805ba95209 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -52,482 +52,163 @@ public class Movie { protected String writer; protected String year; - /** - * Recupera il valore della propriet� actors. - * - * @return - * possible object is - * {@link String } - * - */ + public String getActors() { return actors; } - /** - * Imposta il valore della propriet� actors. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setActors(String value) { this.actors = value; } - /** - * Recupera il valore della propriet� awards. - * - * @return - * possible object is - * {@link String } - * - */ public String getAwards() { return awards; } - /** - * Imposta il valore della propriet� awards. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setAwards(String value) { this.awards = value; } - /** - * Recupera il valore della propriet� country. - * - * @return - * possible object is - * {@link String } - * - */ public String getCountry() { return country; } - /** - * Imposta il valore della propriet� country. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setCountry(String value) { this.country = value; } - /** - * Recupera il valore della propriet� director. - * - * @return - * possible object is - * {@link String } - * - */ public String getDirector() { return director; } - /** - * Imposta il valore della propriet� director. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setDirector(String value) { this.director = value; } - /** - * Recupera il valore della propriet� genre. - * - * @return - * possible object is - * {@link String } - * - */ public String getGenre() { return genre; } - /** - * Imposta il valore della propriet� genre. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setGenre(String value) { this.genre = value; } - /** - * Recupera il valore della propriet� imdbId. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbId() { return imdbId; } - /** - * Imposta il valore della propriet� imdbId. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setImdbId(String value) { this.imdbId = value; } - /** - * Recupera il valore della propriet� imdbRating. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbRating() { return imdbRating; } - /** - * Imposta il valore della propriet� imdbRating. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setImdbRating(String value) { this.imdbRating = value; } - /** - * Recupera il valore della propriet� imdbVotes. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbVotes() { return imdbVotes; } - /** - * Imposta il valore della propriet� imdbVotes. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setImdbVotes(String value) { this.imdbVotes = value; } - /** - * Recupera il valore della propriet� language. - * - * @return - * possible object is - * {@link String } - * - */ public String getLanguage() { return language; } - /** - * Imposta il valore della propriet� language. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setLanguage(String value) { this.language = value; } - /** - * Recupera il valore della propriet� metascore. - * - * @return - * possible object is - * {@link String } - * - */ public String getMetascore() { return metascore; } - /** - * Imposta il valore della propriet� metascore. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setMetascore(String value) { this.metascore = value; } - /** - * Recupera il valore della propriet� plot. - * - * @return - * possible object is - * {@link String } - * - */ public String getPlot() { return plot; } - /** - * Imposta il valore della propriet� plot. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setPlot(String value) { this.plot = value; } - /** - * Recupera il valore della propriet� poster. - * - * @return - * possible object is - * {@link String } - * - */ public String getPoster() { return poster; } - /** - * Imposta il valore della propriet� poster. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setPoster(String value) { this.poster = value; } - /** - * Recupera il valore della propriet� rated. - * - * @return - * possible object is - * {@link String } - * - */ public String getRated() { return rated; } - /** - * Imposta il valore della propriet� rated. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setRated(String value) { this.rated = value; } - /** - * Recupera il valore della propriet� released. - * - * @return - * possible object is - * {@link String } - * - */ public String getReleased() { return released; } - /** - * Imposta il valore della propriet� released. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setReleased(String value) { this.released = value; } - /** - * Recupera il valore della propriet� response. - * - * @return - * possible object is - * {@link String } - * - */ public String getResponse() { return response; } - /** - * Imposta il valore della propriet� response. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setResponse(String value) { this.response = value; } - /** - * Recupera il valore della propriet� runtime. - * - * @return - * possible object is - * {@link String } - * - */ public String getRuntime() { return runtime; } - /** - * Imposta il valore della propriet� runtime. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setRuntime(String value) { this.runtime = value; } - /** - * Recupera il valore della propriet� title. - * - * @return - * possible object is - * {@link String } - * - */ public String getTitle() { return title; } - /** - * Imposta il valore della propriet� title. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setTitle(String value) { this.title = value; } - /** - * Recupera il valore della propriet� type. - * - * @return - * possible object is - * {@link String } - * - */ public String getType() { return type; } - /** - * Imposta il valore della propriet� type. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setType(String value) { this.type = value; } - /** - * Recupera il valore della propriet� writer. - * - * @return - * possible object is - * {@link String } - * - */ public String getWriter() { return writer; } - /** - * Imposta il valore della propriet� writer. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setWriter(String value) { this.writer = value; } - /** - * Recupera il valore della propriet� year. - * - * @return - * possible object is - * {@link String } - * - */ public String getYear() { return year; } - /** - * Imposta il valore della propriet� year. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setYear(String value) { this.year = value; } From 31fbff34eb181c3898691c778920db10e8ffa18b Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:55:46 +0100 Subject: [PATCH 234/309] CleanUp Code --- RestEasy Example/pom.xml | 3 +- .../baeldung/client/ServicesInterface.java | 1 - .../main/java/com/baeldung/model/Movie.java | 2 -- .../com/baeldung/server/MovieCrudService.java | 17 ++++------- .../com/baeldung/server/RestEasyServices.java | 8 ----- .../src/main/resources/schema1.xsd | 29 ------------------- .../src/main/webapp/WEB-INF/web.xml | 3 -- .../java/baeldung/client/RestEasyClient.java | 7 ----- .../baeldung/server/RestEasyClientTest.java | 1 - 9 files changed, 7 insertions(+), 64 deletions(-) delete mode 100644 RestEasy Example/src/main/resources/schema1.xsd delete mode 100644 RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index 6935238d91..9c890da2b7 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -36,7 +36,7 @@ - + org.jboss.resteasy jaxrs-api @@ -101,5 +101,4 @@ - \ No newline at end of file diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 749cabc757..3c8d6abc00 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -1,7 +1,6 @@ package com.baeldung.client; import com.baeldung.model.Movie; - import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 805ba95209..56ba766ff4 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -1,11 +1,9 @@ - package com.baeldung.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; - @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "movie", propOrder = { "actors", diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 29226aa0e0..bbb3b1e953 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -1,7 +1,6 @@ package com.baeldung.server; import com.baeldung.model.Movie; - import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -11,23 +10,21 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; - @Path("/movies") public class MovieCrudService { - private Map inventory = new HashMap(); @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbId") String imdbID){ + public Movie movieByImdbId(@QueryParam("imdbId") String imdbId){ System.out.println("*** Calling getinfo for a given ImdbID***"); - if(inventory.containsKey(imdbID)){ - return inventory.get(imdbID); + if(inventory.containsKey(imdbId)){ + return inventory.get(imdbId); }else return null; } @@ -70,16 +67,16 @@ public class MovieCrudService { @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbId") String imdbID){ + public Response deleteMovie(@QueryParam("imdbId") String imdbId){ System.out.println("*** Calling deleteMovie ***"); - if (null==inventory.get(imdbID)){ + if (null==inventory.get(imdbId)){ return Response.status(Response.Status.NOT_FOUND) .entity("Movie is not in the database.\nUnable to Delete").build(); } - inventory.remove(imdbID); + inventory.remove(imdbId); return Response.status(Response.Status.OK).build(); } @@ -93,6 +90,4 @@ public class MovieCrudService { } - - } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java index 8c57d2c9b4..7726e49f38 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java @@ -1,19 +1,11 @@ package com.baeldung.server; - import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; -import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; -/** - * Created by Admin on 29/01/2016. - */ - - - @ApplicationPath("/rest") public class RestEasyServices extends Application { diff --git a/RestEasy Example/src/main/resources/schema1.xsd b/RestEasy Example/src/main/resources/schema1.xsd deleted file mode 100644 index 0d74b7c366..0000000000 --- a/RestEasy Example/src/main/resources/schema1.xsd +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index f70fdf7975..1e7f64004d 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -5,12 +5,9 @@ RestEasy Example - resteasy.servlet.mapping.prefix /rest - - \ No newline at end of file diff --git a/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java b/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java deleted file mode 100644 index b474b3d4f8..0000000000 --- a/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java +++ /dev/null @@ -1,7 +0,0 @@ -package baeldung.client; - -/** - * Created by Admin on 29/01/2016. - */ -public class RestEasyClient { -} diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java index b6a2e2a0c1..faa39e0199 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -10,7 +10,6 @@ import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.junit.Before; import org.junit.Test; - import javax.naming.NamingException; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; From 37acdef2a7bbe867416c1e1208cd93a068cd5bbc Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Mon, 8 Feb 2016 14:00:11 +0100 Subject: [PATCH 235/309] CleanUp and reformatting Code; dependency fix in pom.xml --- RestEasy Example/pom.xml | 147 +++++++----------- .../baeldung/client/ServicesInterface.java | 15 +- .../main/java/com/baeldung/model/Movie.java | 56 ++----- .../com/baeldung/server/MovieCrudService.java | 49 +++--- .../WEB-INF/jboss-deployment-structure.xml | 22 +-- .../src/main/webapp/WEB-INF/web.xml | 14 +- .../baeldung/server/RestEasyClientTest.java | 23 ++- .../com/baeldung/server/movies/batman.json | 2 +- .../baeldung/server/movies/transformer.json | 2 +- 9 files changed, 125 insertions(+), 205 deletions(-) diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index 9c890da2b7..ec9e87b0d1 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -1,104 +1,77 @@ - - 4.0.0 + + 4.0.0 - com.baeldung - resteasy-tutorial - 1.0 - war + com.baeldung + resteasy-tutorial + 1.0 + war - - - jboss - http://repository.jboss.org/nexus/content/groups/public/ - - + + 3.0.14.Final + - - 3.0.14.Final - runtime - + + RestEasyTutorial + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + - - RestEasyTutorial - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - + - + - - org.jboss.resteasy - jaxrs-api - 3.0.12.Final - ${resteasy.scope} - - - - org.jboss.resteasy - resteasy-servlet-initializer - ${resteasy.version} - ${resteasy.scope} - - - jboss-jaxrs-api_2.0_spec - org.jboss.spec.javax.ws.rs - - - - - - org.jboss.resteasy - resteasy-client - ${resteasy.version} - ${resteasy.scope} - + + org.jboss.resteasy + resteasy-servlet-initializer + ${resteasy.version} + - - javax.ws.rs - javax.ws.rs-api - 2.0.1 - + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + - - org.jboss.resteasy - resteasy-jackson-provider - ${resteasy.version} - ${resteasy.scope} - + - - org.jboss.resteasy - resteasy-jaxb-provider - ${resteasy.version} - ${resteasy.scope} - + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy.version} + - + + org.jboss.resteasy + resteasy-jackson-provider + ${resteasy.version} + - - junit - junit - 4.4 - + - - commons-io - commons-io - 2.4 - + + junit + junit + 4.4 + + + + commons-io + commons-io + 2.4 + + + - \ No newline at end of file diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 3c8d6abc00..3d03c16faf 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -9,35 +9,28 @@ import java.util.List; @Path("/movies") public interface ServicesInterface { - @GET @Path("/getinfo") - @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Movie movieByImdbId(@QueryParam("imdbId") String imdbId); - @GET @Path("/listmovies") - @Produces({"application/json"}) + @Produces({ "application/json" }) List listMovies(); - @POST @Path("/addmovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Response addMovie(Movie movie); - @PUT @Path("/updatemovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Response updateMovie(Movie movie); - @DELETE @Path("/deletemovie") Response deleteMovie(@QueryParam("imdbId") String imdbID); - - } diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 56ba766ff4..a959682a75 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -5,28 +5,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "movie", propOrder = { - "actors", - "awards", - "country", - "director", - "genre", - "imdbId", - "imdbRating", - "imdbVotes", - "language", - "metascore", - "plot", - "poster", - "rated", - "released", - "response", - "runtime", - "title", - "type", - "writer", - "year" -}) +@XmlType(name = "movie", propOrder = { "actors", "awards", "country", "director", "genre", "imdbId", "imdbRating", "imdbVotes", "language", "metascore", "plot", "poster", "rated", "released", "response", "runtime", "title", "type", "writer", "year" }) public class Movie { protected String actors; @@ -213,37 +192,22 @@ public class Movie { @Override public String toString() { - return "Movie{" + - "actors='" + actors + '\'' + - ", awards='" + awards + '\'' + - ", country='" + country + '\'' + - ", director='" + director + '\'' + - ", genre='" + genre + '\'' + - ", imdbId='" + imdbId + '\'' + - ", imdbRating='" + imdbRating + '\'' + - ", imdbVotes='" + imdbVotes + '\'' + - ", language='" + language + '\'' + - ", metascore='" + metascore + '\'' + - ", poster='" + poster + '\'' + - ", rated='" + rated + '\'' + - ", released='" + released + '\'' + - ", response='" + response + '\'' + - ", runtime='" + runtime + '\'' + - ", title='" + title + '\'' + - ", type='" + type + '\'' + - ", writer='" + writer + '\'' + - ", year='" + year + '\'' + - '}'; + return "Movie{" + "actors='" + actors + '\'' + ", awards='" + awards + '\'' + ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + ", imdbId='" + imdbId + '\'' + ", imdbRating='" + imdbRating + '\'' + + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + ", metascore='" + metascore + '\'' + ", poster='" + poster + '\'' + ", rated='" + rated + '\'' + ", released='" + released + '\'' + ", response='" + response + '\'' + + ", runtime='" + runtime + '\'' + ", title='" + title + '\'' + ", type='" + type + '\'' + ", writer='" + writer + '\'' + ", year='" + year + '\'' + '}'; } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Movie movie = (Movie) o; - if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; + if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) + return false; return title != null ? title.equals(movie.title) : movie.title == null; } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index bbb3b1e953..6a0699874a 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -13,78 +13,71 @@ import java.util.stream.Collectors; @Path("/movies") public class MovieCrudService { - private Map inventory = new HashMap(); - + private Map inventory = new HashMap(); @GET @Path("/getinfo") - @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbId(@QueryParam("imdbId") String imdbId){ + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Movie movieByImdbId(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling getinfo for a given ImdbID***"); - if(inventory.containsKey(imdbId)){ + if (inventory.containsKey(imdbId)) { return inventory.get(imdbId); - }else return null; + } else + return null; } - @POST @Path("/addmovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Response addMovie(Movie movie){ + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Response addMovie(Movie movie) { System.out.println("*** Calling addMovie ***"); - if (null!=inventory.get(movie.getImdbId())){ - return Response.status(Response.Status.NOT_MODIFIED) - .entity("Movie is Already in the database.").build(); + if (null != inventory.get(movie.getImdbId())) { + return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is Already in the database.").build(); } - inventory.put(movie.getImdbId(),movie); + inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.CREATED).build(); } - @PUT @Path("/updatemovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Response updateMovie(Movie movie){ + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Response updateMovie(Movie movie) { System.out.println("*** Calling updateMovie ***"); - if (null==inventory.get(movie.getImdbId())){ - return Response.status(Response.Status.NOT_MODIFIED) - .entity("Movie is not in the database.\nUnable to Update").build(); + if (null == inventory.get(movie.getImdbId())) { + return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is not in the database.\nUnable to Update").build(); } - inventory.put(movie.getImdbId(),movie); + inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.OK).build(); } - @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbId") String imdbId){ + public Response deleteMovie(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling deleteMovie ***"); - if (null==inventory.get(imdbId)){ - return Response.status(Response.Status.NOT_FOUND) - .entity("Movie is not in the database.\nUnable to Delete").build(); + if (null == inventory.get(imdbId)) { + return Response.status(Response.Status.NOT_FOUND).entity("Movie is not in the database.\nUnable to Delete").build(); } inventory.remove(imdbId); return Response.status(Response.Status.OK).build(); } - @GET @Path("/listmovies") - @Produces({"application/json"}) - public List listMovies(){ + @Produces({ "application/json" }) + public List listMovies() { return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml index 84d75934a7..7879603d19 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -1,16 +1,16 @@ - - - - + + + + - - - - - + + + + + - - + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index 1e7f64004d..d5f00293f4 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -1,13 +1,13 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> - RestEasy Example + RestEasy Example - - resteasy.servlet.mapping.prefix - /rest - + + resteasy.servlet.mapping.prefix + /rest + \ No newline at end of file diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java index faa39e0199..3760ae2415 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -21,14 +21,14 @@ import java.util.Locale; public class RestEasyClientTest { - Movie transformerMovie=null; - Movie batmanMovie=null; - ObjectMapper jsonMapper=null; + Movie transformerMovie = null; + Movie batmanMovie = null; + ObjectMapper jsonMapper = null; @Before public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); jsonMapper.setDateFormat(sdf); @@ -69,7 +69,7 @@ public class RestEasyClientTest { @Test public void testMovieByImdbId() { - String transformerImdbId="tt0418279"; + String transformerImdbId = "tt0418279"; ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); @@ -82,7 +82,6 @@ public class RestEasyClientTest { System.out.println(movies); } - @Test public void testAddMovie() { @@ -99,10 +98,9 @@ public class RestEasyClientTest { } moviesResponse.close(); - System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); } - @Test public void testDeleteMovi1e() { @@ -116,14 +114,13 @@ public class RestEasyClientTest { if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); + throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); - System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); } - @Test public void testUpdateMovie() { @@ -137,11 +134,11 @@ public class RestEasyClientTest { moviesResponse = simple.updateMovie(batmanMovie); if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); - System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); } } \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json index 28061d5bf9..173901c948 100644 --- a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json @@ -16,7 +16,7 @@ "metascore": "66", "imdbRating": "7.6", "imdbVotes": "256,000", - "imdbID": "tt0096895", + "imdbId": "tt0096895", "type": "movie", "response": "True" } \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json index a3b033a8ba..a4fd061a82 100644 --- a/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json @@ -16,7 +16,7 @@ "metascore": "61", "imdbRating": "7.1", "imdbVotes": "492,225", - "imdbID": "tt0418279", + "imdbId": "tt0418279", "type": "movie", "response": "True" } \ No newline at end of file From 06bbf19265938d444d07841989397369cf01d3fd Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Mon, 8 Feb 2016 16:08:15 +0100 Subject: [PATCH 236/309] CleanUp and reformatting Code. --- .../src/main/java/com/baeldung/server/MovieCrudService.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 6a0699874a..b7f3215f3f 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -26,7 +26,6 @@ public class MovieCrudService { return inventory.get(imdbId); } else return null; - } @POST @@ -41,7 +40,6 @@ public class MovieCrudService { } inventory.put(movie.getImdbId(), movie); - return Response.status(Response.Status.CREATED).build(); } @@ -55,9 +53,9 @@ public class MovieCrudService { if (null == inventory.get(movie.getImdbId())) { return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is not in the database.\nUnable to Update").build(); } + inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.OK).build(); - } @DELETE @@ -80,7 +78,6 @@ public class MovieCrudService { public List listMovies() { return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); - } } From 4d3ce9afe9cf7c73a2955c0852c3b335828f3c3a Mon Sep 17 00:00:00 2001 From: Oleksandr Borkovskyi Date: Tue, 9 Feb 2016 13:59:35 +0200 Subject: [PATCH 237/309] Updated test --- .../src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java index 4569019e60..903381bd29 100644 --- a/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java +++ b/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java @@ -27,7 +27,7 @@ public class GuavaMiscUtilsTest { List stackTraceElements = Throwables.lazyStackTrace(e); - assertEquals(27, stackTraceElements.size()); + assertTrue(stackTraceElements.size() > 0); } @Test From 420cbb202b3d101b10ea1b4eb9f8784ede50f112 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 9 Feb 2016 14:27:46 +0200 Subject: [PATCH 238/309] Update README.md --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 9a7c0d3776..23fe12465f 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -12,3 +12,4 @@ - [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set) - [Java – Write to File](http://www.baeldung.com/java-write-to-file) - [Java Scanner](http://www.baeldung.com/java-scanner) +- [Java Timer](http://www.baeldung.com/java-timer-and-timertask) From 0757706c4718548c8031ef97be8c702196689977 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 9 Feb 2016 14:30:27 +0200 Subject: [PATCH 239/309] Update README.md --- jackson/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jackson/README.md b/jackson/README.md index 046c6b6cfb..d49ad9088a 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -10,3 +10,4 @@ - [Jackson – Custom Deserializer](http://www.baeldung.com/jackson-deserialization) - [Jackson Exceptions – Problems and Solutions](http://www.baeldung.com/jackson-exception) - [Jackson Date](http://www.baeldung.com/jackson-serialize-dates) +- [Jackson – Bidirectional Relationships](http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion) From 86157e6beeb25cd85221038fbeb7291b48127aef Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 9 Feb 2016 14:31:59 +0200 Subject: [PATCH 240/309] Update README.md --- spring-security-login-and-registration/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-login-and-registration/README.md b/spring-security-login-and-registration/README.md index a5a9701ff8..57e7fd28f0 100644 --- a/spring-security-login-and-registration/README.md +++ b/spring-security-login-and-registration/README.md @@ -7,7 +7,7 @@ - [Spring Security Registration Tutorial](http://www.baeldung.com/spring-security-registration) - [The Registration Process With Spring Security](http://www.baeldung.com/registration-with-spring-mvc-and-spring-security) - [Registration – Activate a New Account by Email](http://www.baeldung.com/registration-verify-user-by-email) - +- [Registration with Spring Security – Password Encoding](http://www.baeldung.com/spring-security-registration-password-encoding-bcrypt) ### Build the Project ``` From 58d169cd241c998618969c2ead01eac5b2262ee9 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 9 Feb 2016 14:33:43 +0200 Subject: [PATCH 241/309] Update README.md --- spring-security-login-and-registration/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-login-and-registration/README.md b/spring-security-login-and-registration/README.md index 57e7fd28f0..299d096c37 100644 --- a/spring-security-login-and-registration/README.md +++ b/spring-security-login-and-registration/README.md @@ -8,6 +8,7 @@ - [The Registration Process With Spring Security](http://www.baeldung.com/registration-with-spring-mvc-and-spring-security) - [Registration – Activate a New Account by Email](http://www.baeldung.com/registration-verify-user-by-email) - [Registration with Spring Security – Password Encoding](http://www.baeldung.com/spring-security-registration-password-encoding-bcrypt) +- [Spring Security – Roles and Privileges](http://www.baeldung.com/role-and-privilege-for-spring-security-registration) ### Build the Project ``` From d806fa3925b681e4e81a74de4a27dc093d267806 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 9 Feb 2016 14:35:18 +0200 Subject: [PATCH 242/309] Update README.md --- spring-security-rest-full/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index cffbcf40f0..64478589a3 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -13,6 +13,7 @@ - [Integration Testing with the Maven Cargo plugin](http://www.baeldung.com/2011/10/16/how-to-set-up-integration-testing-with-the-maven-cargo-plugin/) - [Introduction to Spring Data JPA](http://www.baeldung.com/2011/12/22/the-persistence-layer-with-spring-data-jpa/) - [Project Configuration with Spring](http://www.baeldung.com/2012/03/12/project-configuration-with-spring/) +- [REST Query Language with Spring and JPA Criteria](http://www.baeldung.com/rest-search-language-spring-jpa-criteria) ### Build the Project From ad0dd95004b88106744065cf68c28770433466bf Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 9 Feb 2016 14:38:17 +0200 Subject: [PATCH 243/309] Update README.md --- spring-security-rest-full/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index 64478589a3..c5f52f44ad 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -14,6 +14,7 @@ - [Introduction to Spring Data JPA](http://www.baeldung.com/2011/12/22/the-persistence-layer-with-spring-data-jpa/) - [Project Configuration with Spring](http://www.baeldung.com/2012/03/12/project-configuration-with-spring/) - [REST Query Language with Spring and JPA Criteria](http://www.baeldung.com/rest-search-language-spring-jpa-criteria) +- [REST Query Language with Spring Data JPA Specifications](http://www.baeldung.com/rest-api-search-language-spring-data-specifications) ### Build the Project From 00ecb8c947a542eba055e214e3cda4d17a43c903 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 9 Feb 2016 14:43:43 +0200 Subject: [PATCH 244/309] Update README.md --- spring-security-rest-full/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index c5f52f44ad..e2db0e0307 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -15,6 +15,7 @@ - [Project Configuration with Spring](http://www.baeldung.com/2012/03/12/project-configuration-with-spring/) - [REST Query Language with Spring and JPA Criteria](http://www.baeldung.com/rest-search-language-spring-jpa-criteria) - [REST Query Language with Spring Data JPA Specifications](http://www.baeldung.com/rest-api-search-language-spring-data-specifications) +- [REST Query Language with Spring Data JPA and QueryDSL](http://www.baeldung.com/rest-api-search-language-spring-data-querydsl) ### Build the Project From 2bad287a2eee1acd22deaf9b6ef5c00d08a6d149 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 9 Feb 2016 14:44:49 +0200 Subject: [PATCH 245/309] Update README.md --- spring-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-jpa/README.md b/spring-jpa/README.md index da55ca7b75..f974c6e22c 100644 --- a/spring-jpa/README.md +++ b/spring-jpa/README.md @@ -9,3 +9,4 @@ - [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa) - [JPA Pagination](http://www.baeldung.com/jpa-pagination) - [Sorting with JPA](http://www.baeldung.com/jpa-sort) +- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) From 5d896c28d386e6f86783dac649f0ba10fd1d54ff Mon Sep 17 00:00:00 2001 From: David Morley Date: Wed, 10 Feb 2016 05:14:57 -0600 Subject: [PATCH 246/309] Clean up Guava 19 examples --- .../test/java/com/baeldung/guava/GuavaMiscUtilsTest.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java index 903381bd29..c7b8441b78 100644 --- a/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java +++ b/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java @@ -1,16 +1,9 @@ package com.baeldung.guava; -import com.baeldung.guava.entity.User; -import com.google.common.base.CharMatcher; import com.google.common.base.Throwables; import com.google.common.collect.*; -import com.google.common.hash.HashCode; -import com.google.common.hash.HashFunction; -import com.google.common.hash.Hashing; -import com.google.common.reflect.TypeToken; import org.junit.Test; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; From ed0c9aca109f02ea1e68db24df642578c67dc501 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:33:35 +0200 Subject: [PATCH 247/309] Update README.md --- spring-security-login-and-registration/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-login-and-registration/README.md b/spring-security-login-and-registration/README.md index 299d096c37..7235ef3bf6 100644 --- a/spring-security-login-and-registration/README.md +++ b/spring-security-login-and-registration/README.md @@ -9,6 +9,7 @@ - [Registration – Activate a New Account by Email](http://www.baeldung.com/registration-verify-user-by-email) - [Registration with Spring Security – Password Encoding](http://www.baeldung.com/spring-security-registration-password-encoding-bcrypt) - [Spring Security – Roles and Privileges](http://www.baeldung.com/role-and-privilege-for-spring-security-registration) +- [Prevent Brute Force Authentication Attempts with Spring Security](http://www.baeldung.com/spring-security-block-brute-force-authentication-attempts) ### Build the Project ``` From 855c8b153ca209f171750f069bf007ecb520b803 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:34:34 +0200 Subject: [PATCH 248/309] Update README.md --- spring-security-login-and-registration/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-login-and-registration/README.md b/spring-security-login-and-registration/README.md index 7235ef3bf6..8f47992c1d 100644 --- a/spring-security-login-and-registration/README.md +++ b/spring-security-login-and-registration/README.md @@ -10,6 +10,7 @@ - [Registration with Spring Security – Password Encoding](http://www.baeldung.com/spring-security-registration-password-encoding-bcrypt) - [Spring Security – Roles and Privileges](http://www.baeldung.com/role-and-privilege-for-spring-security-registration) - [Prevent Brute Force Authentication Attempts with Spring Security](http://www.baeldung.com/spring-security-block-brute-force-authentication-attempts) +- [Spring Security – Reset Your Password](http://www.baeldung.com/spring-security-registration-i-forgot-my-password) ### Build the Project ``` From 32373392a952a6c5bdb72fbc5754202889e4962c Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:35:55 +0200 Subject: [PATCH 249/309] Update README.md --- spring-security-rest-full/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index e2db0e0307..3df3947d5e 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -16,6 +16,7 @@ - [REST Query Language with Spring and JPA Criteria](http://www.baeldung.com/rest-search-language-spring-jpa-criteria) - [REST Query Language with Spring Data JPA Specifications](http://www.baeldung.com/rest-api-search-language-spring-data-specifications) - [REST Query Language with Spring Data JPA and QueryDSL](http://www.baeldung.com/rest-api-search-language-spring-data-querydsl) +- [REST Query Language – Advanced Search Operations](http://www.baeldung.com/rest-api-query-search-language-more-operations) ### Build the Project From bf6519b860da52ed8491c7bddeb7cc2d7d684dab Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:37:24 +0200 Subject: [PATCH 250/309] Update README.md --- spring-security-login-and-registration/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-login-and-registration/README.md b/spring-security-login-and-registration/README.md index 8f47992c1d..5b1980dcbf 100644 --- a/spring-security-login-and-registration/README.md +++ b/spring-security-login-and-registration/README.md @@ -11,6 +11,7 @@ - [Spring Security – Roles and Privileges](http://www.baeldung.com/role-and-privilege-for-spring-security-registration) - [Prevent Brute Force Authentication Attempts with Spring Security](http://www.baeldung.com/spring-security-block-brute-force-authentication-attempts) - [Spring Security – Reset Your Password](http://www.baeldung.com/spring-security-registration-i-forgot-my-password) +- [Spring Security Registration – Resend Verification Email](http://www.baeldung.com/spring-security-registration-verification-email) ### Build the Project ``` From e051f36401d19a16a0b36af987807a9f48140a22 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:41:29 +0200 Subject: [PATCH 251/309] Update README.md --- spring-security-login-and-registration/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-login-and-registration/README.md b/spring-security-login-and-registration/README.md index 5b1980dcbf..ee565dca65 100644 --- a/spring-security-login-and-registration/README.md +++ b/spring-security-login-and-registration/README.md @@ -12,6 +12,7 @@ - [Prevent Brute Force Authentication Attempts with Spring Security](http://www.baeldung.com/spring-security-block-brute-force-authentication-attempts) - [Spring Security – Reset Your Password](http://www.baeldung.com/spring-security-registration-i-forgot-my-password) - [Spring Security Registration – Resend Verification Email](http://www.baeldung.com/spring-security-registration-verification-email) +- [The Registration API becomes RESTful](http://www.baeldung.com/registration-restful-api) ### Build the Project ``` From 24a8e3803ce097e584b2b1c46f7ff4b497ce4912 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:42:54 +0200 Subject: [PATCH 252/309] Update README.md --- spring-security-rest-full/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index 3df3947d5e..6b56f4b918 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -17,6 +17,7 @@ - [REST Query Language with Spring Data JPA Specifications](http://www.baeldung.com/rest-api-search-language-spring-data-specifications) - [REST Query Language with Spring Data JPA and QueryDSL](http://www.baeldung.com/rest-api-search-language-spring-data-querydsl) - [REST Query Language – Advanced Search Operations](http://www.baeldung.com/rest-api-query-search-language-more-operations) +- [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) ### Build the Project From 6b0d2165ce7c67a1d367c825dde605e2e121b78a Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:44:08 +0200 Subject: [PATCH 253/309] Update README.md --- spring-security-login-and-registration/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-login-and-registration/README.md b/spring-security-login-and-registration/README.md index ee565dca65..e1b3e61acc 100644 --- a/spring-security-login-and-registration/README.md +++ b/spring-security-login-and-registration/README.md @@ -13,6 +13,7 @@ - [Spring Security – Reset Your Password](http://www.baeldung.com/spring-security-registration-i-forgot-my-password) - [Spring Security Registration – Resend Verification Email](http://www.baeldung.com/spring-security-registration-verification-email) - [The Registration API becomes RESTful](http://www.baeldung.com/registration-restful-api) +- [Registration – Password Strength and Rules](http://www.baeldung.com/registration-password-strength-and-rules) ### Build the Project ``` From 11065cd00481cc472e9144a4274e7400a3ad53ab Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:45:30 +0200 Subject: [PATCH 254/309] Update README.md --- spring-security-login-and-registration/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-login-and-registration/README.md b/spring-security-login-and-registration/README.md index e1b3e61acc..07fb21bfff 100644 --- a/spring-security-login-and-registration/README.md +++ b/spring-security-login-and-registration/README.md @@ -14,6 +14,7 @@ - [Spring Security Registration – Resend Verification Email](http://www.baeldung.com/spring-security-registration-verification-email) - [The Registration API becomes RESTful](http://www.baeldung.com/registration-restful-api) - [Registration – Password Strength and Rules](http://www.baeldung.com/registration-password-strength-and-rules) +- [Updating your Password](http://www.baeldung.com/updating-your-password/) ### Build the Project ``` From 95f51e577bc80b8cafe200d2d9ff5b9732eb9566 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:46:41 +0200 Subject: [PATCH 255/309] Update README.md --- spring-security-rest-full/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index 6b56f4b918..b592f7558c 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -18,6 +18,7 @@ - [REST Query Language with Spring Data JPA and QueryDSL](http://www.baeldung.com/rest-api-search-language-spring-data-querydsl) - [REST Query Language – Advanced Search Operations](http://www.baeldung.com/rest-api-query-search-language-more-operations) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) +- [REST Query Language with RSQL](http://www.baeldung.com/rest-api-search-language-rsql-fiql) ### Build the Project From 9f3be320b49901d8900cab69d010f50346e579c4 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:47:44 +0200 Subject: [PATCH 256/309] Update README.md --- httpclient/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/httpclient/README.md b/httpclient/README.md index 1cf788287c..e06c57da71 100644 --- a/httpclient/README.md +++ b/httpclient/README.md @@ -16,3 +16,4 @@ - [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication) - [Multipart Upload with HttpClient 4](http://www.baeldung.com/httpclient-multipart-upload) - [HttpAsyncClient Tutorial](http://www.baeldung.com/httpasyncclient-tutorial) +- [HttpClient 4 Tutorial](http://www.baeldung.com/httpclient-guide) From ac96fae1a7bd262e77ae1e51b650ad2115bf35a3 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:50:01 +0200 Subject: [PATCH 257/309] Update README.md --- jackson/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jackson/README.md b/jackson/README.md index d49ad9088a..c17d89912f 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -11,3 +11,4 @@ - [Jackson Exceptions – Problems and Solutions](http://www.baeldung.com/jackson-exception) - [Jackson Date](http://www.baeldung.com/jackson-serialize-dates) - [Jackson – Bidirectional Relationships](http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion) +- [Jackson JSON Tutorial](http://www.baeldung.com/jackson) From dbaf47927008cf4fb467d93a66b55982df354083 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:50:52 +0200 Subject: [PATCH 258/309] Update README.md --- jackson/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jackson/README.md b/jackson/README.md index c17d89912f..cd08926386 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -12,3 +12,4 @@ - [Jackson Date](http://www.baeldung.com/jackson-serialize-dates) - [Jackson – Bidirectional Relationships](http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion) - [Jackson JSON Tutorial](http://www.baeldung.com/jackson) +- [Jackson – Working with Maps and nulls](http://www.baeldung.com/jackson-map-null-values-or-null-key) From c273b4eda0ce1a5011dca9c04550d0763309a069 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:52:25 +0200 Subject: [PATCH 259/309] Update README.md --- jackson/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jackson/README.md b/jackson/README.md index cd08926386..1a445b701b 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -13,3 +13,4 @@ - [Jackson – Bidirectional Relationships](http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion) - [Jackson JSON Tutorial](http://www.baeldung.com/jackson) - [Jackson – Working with Maps and nulls](http://www.baeldung.com/jackson-map-null-values-or-null-key) +- [Jackson – Decide What Fields Get Serialized/Deserializaed](http://www.baeldung.com/jackson-field-serializable-deserializable-or-not) From 9bba394195c6d274d4a120cc0be6c0ba869a774d Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 13:53:22 +0200 Subject: [PATCH 260/309] Update README.md --- jackson/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jackson/README.md b/jackson/README.md index 1a445b701b..e226721d61 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -14,3 +14,4 @@ - [Jackson JSON Tutorial](http://www.baeldung.com/jackson) - [Jackson – Working with Maps and nulls](http://www.baeldung.com/jackson-map-null-values-or-null-key) - [Jackson – Decide What Fields Get Serialized/Deserializaed](http://www.baeldung.com/jackson-field-serializable-deserializable-or-not) +- [A Guide to Jackson Annotations](http://www.baeldung.com/jackson-annotations) From 6a56dcaa15798e1f6724f3c74683f4e8512778f7 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:03:31 +0200 Subject: [PATCH 261/309] Create README.md --- spring-data-mongodb/README.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 spring-data-mongodb/README.md diff --git a/spring-data-mongodb/README.md b/spring-data-mongodb/README.md new file mode 100644 index 0000000000..7d194b72c8 --- /dev/null +++ b/spring-data-mongodb/README.md @@ -0,0 +1,7 @@ +========= + +## Spring Data MongoDB + + +### Relevant Articles: +-[A Guide to Queries in Spring Data MongoDB](http://www.baeldung.com/queries-in-spring-data-mongodb) From 034c57571330f02a7616ca4406478728c10c42d6 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:03:50 +0200 Subject: [PATCH 262/309] Update README.md --- spring-data-mongodb/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-data-mongodb/README.md b/spring-data-mongodb/README.md index 7d194b72c8..d92edc8940 100644 --- a/spring-data-mongodb/README.md +++ b/spring-data-mongodb/README.md @@ -4,4 +4,4 @@ ### Relevant Articles: --[A Guide to Queries in Spring Data MongoDB](http://www.baeldung.com/queries-in-spring-data-mongodb) +- [A Guide to Queries in Spring Data MongoDB](http://www.baeldung.com/queries-in-spring-data-mongodb) From 344c29cc11c84e3de0d042fa448076d5bd63aa24 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:11:27 +0200 Subject: [PATCH 263/309] Update README.md --- spring-data-mongodb/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-data-mongodb/README.md b/spring-data-mongodb/README.md index d92edc8940..4a140c1be6 100644 --- a/spring-data-mongodb/README.md +++ b/spring-data-mongodb/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [A Guide to Queries in Spring Data MongoDB](http://www.baeldung.com/queries-in-spring-data-mongodb) +- [Spring Data MongoDB – Indexes, Annotations and Converters](http://www.baeldung.com/spring-data-mongodb-index-annotations-converter) From 04947776da282b21b1b640bef6d76e9167fe7aa5 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:12:20 +0200 Subject: [PATCH 264/309] Update README.md --- spring-data-mongodb/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-data-mongodb/README.md b/spring-data-mongodb/README.md index 4a140c1be6..e784176879 100644 --- a/spring-data-mongodb/README.md +++ b/spring-data-mongodb/README.md @@ -6,3 +6,4 @@ ### Relevant Articles: - [A Guide to Queries in Spring Data MongoDB](http://www.baeldung.com/queries-in-spring-data-mongodb) - [Spring Data MongoDB – Indexes, Annotations and Converters](http://www.baeldung.com/spring-data-mongodb-index-annotations-converter) +- [Custom Cascading in Spring Data MongoDB](http://www.baeldung.com/cascading-with-dbref-and-lifecycle-events-in-spring-data-mongodb) From 11b30eea02668bf6c54f5e78a48821e843b07672 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:13:27 +0200 Subject: [PATCH 265/309] Update README.md --- spring-security-rest-full/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index b592f7558c..c6d6ed5848 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -19,6 +19,7 @@ - [REST Query Language – Advanced Search Operations](http://www.baeldung.com/rest-api-query-search-language-more-operations) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) - [REST Query Language with RSQL](http://www.baeldung.com/rest-api-search-language-rsql-fiql) +- [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) ### Build the Project From 09e896a3577ff8a42c8516f972bdaf8c5abdeeda Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:20:12 +0200 Subject: [PATCH 266/309] Create README.md --- spring-katharsis/README.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 spring-katharsis/README.md diff --git a/spring-katharsis/README.md b/spring-katharsis/README.md new file mode 100644 index 0000000000..ec0141f41a --- /dev/null +++ b/spring-katharsis/README.md @@ -0,0 +1,6 @@ +========= + +## Java Web Application + +### Relevant Articles: +- [JSON API in a Java Web Application](http://www.baeldung.com/json-api-java-spring-web-app) From 15b5ac439e675d47bd1151caad401654e129ab92 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:24:04 +0200 Subject: [PATCH 267/309] Update README.md --- spring-all/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-all/README.md b/spring-all/README.md index baab7ec083..977b8b7357 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -8,3 +8,4 @@ This project is used to replicate Spring Exceptions only. ### Relevant articles: - [Properties with Spring](http://www.baeldung.com/2012/02/06/properties-with-spring) - checkout the `org.baeldung.properties` package for all scenarios of properties injection and usage - [Spring Profiles](http://www.baeldung.com/spring-profiles) +- [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) From 0b55104f32e22152e9dd2657a3359c0f2fe57e85 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:25:03 +0200 Subject: [PATCH 268/309] Update README.md --- spring-data-mongodb/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-data-mongodb/README.md b/spring-data-mongodb/README.md index e784176879..c5d2d2df41 100644 --- a/spring-data-mongodb/README.md +++ b/spring-data-mongodb/README.md @@ -7,3 +7,4 @@ - [A Guide to Queries in Spring Data MongoDB](http://www.baeldung.com/queries-in-spring-data-mongodb) - [Spring Data MongoDB – Indexes, Annotations and Converters](http://www.baeldung.com/spring-data-mongodb-index-annotations-converter) - [Custom Cascading in Spring Data MongoDB](http://www.baeldung.com/cascading-with-dbref-and-lifecycle-events-in-spring-data-mongodb) +- [GridFS in Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-gridfs) From f602cea186c7fe224b2c537116d4e7db9fe73e97 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:25:49 +0200 Subject: [PATCH 269/309] Update README.md --- spring-mvc-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index bf76c7e1d4..113f690920 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -4,3 +4,4 @@ ### Relevant Articles: +- [http://www.baeldung.com/spring-bean-annotations](http://www.baeldung.com/spring-bean-annotations) From d91f7672ff4f8f4b7938be4fd686f3685cce4ac8 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:26:17 +0200 Subject: [PATCH 270/309] Update README.md --- spring-mvc-java/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 113f690920..ccbd1288f0 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -4,4 +4,4 @@ ### Relevant Articles: -- [http://www.baeldung.com/spring-bean-annotations](http://www.baeldung.com/spring-bean-annotations) +- [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) From eb3b30e9b1fa190c26629ef7152607e1c7e02bea Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:27:10 +0200 Subject: [PATCH 271/309] Update README.md --- spring-security-rest/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index a3fce32a9c..d17cb24f7e 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Spring REST Service Security](http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/) +- [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) From 238f5d340f286e64f91da86a0eb49864e29ea4b6 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:28:15 +0200 Subject: [PATCH 272/309] Update README.md --- spring-mvc-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index ccbd1288f0..f6bb37b600 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) +- [Introduction to Pointcut Expressions in Spring](http://www.baeldung.com/spring-aop-pointcut-tutorial) From fda7b00e6be4707912c038b7d28e74b52964839b Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:29:26 +0200 Subject: [PATCH 273/309] Update README.md --- spring-mvc-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index f6bb37b600..2de2373149 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -6,3 +6,4 @@ ### Relevant Articles: - [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) - [Introduction to Pointcut Expressions in Spring](http://www.baeldung.com/spring-aop-pointcut-tutorial) +- [Introduction to Advice Types in Spring](http://www.baeldung.com/spring-aop-advice-tutorial) From 03ddc9056e271240838413ddd857d520d2995db2 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:30:23 +0200 Subject: [PATCH 274/309] Update README.md --- spring-data-cassandra/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-data-cassandra/README.md b/spring-data-cassandra/README.md index a245ff62a1..85ea3b8649 100644 --- a/spring-data-cassandra/README.md +++ b/spring-data-cassandra/README.md @@ -2,7 +2,7 @@ ### Relevant Articles: - [Introduction to Spring Data Cassandra](http://www.baeldung.com/spring-data-cassandra-tutorial) - +- [http://www.baeldung.com/spring-data-cassandratemplate-cqltemplate](http://www.baeldung.com/spring-data-cassandratemplate-cqltemplate) ### Build the Project with Tests Running ``` mvn clean install From cde526808ad9c504871c6aa8b7aecb28f2b9542b Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:31:11 +0200 Subject: [PATCH 275/309] Update README.md --- spring-data-cassandra/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-data-cassandra/README.md b/spring-data-cassandra/README.md index 85ea3b8649..456eefcf18 100644 --- a/spring-data-cassandra/README.md +++ b/spring-data-cassandra/README.md @@ -2,7 +2,8 @@ ### Relevant Articles: - [Introduction to Spring Data Cassandra](http://www.baeldung.com/spring-data-cassandra-tutorial) -- [http://www.baeldung.com/spring-data-cassandratemplate-cqltemplate](http://www.baeldung.com/spring-data-cassandratemplate-cqltemplate) +- [Using the CassandraTemplate from Spring Data](http://www.baeldung.com/spring-data-cassandratemplate-cqltemplate) + ### Build the Project with Tests Running ``` mvn clean install From cd8c2517dbf51fdd0a590afb8ab3b9f000ab62b3 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:32:10 +0200 Subject: [PATCH 276/309] Update README.md --- guava18/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/guava18/README.md b/guava18/README.md index 8960b4676e..9924d7c16f 100644 --- a/guava18/README.md +++ b/guava18/README.md @@ -7,7 +7,6 @@ - [Guava Collections Cookbook](http://www.baeldung.com/guava-collections) - [Guava Ordering Cookbook](http://www.baeldung.com/guava-order) - [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates) - - [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays) - - [Partition a List in Java](http://www.baeldung.com/java-list-split) +- [Guava 18: What’s New?](http://www.baeldung.com/whats-new-in-guava-18) From f7bd8093d037108b03591e7c32b584b5c495fdba Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:33:03 +0200 Subject: [PATCH 277/309] Update README.md --- core-java-8/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-8/README.md b/core-java-8/README.md index e3fa3f9848..62040ba5cf 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: // - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) - [Java – Directory Size](http://www.baeldung.com/java-folder-size) +- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources) From 2b4b9fa79c3fdb70590e7ee8f356da6e2cdac740 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:33:55 +0200 Subject: [PATCH 278/309] Update README.md --- spring-security-mvc-ldap/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-mvc-ldap/README.md b/spring-security-mvc-ldap/README.md index 260b4b38d8..686f611f99 100644 --- a/spring-security-mvc-ldap/README.md +++ b/spring-security-mvc-ldap/README.md @@ -5,7 +5,7 @@ ### Relevant Article: - [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll) - [Spring Security Basic Authentication](http://www.baeldung.com/spring-security-basic-authentication) - +- [Intro to Spring Security LDAP](http://www.baeldung.com/spring-security-ldap) ### Notes - the project uses Spring Boot - simply run 'SampleLDAPApplication.java' to start up Spring Boot with a Tomcat container and embedded LDAP server. From 573f4bed69eafd21bbbb3908f538bb746de175dc Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Wed, 10 Feb 2016 14:35:56 +0200 Subject: [PATCH 279/309] Update README.md --- spring-batch/README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/spring-batch/README.md b/spring-batch/README.md index 8b13789179..953e652cea 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -1 +1,7 @@ +========= +## Spring Batch + + +### Relevant Articles: +- [Introduction to Spring Batch](http://www.baeldung.com/introduction-to-spring-batch) From ebce69d28d14f77da8c390b92db58d15cd66ce04 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 02:25:41 +0200 Subject: [PATCH 280/309] Update README.md --- spring-data-mongodb/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-data-mongodb/README.md b/spring-data-mongodb/README.md index c5d2d2df41..d656bc897c 100644 --- a/spring-data-mongodb/README.md +++ b/spring-data-mongodb/README.md @@ -8,3 +8,4 @@ - [Spring Data MongoDB – Indexes, Annotations and Converters](http://www.baeldung.com/spring-data-mongodb-index-annotations-converter) - [Custom Cascading in Spring Data MongoDB](http://www.baeldung.com/cascading-with-dbref-and-lifecycle-events-in-spring-data-mongodb) - [GridFS in Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-gridfs) +- [Introduction to Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-tutorial) From c3e5eb7ccfd942761e01d9b15ed21cf57f8511fe Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 02:40:35 +0200 Subject: [PATCH 281/309] Update README.md --- core-java-8/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-8/README.md b/core-java-8/README.md index 62040ba5cf..ab89bbdaf2 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -6,3 +6,4 @@ // - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) - [Java – Directory Size](http://www.baeldung.com/java-folder-size) - [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources) +- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) From a7cd46c02230f5f589fa58bb60e3873f092de5ec Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 02:45:49 +0200 Subject: [PATCH 282/309] Create README.md --- mockito-mocks-spring-beans/README.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 mockito-mocks-spring-beans/README.md diff --git a/mockito-mocks-spring-beans/README.md b/mockito-mocks-spring-beans/README.md new file mode 100644 index 0000000000..3ced7161fa --- /dev/null +++ b/mockito-mocks-spring-beans/README.md @@ -0,0 +1,7 @@ +========= + +## Mockito Mocks into Spring Beans + + +### Relevant Articles: +- [Injecting Mockito Mocks into Spring Beans](http://www.baeldung.com/injecting-mocks-in-spring) From fffeb216f5c22fa3399e61d4a0211c0595be9bfc Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 02:47:43 +0200 Subject: [PATCH 283/309] Update README.md --- spring-security-rest/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index d17cb24f7e..6261fbe83d 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -6,3 +6,4 @@ ### Relevant Articles: - [Spring REST Service Security](http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/) - [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) +- [Custom Error Message Handling for REST API](http://www.baeldung.com/global-error-handler-in-a-spring-rest-api) From ae8d5ca8db2087d120e236c8d1a01d693fb3068b Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 02:48:47 +0200 Subject: [PATCH 284/309] Update README.md --- spring-hibernate4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-hibernate4/README.md b/spring-hibernate4/README.md index acf20632fe..4c0c6706d6 100644 --- a/spring-hibernate4/README.md +++ b/spring-hibernate4/README.md @@ -7,6 +7,7 @@ - [The DAO with Spring 3 and Hibernate](http://www.baeldung.com/2011/12/02/the-persistence-layer-with-spring-3-1-and-hibernate/) - [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination) - [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort) +- [Auditing with JPA, Hibernate, and Spring Data JPA](http://www.baeldung.com/database-auditing-jpa) ### Quick Start From 80da6e8668dbe02bcd3777529ec801dafb10e8d9 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 02:51:08 +0200 Subject: [PATCH 285/309] Create README.md --- spring-freemarker/README.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 spring-freemarker/README.md diff --git a/spring-freemarker/README.md b/spring-freemarker/README.md new file mode 100644 index 0000000000..bd939d11e9 --- /dev/null +++ b/spring-freemarker/README.md @@ -0,0 +1,7 @@ +========= + +## Using FreeMarker in Spring MVC + + +### Relevant Articles: +- [Introduction to Using FreeMarker in Spring MVC](http://www.baeldung.com/freemarker-in-spring-mvc-tutorial) From 02ebbd4044ef107f69bc89823827f37064afe50b Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 02:52:17 +0200 Subject: [PATCH 286/309] Update README.md --- spring-security-rest-full/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index c6d6ed5848..f648c49244 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -20,7 +20,7 @@ - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) - [REST Query Language with RSQL](http://www.baeldung.com/rest-api-search-language-rsql-fiql) - [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) - +- [A Guide to CSRF Protection in Spring Security](http://www.baeldung.com/spring-security-csrf) ### Build the Project ``` From 7011fa40fec956a2bfce298d896129ccccc96354 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 02:53:18 +0200 Subject: [PATCH 287/309] Update README.md --- jackson/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jackson/README.md b/jackson/README.md index e226721d61..53b9c7c31d 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -15,3 +15,4 @@ - [Jackson – Working with Maps and nulls](http://www.baeldung.com/jackson-map-null-values-or-null-key) - [Jackson – Decide What Fields Get Serialized/Deserializaed](http://www.baeldung.com/jackson-field-serializable-deserializable-or-not) - [A Guide to Jackson Annotations](http://www.baeldung.com/jackson-annotations) +- [Working with Tree Model Nodes in Jackson](http://www.baeldung.com/jackson-json-node-tree-model) From edcb2e2e69edcc25c8f9233a899fab5020a2f7f4 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 02:54:21 +0200 Subject: [PATCH 288/309] Update README.md --- core-java-8/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-8/README.md b/core-java-8/README.md index ab89bbdaf2..8bef3a1be0 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -7,3 +7,4 @@ - [Java – Directory Size](http://www.baeldung.com/java-folder-size) - [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources) - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) +- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) From 71ef292b3a18992345b58007cb0b9c26d63ff56c Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 02:56:17 +0200 Subject: [PATCH 289/309] Create README.md --- spring-zuul/README.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 spring-zuul/README.md diff --git a/spring-zuul/README.md b/spring-zuul/README.md new file mode 100644 index 0000000000..41a77f70c8 --- /dev/null +++ b/spring-zuul/README.md @@ -0,0 +1,7 @@ +========= + +## Spring REST with a Zuul + + +### Relevant Articles: +- [Spring REST with a Zuul Proxy](http://www.baeldung.com/spring-rest-with-zuul-proxy) From e77e6ebfcf045138cf9e8b2cf9650516d09718e0 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 03:03:08 +0200 Subject: [PATCH 290/309] Update README.md --- spring-rest/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-rest/README.md b/spring-rest/README.md index 3b93b06d66..9d373962c4 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -7,3 +7,4 @@ - [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest) - [Redirect in Spring](http://www.baeldung.com/spring-redirect-and-forward) +- [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code) From b0d8d832804b8366d025e02f01e5d6ea2821af81 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Thu, 11 Feb 2016 03:04:45 +0200 Subject: [PATCH 291/309] Update README.md --- spring-mvc-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 2de2373149..e5264b0370 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -7,3 +7,4 @@ - [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) - [Introduction to Pointcut Expressions in Spring](http://www.baeldung.com/spring-aop-pointcut-tutorial) - [Introduction to Advice Types in Spring](http://www.baeldung.com/spring-aop-advice-tutorial) +- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) From 45358317b6b4f33ead9c4d923c3d7d3bf3e7c281 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 13 Feb 2016 22:25:31 +0200 Subject: [PATCH 292/309] OpenID Connect example --- spring-openid/.classpath | 32 ++++++++ spring-openid/.project | 48 +++++++++++ spring-openid/pom.xml | 68 ++++++++++++++++ .../config/GoogleOpenIdConnectConfig.java | 51 ++++++++++++ .../org/baeldung/config/HomeController.java | 22 +++++ .../org/baeldung/config/SecurityConfig.java | 49 +++++++++++ .../config/SpringOpenidApplication.java | 13 +++ .../security/OpenIdConnectFilter.java | 71 ++++++++++++++++ .../security/OpenIdConnectUserDetails.java | 81 +++++++++++++++++++ .../src/main/resources/application.properties | 6 ++ 10 files changed, 441 insertions(+) create mode 100644 spring-openid/.classpath create mode 100644 spring-openid/.project create mode 100644 spring-openid/pom.xml create mode 100644 spring-openid/src/main/java/org/baeldung/config/GoogleOpenIdConnectConfig.java create mode 100644 spring-openid/src/main/java/org/baeldung/config/HomeController.java create mode 100644 spring-openid/src/main/java/org/baeldung/config/SecurityConfig.java create mode 100644 spring-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java create mode 100644 spring-openid/src/main/java/org/baeldung/security/OpenIdConnectFilter.java create mode 100644 spring-openid/src/main/java/org/baeldung/security/OpenIdConnectUserDetails.java create mode 100644 spring-openid/src/main/resources/application.properties diff --git a/spring-openid/.classpath b/spring-openid/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-openid/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-openid/.project b/spring-openid/.project new file mode 100644 index 0000000000..81874eb896 --- /dev/null +++ b/spring-openid/.project @@ -0,0 +1,48 @@ + + + spring-openid + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-openid/pom.xml b/spring-openid/pom.xml new file mode 100644 index 0000000000..641fe93a09 --- /dev/null +++ b/spring-openid/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + org.baeldung + spring-openid + 0.0.1-SNAPSHOT + war + + spring-openid + Spring OpenID sample project + + + org.springframework.boot + spring-boot-starter-parent + 1.3.2.RELEASE + + + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.security.oauth + spring-security-oauth2 + + + + org.springframework.security + spring-security-jwt + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + diff --git a/spring-openid/src/main/java/org/baeldung/config/GoogleOpenIdConnectConfig.java b/spring-openid/src/main/java/org/baeldung/config/GoogleOpenIdConnectConfig.java new file mode 100644 index 0000000000..8e9c6e974e --- /dev/null +++ b/spring-openid/src/main/java/org/baeldung/config/GoogleOpenIdConnectConfig.java @@ -0,0 +1,51 @@ +package org.baeldung.config; + +import java.util.Arrays; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.client.OAuth2ClientContext; +import org.springframework.security.oauth2.client.OAuth2RestTemplate; +import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails; +import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; + +@Configuration +@EnableOAuth2Client +public class GoogleOpenIdConnectConfig { + @Value("${google.clientId}") + private String clientId; + + @Value("${google.clientSecret}") + private String clientSecret; + + @Value("${google.accessTokenUri}") + private String accessTokenUri; + + @Value("${google.userAuthorizationUri}") + private String userAuthorizationUri; + + @Value("${google.redirectUri}") + private String redirectUri; + + @Bean + public OAuth2ProtectedResourceDetails googleOpenId() { + final AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails(); + details.setClientId(clientId); + details.setClientSecret(clientSecret); + details.setAccessTokenUri(accessTokenUri); + details.setUserAuthorizationUri(userAuthorizationUri); + details.setScope(Arrays.asList("openid", "email")); + details.setPreEstablishedRedirectUri(redirectUri); + details.setUseCurrentUri(false); + return details; + } + + @Bean + public OAuth2RestTemplate googleOpenIdTemplate(final OAuth2ClientContext clientContext) { + final OAuth2RestTemplate template = new OAuth2RestTemplate(googleOpenId(), clientContext); + return template; + } + +} diff --git a/spring-openid/src/main/java/org/baeldung/config/HomeController.java b/spring-openid/src/main/java/org/baeldung/config/HomeController.java new file mode 100644 index 0000000000..f0a5378019 --- /dev/null +++ b/spring-openid/src/main/java/org/baeldung/config/HomeController.java @@ -0,0 +1,22 @@ +package org.baeldung.config; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class HomeController { + private final Logger logger = LoggerFactory.getLogger(getClass()); + + @RequestMapping("/") + @ResponseBody + public final String home() { + final String username = SecurityContextHolder.getContext().getAuthentication().getName(); + logger.info(username); + return "Welcome, " + username; + } + +} diff --git a/spring-openid/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-openid/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..d929bfd631 --- /dev/null +++ b/spring-openid/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,49 @@ +package org.baeldung.config; + +import org.baeldung.security.OpenIdConnectFilter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.oauth2.client.OAuth2RestTemplate; +import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter; +import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; +import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + @Autowired + private OAuth2RestTemplate restTemplate; + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Bean + public OpenIdConnectFilter myFilter() { + final OpenIdConnectFilter filter = new OpenIdConnectFilter("/google-login"); + filter.setRestTemplate(restTemplate); + return filter; + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http + .addFilterAfter(new OAuth2ClientContextFilter(), AbstractPreAuthenticatedProcessingFilter.class) + .addFilterAfter(myFilter(), OAuth2ClientContextFilter.class) + .httpBasic().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/google-login")) + .and() + .authorizeRequests() + // .antMatchers("/","/index*").permitAll() + .anyRequest().authenticated() + ; + + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java b/spring-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java new file mode 100644 index 0000000000..608e8a6819 --- /dev/null +++ b/spring-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java @@ -0,0 +1,13 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringOpenidApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringOpenidApplication.class, args); + } + +} diff --git a/spring-openid/src/main/java/org/baeldung/security/OpenIdConnectFilter.java b/spring-openid/src/main/java/org/baeldung/security/OpenIdConnectFilter.java new file mode 100644 index 0000000000..c0970ab3cf --- /dev/null +++ b/spring-openid/src/main/java/org/baeldung/security/OpenIdConnectFilter.java @@ -0,0 +1,71 @@ +package org.baeldung.security; + +import java.io.IOException; +import java.util.Map; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.jwt.Jwt; +import org.springframework.security.jwt.JwtHelper; +import org.springframework.security.oauth2.client.OAuth2RestOperations; +import org.springframework.security.oauth2.client.OAuth2RestTemplate; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; +import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; +import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class OpenIdConnectFilter extends AbstractAuthenticationProcessingFilter { + public OAuth2RestOperations restTemplate; + + public OpenIdConnectFilter(String defaultFilterProcessesUrl) { + super(defaultFilterProcessesUrl); + setAuthenticationManager(new NoopAuthenticationManager()); + } + + @Override + public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { + + OAuth2AccessToken accessToken; + try { + accessToken = restTemplate.getAccessToken(); + } catch (final OAuth2Exception e) { + throw new BadCredentialsException("Could not obtain access token", e); + } + try { + final String idToken = accessToken.getAdditionalInformation().get("id_token").toString(); + final Jwt tokenDecoded = JwtHelper.decode(idToken); + System.out.println("===== : " + tokenDecoded.getClaims()); + + final Map authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class); + + final OpenIdConnectUserDetails user = new OpenIdConnectUserDetails(authInfo, accessToken); + return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); + } catch (final InvalidTokenException e) { + throw new BadCredentialsException("Could not obtain user details from token", e); + } + + } + + public void setRestTemplate(OAuth2RestTemplate restTemplate2) { + restTemplate = restTemplate2; + + } + + private static class NoopAuthenticationManager implements AuthenticationManager { + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager"); + } + + } +} diff --git a/spring-openid/src/main/java/org/baeldung/security/OpenIdConnectUserDetails.java b/spring-openid/src/main/java/org/baeldung/security/OpenIdConnectUserDetails.java new file mode 100644 index 0000000000..f0d91fdc27 --- /dev/null +++ b/spring-openid/src/main/java/org/baeldung/security/OpenIdConnectUserDetails.java @@ -0,0 +1,81 @@ +package org.baeldung.security; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.oauth2.common.OAuth2AccessToken; + +public class OpenIdConnectUserDetails implements UserDetails { + + private static final long serialVersionUID = 1L; + + private String userId; + private String username; + private OAuth2AccessToken token; + + public OpenIdConnectUserDetails(Map userInfo, OAuth2AccessToken token) { + this.userId = userInfo.get("sub"); + this.username = userInfo.get("email"); + this.token = token; + } + + @Override + public String getUsername() { + return username; + } + + @Override + public Collection getAuthorities() { + return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")); + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public OAuth2AccessToken getToken() { + return token; + } + + public void setToken(OAuth2AccessToken token) { + this.token = token; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public String getPassword() { + return null; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + +} diff --git a/spring-openid/src/main/resources/application.properties b/spring-openid/src/main/resources/application.properties new file mode 100644 index 0000000000..fa567a164c --- /dev/null +++ b/spring-openid/src/main/resources/application.properties @@ -0,0 +1,6 @@ +server.port=8081 +google.clientId=497324626536-d6fphsh1qpl2o6j2j66nukajrfqc0rtq.apps.googleusercontent.com +google.clientSecret=vtueZycMsrRjjCjnY6JzbEZT +google.accessTokenUri=https://www.googleapis.com/oauth2/v3/token +google.userAuthorizationUri=https://accounts.google.com/o/oauth2/auth +google.redirectUri=http://localhost:8081/google-login \ No newline at end of file From 4b5ad0629a854078437e8248bbbf341165f7e4f8 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sat, 30 Jan 2016 17:48:56 +0100 Subject: [PATCH 293/309] RestEasy Tutorial, CRUD Services example --- RestEasy Example/pom.xml | 91 +++ .../src/main/java/com/baeldung/Movie.java | 535 ++++++++++++++++++ .../baeldung/client/ServicesInterface.java | 44 ++ .../server/service/MovieCrudService.java | 94 +++ .../server/service/RestEasyServices.java | 40 ++ .../src/main/resources/schema1.xsd | 29 + .../main/webapp/WEB-INF/classes/logback.xml | 3 + .../WEB-INF/jboss-deployment-structure.xml | 16 + .../src/main/webapp/WEB-INF/jboss-web.xml | 4 + .../src/main/webapp/WEB-INF/web.xml | 51 ++ .../com/baeldung/server/RestEasyClient.java | 50 ++ .../resources/server/movies/transformer.json | 22 + 12 files changed, 979 insertions(+) create mode 100644 RestEasy Example/pom.xml create mode 100644 RestEasy Example/src/main/java/com/baeldung/Movie.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java create mode 100644 RestEasy Example/src/main/resources/schema1.xsd create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml create mode 100644 RestEasy Example/src/main/webapp/WEB-INF/web.xml create mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java create mode 100644 RestEasy Example/src/test/resources/server/movies/transformer.json diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml new file mode 100644 index 0000000000..b16c5e8267 --- /dev/null +++ b/RestEasy Example/pom.xml @@ -0,0 +1,91 @@ + + + 4.0.0 + + com.baeldung + resteasy-tutorial + 1.0 + war + + + + jboss + http://repository.jboss.org/nexus/content/groups/public/ + + + + + 3.0.14.Final + runtime + + + + RestEasyTutorial + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + + org.jboss.resteasy + jaxrs-api + 3.0.12.Final + ${resteasy.scope} + + + + org.jboss.resteasy + resteasy-servlet-initializer + ${resteasy.version} + ${resteasy.scope} + + + jboss-jaxrs-api_2.0_spec + org.jboss.spec.javax.ws.rs + + + + + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + ${resteasy.scope} + + + + + javax.ws.rs + javax.ws.rs-api + 2.0.1 + + + + org.jboss.resteasy + resteasy-jackson-provider + ${resteasy.version} + ${resteasy.scope} + + + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy.version} + ${resteasy.scope} + + + + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/Movie.java new file mode 100644 index 0000000000..c0041d2e95 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/Movie.java @@ -0,0 +1,535 @@ + +package com.baeldung; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; + + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "movie", propOrder = { + "actors", + "awards", + "country", + "director", + "genre", + "imdbID", + "imdbRating", + "imdbVotes", + "language", + "metascore", + "plot", + "poster", + "rated", + "released", + "response", + "runtime", + "title", + "type", + "writer", + "year" +}) +public class Movie { + + protected String actors; + protected String awards; + protected String country; + protected String director; + protected String genre; + protected String imdbID; + protected String imdbRating; + protected String imdbVotes; + protected String language; + protected String metascore; + protected String plot; + protected String poster; + protected String rated; + protected String released; + protected String response; + protected String runtime; + protected String title; + protected String type; + protected String writer; + protected String year; + + /** + * Recupera il valore della propriet� actors. + * + * @return + * possible object is + * {@link String } + * + */ + public String getActors() { + return actors; + } + + /** + * Imposta il valore della propriet� actors. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setActors(String value) { + this.actors = value; + } + + /** + * Recupera il valore della propriet� awards. + * + * @return + * possible object is + * {@link String } + * + */ + public String getAwards() { + return awards; + } + + /** + * Imposta il valore della propriet� awards. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setAwards(String value) { + this.awards = value; + } + + /** + * Recupera il valore della propriet� country. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCountry() { + return country; + } + + /** + * Imposta il valore della propriet� country. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCountry(String value) { + this.country = value; + } + + /** + * Recupera il valore della propriet� director. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDirector() { + return director; + } + + /** + * Imposta il valore della propriet� director. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDirector(String value) { + this.director = value; + } + + /** + * Recupera il valore della propriet� genre. + * + * @return + * possible object is + * {@link String } + * + */ + public String getGenre() { + return genre; + } + + /** + * Imposta il valore della propriet� genre. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setGenre(String value) { + this.genre = value; + } + + /** + * Recupera il valore della propriet� imdbID. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbID() { + return imdbID; + } + + /** + * Imposta il valore della propriet� imdbID. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbID(String value) { + this.imdbID = value; + } + + /** + * Recupera il valore della propriet� imdbRating. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbRating() { + return imdbRating; + } + + /** + * Imposta il valore della propriet� imdbRating. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbRating(String value) { + this.imdbRating = value; + } + + /** + * Recupera il valore della propriet� imdbVotes. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbVotes() { + return imdbVotes; + } + + /** + * Imposta il valore della propriet� imdbVotes. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbVotes(String value) { + this.imdbVotes = value; + } + + /** + * Recupera il valore della propriet� language. + * + * @return + * possible object is + * {@link String } + * + */ + public String getLanguage() { + return language; + } + + /** + * Imposta il valore della propriet� language. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setLanguage(String value) { + this.language = value; + } + + /** + * Recupera il valore della propriet� metascore. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMetascore() { + return metascore; + } + + /** + * Imposta il valore della propriet� metascore. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMetascore(String value) { + this.metascore = value; + } + + /** + * Recupera il valore della propriet� plot. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPlot() { + return plot; + } + + /** + * Imposta il valore della propriet� plot. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPlot(String value) { + this.plot = value; + } + + /** + * Recupera il valore della propriet� poster. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPoster() { + return poster; + } + + /** + * Imposta il valore della propriet� poster. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPoster(String value) { + this.poster = value; + } + + /** + * Recupera il valore della propriet� rated. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRated() { + return rated; + } + + /** + * Imposta il valore della propriet� rated. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRated(String value) { + this.rated = value; + } + + /** + * Recupera il valore della propriet� released. + * + * @return + * possible object is + * {@link String } + * + */ + public String getReleased() { + return released; + } + + /** + * Imposta il valore della propriet� released. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setReleased(String value) { + this.released = value; + } + + /** + * Recupera il valore della propriet� response. + * + * @return + * possible object is + * {@link String } + * + */ + public String getResponse() { + return response; + } + + /** + * Imposta il valore della propriet� response. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setResponse(String value) { + this.response = value; + } + + /** + * Recupera il valore della propriet� runtime. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRuntime() { + return runtime; + } + + /** + * Imposta il valore della propriet� runtime. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRuntime(String value) { + this.runtime = value; + } + + /** + * Recupera il valore della propriet� title. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTitle() { + return title; + } + + /** + * Imposta il valore della propriet� title. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTitle(String value) { + this.title = value; + } + + /** + * Recupera il valore della propriet� type. + * + * @return + * possible object is + * {@link String } + * + */ + public String getType() { + return type; + } + + /** + * Imposta il valore della propriet� type. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setType(String value) { + this.type = value; + } + + /** + * Recupera il valore della propriet� writer. + * + * @return + * possible object is + * {@link String } + * + */ + public String getWriter() { + return writer; + } + + /** + * Imposta il valore della propriet� writer. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setWriter(String value) { + this.writer = value; + } + + /** + * Recupera il valore della propriet� year. + * + * @return + * possible object is + * {@link String } + * + */ + public String getYear() { + return year; + } + + /** + * Imposta il valore della propriet� year. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setYear(String value) { + this.year = value; + } + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java new file mode 100644 index 0000000000..53e88961be --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -0,0 +1,44 @@ +package com.baeldung.client; + +import com.baeldung.Movie; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + + +public interface ServicesInterface { + + + @GET + @Path("/getinfo") + @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + Movie movieByImdbID(@QueryParam("imdbID") String imdbID); + + + @POST + @Path("/addmovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + Response addMovie(Movie movie); + + + @PUT + @Path("/updatemovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + Response updateMovie(Movie movie); + + + @DELETE + @Path("/deletemovie") + Response deleteMovie(@QueryParam("imdbID") String imdbID); + + + @GET + @Path("/listmovies") + @Produces({"application/json"}) + List listMovies(); + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java new file mode 100644 index 0000000000..d1973e7037 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java @@ -0,0 +1,94 @@ +package com.baeldung.server.service; + +import com.baeldung.Movie; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + + +@Path("/movies") +public class MovieCrudService { + + + private Map inventory = new HashMap(); + + @GET + @Path("/getinfo") + @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ + + System.out.println("*** Calling getinfo ***"); + + Movie movie=new Movie(); + movie.setImdbID(imdbID); + return movie; + } + + @POST + @Path("/addmovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Response addMovie(Movie movie){ + + System.out.println("*** Calling addMovie ***"); + + if (null!=inventory.get(movie.getImdbID())){ + return Response.status(Response.Status.NOT_MODIFIED) + .entity("Movie is Already in the database.").build(); + } + inventory.put(movie.getImdbID(),movie); + + return Response.status(Response.Status.CREATED).build(); + } + + + @PUT + @Path("/updatemovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Response updateMovie(Movie movie){ + + System.out.println("*** Calling updateMovie ***"); + + if (null!=inventory.get(movie.getImdbID())){ + return Response.status(Response.Status.NOT_MODIFIED) + .entity("Movie is not in the database.\nUnable to Update").build(); + } + inventory.put(movie.getImdbID(),movie); + return Response.status(Response.Status.OK).build(); + + } + + + @DELETE + @Path("/deletemovie") + public Response deleteMovie(@QueryParam("imdbID") String imdbID){ + + System.out.println("*** Calling deleteMovie ***"); + + if (null==inventory.get(imdbID)){ + return Response.status(Response.Status.NOT_FOUND) + .entity("Movie is not in the database.\nUnable to Delete").build(); + } + + inventory.remove(imdbID); + return Response.status(Response.Status.OK).build(); + } + + @GET + @Path("/listmovies") + @Produces({"application/json"}) + public List listMovies(){ + + return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); + + } + + + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java new file mode 100644 index 0000000000..16b6200ad1 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java @@ -0,0 +1,40 @@ +package com.baeldung.server.service; + + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Created by Admin on 29/01/2016. + */ + + + +@ApplicationPath("/rest") +public class RestEasyServices extends Application { + + private Set singletons = new HashSet(); + + public RestEasyServices() { + singletons.add(new MovieCrudService()); + } + + @Override + public Set getSingletons() { + return singletons; + } + + @Override + public Set> getClasses() { + return super.getClasses(); + } + + @Override + public Map getProperties() { + return super.getProperties(); + } +} diff --git a/RestEasy Example/src/main/resources/schema1.xsd b/RestEasy Example/src/main/resources/schema1.xsd new file mode 100644 index 0000000000..0d74b7c366 --- /dev/null +++ b/RestEasy Example/src/main/resources/schema1.xsd @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml b/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml new file mode 100644 index 0000000000..d94e9f71ab --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml new file mode 100644 index 0000000000..84d75934a7 --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml new file mode 100644 index 0000000000..694bb71332 --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..c66d3b56ae --- /dev/null +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,51 @@ + + + + RestEasy Example + + + + org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap + + + + RestEasy Example + + + webAppRootKey + RestEasyExample + + + + + + resteasy.servlet.mapping.prefix + /rest + + + + + resteasy-servlet + + org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher + + + javax.ws.rs.Application + com.baeldung.server.service.RestEasyServices + + + + + resteasy-servlet + /rest/* + + + + + index.html + + + + \ No newline at end of file diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java new file mode 100644 index 0000000000..e711233979 --- /dev/null +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java @@ -0,0 +1,50 @@ +package com.baeldung.server; + +import com.baeldung.Movie; +import com.baeldung.client.ServicesInterface; +import org.jboss.resteasy.client.jaxrs.ResteasyClient; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; + +import java.util.List; + +public class RestEasyClient { + + public static void main(String[] args) { + + Movie st = new Movie(); + st.setImdbID("12345"); + + /* + * Alternatively you can use this simple String to send + * instead of using a Student instance + * + * String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}"; + */ + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies"); + + ServicesInterface simple = target.proxy(ServicesInterface.class); + final List movies = simple.listMovies(); + + /* + if (response.getStatus() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + + response.getStatus()); + } + + System.out.println("Server response : \n"); + System.out.println(response.readEntity(String.class)); + + response.close(); +*/ + } catch (Exception e) { + + e.printStackTrace(); + + } + } + +} \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/server/movies/transformer.json new file mode 100644 index 0000000000..2154868265 --- /dev/null +++ b/RestEasy Example/src/test/resources/server/movies/transformer.json @@ -0,0 +1,22 @@ +{ + "title": "Transformers", + "year": "2007", + "rated": "PG-13", + "released": "03 Jul 2007", + "runtime": "144 min", + "genre": "Action, Adventure, Sci-Fi", + "director": "Michael Bay", + "writer": "Roberto Orci (screenplay), Alex Kurtzman (screenplay), John Rogers (story), Roberto Orci (story), Alex Kurtzman (story)", + "actors": "Shia LaBeouf, Megan Fox, Josh Duhamel, Tyrese Gibson", + "plot": "A long time ago, far away on the planet of Cybertron, a war is being waged between the noble Autobots (led by the wise Optimus Prime) and the devious Decepticons (commanded by the dreaded Megatron) for control over the Allspark, a mystical talisman that would grant unlimited power to whoever possesses it. The Autobots managed to smuggle the Allspark off the planet, but Megatron blasts off in search of it. He eventually tracks it to the planet of Earth (circa 1850), but his reckless desire for power sends him right into the Arctic Ocean, and the sheer cold forces him into a paralyzed state. His body is later found by Captain Archibald Witwicky, but before going into a comatose state Megatron uses the last of his energy to engrave into the Captain's glasses a map showing the location of the Allspark, and to send a transmission to Cybertron. Megatron is then carried away aboard the Captain's ship. A century later, Captain Witwicky's grandson Sam Witwicky (nicknamed Spike by his friends) buys his first car. To his shock, he discovers it to be Bumblebee, an Autobot in disguise who is to protect Spike, who possesses the Captain's glasses and the map engraved on them. But Bumblebee is not the only Transformer to have arrived on Earth - in the desert of Qatar, the Decepticons Blackout and Scorponok attack a U.S. military base, causing the Pentagon to send their special Sector Seven agents to capture all \"specimens of this alien race.\" Spike and his girlfriend Mikaela find themselves in the midst of a grand battle between the Autobots and the Decepticons, stretching from Hoover Dam all the way to Los Angeles. Meanwhile, deep inside Hoover Dam, the cryogenically stored body of Megatron awakens.", + "language": "English, Spanish", + "country": "USA", + "awards": "Nominated for 3 Oscars. Another 18 wins & 40 nominations.", + "poster": "http://ia.media-imdb.com/images/M/MV5BMTQwNjU5MzUzNl5BMl5BanBnXkFtZTYwMzc1MTI3._V1_SX300.jpg", + "metascore": "61", + "imdbRating": "7.1", + "imdbVotes": "492,225", + "imdbID": "tt0418279", + "Type": "movie", + "response": "True" +} \ No newline at end of file From 663def8e2c00957b8913afcb118bde494c85f987 Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sat, 30 Jan 2016 20:39:28 +0100 Subject: [PATCH 294/309] Added testCase for List All Movies and Add a Movie --- RestEasy Example/pom.xml | 29 +++++ .../baeldung/client/ServicesInterface.java | 6 +- .../java/com/baeldung/{ => model}/Movie.java | 45 +++++++- .../{service => }/MovieCrudService.java | 5 +- .../{service => }/RestEasyServices.java | 2 +- .../com/baeldung/server/RestEasyClient.java | 104 ++++++++++++++---- .../com/baeldung/server/movies/batman.json | 22 ++++ .../baeldung}/server/movies/transformer.json | 2 +- 8 files changed, 184 insertions(+), 31 deletions(-) rename RestEasy Example/src/main/java/com/baeldung/{ => model}/Movie.java (86%) rename RestEasy Example/src/main/java/com/baeldung/server/{service => }/MovieCrudService.java (96%) rename RestEasy Example/src/main/java/com/baeldung/server/{service => }/RestEasyServices.java (95%) create mode 100644 RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json rename RestEasy Example/src/test/resources/{ => com/baeldung}/server/movies/transformer.json (99%) diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index b16c5e8267..8dabfc863b 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -85,6 +85,35 @@ ${resteasy.scope} + + + + junit + junit + 4.4 + + + + commons-io + commons-io + 2.4 + + + + com.fasterxml.jackson.core + jackson-core + 2.7.0 + + + + com.fasterxml.jackson.core + jackson-annotations + 2.7.0 + + + + + diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 53e88961be..2585c32438 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -1,15 +1,13 @@ package com.baeldung.client; -import com.baeldung.Movie; +import com.baeldung.model.Movie; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; - +@Path("/movies") public interface ServicesInterface { diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java similarity index 86% rename from RestEasy Example/src/main/java/com/baeldung/Movie.java rename to RestEasy Example/src/main/java/com/baeldung/model/Movie.java index c0041d2e95..052ba081c1 100644 --- a/RestEasy Example/src/main/java/com/baeldung/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -1,5 +1,5 @@ -package com.baeldung; +package com.baeldung.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -532,4 +532,47 @@ public class Movie { this.year = value; } + @Override + public String toString() { + return "Movie{" + + "actors='" + actors + '\'' + + ", awards='" + awards + '\'' + + ", country='" + country + '\'' + + ", director='" + director + '\'' + + ", genre='" + genre + '\'' + + ", imdbID='" + imdbID + '\'' + + ", imdbRating='" + imdbRating + '\'' + + ", imdbVotes='" + imdbVotes + '\'' + + ", language='" + language + '\'' + + ", metascore='" + metascore + '\'' + + ", poster='" + poster + '\'' + + ", rated='" + rated + '\'' + + ", released='" + released + '\'' + + ", response='" + response + '\'' + + ", runtime='" + runtime + '\'' + + ", title='" + title + '\'' + + ", type='" + type + '\'' + + ", writer='" + writer + '\'' + + ", year='" + year + '\'' + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Movie movie = (Movie) o; + + if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false; + return title != null ? title.equals(movie.title) : movie.title == null; + + } + + @Override + public int hashCode() { + int result = imdbID != null ? imdbID.hashCode() : 0; + result = 31 * result + (title != null ? title.hashCode() : 0); + return result; + } } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java similarity index 96% rename from RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java rename to RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index d1973e7037..60e0121966 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -1,11 +1,10 @@ -package com.baeldung.server.service; +package com.baeldung.server; -import com.baeldung.Movie; +import com.baeldung.model.Movie; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java similarity index 95% rename from RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java rename to RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java index 16b6200ad1..8c57d2c9b4 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java @@ -1,4 +1,4 @@ -package com.baeldung.server.service; +package com.baeldung.server; import javax.ws.rs.ApplicationPath; diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java index e711233979..c77f494862 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java @@ -1,49 +1,111 @@ package com.baeldung.server; -import com.baeldung.Movie; +import com.baeldung.model.Movie; import com.baeldung.client.ServicesInterface; +import org.apache.commons.io.IOUtils; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.ObjectMapper; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import javax.naming.NamingException; +import javax.ws.rs.core.Link; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Arrays; import java.util.List; +import java.util.Locale; public class RestEasyClient { - public static void main(String[] args) { - Movie st = new Movie(); - st.setImdbID("12345"); + Movie transformerMovie=null; + Movie batmanMovie=null; + ObjectMapper jsonMapper=null; - /* - * Alternatively you can use this simple String to send - * instead of using a Student instance - * - * String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}"; - */ + @BeforeClass + public static void loadMovieInventory(){ + + + + } + + @Before + public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { + + + jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + jsonMapper.setDateFormat(sdf); + + try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) { + String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) { + String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + } + + @Test + public void testListAllMovies() { try { ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies"); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + final List movies = simple.listMovies(); + System.out.println(movies); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Test + public void testAddMovie() { + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); ServicesInterface simple = target.proxy(ServicesInterface.class); - final List movies = simple.listMovies(); + final Response moviesResponse = simple.addMovie(batmanMovie); - /* - if (response.getStatus() != 200) { + if (moviesResponse.getStatus() != 201) { + System.out.println(moviesResponse.readEntity(String.class)); throw new RuntimeException("Failed : HTTP error code : " - + response.getStatus()); + + moviesResponse.getStatus()); } - System.out.println("Server response : \n"); - System.out.println(response.readEntity(String.class)); + moviesResponse.close(); - response.close(); -*/ } catch (Exception e) { - e.printStackTrace(); - } } diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json new file mode 100644 index 0000000000..28061d5bf9 --- /dev/null +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json @@ -0,0 +1,22 @@ +{ + "title": "Batman", + "year": "1989", + "rated": "PG-13", + "released": "23 Jun 1989", + "runtime": "126 min", + "genre": "Action, Adventure", + "director": "Tim Burton", + "writer": "Bob Kane (Batman characters), Sam Hamm (story), Sam Hamm (screenplay), Warren Skaaren (screenplay)", + "actors": "Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl", + "plot": "The Dark Knight of Gotham City begins his war on crime with his first major enemy being the clownishly homicidal Joker.", + "language": "English, French", + "country": "USA, UK", + "awards": "Won 1 Oscar. Another 9 wins & 22 nominations.", + "poster": "http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg", + "metascore": "66", + "imdbRating": "7.6", + "imdbVotes": "256,000", + "imdbID": "tt0096895", + "type": "movie", + "response": "True" +} \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json similarity index 99% rename from RestEasy Example/src/test/resources/server/movies/transformer.json rename to RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json index 2154868265..a3b033a8ba 100644 --- a/RestEasy Example/src/test/resources/server/movies/transformer.json +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json @@ -17,6 +17,6 @@ "imdbRating": "7.1", "imdbVotes": "492,225", "imdbID": "tt0418279", - "Type": "movie", + "type": "movie", "response": "True" } \ No newline at end of file From b39ec7d76ee55ffe0165aa82ff23f2da3bd8475c Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sun, 31 Jan 2016 11:05:11 +0100 Subject: [PATCH 295/309] Added testCase for all Services --- RestEasy Example/pom.xml | 15 -- .../baeldung/client/ServicesInterface.java | 10 +- .../com/baeldung/server/MovieCrudService.java | 15 +- .../src/main/webapp/WEB-INF/web.xml | 2 +- .../com/baeldung/server/RestEasyClient.java | 112 ----------- .../baeldung/server/RestEasyClientTest.java | 189 ++++++++++++++++++ 6 files changed, 206 insertions(+), 137 deletions(-) delete mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java create mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index 8dabfc863b..6935238d91 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -99,21 +99,6 @@ 2.4 - - com.fasterxml.jackson.core - jackson-core - 2.7.0 - - - - com.fasterxml.jackson.core - jackson-annotations - 2.7.0 - - - - - diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 2585c32438..7efed546d8 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -17,6 +17,12 @@ public interface ServicesInterface { Movie movieByImdbID(@QueryParam("imdbID") String imdbID); + @GET + @Path("/listmovies") + @Produces({"application/json"}) + List listMovies(); + + @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @@ -34,9 +40,5 @@ public interface ServicesInterface { Response deleteMovie(@QueryParam("imdbID") String imdbID); - @GET - @Path("/listmovies") - @Produces({"application/json"}) - List listMovies(); } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 60e0121966..18366e2faa 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -18,18 +18,21 @@ public class MovieCrudService { private Map inventory = new HashMap(); + @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ - System.out.println("*** Calling getinfo ***"); + System.out.println("*** Calling getinfo for a given ImdbID***"); + + if(inventory.containsKey(imdbID)){ + return inventory.get(imdbID); + }else return null; - Movie movie=new Movie(); - movie.setImdbID(imdbID); - return movie; } + @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @@ -41,6 +44,7 @@ public class MovieCrudService { return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } + inventory.put(movie.getImdbID(),movie); return Response.status(Response.Status.CREATED).build(); @@ -54,7 +58,7 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null!=inventory.get(movie.getImdbID())){ + if (null==inventory.get(movie.getImdbID())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } @@ -79,6 +83,7 @@ public class MovieCrudService { return Response.status(Response.Status.OK).build(); } + @GET @Path("/listmovies") @Produces({"application/json"}) diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index c66d3b56ae..ab3bc1aa83 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -33,7 +33,7 @@ javax.ws.rs.Application - com.baeldung.server.service.RestEasyServices + com.baeldung.server.RestEasyServices diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java deleted file mode 100644 index c77f494862..0000000000 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.model.Movie; -import com.baeldung.client.ServicesInterface; -import org.apache.commons.io.IOUtils; -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; -import org.jboss.resteasy.client.jaxrs.ResteasyClient; -import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; -import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import javax.naming.NamingException; -import javax.ws.rs.core.Link; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -public class RestEasyClient { - - - Movie transformerMovie=null; - Movie batmanMovie=null; - ObjectMapper jsonMapper=null; - - @BeforeClass - public static void loadMovieInventory(){ - - - - } - - @Before - public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - - - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); - jsonMapper.setDateFormat(sdf); - - try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) { - String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Test is going to die ...", e); - } - - try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) { - String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); - - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Test is going to die ...", e); - } - - } - - @Test - public void testListAllMovies() { - - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); - - final List movies = simple.listMovies(); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - @Test - public void testAddMovie() { - - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - - ServicesInterface simple = target.proxy(ServicesInterface.class); - final Response moviesResponse = simple.addMovie(batmanMovie); - - if (moviesResponse.getStatus() != 201) { - System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " - + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java new file mode 100644 index 0000000000..fb4205bcd7 --- /dev/null +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -0,0 +1,189 @@ +package com.baeldung.server; + +import com.baeldung.model.Movie; +import com.baeldung.client.ServicesInterface; +import org.apache.commons.io.IOUtils; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.ObjectMapper; +import org.jboss.resteasy.client.jaxrs.ResteasyClient; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.naming.NamingException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Locale; + +public class RestEasyClientTest { + + + Movie transformerMovie=null; + Movie batmanMovie=null; + ObjectMapper jsonMapper=null; + + @BeforeClass + public static void loadMovieInventory(){ + + + + } + + @Before + public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { + + + jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + jsonMapper.setDateFormat(sdf); + + try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/transformer.json")) { + String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/batman.json")) { + String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + } + + + @Test + public void testListAllMovies() { + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + + final List movies = simple.listMovies(); + System.out.println(movies); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testMovieByImdbID() { + + String transformerImdbId="tt0418279"; + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + + final Movie movies = simple.movieByImdbID(transformerImdbId); + System.out.println(movies); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testAddMovie() { + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(transformerMovie); + + if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { + //System.out.println(moviesResponse.readEntity(String.class)); + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + moviesResponse.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testDeleteMovie() { + + String transformerImdbId="tt0418279"; + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.deleteMovie(transformerImdbId); + moviesResponse.close(); + + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println(moviesResponse.readEntity(String.class)); + throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + + moviesResponse.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testUpdateMovie() { + + try { + + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + batmanMovie.setImdbVotes("300,000"); + moviesResponse = simple.updateMovie(batmanMovie); + + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + //System.out.println(moviesResponse.readEntity(String.class)); + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + + moviesResponse.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + +} \ No newline at end of file From 5cdf7185a4eed764473b76b365f14c2737f7c0bb Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:29:30 +0100 Subject: [PATCH 296/309] Minor Bugfix --- .../baeldung/client/ServicesInterface.java | 4 +- .../main/java/com/baeldung/model/Movie.java | 22 +-- .../com/baeldung/server/MovieCrudService.java | 12 +- .../src/main/webapp/WEB-INF/web.xml | 37 +---- .../java/baeldung/client/RestEasyClient.java | 7 + .../baeldung/server/RestEasyClientTest.java | 149 +++++++----------- 6 files changed, 81 insertions(+), 150 deletions(-) create mode 100644 RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 7efed546d8..749cabc757 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -14,7 +14,7 @@ public interface ServicesInterface { @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - Movie movieByImdbID(@QueryParam("imdbID") String imdbID); + Movie movieByImdbId(@QueryParam("imdbId") String imdbId); @GET @@ -37,7 +37,7 @@ public interface ServicesInterface { @DELETE @Path("/deletemovie") - Response deleteMovie(@QueryParam("imdbID") String imdbID); + Response deleteMovie(@QueryParam("imdbId") String imdbID); diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 052ba081c1..a2b2bd5250 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -13,7 +13,7 @@ import javax.xml.bind.annotation.XmlType; "country", "director", "genre", - "imdbID", + "imdbId", "imdbRating", "imdbVotes", "language", @@ -36,7 +36,7 @@ public class Movie { protected String country; protected String director; protected String genre; - protected String imdbID; + protected String imdbId; protected String imdbRating; protected String imdbVotes; protected String language; @@ -173,27 +173,27 @@ public class Movie { } /** - * Recupera il valore della propriet� imdbID. + * Recupera il valore della propriet� imdbId. * * @return * possible object is * {@link String } * */ - public String getImdbID() { - return imdbID; + public String getImdbId() { + return imdbId; } /** - * Imposta il valore della propriet� imdbID. + * Imposta il valore della propriet� imdbId. * * @param value * allowed object is * {@link String } * */ - public void setImdbID(String value) { - this.imdbID = value; + public void setImdbId(String value) { + this.imdbId = value; } /** @@ -540,7 +540,7 @@ public class Movie { ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + - ", imdbID='" + imdbID + '\'' + + ", imdbId='" + imdbId + '\'' + ", imdbRating='" + imdbRating + '\'' + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + @@ -564,14 +564,14 @@ public class Movie { Movie movie = (Movie) o; - if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false; + if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; return title != null ? title.equals(movie.title) : movie.title == null; } @Override public int hashCode() { - int result = imdbID != null ? imdbID.hashCode() : 0; + int result = imdbId != null ? imdbId.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); return result; } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 18366e2faa..29226aa0e0 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -22,7 +22,7 @@ public class MovieCrudService { @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ + public Movie movieByImdbID(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling getinfo for a given ImdbID***"); @@ -40,12 +40,12 @@ public class MovieCrudService { System.out.println("*** Calling addMovie ***"); - if (null!=inventory.get(movie.getImdbID())){ + if (null!=inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.CREATED).build(); } @@ -58,11 +58,11 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null==inventory.get(movie.getImdbID())){ + if (null==inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.OK).build(); } @@ -70,7 +70,7 @@ public class MovieCrudService { @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbID") String imdbID){ + public Response deleteMovie(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling deleteMovie ***"); diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index ab3bc1aa83..f70fdf7975 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -5,47 +5,12 @@ RestEasy Example - - - org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap - - - - RestEasy Example - - - webAppRootKey - RestEasyExample - - - - + resteasy.servlet.mapping.prefix /rest - - resteasy-servlet - - org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher - - - javax.ws.rs.Application - com.baeldung.server.RestEasyServices - - - - - resteasy-servlet - /rest/* - - - - - index.html - - \ No newline at end of file diff --git a/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java b/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java new file mode 100644 index 0000000000..b474b3d4f8 --- /dev/null +++ b/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java @@ -0,0 +1,7 @@ +package baeldung.client; + +/** + * Created by Admin on 29/01/2016. + */ +public class RestEasyClient { +} diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java index fb4205bcd7..b6a2e2a0c1 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -1,7 +1,7 @@ package com.baeldung.server; -import com.baeldung.model.Movie; import com.baeldung.client.ServicesInterface; +import com.baeldung.model.Movie; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; @@ -9,7 +9,6 @@ import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import javax.naming.NamingException; @@ -23,22 +22,13 @@ import java.util.Locale; public class RestEasyClientTest { - Movie transformerMovie=null; Movie batmanMovie=null; ObjectMapper jsonMapper=null; - @BeforeClass - public static void loadMovieInventory(){ - - - - } - @Before public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); @@ -57,133 +47,102 @@ public class RestEasyClientTest { batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); } catch (Exception e) { - e.printStackTrace(); throw new RuntimeException("Test is going to die ...", e); } - } - @Test public void testListAllMovies() { - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(transformerMovie); - moviesResponse.close(); - moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); - final List movies = simple.listMovies(); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } + List movies = simple.listMovies(); + System.out.println(movies); } - @Test - public void testMovieByImdbID() { + public void testMovieByImdbId() { String transformerImdbId="tt0418279"; - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(transformerMovie); - moviesResponse.close(); + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); - final Movie movies = simple.movieByImdbID(transformerImdbId); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } + Movie movies = simple.movieByImdbId(transformerImdbId); + System.out.println(movies); } @Test public void testAddMovie() { - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - moviesResponse = simple.addMovie(transformerMovie); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(transformerMovie); - if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { - //System.out.println(moviesResponse.readEntity(String.class)); - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } @Test - public void testDeleteMovie() { + public void testDeleteMovi1e() { - String transformerImdbId="tt0418279"; + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.deleteMovie(batmanMovie.getImdbId()); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - moviesResponse = simple.deleteMovie(transformerImdbId); - moviesResponse.close(); - - if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println(moviesResponse.readEntity(String.class)); + throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } @Test public void testUpdateMovie() { - try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + batmanMovie.setImdbVotes("300,000"); + moviesResponse = simple.updateMovie(batmanMovie); - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - batmanMovie.setImdbVotes("300,000"); - moviesResponse = simple.updateMovie(batmanMovie); - - if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - //System.out.println(moviesResponse.readEntity(String.class)); - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } + + moviesResponse.close(); + System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); } } \ No newline at end of file From 9b5818262decbcfcfc302ab15c5f3347dbaeecfd Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sat, 30 Jan 2016 17:48:56 +0100 Subject: [PATCH 297/309] RestEasy Tutorial, CRUD Services example --- .../src/main/java/com/baeldung/Movie.java | 535 ++++++++++++++++++ .../server/service/MovieCrudService.java | 94 +++ .../server/service/RestEasyServices.java | 40 ++ .../com/baeldung/server/RestEasyClient.java | 50 ++ .../resources/server/movies/transformer.json | 22 + 5 files changed, 741 insertions(+) create mode 100644 RestEasy Example/src/main/java/com/baeldung/Movie.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java create mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java create mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java create mode 100644 RestEasy Example/src/test/resources/server/movies/transformer.json diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/Movie.java new file mode 100644 index 0000000000..c0041d2e95 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/Movie.java @@ -0,0 +1,535 @@ + +package com.baeldung; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; + + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "movie", propOrder = { + "actors", + "awards", + "country", + "director", + "genre", + "imdbID", + "imdbRating", + "imdbVotes", + "language", + "metascore", + "plot", + "poster", + "rated", + "released", + "response", + "runtime", + "title", + "type", + "writer", + "year" +}) +public class Movie { + + protected String actors; + protected String awards; + protected String country; + protected String director; + protected String genre; + protected String imdbID; + protected String imdbRating; + protected String imdbVotes; + protected String language; + protected String metascore; + protected String plot; + protected String poster; + protected String rated; + protected String released; + protected String response; + protected String runtime; + protected String title; + protected String type; + protected String writer; + protected String year; + + /** + * Recupera il valore della propriet� actors. + * + * @return + * possible object is + * {@link String } + * + */ + public String getActors() { + return actors; + } + + /** + * Imposta il valore della propriet� actors. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setActors(String value) { + this.actors = value; + } + + /** + * Recupera il valore della propriet� awards. + * + * @return + * possible object is + * {@link String } + * + */ + public String getAwards() { + return awards; + } + + /** + * Imposta il valore della propriet� awards. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setAwards(String value) { + this.awards = value; + } + + /** + * Recupera il valore della propriet� country. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCountry() { + return country; + } + + /** + * Imposta il valore della propriet� country. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCountry(String value) { + this.country = value; + } + + /** + * Recupera il valore della propriet� director. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDirector() { + return director; + } + + /** + * Imposta il valore della propriet� director. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDirector(String value) { + this.director = value; + } + + /** + * Recupera il valore della propriet� genre. + * + * @return + * possible object is + * {@link String } + * + */ + public String getGenre() { + return genre; + } + + /** + * Imposta il valore della propriet� genre. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setGenre(String value) { + this.genre = value; + } + + /** + * Recupera il valore della propriet� imdbID. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbID() { + return imdbID; + } + + /** + * Imposta il valore della propriet� imdbID. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbID(String value) { + this.imdbID = value; + } + + /** + * Recupera il valore della propriet� imdbRating. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbRating() { + return imdbRating; + } + + /** + * Imposta il valore della propriet� imdbRating. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbRating(String value) { + this.imdbRating = value; + } + + /** + * Recupera il valore della propriet� imdbVotes. + * + * @return + * possible object is + * {@link String } + * + */ + public String getImdbVotes() { + return imdbVotes; + } + + /** + * Imposta il valore della propriet� imdbVotes. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setImdbVotes(String value) { + this.imdbVotes = value; + } + + /** + * Recupera il valore della propriet� language. + * + * @return + * possible object is + * {@link String } + * + */ + public String getLanguage() { + return language; + } + + /** + * Imposta il valore della propriet� language. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setLanguage(String value) { + this.language = value; + } + + /** + * Recupera il valore della propriet� metascore. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMetascore() { + return metascore; + } + + /** + * Imposta il valore della propriet� metascore. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMetascore(String value) { + this.metascore = value; + } + + /** + * Recupera il valore della propriet� plot. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPlot() { + return plot; + } + + /** + * Imposta il valore della propriet� plot. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPlot(String value) { + this.plot = value; + } + + /** + * Recupera il valore della propriet� poster. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPoster() { + return poster; + } + + /** + * Imposta il valore della propriet� poster. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPoster(String value) { + this.poster = value; + } + + /** + * Recupera il valore della propriet� rated. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRated() { + return rated; + } + + /** + * Imposta il valore della propriet� rated. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRated(String value) { + this.rated = value; + } + + /** + * Recupera il valore della propriet� released. + * + * @return + * possible object is + * {@link String } + * + */ + public String getReleased() { + return released; + } + + /** + * Imposta il valore della propriet� released. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setReleased(String value) { + this.released = value; + } + + /** + * Recupera il valore della propriet� response. + * + * @return + * possible object is + * {@link String } + * + */ + public String getResponse() { + return response; + } + + /** + * Imposta il valore della propriet� response. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setResponse(String value) { + this.response = value; + } + + /** + * Recupera il valore della propriet� runtime. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRuntime() { + return runtime; + } + + /** + * Imposta il valore della propriet� runtime. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRuntime(String value) { + this.runtime = value; + } + + /** + * Recupera il valore della propriet� title. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTitle() { + return title; + } + + /** + * Imposta il valore della propriet� title. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTitle(String value) { + this.title = value; + } + + /** + * Recupera il valore della propriet� type. + * + * @return + * possible object is + * {@link String } + * + */ + public String getType() { + return type; + } + + /** + * Imposta il valore della propriet� type. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setType(String value) { + this.type = value; + } + + /** + * Recupera il valore della propriet� writer. + * + * @return + * possible object is + * {@link String } + * + */ + public String getWriter() { + return writer; + } + + /** + * Imposta il valore della propriet� writer. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setWriter(String value) { + this.writer = value; + } + + /** + * Recupera il valore della propriet� year. + * + * @return + * possible object is + * {@link String } + * + */ + public String getYear() { + return year; + } + + /** + * Imposta il valore della propriet� year. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setYear(String value) { + this.year = value; + } + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java new file mode 100644 index 0000000000..d1973e7037 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java @@ -0,0 +1,94 @@ +package com.baeldung.server.service; + +import com.baeldung.Movie; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + + +@Path("/movies") +public class MovieCrudService { + + + private Map inventory = new HashMap(); + + @GET + @Path("/getinfo") + @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ + + System.out.println("*** Calling getinfo ***"); + + Movie movie=new Movie(); + movie.setImdbID(imdbID); + return movie; + } + + @POST + @Path("/addmovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Response addMovie(Movie movie){ + + System.out.println("*** Calling addMovie ***"); + + if (null!=inventory.get(movie.getImdbID())){ + return Response.status(Response.Status.NOT_MODIFIED) + .entity("Movie is Already in the database.").build(); + } + inventory.put(movie.getImdbID(),movie); + + return Response.status(Response.Status.CREATED).build(); + } + + + @PUT + @Path("/updatemovie") + @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + public Response updateMovie(Movie movie){ + + System.out.println("*** Calling updateMovie ***"); + + if (null!=inventory.get(movie.getImdbID())){ + return Response.status(Response.Status.NOT_MODIFIED) + .entity("Movie is not in the database.\nUnable to Update").build(); + } + inventory.put(movie.getImdbID(),movie); + return Response.status(Response.Status.OK).build(); + + } + + + @DELETE + @Path("/deletemovie") + public Response deleteMovie(@QueryParam("imdbID") String imdbID){ + + System.out.println("*** Calling deleteMovie ***"); + + if (null==inventory.get(imdbID)){ + return Response.status(Response.Status.NOT_FOUND) + .entity("Movie is not in the database.\nUnable to Delete").build(); + } + + inventory.remove(imdbID); + return Response.status(Response.Status.OK).build(); + } + + @GET + @Path("/listmovies") + @Produces({"application/json"}) + public List listMovies(){ + + return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); + + } + + + +} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java new file mode 100644 index 0000000000..16b6200ad1 --- /dev/null +++ b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java @@ -0,0 +1,40 @@ +package com.baeldung.server.service; + + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Created by Admin on 29/01/2016. + */ + + + +@ApplicationPath("/rest") +public class RestEasyServices extends Application { + + private Set singletons = new HashSet(); + + public RestEasyServices() { + singletons.add(new MovieCrudService()); + } + + @Override + public Set getSingletons() { + return singletons; + } + + @Override + public Set> getClasses() { + return super.getClasses(); + } + + @Override + public Map getProperties() { + return super.getProperties(); + } +} diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java new file mode 100644 index 0000000000..e711233979 --- /dev/null +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java @@ -0,0 +1,50 @@ +package com.baeldung.server; + +import com.baeldung.Movie; +import com.baeldung.client.ServicesInterface; +import org.jboss.resteasy.client.jaxrs.ResteasyClient; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; + +import java.util.List; + +public class RestEasyClient { + + public static void main(String[] args) { + + Movie st = new Movie(); + st.setImdbID("12345"); + + /* + * Alternatively you can use this simple String to send + * instead of using a Student instance + * + * String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}"; + */ + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies"); + + ServicesInterface simple = target.proxy(ServicesInterface.class); + final List movies = simple.listMovies(); + + /* + if (response.getStatus() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + + response.getStatus()); + } + + System.out.println("Server response : \n"); + System.out.println(response.readEntity(String.class)); + + response.close(); +*/ + } catch (Exception e) { + + e.printStackTrace(); + + } + } + +} \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/server/movies/transformer.json new file mode 100644 index 0000000000..2154868265 --- /dev/null +++ b/RestEasy Example/src/test/resources/server/movies/transformer.json @@ -0,0 +1,22 @@ +{ + "title": "Transformers", + "year": "2007", + "rated": "PG-13", + "released": "03 Jul 2007", + "runtime": "144 min", + "genre": "Action, Adventure, Sci-Fi", + "director": "Michael Bay", + "writer": "Roberto Orci (screenplay), Alex Kurtzman (screenplay), John Rogers (story), Roberto Orci (story), Alex Kurtzman (story)", + "actors": "Shia LaBeouf, Megan Fox, Josh Duhamel, Tyrese Gibson", + "plot": "A long time ago, far away on the planet of Cybertron, a war is being waged between the noble Autobots (led by the wise Optimus Prime) and the devious Decepticons (commanded by the dreaded Megatron) for control over the Allspark, a mystical talisman that would grant unlimited power to whoever possesses it. The Autobots managed to smuggle the Allspark off the planet, but Megatron blasts off in search of it. He eventually tracks it to the planet of Earth (circa 1850), but his reckless desire for power sends him right into the Arctic Ocean, and the sheer cold forces him into a paralyzed state. His body is later found by Captain Archibald Witwicky, but before going into a comatose state Megatron uses the last of his energy to engrave into the Captain's glasses a map showing the location of the Allspark, and to send a transmission to Cybertron. Megatron is then carried away aboard the Captain's ship. A century later, Captain Witwicky's grandson Sam Witwicky (nicknamed Spike by his friends) buys his first car. To his shock, he discovers it to be Bumblebee, an Autobot in disguise who is to protect Spike, who possesses the Captain's glasses and the map engraved on them. But Bumblebee is not the only Transformer to have arrived on Earth - in the desert of Qatar, the Decepticons Blackout and Scorponok attack a U.S. military base, causing the Pentagon to send their special Sector Seven agents to capture all \"specimens of this alien race.\" Spike and his girlfriend Mikaela find themselves in the midst of a grand battle between the Autobots and the Decepticons, stretching from Hoover Dam all the way to Los Angeles. Meanwhile, deep inside Hoover Dam, the cryogenically stored body of Megatron awakens.", + "language": "English, Spanish", + "country": "USA", + "awards": "Nominated for 3 Oscars. Another 18 wins & 40 nominations.", + "poster": "http://ia.media-imdb.com/images/M/MV5BMTQwNjU5MzUzNl5BMl5BanBnXkFtZTYwMzc1MTI3._V1_SX300.jpg", + "metascore": "61", + "imdbRating": "7.1", + "imdbVotes": "492,225", + "imdbID": "tt0418279", + "Type": "movie", + "response": "True" +} \ No newline at end of file From df982db26b1a356a77b0b9eaf1ba6e2bb32c9b51 Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sat, 30 Jan 2016 20:39:28 +0100 Subject: [PATCH 298/309] Added testCase for List All Movies and Add a Movie --- .../src/main/java/com/baeldung/Movie.java | 535 ------------------ .../main/java/com/baeldung/model/Movie.java | 22 +- .../com/baeldung/server/MovieCrudService.java | 25 +- .../server/service/MovieCrudService.java | 94 --- .../server/service/RestEasyServices.java | 40 -- .../com/baeldung/server/RestEasyClient.java | 104 +++- .../resources/server/movies/transformer.json | 22 - 7 files changed, 104 insertions(+), 738 deletions(-) delete mode 100644 RestEasy Example/src/main/java/com/baeldung/Movie.java delete mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java delete mode 100644 RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java delete mode 100644 RestEasy Example/src/test/resources/server/movies/transformer.json diff --git a/RestEasy Example/src/main/java/com/baeldung/Movie.java b/RestEasy Example/src/main/java/com/baeldung/Movie.java deleted file mode 100644 index c0041d2e95..0000000000 --- a/RestEasy Example/src/main/java/com/baeldung/Movie.java +++ /dev/null @@ -1,535 +0,0 @@ - -package com.baeldung; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "movie", propOrder = { - "actors", - "awards", - "country", - "director", - "genre", - "imdbID", - "imdbRating", - "imdbVotes", - "language", - "metascore", - "plot", - "poster", - "rated", - "released", - "response", - "runtime", - "title", - "type", - "writer", - "year" -}) -public class Movie { - - protected String actors; - protected String awards; - protected String country; - protected String director; - protected String genre; - protected String imdbID; - protected String imdbRating; - protected String imdbVotes; - protected String language; - protected String metascore; - protected String plot; - protected String poster; - protected String rated; - protected String released; - protected String response; - protected String runtime; - protected String title; - protected String type; - protected String writer; - protected String year; - - /** - * Recupera il valore della propriet� actors. - * - * @return - * possible object is - * {@link String } - * - */ - public String getActors() { - return actors; - } - - /** - * Imposta il valore della propriet� actors. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setActors(String value) { - this.actors = value; - } - - /** - * Recupera il valore della propriet� awards. - * - * @return - * possible object is - * {@link String } - * - */ - public String getAwards() { - return awards; - } - - /** - * Imposta il valore della propriet� awards. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setAwards(String value) { - this.awards = value; - } - - /** - * Recupera il valore della propriet� country. - * - * @return - * possible object is - * {@link String } - * - */ - public String getCountry() { - return country; - } - - /** - * Imposta il valore della propriet� country. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setCountry(String value) { - this.country = value; - } - - /** - * Recupera il valore della propriet� director. - * - * @return - * possible object is - * {@link String } - * - */ - public String getDirector() { - return director; - } - - /** - * Imposta il valore della propriet� director. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setDirector(String value) { - this.director = value; - } - - /** - * Recupera il valore della propriet� genre. - * - * @return - * possible object is - * {@link String } - * - */ - public String getGenre() { - return genre; - } - - /** - * Imposta il valore della propriet� genre. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setGenre(String value) { - this.genre = value; - } - - /** - * Recupera il valore della propriet� imdbID. - * - * @return - * possible object is - * {@link String } - * - */ - public String getImdbID() { - return imdbID; - } - - /** - * Imposta il valore della propriet� imdbID. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setImdbID(String value) { - this.imdbID = value; - } - - /** - * Recupera il valore della propriet� imdbRating. - * - * @return - * possible object is - * {@link String } - * - */ - public String getImdbRating() { - return imdbRating; - } - - /** - * Imposta il valore della propriet� imdbRating. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setImdbRating(String value) { - this.imdbRating = value; - } - - /** - * Recupera il valore della propriet� imdbVotes. - * - * @return - * possible object is - * {@link String } - * - */ - public String getImdbVotes() { - return imdbVotes; - } - - /** - * Imposta il valore della propriet� imdbVotes. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setImdbVotes(String value) { - this.imdbVotes = value; - } - - /** - * Recupera il valore della propriet� language. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLanguage() { - return language; - } - - /** - * Imposta il valore della propriet� language. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLanguage(String value) { - this.language = value; - } - - /** - * Recupera il valore della propriet� metascore. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMetascore() { - return metascore; - } - - /** - * Imposta il valore della propriet� metascore. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMetascore(String value) { - this.metascore = value; - } - - /** - * Recupera il valore della propriet� plot. - * - * @return - * possible object is - * {@link String } - * - */ - public String getPlot() { - return plot; - } - - /** - * Imposta il valore della propriet� plot. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setPlot(String value) { - this.plot = value; - } - - /** - * Recupera il valore della propriet� poster. - * - * @return - * possible object is - * {@link String } - * - */ - public String getPoster() { - return poster; - } - - /** - * Imposta il valore della propriet� poster. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setPoster(String value) { - this.poster = value; - } - - /** - * Recupera il valore della propriet� rated. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRated() { - return rated; - } - - /** - * Imposta il valore della propriet� rated. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRated(String value) { - this.rated = value; - } - - /** - * Recupera il valore della propriet� released. - * - * @return - * possible object is - * {@link String } - * - */ - public String getReleased() { - return released; - } - - /** - * Imposta il valore della propriet� released. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setReleased(String value) { - this.released = value; - } - - /** - * Recupera il valore della propriet� response. - * - * @return - * possible object is - * {@link String } - * - */ - public String getResponse() { - return response; - } - - /** - * Imposta il valore della propriet� response. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setResponse(String value) { - this.response = value; - } - - /** - * Recupera il valore della propriet� runtime. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRuntime() { - return runtime; - } - - /** - * Imposta il valore della propriet� runtime. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRuntime(String value) { - this.runtime = value; - } - - /** - * Recupera il valore della propriet� title. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTitle() { - return title; - } - - /** - * Imposta il valore della propriet� title. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTitle(String value) { - this.title = value; - } - - /** - * Recupera il valore della propriet� type. - * - * @return - * possible object is - * {@link String } - * - */ - public String getType() { - return type; - } - - /** - * Imposta il valore della propriet� type. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setType(String value) { - this.type = value; - } - - /** - * Recupera il valore della propriet� writer. - * - * @return - * possible object is - * {@link String } - * - */ - public String getWriter() { - return writer; - } - - /** - * Imposta il valore della propriet� writer. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setWriter(String value) { - this.writer = value; - } - - /** - * Recupera il valore della propriet� year. - * - * @return - * possible object is - * {@link String } - * - */ - public String getYear() { - return year; - } - - /** - * Imposta il valore della propriet� year. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setYear(String value) { - this.year = value; - } - -} diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index a2b2bd5250..052ba081c1 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -13,7 +13,7 @@ import javax.xml.bind.annotation.XmlType; "country", "director", "genre", - "imdbId", + "imdbID", "imdbRating", "imdbVotes", "language", @@ -36,7 +36,7 @@ public class Movie { protected String country; protected String director; protected String genre; - protected String imdbId; + protected String imdbID; protected String imdbRating; protected String imdbVotes; protected String language; @@ -173,27 +173,27 @@ public class Movie { } /** - * Recupera il valore della propriet� imdbId. + * Recupera il valore della propriet� imdbID. * * @return * possible object is * {@link String } * */ - public String getImdbId() { - return imdbId; + public String getImdbID() { + return imdbID; } /** - * Imposta il valore della propriet� imdbId. + * Imposta il valore della propriet� imdbID. * * @param value * allowed object is * {@link String } * */ - public void setImdbId(String value) { - this.imdbId = value; + public void setImdbID(String value) { + this.imdbID = value; } /** @@ -540,7 +540,7 @@ public class Movie { ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + - ", imdbId='" + imdbId + '\'' + + ", imdbID='" + imdbID + '\'' + ", imdbRating='" + imdbRating + '\'' + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + @@ -564,14 +564,14 @@ public class Movie { Movie movie = (Movie) o; - if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; + if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false; return title != null ? title.equals(movie.title) : movie.title == null; } @Override public int hashCode() { - int result = imdbId != null ? imdbId.hashCode() : 0; + int result = imdbID != null ? imdbID.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); return result; } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 29226aa0e0..60e0121966 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -18,21 +18,18 @@ public class MovieCrudService { private Map inventory = new HashMap(); - @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbId") String imdbID){ + public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ - System.out.println("*** Calling getinfo for a given ImdbID***"); - - if(inventory.containsKey(imdbID)){ - return inventory.get(imdbID); - }else return null; + System.out.println("*** Calling getinfo ***"); + Movie movie=new Movie(); + movie.setImdbID(imdbID); + return movie; } - @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @@ -40,12 +37,11 @@ public class MovieCrudService { System.out.println("*** Calling addMovie ***"); - if (null!=inventory.get(movie.getImdbId())){ + if (null!=inventory.get(movie.getImdbID())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } - - inventory.put(movie.getImdbId(),movie); + inventory.put(movie.getImdbID(),movie); return Response.status(Response.Status.CREATED).build(); } @@ -58,11 +54,11 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null==inventory.get(movie.getImdbId())){ + if (null!=inventory.get(movie.getImdbID())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } - inventory.put(movie.getImdbId(),movie); + inventory.put(movie.getImdbID(),movie); return Response.status(Response.Status.OK).build(); } @@ -70,7 +66,7 @@ public class MovieCrudService { @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbId") String imdbID){ + public Response deleteMovie(@QueryParam("imdbID") String imdbID){ System.out.println("*** Calling deleteMovie ***"); @@ -83,7 +79,6 @@ public class MovieCrudService { return Response.status(Response.Status.OK).build(); } - @GET @Path("/listmovies") @Produces({"application/json"}) diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java deleted file mode 100644 index d1973e7037..0000000000 --- a/RestEasy Example/src/main/java/com/baeldung/server/service/MovieCrudService.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.baeldung.server.service; - -import com.baeldung.Movie; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - - -@Path("/movies") -public class MovieCrudService { - - - private Map inventory = new HashMap(); - - @GET - @Path("/getinfo") - @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ - - System.out.println("*** Calling getinfo ***"); - - Movie movie=new Movie(); - movie.setImdbID(imdbID); - return movie; - } - - @POST - @Path("/addmovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Response addMovie(Movie movie){ - - System.out.println("*** Calling addMovie ***"); - - if (null!=inventory.get(movie.getImdbID())){ - return Response.status(Response.Status.NOT_MODIFIED) - .entity("Movie is Already in the database.").build(); - } - inventory.put(movie.getImdbID(),movie); - - return Response.status(Response.Status.CREATED).build(); - } - - - @PUT - @Path("/updatemovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Response updateMovie(Movie movie){ - - System.out.println("*** Calling updateMovie ***"); - - if (null!=inventory.get(movie.getImdbID())){ - return Response.status(Response.Status.NOT_MODIFIED) - .entity("Movie is not in the database.\nUnable to Update").build(); - } - inventory.put(movie.getImdbID(),movie); - return Response.status(Response.Status.OK).build(); - - } - - - @DELETE - @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbID") String imdbID){ - - System.out.println("*** Calling deleteMovie ***"); - - if (null==inventory.get(imdbID)){ - return Response.status(Response.Status.NOT_FOUND) - .entity("Movie is not in the database.\nUnable to Delete").build(); - } - - inventory.remove(imdbID); - return Response.status(Response.Status.OK).build(); - } - - @GET - @Path("/listmovies") - @Produces({"application/json"}) - public List listMovies(){ - - return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); - - } - - - -} diff --git a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java deleted file mode 100644 index 16b6200ad1..0000000000 --- a/RestEasy Example/src/main/java/com/baeldung/server/service/RestEasyServices.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.server.service; - - -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * Created by Admin on 29/01/2016. - */ - - - -@ApplicationPath("/rest") -public class RestEasyServices extends Application { - - private Set singletons = new HashSet(); - - public RestEasyServices() { - singletons.add(new MovieCrudService()); - } - - @Override - public Set getSingletons() { - return singletons; - } - - @Override - public Set> getClasses() { - return super.getClasses(); - } - - @Override - public Map getProperties() { - return super.getProperties(); - } -} diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java index e711233979..c77f494862 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java @@ -1,49 +1,111 @@ package com.baeldung.server; -import com.baeldung.Movie; +import com.baeldung.model.Movie; import com.baeldung.client.ServicesInterface; +import org.apache.commons.io.IOUtils; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.ObjectMapper; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import javax.naming.NamingException; +import javax.ws.rs.core.Link; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Arrays; import java.util.List; +import java.util.Locale; public class RestEasyClient { - public static void main(String[] args) { - Movie st = new Movie(); - st.setImdbID("12345"); + Movie transformerMovie=null; + Movie batmanMovie=null; + ObjectMapper jsonMapper=null; - /* - * Alternatively you can use this simple String to send - * instead of using a Student instance - * - * String jsonString = "{\"id\":12,\"firstName\":\"Catain\",\"lastName\":\"Hook\",\"age\":10}"; - */ + @BeforeClass + public static void loadMovieInventory(){ + + + + } + + @Before + public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { + + + jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + jsonMapper.setDateFormat(sdf); + + try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) { + String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) { + String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + } + + @Test + public void testListAllMovies() { try { ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target("http://localhost:8080/RestEasyTutorial/rest/movies/listmovies"); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + final List movies = simple.listMovies(); + System.out.println(movies); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Test + public void testAddMovie() { + + try { + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); ServicesInterface simple = target.proxy(ServicesInterface.class); - final List movies = simple.listMovies(); + final Response moviesResponse = simple.addMovie(batmanMovie); - /* - if (response.getStatus() != 200) { + if (moviesResponse.getStatus() != 201) { + System.out.println(moviesResponse.readEntity(String.class)); throw new RuntimeException("Failed : HTTP error code : " - + response.getStatus()); + + moviesResponse.getStatus()); } - System.out.println("Server response : \n"); - System.out.println(response.readEntity(String.class)); + moviesResponse.close(); - response.close(); -*/ } catch (Exception e) { - e.printStackTrace(); - } } diff --git a/RestEasy Example/src/test/resources/server/movies/transformer.json b/RestEasy Example/src/test/resources/server/movies/transformer.json deleted file mode 100644 index 2154868265..0000000000 --- a/RestEasy Example/src/test/resources/server/movies/transformer.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "title": "Transformers", - "year": "2007", - "rated": "PG-13", - "released": "03 Jul 2007", - "runtime": "144 min", - "genre": "Action, Adventure, Sci-Fi", - "director": "Michael Bay", - "writer": "Roberto Orci (screenplay), Alex Kurtzman (screenplay), John Rogers (story), Roberto Orci (story), Alex Kurtzman (story)", - "actors": "Shia LaBeouf, Megan Fox, Josh Duhamel, Tyrese Gibson", - "plot": "A long time ago, far away on the planet of Cybertron, a war is being waged between the noble Autobots (led by the wise Optimus Prime) and the devious Decepticons (commanded by the dreaded Megatron) for control over the Allspark, a mystical talisman that would grant unlimited power to whoever possesses it. The Autobots managed to smuggle the Allspark off the planet, but Megatron blasts off in search of it. He eventually tracks it to the planet of Earth (circa 1850), but his reckless desire for power sends him right into the Arctic Ocean, and the sheer cold forces him into a paralyzed state. His body is later found by Captain Archibald Witwicky, but before going into a comatose state Megatron uses the last of his energy to engrave into the Captain's glasses a map showing the location of the Allspark, and to send a transmission to Cybertron. Megatron is then carried away aboard the Captain's ship. A century later, Captain Witwicky's grandson Sam Witwicky (nicknamed Spike by his friends) buys his first car. To his shock, he discovers it to be Bumblebee, an Autobot in disguise who is to protect Spike, who possesses the Captain's glasses and the map engraved on them. But Bumblebee is not the only Transformer to have arrived on Earth - in the desert of Qatar, the Decepticons Blackout and Scorponok attack a U.S. military base, causing the Pentagon to send their special Sector Seven agents to capture all \"specimens of this alien race.\" Spike and his girlfriend Mikaela find themselves in the midst of a grand battle between the Autobots and the Decepticons, stretching from Hoover Dam all the way to Los Angeles. Meanwhile, deep inside Hoover Dam, the cryogenically stored body of Megatron awakens.", - "language": "English, Spanish", - "country": "USA", - "awards": "Nominated for 3 Oscars. Another 18 wins & 40 nominations.", - "poster": "http://ia.media-imdb.com/images/M/MV5BMTQwNjU5MzUzNl5BMl5BanBnXkFtZTYwMzc1MTI3._V1_SX300.jpg", - "metascore": "61", - "imdbRating": "7.1", - "imdbVotes": "492,225", - "imdbID": "tt0418279", - "Type": "movie", - "response": "True" -} \ No newline at end of file From 6db36f902b1e7cf6f1c7857e5a14295e8881c732 Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sun, 31 Jan 2016 11:05:11 +0100 Subject: [PATCH 299/309] Added testCase for all Services --- .../baeldung/client/ServicesInterface.java | 6 + .../com/baeldung/server/MovieCrudService.java | 15 ++- .../com/baeldung/server/RestEasyClient.java | 112 ------------------ 3 files changed, 16 insertions(+), 117 deletions(-) delete mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 749cabc757..8898b83483 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -23,6 +23,12 @@ public interface ServicesInterface { List listMovies(); + @GET + @Path("/listmovies") + @Produces({"application/json"}) + List listMovies(); + + @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 60e0121966..18366e2faa 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -18,18 +18,21 @@ public class MovieCrudService { private Map inventory = new HashMap(); + @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ - System.out.println("*** Calling getinfo ***"); + System.out.println("*** Calling getinfo for a given ImdbID***"); + + if(inventory.containsKey(imdbID)){ + return inventory.get(imdbID); + }else return null; - Movie movie=new Movie(); - movie.setImdbID(imdbID); - return movie; } + @POST @Path("/addmovie") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @@ -41,6 +44,7 @@ public class MovieCrudService { return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } + inventory.put(movie.getImdbID(),movie); return Response.status(Response.Status.CREATED).build(); @@ -54,7 +58,7 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null!=inventory.get(movie.getImdbID())){ + if (null==inventory.get(movie.getImdbID())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } @@ -79,6 +83,7 @@ public class MovieCrudService { return Response.status(Response.Status.OK).build(); } + @GET @Path("/listmovies") @Produces({"application/json"}) diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java deleted file mode 100644 index c77f494862..0000000000 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClient.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.model.Movie; -import com.baeldung.client.ServicesInterface; -import org.apache.commons.io.IOUtils; -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; -import org.jboss.resteasy.client.jaxrs.ResteasyClient; -import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; -import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import javax.naming.NamingException; -import javax.ws.rs.core.Link; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -public class RestEasyClient { - - - Movie transformerMovie=null; - Movie batmanMovie=null; - ObjectMapper jsonMapper=null; - - @BeforeClass - public static void loadMovieInventory(){ - - - - } - - @Before - public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - - - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); - jsonMapper.setDateFormat(sdf); - - try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/transformer.json")) { - String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Test is going to die ...", e); - } - - try (InputStream inputStream = new RestEasyClient().getClass().getResourceAsStream("./movies/batman.json")) { - String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); - - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Test is going to die ...", e); - } - - } - - @Test - public void testListAllMovies() { - - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); - - final List movies = simple.listMovies(); - System.out.println(movies); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - @Test - public void testAddMovie() { - - try { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://localhost:8080/RestEasyTutorial/rest")); - - ServicesInterface simple = target.proxy(ServicesInterface.class); - final Response moviesResponse = simple.addMovie(batmanMovie); - - if (moviesResponse.getStatus() != 201) { - System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " - + moviesResponse.getStatus()); - } - - moviesResponse.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file From 33223becff3f88fd3bb8e5734f621c780c1ba454 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:29:30 +0100 Subject: [PATCH 300/309] Minor Bugfix --- .../main/java/com/baeldung/model/Movie.java | 22 +++++++++---------- .../com/baeldung/server/MovieCrudService.java | 12 +++++----- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 052ba081c1..a2b2bd5250 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -13,7 +13,7 @@ import javax.xml.bind.annotation.XmlType; "country", "director", "genre", - "imdbID", + "imdbId", "imdbRating", "imdbVotes", "language", @@ -36,7 +36,7 @@ public class Movie { protected String country; protected String director; protected String genre; - protected String imdbID; + protected String imdbId; protected String imdbRating; protected String imdbVotes; protected String language; @@ -173,27 +173,27 @@ public class Movie { } /** - * Recupera il valore della propriet� imdbID. + * Recupera il valore della propriet� imdbId. * * @return * possible object is * {@link String } * */ - public String getImdbID() { - return imdbID; + public String getImdbId() { + return imdbId; } /** - * Imposta il valore della propriet� imdbID. + * Imposta il valore della propriet� imdbId. * * @param value * allowed object is * {@link String } * */ - public void setImdbID(String value) { - this.imdbID = value; + public void setImdbId(String value) { + this.imdbId = value; } /** @@ -540,7 +540,7 @@ public class Movie { ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + - ", imdbID='" + imdbID + '\'' + + ", imdbId='" + imdbId + '\'' + ", imdbRating='" + imdbRating + '\'' + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + @@ -564,14 +564,14 @@ public class Movie { Movie movie = (Movie) o; - if (imdbID != null ? !imdbID.equals(movie.imdbID) : movie.imdbID != null) return false; + if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; return title != null ? title.equals(movie.title) : movie.title == null; } @Override public int hashCode() { - int result = imdbID != null ? imdbID.hashCode() : 0; + int result = imdbId != null ? imdbId.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); return result; } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 18366e2faa..29226aa0e0 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -22,7 +22,7 @@ public class MovieCrudService { @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbID") String imdbID){ + public Movie movieByImdbID(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling getinfo for a given ImdbID***"); @@ -40,12 +40,12 @@ public class MovieCrudService { System.out.println("*** Calling addMovie ***"); - if (null!=inventory.get(movie.getImdbID())){ + if (null!=inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is Already in the database.").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.CREATED).build(); } @@ -58,11 +58,11 @@ public class MovieCrudService { System.out.println("*** Calling updateMovie ***"); - if (null==inventory.get(movie.getImdbID())){ + if (null==inventory.get(movie.getImdbId())){ return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } - inventory.put(movie.getImdbID(),movie); + inventory.put(movie.getImdbId(),movie); return Response.status(Response.Status.OK).build(); } @@ -70,7 +70,7 @@ public class MovieCrudService { @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbID") String imdbID){ + public Response deleteMovie(@QueryParam("imdbId") String imdbID){ System.out.println("*** Calling deleteMovie ***"); From 783dc6bdc2cb172dd3bacf01faba9531675c45ab Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:39:35 +0100 Subject: [PATCH 301/309] Minor Bugfix --- .../main/java/com/baeldung/model/Movie.java | 321 +----------------- 1 file changed, 1 insertion(+), 320 deletions(-) diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index a2b2bd5250..805ba95209 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -52,482 +52,163 @@ public class Movie { protected String writer; protected String year; - /** - * Recupera il valore della propriet� actors. - * - * @return - * possible object is - * {@link String } - * - */ + public String getActors() { return actors; } - /** - * Imposta il valore della propriet� actors. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setActors(String value) { this.actors = value; } - /** - * Recupera il valore della propriet� awards. - * - * @return - * possible object is - * {@link String } - * - */ public String getAwards() { return awards; } - /** - * Imposta il valore della propriet� awards. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setAwards(String value) { this.awards = value; } - /** - * Recupera il valore della propriet� country. - * - * @return - * possible object is - * {@link String } - * - */ public String getCountry() { return country; } - /** - * Imposta il valore della propriet� country. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setCountry(String value) { this.country = value; } - /** - * Recupera il valore della propriet� director. - * - * @return - * possible object is - * {@link String } - * - */ public String getDirector() { return director; } - /** - * Imposta il valore della propriet� director. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setDirector(String value) { this.director = value; } - /** - * Recupera il valore della propriet� genre. - * - * @return - * possible object is - * {@link String } - * - */ public String getGenre() { return genre; } - /** - * Imposta il valore della propriet� genre. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setGenre(String value) { this.genre = value; } - /** - * Recupera il valore della propriet� imdbId. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbId() { return imdbId; } - /** - * Imposta il valore della propriet� imdbId. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setImdbId(String value) { this.imdbId = value; } - /** - * Recupera il valore della propriet� imdbRating. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbRating() { return imdbRating; } - /** - * Imposta il valore della propriet� imdbRating. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setImdbRating(String value) { this.imdbRating = value; } - /** - * Recupera il valore della propriet� imdbVotes. - * - * @return - * possible object is - * {@link String } - * - */ public String getImdbVotes() { return imdbVotes; } - /** - * Imposta il valore della propriet� imdbVotes. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setImdbVotes(String value) { this.imdbVotes = value; } - /** - * Recupera il valore della propriet� language. - * - * @return - * possible object is - * {@link String } - * - */ public String getLanguage() { return language; } - /** - * Imposta il valore della propriet� language. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setLanguage(String value) { this.language = value; } - /** - * Recupera il valore della propriet� metascore. - * - * @return - * possible object is - * {@link String } - * - */ public String getMetascore() { return metascore; } - /** - * Imposta il valore della propriet� metascore. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setMetascore(String value) { this.metascore = value; } - /** - * Recupera il valore della propriet� plot. - * - * @return - * possible object is - * {@link String } - * - */ public String getPlot() { return plot; } - /** - * Imposta il valore della propriet� plot. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setPlot(String value) { this.plot = value; } - /** - * Recupera il valore della propriet� poster. - * - * @return - * possible object is - * {@link String } - * - */ public String getPoster() { return poster; } - /** - * Imposta il valore della propriet� poster. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setPoster(String value) { this.poster = value; } - /** - * Recupera il valore della propriet� rated. - * - * @return - * possible object is - * {@link String } - * - */ public String getRated() { return rated; } - /** - * Imposta il valore della propriet� rated. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setRated(String value) { this.rated = value; } - /** - * Recupera il valore della propriet� released. - * - * @return - * possible object is - * {@link String } - * - */ public String getReleased() { return released; } - /** - * Imposta il valore della propriet� released. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setReleased(String value) { this.released = value; } - /** - * Recupera il valore della propriet� response. - * - * @return - * possible object is - * {@link String } - * - */ public String getResponse() { return response; } - /** - * Imposta il valore della propriet� response. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setResponse(String value) { this.response = value; } - /** - * Recupera il valore della propriet� runtime. - * - * @return - * possible object is - * {@link String } - * - */ public String getRuntime() { return runtime; } - /** - * Imposta il valore della propriet� runtime. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setRuntime(String value) { this.runtime = value; } - /** - * Recupera il valore della propriet� title. - * - * @return - * possible object is - * {@link String } - * - */ public String getTitle() { return title; } - /** - * Imposta il valore della propriet� title. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setTitle(String value) { this.title = value; } - /** - * Recupera il valore della propriet� type. - * - * @return - * possible object is - * {@link String } - * - */ public String getType() { return type; } - /** - * Imposta il valore della propriet� type. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setType(String value) { this.type = value; } - /** - * Recupera il valore della propriet� writer. - * - * @return - * possible object is - * {@link String } - * - */ public String getWriter() { return writer; } - /** - * Imposta il valore della propriet� writer. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setWriter(String value) { this.writer = value; } - /** - * Recupera il valore della propriet� year. - * - * @return - * possible object is - * {@link String } - * - */ public String getYear() { return year; } - /** - * Imposta il valore della propriet� year. - * - * @param value - * allowed object is - * {@link String } - * - */ public void setYear(String value) { this.year = value; } From 71793635d32d50427bc4165b29b39aaabec3d743 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 7 Feb 2016 20:55:46 +0100 Subject: [PATCH 302/309] CleanUp Code --- RestEasy Example/pom.xml | 3 +- .../baeldung/client/ServicesInterface.java | 1 - .../main/java/com/baeldung/model/Movie.java | 2 -- .../com/baeldung/server/MovieCrudService.java | 17 ++++------- .../com/baeldung/server/RestEasyServices.java | 8 ----- .../src/main/resources/schema1.xsd | 29 ------------------- .../src/main/webapp/WEB-INF/web.xml | 3 -- .../java/baeldung/client/RestEasyClient.java | 7 ----- .../baeldung/server/RestEasyClientTest.java | 1 - 9 files changed, 7 insertions(+), 64 deletions(-) delete mode 100644 RestEasy Example/src/main/resources/schema1.xsd delete mode 100644 RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index 6935238d91..9c890da2b7 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -36,7 +36,7 @@ - + org.jboss.resteasy jaxrs-api @@ -101,5 +101,4 @@ - \ No newline at end of file diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 8898b83483..22669717a8 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -1,7 +1,6 @@ package com.baeldung.client; import com.baeldung.model.Movie; - import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 805ba95209..56ba766ff4 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -1,11 +1,9 @@ - package com.baeldung.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; - @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "movie", propOrder = { "actors", diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 29226aa0e0..bbb3b1e953 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -1,7 +1,6 @@ package com.baeldung.server; import com.baeldung.model.Movie; - import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -11,23 +10,21 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; - @Path("/movies") public class MovieCrudService { - private Map inventory = new HashMap(); @GET @Path("/getinfo") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbID(@QueryParam("imdbId") String imdbID){ + public Movie movieByImdbId(@QueryParam("imdbId") String imdbId){ System.out.println("*** Calling getinfo for a given ImdbID***"); - if(inventory.containsKey(imdbID)){ - return inventory.get(imdbID); + if(inventory.containsKey(imdbId)){ + return inventory.get(imdbId); }else return null; } @@ -70,16 +67,16 @@ public class MovieCrudService { @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbId") String imdbID){ + public Response deleteMovie(@QueryParam("imdbId") String imdbId){ System.out.println("*** Calling deleteMovie ***"); - if (null==inventory.get(imdbID)){ + if (null==inventory.get(imdbId)){ return Response.status(Response.Status.NOT_FOUND) .entity("Movie is not in the database.\nUnable to Delete").build(); } - inventory.remove(imdbID); + inventory.remove(imdbId); return Response.status(Response.Status.OK).build(); } @@ -93,6 +90,4 @@ public class MovieCrudService { } - - } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java index 8c57d2c9b4..7726e49f38 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java @@ -1,19 +1,11 @@ package com.baeldung.server; - import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; -import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; -/** - * Created by Admin on 29/01/2016. - */ - - - @ApplicationPath("/rest") public class RestEasyServices extends Application { diff --git a/RestEasy Example/src/main/resources/schema1.xsd b/RestEasy Example/src/main/resources/schema1.xsd deleted file mode 100644 index 0d74b7c366..0000000000 --- a/RestEasy Example/src/main/resources/schema1.xsd +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index f70fdf7975..1e7f64004d 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -5,12 +5,9 @@ RestEasy Example - resteasy.servlet.mapping.prefix /rest - - \ No newline at end of file diff --git a/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java b/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java deleted file mode 100644 index b474b3d4f8..0000000000 --- a/RestEasy Example/src/test/java/baeldung/client/RestEasyClient.java +++ /dev/null @@ -1,7 +0,0 @@ -package baeldung.client; - -/** - * Created by Admin on 29/01/2016. - */ -public class RestEasyClient { -} diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java index b6a2e2a0c1..faa39e0199 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -10,7 +10,6 @@ import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.junit.Before; import org.junit.Test; - import javax.naming.NamingException; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; From 04d9bbb7682999c0d90054150aac69cbfa442781 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Mon, 8 Feb 2016 14:00:11 +0100 Subject: [PATCH 303/309] CleanUp and reformatting Code; dependency fix in pom.xml --- RestEasy Example/pom.xml | 147 +++++++----------- .../baeldung/client/ServicesInterface.java | 21 +-- .../main/java/com/baeldung/model/Movie.java | 56 ++----- .../com/baeldung/server/MovieCrudService.java | 49 +++--- .../WEB-INF/jboss-deployment-structure.xml | 22 +-- .../src/main/webapp/WEB-INF/web.xml | 14 +- .../baeldung/server/RestEasyClientTest.java | 23 ++- .../com/baeldung/server/movies/batman.json | 2 +- .../baeldung/server/movies/transformer.json | 2 +- 9 files changed, 125 insertions(+), 211 deletions(-) diff --git a/RestEasy Example/pom.xml b/RestEasy Example/pom.xml index 9c890da2b7..ec9e87b0d1 100644 --- a/RestEasy Example/pom.xml +++ b/RestEasy Example/pom.xml @@ -1,104 +1,77 @@ - - 4.0.0 + + 4.0.0 - com.baeldung - resteasy-tutorial - 1.0 - war + com.baeldung + resteasy-tutorial + 1.0 + war - - - jboss - http://repository.jboss.org/nexus/content/groups/public/ - - + + 3.0.14.Final + - - 3.0.14.Final - runtime - + + RestEasyTutorial + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + - - RestEasyTutorial - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - + - + - - org.jboss.resteasy - jaxrs-api - 3.0.12.Final - ${resteasy.scope} - - - - org.jboss.resteasy - resteasy-servlet-initializer - ${resteasy.version} - ${resteasy.scope} - - - jboss-jaxrs-api_2.0_spec - org.jboss.spec.javax.ws.rs - - - - - - org.jboss.resteasy - resteasy-client - ${resteasy.version} - ${resteasy.scope} - + + org.jboss.resteasy + resteasy-servlet-initializer + ${resteasy.version} + - - javax.ws.rs - javax.ws.rs-api - 2.0.1 - + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + - - org.jboss.resteasy - resteasy-jackson-provider - ${resteasy.version} - ${resteasy.scope} - + - - org.jboss.resteasy - resteasy-jaxb-provider - ${resteasy.version} - ${resteasy.scope} - + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy.version} + - + + org.jboss.resteasy + resteasy-jackson-provider + ${resteasy.version} + - - junit - junit - 4.4 - + - - commons-io - commons-io - 2.4 - + + junit + junit + 4.4 + + + + commons-io + commons-io + 2.4 + + + - \ No newline at end of file diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java index 22669717a8..3d03c16faf 100644 --- a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java @@ -9,41 +9,28 @@ import java.util.List; @Path("/movies") public interface ServicesInterface { - @GET @Path("/getinfo") - @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Movie movieByImdbId(@QueryParam("imdbId") String imdbId); - @GET @Path("/listmovies") - @Produces({"application/json"}) + @Produces({ "application/json" }) List listMovies(); - - @GET - @Path("/listmovies") - @Produces({"application/json"}) - List listMovies(); - - @POST @Path("/addmovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Response addMovie(Movie movie); - @PUT @Path("/updatemovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Response updateMovie(Movie movie); - @DELETE @Path("/deletemovie") Response deleteMovie(@QueryParam("imdbId") String imdbID); - - } diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 56ba766ff4..a959682a75 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -5,28 +5,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "movie", propOrder = { - "actors", - "awards", - "country", - "director", - "genre", - "imdbId", - "imdbRating", - "imdbVotes", - "language", - "metascore", - "plot", - "poster", - "rated", - "released", - "response", - "runtime", - "title", - "type", - "writer", - "year" -}) +@XmlType(name = "movie", propOrder = { "actors", "awards", "country", "director", "genre", "imdbId", "imdbRating", "imdbVotes", "language", "metascore", "plot", "poster", "rated", "released", "response", "runtime", "title", "type", "writer", "year" }) public class Movie { protected String actors; @@ -213,37 +192,22 @@ public class Movie { @Override public String toString() { - return "Movie{" + - "actors='" + actors + '\'' + - ", awards='" + awards + '\'' + - ", country='" + country + '\'' + - ", director='" + director + '\'' + - ", genre='" + genre + '\'' + - ", imdbId='" + imdbId + '\'' + - ", imdbRating='" + imdbRating + '\'' + - ", imdbVotes='" + imdbVotes + '\'' + - ", language='" + language + '\'' + - ", metascore='" + metascore + '\'' + - ", poster='" + poster + '\'' + - ", rated='" + rated + '\'' + - ", released='" + released + '\'' + - ", response='" + response + '\'' + - ", runtime='" + runtime + '\'' + - ", title='" + title + '\'' + - ", type='" + type + '\'' + - ", writer='" + writer + '\'' + - ", year='" + year + '\'' + - '}'; + return "Movie{" + "actors='" + actors + '\'' + ", awards='" + awards + '\'' + ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + ", imdbId='" + imdbId + '\'' + ", imdbRating='" + imdbRating + '\'' + + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + ", metascore='" + metascore + '\'' + ", poster='" + poster + '\'' + ", rated='" + rated + '\'' + ", released='" + released + '\'' + ", response='" + response + '\'' + + ", runtime='" + runtime + '\'' + ", title='" + title + '\'' + ", type='" + type + '\'' + ", writer='" + writer + '\'' + ", year='" + year + '\'' + '}'; } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Movie movie = (Movie) o; - if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; + if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) + return false; return title != null ? title.equals(movie.title) : movie.title == null; } diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index bbb3b1e953..6a0699874a 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -13,78 +13,71 @@ import java.util.stream.Collectors; @Path("/movies") public class MovieCrudService { - private Map inventory = new HashMap(); - + private Map inventory = new HashMap(); @GET @Path("/getinfo") - @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Movie movieByImdbId(@QueryParam("imdbId") String imdbId){ + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Movie movieByImdbId(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling getinfo for a given ImdbID***"); - if(inventory.containsKey(imdbId)){ + if (inventory.containsKey(imdbId)) { return inventory.get(imdbId); - }else return null; + } else + return null; } - @POST @Path("/addmovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Response addMovie(Movie movie){ + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Response addMovie(Movie movie) { System.out.println("*** Calling addMovie ***"); - if (null!=inventory.get(movie.getImdbId())){ - return Response.status(Response.Status.NOT_MODIFIED) - .entity("Movie is Already in the database.").build(); + if (null != inventory.get(movie.getImdbId())) { + return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is Already in the database.").build(); } - inventory.put(movie.getImdbId(),movie); + inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.CREATED).build(); } - @PUT @Path("/updatemovie") - @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) - public Response updateMovie(Movie movie){ + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Response updateMovie(Movie movie) { System.out.println("*** Calling updateMovie ***"); - if (null==inventory.get(movie.getImdbId())){ - return Response.status(Response.Status.NOT_MODIFIED) - .entity("Movie is not in the database.\nUnable to Update").build(); + if (null == inventory.get(movie.getImdbId())) { + return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is not in the database.\nUnable to Update").build(); } - inventory.put(movie.getImdbId(),movie); + inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.OK).build(); } - @DELETE @Path("/deletemovie") - public Response deleteMovie(@QueryParam("imdbId") String imdbId){ + public Response deleteMovie(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling deleteMovie ***"); - if (null==inventory.get(imdbId)){ - return Response.status(Response.Status.NOT_FOUND) - .entity("Movie is not in the database.\nUnable to Delete").build(); + if (null == inventory.get(imdbId)) { + return Response.status(Response.Status.NOT_FOUND).entity("Movie is not in the database.\nUnable to Delete").build(); } inventory.remove(imdbId); return Response.status(Response.Status.OK).build(); } - @GET @Path("/listmovies") - @Produces({"application/json"}) - public List listMovies(){ + @Produces({ "application/json" }) + public List listMovies() { return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml index 84d75934a7..7879603d19 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -1,16 +1,16 @@ - - - - + + + + - - - - - + + + + + - - + + \ No newline at end of file diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/RestEasy Example/src/main/webapp/WEB-INF/web.xml index 1e7f64004d..d5f00293f4 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/web.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/web.xml @@ -1,13 +1,13 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> - RestEasy Example + RestEasy Example - - resteasy.servlet.mapping.prefix - /rest - + + resteasy.servlet.mapping.prefix + /rest + \ No newline at end of file diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java index faa39e0199..3760ae2415 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -21,14 +21,14 @@ import java.util.Locale; public class RestEasyClientTest { - Movie transformerMovie=null; - Movie batmanMovie=null; - ObjectMapper jsonMapper=null; + Movie transformerMovie = null; + Movie batmanMovie = null; + ObjectMapper jsonMapper = null; @Before public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - jsonMapper=new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); jsonMapper.setDateFormat(sdf); @@ -69,7 +69,7 @@ public class RestEasyClientTest { @Test public void testMovieByImdbId() { - String transformerImdbId="tt0418279"; + String transformerImdbId = "tt0418279"; ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); @@ -82,7 +82,6 @@ public class RestEasyClientTest { System.out.println(movies); } - @Test public void testAddMovie() { @@ -99,10 +98,9 @@ public class RestEasyClientTest { } moviesResponse.close(); - System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); } - @Test public void testDeleteMovi1e() { @@ -116,14 +114,13 @@ public class RestEasyClientTest { if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); + throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); - System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); } - @Test public void testUpdateMovie() { @@ -137,11 +134,11 @@ public class RestEasyClientTest { moviesResponse = simple.updateMovie(batmanMovie); if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); - System.out.println("Response Code: "+Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); } } \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json index 28061d5bf9..173901c948 100644 --- a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json @@ -16,7 +16,7 @@ "metascore": "66", "imdbRating": "7.6", "imdbVotes": "256,000", - "imdbID": "tt0096895", + "imdbId": "tt0096895", "type": "movie", "response": "True" } \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json index a3b033a8ba..a4fd061a82 100644 --- a/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json @@ -16,7 +16,7 @@ "metascore": "61", "imdbRating": "7.1", "imdbVotes": "492,225", - "imdbID": "tt0418279", + "imdbId": "tt0418279", "type": "movie", "response": "True" } \ No newline at end of file From 81f498407142bcc91071110ef20d0ee9a5b5da98 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Mon, 8 Feb 2016 16:08:15 +0100 Subject: [PATCH 304/309] CleanUp and reformatting Code. --- .../src/main/java/com/baeldung/server/MovieCrudService.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java index 6a0699874a..b7f3215f3f 100644 --- a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java +++ b/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java @@ -26,7 +26,6 @@ public class MovieCrudService { return inventory.get(imdbId); } else return null; - } @POST @@ -41,7 +40,6 @@ public class MovieCrudService { } inventory.put(movie.getImdbId(), movie); - return Response.status(Response.Status.CREATED).build(); } @@ -55,9 +53,9 @@ public class MovieCrudService { if (null == inventory.get(movie.getImdbId())) { return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is not in the database.\nUnable to Update").build(); } + inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.OK).build(); - } @DELETE @@ -80,7 +78,6 @@ public class MovieCrudService { public List listMovies() { return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); - } } From 1c8e8a2e0c5683bcc0b992e631807b016d1d45a6 Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sat, 13 Feb 2016 23:48:11 +0100 Subject: [PATCH 305/309] Formatting and many fields removed from Movie class --- .../main/java/com/baeldung/model/Movie.java | 188 ++---------------- .../WEB-INF/jboss-deployment-structure.xml | 3 - .../baeldung/server/RestEasyClientTest.java | 2 +- .../com/baeldung/server/movies/batman.json | 20 +- .../baeldung/server/movies/transformer.json | 20 +- 5 files changed, 20 insertions(+), 213 deletions(-) diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java index 5aade4591a..408f2144fb 100644 --- a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java +++ b/RestEasy Example/src/main/java/com/baeldung/model/Movie.java @@ -5,195 +5,33 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "movie", propOrder = { "actors", "awards", "country", "director", "genre", "imdbId", "imdbRating", "imdbVotes", "language", "metascore", "plot", "poster", "rated", "released", "response", "runtime", "title", "type", "writer", "year" }) +@XmlType(name = "movie", propOrder = { "imdbId", "title" }) public class Movie { - protected String actors; - protected String awards; - protected String country; - protected String director; - protected String genre; protected String imdbId; - protected String imdbRating; - protected String imdbVotes; - protected String language; - protected String metascore; - protected String plot; - protected String poster; - protected String rated; - protected String released; - protected String response; - protected String runtime; protected String title; - protected String type; - protected String writer; - protected String year; - public String getActors() { - return actors; + public Movie(String imdbId, String title) { + this.imdbId = imdbId; + this.title = title; } - public void setActors(String value) { - this.actors = value; - } - - public String getAwards() { - return awards; - } - - public void setAwards(String value) { - this.awards = value; - } - - public String getCountry() { - return country; - } - - public void setCountry(String value) { - this.country = value; - } - - public String getDirector() { - return director; - } - - public void setDirector(String value) { - this.director = value; - } - - public String getGenre() { - return genre; - } - - public void setGenre(String value) { - this.genre = value; - } + public Movie() {} public String getImdbId() { return imdbId; } - public void setImdbId(String value) { - this.imdbId = value; - } - - public String getImdbRating() { - return imdbRating; - } - - public void setImdbRating(String value) { - this.imdbRating = value; - } - - public String getImdbVotes() { - return imdbVotes; - } - - public void setImdbVotes(String value) { - this.imdbVotes = value; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String value) { - this.language = value; - } - - public String getMetascore() { - return metascore; - } - - public void setMetascore(String value) { - this.metascore = value; - } - - public String getPlot() { - return plot; - } - - public void setPlot(String value) { - this.plot = value; - } - - public String getPoster() { - return poster; - } - - public void setPoster(String value) { - this.poster = value; - } - - public String getRated() { - return rated; - } - - public void setRated(String value) { - this.rated = value; - } - - public String getReleased() { - return released; - } - - public void setReleased(String value) { - this.released = value; - } - - public String getResponse() { - return response; - } - - public void setResponse(String value) { - this.response = value; - } - - public String getRuntime() { - return runtime; - } - - public void setRuntime(String value) { - this.runtime = value; + public void setImdbId(String imdbId) { + this.imdbId = imdbId; } public String getTitle() { return title; } - public void setTitle(String value) { - this.title = value; - } - - public String getType() { - return type; - } - - public void setType(String value) { - this.type = value; - } - - public String getWriter() { - return writer; - } - - public void setWriter(String value) { - this.writer = value; - } - - public String getYear() { - return year; - } - - public void setYear(String value) { - this.year = value; - } - - @Override - public String toString() { - return "Movie{" + "actors='" + actors + '\'' + ", awards='" + awards + '\'' + ", country='" + country + '\'' + ", director='" + director + '\'' + ", genre='" + genre + '\'' + ", imdbId='" + imdbId + '\'' + ", imdbRating='" + imdbRating + '\'' - + ", imdbVotes='" + imdbVotes + '\'' + ", language='" + language + '\'' + ", metascore='" + metascore + '\'' + ", poster='" + poster + '\'' + ", rated='" + rated + '\'' + ", released='" + released + '\'' + ", response='" + response + '\'' - + ", runtime='" + runtime + '\'' + ", title='" + title + '\'' + ", type='" + type + '\'' + ", writer='" + writer + '\'' + ", year='" + year + '\'' + '}'; + public void setTitle(String title) { + this.title = title; } @Override @@ -217,4 +55,12 @@ public class Movie { result = 31 * result + (title != null ? title.hashCode() : 0); return result; } + + @Override + public String toString() { + return "Movie{" + + "imdbId='" + imdbId + '\'' + + ", title='" + title + '\'' + + '}'; + } } diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml index 7879603d19..e5b893e56a 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -3,14 +3,11 @@ - - - \ No newline at end of file diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java index 3760ae2415..2a13465ebc 100644 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -130,7 +130,7 @@ public class RestEasyClientTest { Response moviesResponse = simple.addMovie(batmanMovie); moviesResponse.close(); - batmanMovie.setImdbVotes("300,000"); + batmanMovie.setTitle("Batman Begins"); moviesResponse = simple.updateMovie(batmanMovie); if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json index 173901c948..82aaaa8f40 100644 --- a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json @@ -1,22 +1,4 @@ { "title": "Batman", - "year": "1989", - "rated": "PG-13", - "released": "23 Jun 1989", - "runtime": "126 min", - "genre": "Action, Adventure", - "director": "Tim Burton", - "writer": "Bob Kane (Batman characters), Sam Hamm (story), Sam Hamm (screenplay), Warren Skaaren (screenplay)", - "actors": "Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl", - "plot": "The Dark Knight of Gotham City begins his war on crime with his first major enemy being the clownishly homicidal Joker.", - "language": "English, French", - "country": "USA, UK", - "awards": "Won 1 Oscar. Another 9 wins & 22 nominations.", - "poster": "http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg", - "metascore": "66", - "imdbRating": "7.6", - "imdbVotes": "256,000", - "imdbId": "tt0096895", - "type": "movie", - "response": "True" + "imdbId": "tt0096895" } \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json index a4fd061a82..634cefc73c 100644 --- a/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json +++ b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json @@ -1,22 +1,4 @@ { "title": "Transformers", - "year": "2007", - "rated": "PG-13", - "released": "03 Jul 2007", - "runtime": "144 min", - "genre": "Action, Adventure, Sci-Fi", - "director": "Michael Bay", - "writer": "Roberto Orci (screenplay), Alex Kurtzman (screenplay), John Rogers (story), Roberto Orci (story), Alex Kurtzman (story)", - "actors": "Shia LaBeouf, Megan Fox, Josh Duhamel, Tyrese Gibson", - "plot": "A long time ago, far away on the planet of Cybertron, a war is being waged between the noble Autobots (led by the wise Optimus Prime) and the devious Decepticons (commanded by the dreaded Megatron) for control over the Allspark, a mystical talisman that would grant unlimited power to whoever possesses it. The Autobots managed to smuggle the Allspark off the planet, but Megatron blasts off in search of it. He eventually tracks it to the planet of Earth (circa 1850), but his reckless desire for power sends him right into the Arctic Ocean, and the sheer cold forces him into a paralyzed state. His body is later found by Captain Archibald Witwicky, but before going into a comatose state Megatron uses the last of his energy to engrave into the Captain's glasses a map showing the location of the Allspark, and to send a transmission to Cybertron. Megatron is then carried away aboard the Captain's ship. A century later, Captain Witwicky's grandson Sam Witwicky (nicknamed Spike by his friends) buys his first car. To his shock, he discovers it to be Bumblebee, an Autobot in disguise who is to protect Spike, who possesses the Captain's glasses and the map engraved on them. But Bumblebee is not the only Transformer to have arrived on Earth - in the desert of Qatar, the Decepticons Blackout and Scorponok attack a U.S. military base, causing the Pentagon to send their special Sector Seven agents to capture all \"specimens of this alien race.\" Spike and his girlfriend Mikaela find themselves in the midst of a grand battle between the Autobots and the Decepticons, stretching from Hoover Dam all the way to Los Angeles. Meanwhile, deep inside Hoover Dam, the cryogenically stored body of Megatron awakens.", - "language": "English, Spanish", - "country": "USA", - "awards": "Nominated for 3 Oscars. Another 18 wins & 40 nominations.", - "poster": "http://ia.media-imdb.com/images/M/MV5BMTQwNjU5MzUzNl5BMl5BanBnXkFtZTYwMzc1MTI3._V1_SX300.jpg", - "metascore": "61", - "imdbRating": "7.1", - "imdbVotes": "492,225", - "imdbId": "tt0418279", - "type": "movie", - "response": "True" + "imdbId": "tt0418279" } \ No newline at end of file From 957b0958e3190caf2790d8cac15715be20a1e57a Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 14 Feb 2016 00:35:19 +0100 Subject: [PATCH 306/309] Reformatting Code. --- .../main/webapp/WEB-INF/jboss-deployment-structure.xml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml index e5b893e56a..45dfd9f075 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -1,13 +1,17 @@ + - + + - - + + + + \ No newline at end of file From fa39351b6e31f8ed1483e75df5448e3a333cd7b1 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Sun, 14 Feb 2016 00:40:02 +0100 Subject: [PATCH 307/309] Reformatting Code. --- .../WEB-INF/jboss-deployment-structure.xml | 24 ++++++++----------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml index 45dfd9f075..cb258374a1 100644 --- a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml +++ b/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -1,17 +1,13 @@ + - - - - - - + + + + - - - - - - - + + + + - \ No newline at end of file + From 72214652846664333aaa334b1f05d88e13a0c070 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 14 Feb 2016 11:15:29 +0200 Subject: [PATCH 308/309] cleanup work --- spring-security-login-and-registration/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-security-login-and-registration/pom.xml b/spring-security-login-and-registration/pom.xml index f5b62be553..bcbe9371e2 100644 --- a/spring-security-login-and-registration/pom.xml +++ b/spring-security-login-and-registration/pom.xml @@ -269,7 +269,8 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java + **/*LiveTest.java From 33e5f14e86ee2913d11d8df5603dd9d20d70d34b Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sun, 14 Feb 2016 12:34:32 +0100 Subject: [PATCH 309/309] Example folders cleaned --- .../baeldung/server/RestEasyClientTest.java | 144 ------------------ .../com/baeldung/server/movies/batman.json | 4 - .../baeldung/server/movies/transformer.json | 4 - 3 files changed, 152 deletions(-) delete mode 100644 RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java delete mode 100644 RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json delete mode 100644 RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json diff --git a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java b/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java deleted file mode 100644 index 2a13465ebc..0000000000 --- a/RestEasy Example/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.client.ServicesInterface; -import com.baeldung.model.Movie; -import org.apache.commons.io.IOUtils; -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; -import org.jboss.resteasy.client.jaxrs.ResteasyClient; -import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; -import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; -import org.junit.Before; -import org.junit.Test; -import javax.naming.NamingException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.List; -import java.util.Locale; - -public class RestEasyClientTest { - - Movie transformerMovie = null; - Movie batmanMovie = null; - ObjectMapper jsonMapper = null; - - @Before - public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { - - jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); - jsonMapper.setDateFormat(sdf); - - try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/transformer.json")) { - String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Test is going to die ...", e); - } - - try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/batman.json")) { - String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); - - } catch (Exception e) { - throw new RuntimeException("Test is going to die ...", e); - } - } - - @Test - public void testListAllMovies() { - - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); - - Response moviesResponse = simple.addMovie(transformerMovie); - moviesResponse.close(); - moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - - List movies = simple.listMovies(); - System.out.println(movies); - } - - @Test - public void testMovieByImdbId() { - - String transformerImdbId = "tt0418279"; - - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); - - Response moviesResponse = simple.addMovie(transformerMovie); - moviesResponse.close(); - - Movie movies = simple.movieByImdbId(transformerImdbId); - System.out.println(movies); - } - - @Test - public void testAddMovie() { - - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); - - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - moviesResponse = simple.addMovie(transformerMovie); - - if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - - moviesResponse.close(); - System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); - } - - @Test - public void testDeleteMovi1e() { - - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); - - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - moviesResponse = simple.deleteMovie(batmanMovie.getImdbId()); - - if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - System.out.println(moviesResponse.readEntity(String.class)); - throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - - moviesResponse.close(); - System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); - } - - @Test - public void testUpdateMovie() { - - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); - ServicesInterface simple = target.proxy(ServicesInterface.class); - - Response moviesResponse = simple.addMovie(batmanMovie); - moviesResponse.close(); - batmanMovie.setTitle("Batman Begins"); - moviesResponse = simple.updateMovie(batmanMovie); - - if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { - System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); - } - - moviesResponse.close(); - System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); - } - -} \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json deleted file mode 100644 index 82aaaa8f40..0000000000 --- a/RestEasy Example/src/test/resources/com/baeldung/server/movies/batman.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "title": "Batman", - "imdbId": "tt0096895" -} \ No newline at end of file diff --git a/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json b/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json deleted file mode 100644 index 634cefc73c..0000000000 --- a/RestEasy Example/src/test/resources/com/baeldung/server/movies/transformer.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "title": "Transformers", - "imdbId": "tt0418279" -} \ No newline at end of file
/>