From 29e3437545dc89082a89e8781d1b1b2f71f164b7 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 4 Jun 2017 10:07:05 +0200 Subject: [PATCH] Nbosecker merge (#1989) * Solr w Apache SolrJ * Solr w Apache SolrJ * updated test names and moved add to @before method * create apache-solrj module, moved code from spring-data-solr * More examples for indexing,delete,and query for solrj * More examples for indexing,delete,and query for solrj * Jackson Map Serialize/Deserialize * Jackson Map Serialize/Deserialize * Jackson version update * keydeserializer code added * keydeserializer code added * remove explicit types from map instantion * one objectmapper per class * refactor to spring-rest-simple module * Fix spring-rest-simple --- pom.xml | 1 + spring-rest-simple/pom.xml | 370 ++++++++++++++++++ .../java/org/baeldung/config/Application.java | 16 + .../java/org/baeldung/config/WebConfig.java | 61 +++ .../converter/KryoHttpMessageConverter.java | 60 +++ .../BarMappingExamplesController.java | 0 .../BazzNewMappingsExampleController.java | 0 .../web/controller/FooController.java | 39 ++ .../FooMappingExamplesController.java | 0 .../controller/status/ExampleController.java | 0 .../controller/status/ForbiddenException.java | 0 .../main/java/org/baeldung/web/dto/Bazz.java | 0 .../main/java/org/baeldung/web/dto/Foo.java | 45 +++ .../java/org/baeldung/web/dto/FooProtos.java | 0 .../java/org/baeldung/web/util/LinkUtil.java | 36 ++ .../src/main/resources/application.properties | 2 + .../src/main/resources/logback.xml | 19 + .../src/main/webapp/WEB-INF/api-servlet.xml | 56 +++ .../src/main/webapp/WEB-INF/company.html | 44 +++ .../src/main/webapp/WEB-INF/spring-views.xml | 10 + .../src/main/webapp/WEB-INF/web.xml | 41 ++ .../client/RestTemplateBasicLiveTest.java | 216 ++++++++++ .../client/TestRestTemplateBasicLiveTest.java | 117 ++++++ .../web/controller/mediatypes/TestConfig.java | 11 + ...BazzNewMappingsExampleIntegrationTest.java | 17 +- .../web/test/RequestMappingLiveTest.java | 2 +- .../SpringHttpMessageConvertersLiveTest.java | 0 .../baeldung/web/util/HTTPLinkHeaderUtil.java | 69 ++++ .../src/test/resources/.gitignore | 13 + .../java/org/baeldung/config/WebConfig.java | 2 - .../converter/KryoHttpMessageConverter.java | 57 --- .../repository/HeavyResourceRepository.java | 9 +- .../web/controller/FooController.java | 45 --- ...eavyResourceControllerIntegrationTest.java | 13 +- 34 files changed, 1248 insertions(+), 123 deletions(-) create mode 100644 spring-rest-simple/pom.xml create mode 100644 spring-rest-simple/src/main/java/org/baeldung/config/Application.java create mode 100644 spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java create mode 100644 spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java rename {spring-rest => spring-rest-simple}/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java (100%) rename {spring-rest => spring-rest-simple}/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java (100%) create mode 100644 spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java rename {spring-rest => spring-rest-simple}/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java (100%) rename {spring-rest => spring-rest-simple}/src/main/java/org/baeldung/web/controller/status/ExampleController.java (100%) rename {spring-rest => spring-rest-simple}/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java (100%) rename {spring-rest => spring-rest-simple}/src/main/java/org/baeldung/web/dto/Bazz.java (100%) create mode 100644 spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java rename {spring-rest => spring-rest-simple}/src/main/java/org/baeldung/web/dto/FooProtos.java (100%) create mode 100644 spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java create mode 100644 spring-rest-simple/src/main/resources/application.properties create mode 100644 spring-rest-simple/src/main/resources/logback.xml create mode 100644 spring-rest-simple/src/main/webapp/WEB-INF/api-servlet.xml create mode 100644 spring-rest-simple/src/main/webapp/WEB-INF/company.html create mode 100644 spring-rest-simple/src/main/webapp/WEB-INF/spring-views.xml create mode 100644 spring-rest-simple/src/main/webapp/WEB-INF/web.xml create mode 100644 spring-rest-simple/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java create mode 100644 spring-rest-simple/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java create mode 100644 spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java rename spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerIntegrationTest.java => spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java (88%) rename {spring-rest => spring-rest-simple}/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java (98%) rename {spring-rest => spring-rest-simple}/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java (100%) create mode 100644 spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java create mode 100644 spring-rest-simple/src/test/resources/.gitignore delete mode 100644 spring-rest/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java delete mode 100644 spring-rest/src/main/java/org/baeldung/web/controller/FooController.java diff --git a/pom.xml b/pom.xml index 3640713ddd..e53baa77a2 100644 --- a/pom.xml +++ b/pom.xml @@ -174,6 +174,7 @@ spring-rest-angular spring-rest-docs spring-rest + spring-rest-simple spring-security-cache-control spring-security-client/spring-security-jsp-authentication spring-security-client/spring-security-jsp-authorize diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml new file mode 100644 index 0000000000..f662b736ad --- /dev/null +++ b/spring-rest-simple/pom.xml @@ -0,0 +1,370 @@ + + 4.0.0 + com.baeldung + spring-rest-simple + 0.1-SNAPSHOT + spring-rest-simple + war + + + org.springframework.boot + spring-boot-starter-parent + 1.4.3.RELEASE + + + + + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-devtools + + + org.springframework.boot + spring-boot-test + + + + + + org.springframework + spring-web + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + + + org.springframework + spring-oxm + + + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + + + + javax.servlet + javax.servlet-api + provided + + + + javax.servlet + jstl + runtime + + + + + + com.fasterxml.jackson.core + jackson-databind + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + + com.thoughtworks.xstream + xstream + ${xstream.version} + + + + + + com.google.guava + guava + ${guava.version} + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + org.slf4j + jcl-over-slf4j + + + + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + + + + + junit + junit + test + + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + + org.mockito + mockito-core + test + + + + org.springframework + spring-test + + + + com.jayway.restassured + rest-assured + ${rest-assured.version} + + + + + com.google.protobuf + protobuf-java + ${protobuf-java.version} + + + com.googlecode.protobuf-java-format + protobuf-java-format + ${protobuf-java-format.version} + + + + com.esotericsoftware + kryo + ${kryo.version} + + + + com.jayway.jsonpath + json-path + + + + + + spring-rest + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8082 + + + + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + + + + + + + + + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + + + + 1.3.2 + 4.0.0 + 1.4 + 3.1.0 + 3.5 + 1.4.9 + + + 20.0 + 2.9.0 + + + 1.6.0 + 3.0.4 + + + 3.4.1 + + 2.2.0 + + + diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/Application.java b/spring-rest-simple/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..077213b04d --- /dev/null +++ b/spring-rest-simple/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,16 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@EnableAutoConfiguration +@ComponentScan("org.baeldung") +public class Application extends WebMvcConfigurerAdapter { + + public static void main(final String[] args) { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java new file mode 100644 index 0000000000..4eb476411e --- /dev/null +++ b/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java @@ -0,0 +1,61 @@ +package org.baeldung.config; + +import java.text.SimpleDateFormat; +import java.util.List; + +import org.baeldung.config.converter.KryoHttpMessageConverter; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; +import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; +import org.springframework.oxm.xstream.XStreamMarshaller; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +/* + * Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml + */ +@Configuration +@EnableWebMvc +@ComponentScan({ "org.baeldung.web" }) +public class WebConfig extends WebMvcConfigurerAdapter { + + public WebConfig() { + super(); + } + + // + + @Override + public void configureMessageConverters( + final List> messageConverters) { + final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); + builder.indentOutput(true).dateFormat( + new SimpleDateFormat("dd-MM-yyyy hh:mm")); + messageConverters.add(new MappingJackson2HttpMessageConverter(builder + .build())); + // messageConverters.add(new + // MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); + + // messageConverters.add(createXmlHttpMessageConverter()); + // messageConverters.add(new MappingJackson2HttpMessageConverter()); + + messageConverters.add(new ProtobufHttpMessageConverter()); + messageConverters.add(new KryoHttpMessageConverter()); + super.configureMessageConverters(messageConverters); + } + + private HttpMessageConverter createXmlHttpMessageConverter() { + final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); + + final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); + xmlConverter.setMarshaller(xstreamMarshaller); + xmlConverter.setUnmarshaller(xstreamMarshaller); + + return xmlConverter; + } + +} diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java b/spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java new file mode 100644 index 0000000000..6af54c379a --- /dev/null +++ b/spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java @@ -0,0 +1,60 @@ +package org.baeldung.config.converter; + +import java.io.IOException; + +import org.baeldung.web.dto.Foo; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.MediaType; +import org.springframework.http.converter.AbstractHttpMessageConverter; + +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; + +/** + * An {@code HttpMessageConverter} that can read and write Kryo messages. + */ +public class KryoHttpMessageConverter extends + AbstractHttpMessageConverter { + + public static final MediaType KRYO = new MediaType("application", "x-kryo"); + + private static final ThreadLocal kryoThreadLocal = new ThreadLocal() { + @Override + protected Kryo initialValue() { + final Kryo kryo = new Kryo(); + kryo.register(Foo.class, 1); + return kryo; + } + }; + + public KryoHttpMessageConverter() { + super(KRYO); + } + + @Override + protected boolean supports(final Class clazz) { + return Object.class.isAssignableFrom(clazz); + } + + @Override + protected Object readInternal(final Class clazz, + final HttpInputMessage inputMessage) throws IOException { + final Input input = new Input(inputMessage.getBody()); + return kryoThreadLocal.get().readClassAndObject(input); + } + + @Override + protected void writeInternal(final Object object, + final HttpOutputMessage outputMessage) throws IOException { + final Output output = new Output(outputMessage.getBody()); + kryoThreadLocal.get().writeClassAndObject(output, object); + output.flush(); + } + + @Override + protected MediaType getDefaultContentType(final Object object) { + return KRYO; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java b/spring-rest-simple/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java rename to spring-rest-simple/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java b/spring-rest-simple/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java rename to spring-rest-simple/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java new file mode 100644 index 0000000000..6d27ecece4 --- /dev/null +++ b/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java @@ -0,0 +1,39 @@ +package org.baeldung.web.controller; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +import org.baeldung.web.dto.Foo; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +@Controller +public class FooController { + + public FooController() { + super(); + } + + // API - read + + @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") + @ResponseBody + public Foo findById(@PathVariable final long id) { + return new Foo(id, randomAlphabetic(4)); + } + + // API - write + + @RequestMapping(method = RequestMethod.PUT, value = "/foos/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo updateFoo(@PathVariable("id") final String id, + @RequestBody final Foo foo) { + return foo; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java b/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java rename to spring-rest-simple/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/status/ExampleController.java b/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ExampleController.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/web/controller/status/ExampleController.java rename to spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ExampleController.java diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java b/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java rename to spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Bazz.java b/spring-rest-simple/src/main/java/org/baeldung/web/dto/Bazz.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/web/dto/Bazz.java rename to spring-rest-simple/src/main/java/org/baeldung/web/dto/Bazz.java diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java b/spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java new file mode 100644 index 0000000000..240b368b50 --- /dev/null +++ b/spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java @@ -0,0 +1,45 @@ +package org.baeldung.web.dto; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("Foo") +public class Foo { + private long id; + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + public Foo(final long id, final String name) { + super(); + + this.id = id; + this.name = name; + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + +} \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java b/spring-rest-simple/src/main/java/org/baeldung/web/dto/FooProtos.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java rename to spring-rest-simple/src/main/java/org/baeldung/web/dto/FooProtos.java diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java b/spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java new file mode 100644 index 0000000000..b2137aeeff --- /dev/null +++ b/spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java @@ -0,0 +1,36 @@ +package org.baeldung.web.util; + +import javax.servlet.http.HttpServletResponse; + +/** + * Provides some constants and utility methods to build a Link Header to be stored in the {@link HttpServletResponse} object + */ +public final class LinkUtil { + + public static final String REL_COLLECTION = "collection"; + public static final String REL_NEXT = "next"; + public static final String REL_PREV = "prev"; + public static final String REL_FIRST = "first"; + public static final String REL_LAST = "last"; + + private LinkUtil() { + throw new AssertionError(); + } + + // + + /** + * Creates a Link Header to be stored in the {@link HttpServletResponse} to provide Discoverability features to the user + * + * @param uri + * the base uri + * @param rel + * the relative path + * + * @return the complete url + */ + public static String createLinkHeader(final String uri, final String rel) { + return "<" + uri + ">; rel=\"" + rel + "\""; + } + +} diff --git a/spring-rest-simple/src/main/resources/application.properties b/spring-rest-simple/src/main/resources/application.properties new file mode 100644 index 0000000000..300589f561 --- /dev/null +++ b/spring-rest-simple/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port= 8082 +server.context-path=/spring-rest \ No newline at end of file diff --git a/spring-rest-simple/src/main/resources/logback.xml b/spring-rest-simple/src/main/resources/logback.xml new file mode 100644 index 0000000000..ec0dc2469a --- /dev/null +++ b/spring-rest-simple/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-rest-simple/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest-simple/src/main/webapp/WEB-INF/api-servlet.xml new file mode 100644 index 0000000000..0f80990c16 --- /dev/null +++ b/spring-rest-simple/src/main/webapp/WEB-INF/api-servlet.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + /WEB-INF/spring-views.xml + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-rest-simple/src/main/webapp/WEB-INF/company.html b/spring-rest-simple/src/main/webapp/WEB-INF/company.html new file mode 100644 index 0000000000..d2072bfd3c --- /dev/null +++ b/spring-rest-simple/src/main/webapp/WEB-INF/company.html @@ -0,0 +1,44 @@ + + + + + Company Data + + + + + + + +
+ + + \ No newline at end of file diff --git a/spring-rest-simple/src/main/webapp/WEB-INF/spring-views.xml b/spring-rest-simple/src/main/webapp/WEB-INF/spring-views.xml new file mode 100644 index 0000000000..2944828d6d --- /dev/null +++ b/spring-rest-simple/src/main/webapp/WEB-INF/spring-views.xml @@ -0,0 +1,10 @@ + + + + + + + \ No newline at end of file diff --git a/spring-rest-simple/src/main/webapp/WEB-INF/web.xml b/spring-rest-simple/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..a439de8a05 --- /dev/null +++ b/spring-rest-simple/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,41 @@ + + + + Spring MVC Application + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + org.baeldung.config + + + + org.springframework.web.context.ContextLoaderListener + + + + + api + org.springframework.web.servlet.DispatcherServlet + 1 + + + api + / + + + + + + + diff --git a/spring-rest-simple/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java new file mode 100644 index 0000000000..eaf55ee81b --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -0,0 +1,216 @@ +package org.baeldung.client; + +import static org.apache.commons.codec.binary.Base64.encodeBase64; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URI; +import java.util.Arrays; +import java.util.Set; + +import org.baeldung.web.dto.Foo; +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RequestCallback; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Charsets; + +public class RestTemplateBasicLiveTest { + + private RestTemplate restTemplate; + + private static final String fooResourceUrl = String.format("http://localhost:%d/spring-rest/myfoos", 8082); + + @Before + public void beforeTest() { + restTemplate = new RestTemplate(); + } + + // GET + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { + final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException { + final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + + final ObjectMapper mapper = new ObjectMapper(); + final JsonNode root = mapper.readTree(response.getBody()); + final JsonNode name = root.path("name"); + assertThat(name.asText(), notNullValue()); + } + + @Test + public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException { + final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); + + assertThat(foo.getName(), notNullValue()); + assertThat(foo.getId(), is(1L)); + } + + // HEAD, OPTIONS + + @Test + public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { + final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); + + assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); + } + + // POST + + @Test + public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() { + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class); + assertThat(foo, notNullValue()); + assertThat(foo.getName(), is("bar")); + } + + @Test + public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() { + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final URI location = restTemplate.postForLocation(fooResourceUrl, request); + assertThat(location, notNullValue()); + } + + @Test + public void givenFooService_whenPostResource_thenResourceIsCreated() { + final RestTemplate template = new RestTemplate(); + + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + + final ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + final Foo foo = response.getBody(); + assertThat(foo, notNullValue()); + assertThat(foo.getName(), is("bar")); + } + + @Test + public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { + final Set optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl); + final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD }; + + assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); + } + + // PUT + + @Test + public void givenFooService_whenPutExistingEntity_thenItIsUpdated() { + final RestTemplate template = new RestTemplate(); + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create Resource + final ResponseEntity createResponse = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + + // Update Resource + final Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(createResponse.getBody().getId()); + final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody().getId(); + final HttpEntity requestUpdate = new HttpEntity<>(updatedInstance, headers); + template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class); + + // Check that Resource was updated + final ResponseEntity updateResponse = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = updateResponse.getBody(); + assertThat(foo.getName(), is(updatedInstance.getName())); + } + + @Test + public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() { + final RestTemplate template = new RestTemplate(); + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create entity + ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + + // Update entity + final Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(response.getBody().getId()); + final String resourceUrl = fooResourceUrl + '/' + response.getBody().getId(); + template.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); + + // Check that entity was updated + response = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = response.getBody(); + assertThat(foo.getName(), is(updatedInstance.getName())); + } + + // DELETE + + @Test + public void givenFooService_whenCallDelete_thenEntityIsRemoved() { + final Foo foo = new Foo("remove me"); + final ResponseEntity response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + + final String entityUrl = fooResourceUrl + "/" + response.getBody().getId(); + restTemplate.delete(entityUrl); + try { + restTemplate.getForEntity(entityUrl, Foo.class); + fail(); + } catch (final HttpClientErrorException ex) { + assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND)); + } + } + + // + + private HttpHeaders prepareBasicAuthHeaders() { + final HttpHeaders headers = new HttpHeaders(); + final String encodedLogPass = getBase64EncodedLogPass(); + headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass); + return headers; + } + + private String getBase64EncodedLogPass() { + final String logPass = "user1:user1Pass"; + final byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII)); + return new String(authHeaderBytes, Charsets.US_ASCII); + } + + private RequestCallback requestCallback(final Foo updatedInstance) { + return clientHttpRequest -> { + final ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(clientHttpRequest.getBody(), updatedInstance); + clientHttpRequest.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass()); + }; + } + + // Simply setting restTemplate timeout using ClientHttpRequestFactory + + ClientHttpRequestFactory getSimpleClientHttpRequestFactory() { + final int timeout = 5; + final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); + clientHttpRequestFactory.setConnectTimeout(timeout * 1000); + return clientHttpRequestFactory; + } +} diff --git a/spring-rest-simple/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java new file mode 100644 index 0000000000..18fc73d1b4 --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java @@ -0,0 +1,117 @@ +package org.baeldung.client; + +import okhttp3.Request; +import okhttp3.RequestBody; +import org.junit.Before; +import org.junit.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertTrue; + +public class TestRestTemplateBasicLiveTest { + + private RestTemplate restTemplate; + + private static final String FOO_RESOURCE_URL = "http://localhost:" + 8082 + "/spring-rest/myfoos"; + private static final String URL_SECURED_BY_AUTHENTICATION = "http://httpbin.org/basic-auth/user/passwd"; + private static final String BASE_URL = "http://localhost:" + 8082 + "/spring-rest"; + + @Before + public void beforeTest() { + restTemplate = new RestTemplate(); + } + + // GET + @Test + public void givenTestRestTemplate_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenRestTemplateBuilderWrapper_whenSendGetForEntity_thenStatusOk() { + RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); + restTemplateBuilder.build(); + TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, "user", "passwd"); + ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, + String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenTestRestTemplateWithCredentials_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); + ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, + String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenTestRestTemplateWithBasicAuth_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + ResponseEntity response = testRestTemplate.withBasicAuth("user", "passwd"). + getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenTestRestTemplateWithCredentialsAndEnabledCookies_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd", TestRestTemplate. + HttpClientOption.ENABLE_COOKIES); + ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, + String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + // HEAD + @Test + public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeaders() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + final HttpHeaders httpHeaders = testRestTemplate.headForHeaders(FOO_RESOURCE_URL); + assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); + } + + // POST + @Test + public void givenService_whenPostForObject_thenCreatedObjectIsReturned() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); + final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), + "{\"id\":1,\"name\":\"Jim\"}"); + final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); + testRestTemplate.postForObject(URL_SECURED_BY_AUTHENTICATION, request, String.class); + } + + // PUT + @Test + public void givenService_whenPutForObject_thenCreatedObjectIsReturned() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); + final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), + "{\"id\":1,\"name\":\"Jim\"}"); + final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); + testRestTemplate.put(URL_SECURED_BY_AUTHENTICATION, request, String.class); + } + +} diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java b/spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java new file mode 100644 index 0000000000..66ffe4947d --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java @@ -0,0 +1,11 @@ +package org.baeldung.web.controller.mediatypes; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + + +@Configuration +@ComponentScan({ "org.baeldung.web" }) +public class TestConfig { + +} diff --git a/spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerIntegrationTest.java b/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java similarity index 88% rename from spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerIntegrationTest.java rename to spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java index 7bd16a3e97..266ee1938b 100644 --- a/spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerIntegrationTest.java +++ b/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java @@ -1,6 +1,15 @@ package org.baeldung.web.test; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.baeldung.config.WebConfig; import org.junit.Before; import org.junit.Test; @@ -13,17 +22,11 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration -public class BazzNewMappingsExampleControllerIntegrationTest { +public class BazzNewMappingsExampleIntegrationTest { private MockMvc mockMvc; diff --git a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java b/spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java similarity index 98% rename from spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java rename to spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java index 347b683b2d..bf0bbc67dc 100644 --- a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java +++ b/spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java @@ -3,9 +3,9 @@ package org.baeldung.web.test; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import com.jayway.restassured.RestAssured; import org.junit.Test; -import io.restassured.RestAssured; public class RequestMappingLiveTest { private static String BASE_URI = "http://localhost:8082/spring-rest/ex/"; diff --git a/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java b/spring-rest-simple/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java similarity index 100% rename from spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java rename to spring-rest-simple/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java b/spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java new file mode 100644 index 0000000000..bb3919eacc --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java @@ -0,0 +1,69 @@ +package org.baeldung.web.util; + +import java.util.List; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; + +public final class HTTPLinkHeaderUtil { + + private HTTPLinkHeaderUtil() { + throw new AssertionError(); + } + + // + + /** + * ex.
+ * https://api.github.com/users/steveklabnik/gists?page=2>; rel="next", ; rel="last" + */ + public static List extractAllURIs(final String linkHeader) { + Preconditions.checkNotNull(linkHeader); + + final List linkHeaders = Lists.newArrayList(); + final String[] links = linkHeader.split(", "); + for (final String link : links) { + final int positionOfSeparator = link.indexOf(';'); + linkHeaders.add(link.substring(1, positionOfSeparator - 1)); + } + + return linkHeaders; + } + + public static String extractURIByRel(final String linkHeader, final String rel) { + if (linkHeader == null) { + return null; + } + + String uriWithSpecifiedRel = null; + final String[] links = linkHeader.split(", "); + String linkRelation = null; + for (final String link : links) { + final int positionOfSeparator = link.indexOf(';'); + linkRelation = link.substring(positionOfSeparator + 1, link.length()).trim(); + if (extractTypeOfRelation(linkRelation).equals(rel)) { + uriWithSpecifiedRel = link.substring(1, positionOfSeparator - 1); + break; + } + } + + return uriWithSpecifiedRel; + } + + static Object extractTypeOfRelation(final String linkRelation) { + final int positionOfEquals = linkRelation.indexOf('='); + return linkRelation.substring(positionOfEquals + 2, linkRelation.length() - 1).trim(); + } + + /** + * ex.
+ * https://api.github.com/users/steveklabnik/gists?page=2>; rel="next" + */ + public static String extractSingleURI(final String linkHeader) { + Preconditions.checkNotNull(linkHeader); + final int positionOfSeparator = linkHeader.indexOf(';'); + + return linkHeader.substring(1, positionOfSeparator - 1); + } + +} diff --git a/spring-rest-simple/src/test/resources/.gitignore b/spring-rest-simple/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-rest-simple/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-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java index f40c9477d4..a019a5a9bb 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java @@ -1,6 +1,5 @@ package org.baeldung.config; -import org.baeldung.config.converter.KryoHttpMessageConverter; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; @@ -40,7 +39,6 @@ public class WebConfig extends WebMvcConfigurerAdapter { // messageConverters.add(new MappingJackson2HttpMessageConverter()); messageConverters.add(new ProtobufHttpMessageConverter()); - messageConverters.add(new KryoHttpMessageConverter()); super.configureMessageConverters(messageConverters); } diff --git a/spring-rest/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java b/spring-rest/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java deleted file mode 100644 index 7e63a3ba9e..0000000000 --- a/spring-rest/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.baeldung.config.converter; - -import java.io.IOException; - -import org.baeldung.web.dto.Foo; -import org.springframework.http.HttpInputMessage; -import org.springframework.http.HttpOutputMessage; -import org.springframework.http.MediaType; -import org.springframework.http.converter.AbstractHttpMessageConverter; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.io.Input; -import com.esotericsoftware.kryo.io.Output; - -/** - * An {@code HttpMessageConverter} that can read and write Kryo messages. - */ -public class KryoHttpMessageConverter extends AbstractHttpMessageConverter { - - public static final MediaType KRYO = new MediaType("application", "x-kryo"); - - private static final ThreadLocal kryoThreadLocal = new ThreadLocal() { - @Override - protected Kryo initialValue() { - final Kryo kryo = new Kryo(); - kryo.register(Foo.class, 1); - return kryo; - } - }; - - public KryoHttpMessageConverter() { - super(KRYO); - } - - @Override - protected boolean supports(final Class clazz) { - return Object.class.isAssignableFrom(clazz); - } - - @Override - protected Object readInternal(final Class clazz, final HttpInputMessage inputMessage) throws IOException { - final Input input = new Input(inputMessage.getBody()); - return kryoThreadLocal.get().readClassAndObject(input); - } - - @Override - protected void writeInternal(final Object object, final HttpOutputMessage outputMessage) throws IOException { - final Output output = new Output(outputMessage.getBody()); - kryoThreadLocal.get().writeClassAndObject(output, object); - output.flush(); - } - - @Override - protected MediaType getDefaultContentType(final Object object) { - return KRYO; - } -} diff --git a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java b/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java index 5556d85f65..4ed5c21b83 100644 --- a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java +++ b/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java @@ -1,12 +1,11 @@ package org.baeldung.repository; -import org.baeldung.web.dto.HeavyResource; -import org.baeldung.web.dto.HeavyResourceAddressOnly; -import org.baeldung.web.dto.HeavyResourceAddressPartialUpdate; - import java.util.Map; -public class HeavyResourceRepository { +import org.baeldung.web.dto.HeavyResource; +import org.baeldung.web.dto.HeavyResourceAddressOnly; + +public class HeavyResourceRepository { public void save(HeavyResource heavyResource) { } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java deleted file mode 100644 index 21ba3c6d13..0000000000 --- a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.baeldung.web.controller; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; - -import org.baeldung.web.dto.Foo; -import org.baeldung.web.dto.FooProtos; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; - -@Controller -public class FooController { - - public FooController() { - super(); - } - - // API - read - - @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") - @ResponseBody - public Foo findById(@PathVariable final long id) { - return new Foo(id, randomAlphabetic(4)); - } - - // API - write - - @RequestMapping(method = RequestMethod.PUT, value = "/foos/{id}") - @ResponseStatus(HttpStatus.OK) - @ResponseBody - public Foo updateFoo(@PathVariable("id") final String id, @RequestBody final Foo foo) { - return foo; - } - - @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}", produces = { "application/x-protobuf" }) - @ResponseBody - public FooProtos.Foo findProtoById(@PathVariable final long id) { - return FooProtos.Foo.newBuilder().setId(1).setName("Foo Name").build(); - } -} diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java index 1dae559371..478e4948dc 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java @@ -1,6 +1,11 @@ package org.baeldung.web.controller; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.HashMap; + import org.baeldung.config.WebConfig; import org.baeldung.web.dto.HeavyResource; import org.baeldung.web.dto.HeavyResourceAddressOnly; @@ -16,11 +21,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import java.util.HashMap; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class)