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
This commit is contained in:
committed by
GitHub
parent
4b2e7a5e85
commit
29e3437545
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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<HttpMessageConverter<?>> 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<Object> createXmlHttpMessageConverter() {
|
||||
final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
|
||||
|
||||
final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
|
||||
xmlConverter.setMarshaller(xstreamMarshaller);
|
||||
xmlConverter.setUnmarshaller(xstreamMarshaller);
|
||||
|
||||
return xmlConverter;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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<Object> {
|
||||
|
||||
public static final MediaType KRYO = new MediaType("application", "x-kryo");
|
||||
|
||||
private static final ThreadLocal<Kryo> kryoThreadLocal = new ThreadLocal<Kryo>() {
|
||||
@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<? extends Object> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package org.baeldung.web.controller;
|
||||
|
||||
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.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/ex")
|
||||
public class BarMappingExamplesController {
|
||||
|
||||
public BarMappingExamplesController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
// with @RequestParam
|
||||
|
||||
@RequestMapping(value = "/bars")
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithRequestParam(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/bars", params = "id")
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/bars", params = { "id", "second" })
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
// with @PathVariable
|
||||
|
||||
@RequestMapping(value = "/bars/{numericId:[\\d]+}")
|
||||
@ResponseBody
|
||||
public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) {
|
||||
return "Get a specific Bar with id=" + numericId;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package org.baeldung.web.controller;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.web.dto.Bazz;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/bazz")
|
||||
public class BazzNewMappingsExampleController {
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<?> getBazzs() throws JsonProcessingException{
|
||||
List<Bazz> data = Arrays.asList(
|
||||
new Bazz("1", "Bazz1"),
|
||||
new Bazz("2", "Bazz2"),
|
||||
new Bazz("3", "Bazz3"),
|
||||
new Bazz("4", "Bazz4"));
|
||||
return new ResponseEntity<>(data, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<?> getBazz(@PathVariable String id){
|
||||
return new ResponseEntity<>(new Bazz(id, "Bazz"+id), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<?> newBazz(@RequestParam("name") String name){
|
||||
return new ResponseEntity<>(new Bazz("5", name), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<?> updateBazz(@PathVariable String id,
|
||||
@RequestParam("name") String name){
|
||||
return new ResponseEntity<>(new Bazz(id, name), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<?> deleteBazz(@PathVariable String id){
|
||||
return new ResponseEntity<>(new Bazz(id), HttpStatus.OK);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package org.baeldung.web.controller;
|
||||
|
||||
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
|
||||
@RequestMapping(value = "/ex")
|
||||
public class FooMappingExamplesController {
|
||||
|
||||
public FooMappingExamplesController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
// mapping examples
|
||||
|
||||
@RequestMapping(value = "/foos")
|
||||
@ResponseBody
|
||||
public String getFoosBySimplePath() {
|
||||
return "Simple Get some Foos";
|
||||
}
|
||||
|
||||
// with @PathVariable
|
||||
|
||||
@RequestMapping(value = "/foos/{id}")
|
||||
@ResponseBody
|
||||
public String getFoosBySimplePathWithPathVariable(@PathVariable final long id) {
|
||||
return "Get a specific Foo with id=" + id;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foos/{fooid}/bar/{barid}")
|
||||
@ResponseBody
|
||||
public String getFoosBySimplePathWithPathVariables(@PathVariable final long fooid, @PathVariable final long barid) {
|
||||
return "Get a specific Bar with id=" + barid + " from a Foo with id=" + fooid;
|
||||
}
|
||||
|
||||
// other HTTP verbs
|
||||
|
||||
@RequestMapping(value = "/foos", method = RequestMethod.POST)
|
||||
@ResponseBody
|
||||
public String postFoos() {
|
||||
return "Post some Foos";
|
||||
}
|
||||
|
||||
// with headers
|
||||
|
||||
@RequestMapping(value = "/foos", headers = "key=val")
|
||||
@ResponseBody
|
||||
public String getFoosWithHeader() {
|
||||
return "Get some Foos with Header";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foos", headers = { "key1=val1", "key2=val2" })
|
||||
@ResponseBody
|
||||
public String getFoosWithHeaders() {
|
||||
return "Get some Foos with Header";
|
||||
}
|
||||
|
||||
// @RequestMapping(value = "/foos", method = RequestMethod.GET, headers = "Accept=application/json")
|
||||
// @ResponseBody
|
||||
// public String getFoosAsJsonFromBrowser() {
|
||||
// return "Get some Foos with Header Old";
|
||||
// }
|
||||
|
||||
@RequestMapping(value = "/foos", produces = { "application/json", "application/xml" })
|
||||
@ResponseBody
|
||||
public String getFoosAsJsonFromREST() {
|
||||
return "Get some Foos with Header New";
|
||||
}
|
||||
|
||||
// advanced - multiple mappings
|
||||
|
||||
@RequestMapping(value = { "/advanced/bars", "/advanced/foos" })
|
||||
@ResponseBody
|
||||
public String getFoosOrBarsByPath() {
|
||||
return "Advanced - Get some Foos or Bars";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "*")
|
||||
@ResponseBody
|
||||
public String getFallback() {
|
||||
return "Fallback for GET Requests";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "*", method = { RequestMethod.GET, RequestMethod.POST })
|
||||
@ResponseBody
|
||||
public String allFallback() {
|
||||
return "Fallback for All Requests";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST })
|
||||
@ResponseBody
|
||||
public String putAndPostFoos() {
|
||||
return "Advanced - PUT and POST within single method";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.baeldung.web.controller.status;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
public class ExampleController {
|
||||
|
||||
@RequestMapping(value = "/controller", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public ResponseEntity sendViaResponseEntity() {
|
||||
return new ResponseEntity(HttpStatus.NOT_ACCEPTABLE);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/exception", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public ResponseEntity sendViaException() {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package org.baeldung.web.controller.status;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "To show an example of a custom message")
|
||||
public class ForbiddenException extends RuntimeException {
|
||||
private static final long serialVersionUID = 6826605655586311552L;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.baeldung.web.dto;
|
||||
|
||||
public class Bazz {
|
||||
|
||||
|
||||
public String id;
|
||||
public String name;
|
||||
|
||||
public Bazz(String id){
|
||||
this.id = id;
|
||||
}
|
||||
public Bazz(String id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Bazz [id=" + id + ", name=" + name + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,597 @@
|
||||
// Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
// source: FooProtos.proto
|
||||
|
||||
package org.baeldung.web.dto;
|
||||
|
||||
public final class FooProtos {
|
||||
private FooProtos() {
|
||||
}
|
||||
|
||||
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
|
||||
}
|
||||
|
||||
public interface FooOrBuilder extends
|
||||
// @@protoc_insertion_point(interface_extends:baeldung.Foo)
|
||||
com.google.protobuf.MessageOrBuilder {
|
||||
|
||||
/**
|
||||
* <code>required int64 id = 1;</code>
|
||||
*/
|
||||
boolean hasId();
|
||||
|
||||
/**
|
||||
* <code>required int64 id = 1;</code>
|
||||
*/
|
||||
long getId();
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
boolean hasName();
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
java.lang.String getName();
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
com.google.protobuf.ByteString getNameBytes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Protobuf type {@code baeldung.Foo}
|
||||
*/
|
||||
public static final class Foo extends com.google.protobuf.GeneratedMessage implements
|
||||
// @@protoc_insertion_point(message_implements:baeldung.Foo)
|
||||
FooOrBuilder {
|
||||
// Use Foo.newBuilder() to construct.
|
||||
private Foo(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
|
||||
super(builder);
|
||||
this.unknownFields = builder.getUnknownFields();
|
||||
}
|
||||
|
||||
private Foo(boolean noInit) {
|
||||
this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance();
|
||||
}
|
||||
|
||||
private static final Foo defaultInstance;
|
||||
|
||||
public static Foo getDefaultInstance() {
|
||||
return defaultInstance;
|
||||
}
|
||||
|
||||
public Foo getDefaultInstanceForType() {
|
||||
return defaultInstance;
|
||||
}
|
||||
|
||||
private final com.google.protobuf.UnknownFieldSet unknownFields;
|
||||
|
||||
@java.lang.Override
|
||||
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
|
||||
return this.unknownFields;
|
||||
}
|
||||
|
||||
private Foo(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {
|
||||
initFields();
|
||||
int mutable_bitField0_ = 0;
|
||||
com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder();
|
||||
try {
|
||||
boolean done = false;
|
||||
while (!done) {
|
||||
int tag = input.readTag();
|
||||
switch (tag) {
|
||||
case 0:
|
||||
done = true;
|
||||
break;
|
||||
default: {
|
||||
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
|
||||
done = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 8: {
|
||||
bitField0_ |= 0x00000001;
|
||||
id_ = input.readInt64();
|
||||
break;
|
||||
}
|
||||
case 18: {
|
||||
com.google.protobuf.ByteString bs = input.readBytes();
|
||||
bitField0_ |= 0x00000002;
|
||||
name_ = bs;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
|
||||
throw e.setUnfinishedMessage(this);
|
||||
} catch (java.io.IOException e) {
|
||||
throw new com.google.protobuf.InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(this);
|
||||
} finally {
|
||||
this.unknownFields = unknownFields.build();
|
||||
makeExtensionsImmutable();
|
||||
}
|
||||
}
|
||||
|
||||
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
|
||||
return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor;
|
||||
}
|
||||
|
||||
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() {
|
||||
return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class);
|
||||
}
|
||||
|
||||
public static com.google.protobuf.Parser<Foo> PARSER = new com.google.protobuf.AbstractParser<Foo>() {
|
||||
public Foo parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {
|
||||
return new Foo(input, extensionRegistry);
|
||||
}
|
||||
};
|
||||
|
||||
@java.lang.Override
|
||||
public com.google.protobuf.Parser<Foo> getParserForType() {
|
||||
return PARSER;
|
||||
}
|
||||
|
||||
private int bitField0_;
|
||||
public static final int ID_FIELD_NUMBER = 1;
|
||||
private long id_;
|
||||
|
||||
/**
|
||||
* <code>required int64 id = 1;</code>
|
||||
*/
|
||||
public boolean hasId() {
|
||||
return ((bitField0_ & 0x00000001) == 0x00000001);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>required int64 id = 1;</code>
|
||||
*/
|
||||
public long getId() {
|
||||
return id_;
|
||||
}
|
||||
|
||||
public static final int NAME_FIELD_NUMBER = 2;
|
||||
private java.lang.Object name_;
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
public boolean hasName() {
|
||||
return ((bitField0_ & 0x00000002) == 0x00000002);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
public java.lang.String getName() {
|
||||
java.lang.Object ref = name_;
|
||||
if (ref instanceof java.lang.String) {
|
||||
return (java.lang.String) ref;
|
||||
} else {
|
||||
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
|
||||
java.lang.String s = bs.toStringUtf8();
|
||||
if (bs.isValidUtf8()) {
|
||||
name_ = s;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
public com.google.protobuf.ByteString getNameBytes() {
|
||||
java.lang.Object ref = name_;
|
||||
if (ref instanceof java.lang.String) {
|
||||
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
|
||||
name_ = b;
|
||||
return b;
|
||||
} else {
|
||||
return (com.google.protobuf.ByteString) ref;
|
||||
}
|
||||
}
|
||||
|
||||
private void initFields() {
|
||||
id_ = 0L;
|
||||
name_ = "";
|
||||
}
|
||||
|
||||
private byte memoizedIsInitialized = -1;
|
||||
|
||||
public final boolean isInitialized() {
|
||||
byte isInitialized = memoizedIsInitialized;
|
||||
if (isInitialized == 1)
|
||||
return true;
|
||||
if (isInitialized == 0)
|
||||
return false;
|
||||
|
||||
if (!hasId()) {
|
||||
memoizedIsInitialized = 0;
|
||||
return false;
|
||||
}
|
||||
if (!hasName()) {
|
||||
memoizedIsInitialized = 0;
|
||||
return false;
|
||||
}
|
||||
memoizedIsInitialized = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
|
||||
getSerializedSize();
|
||||
if (((bitField0_ & 0x00000001) == 0x00000001)) {
|
||||
output.writeInt64(1, id_);
|
||||
}
|
||||
if (((bitField0_ & 0x00000002) == 0x00000002)) {
|
||||
output.writeBytes(2, getNameBytes());
|
||||
}
|
||||
getUnknownFields().writeTo(output);
|
||||
}
|
||||
|
||||
private int memoizedSerializedSize = -1;
|
||||
|
||||
public int getSerializedSize() {
|
||||
int size = memoizedSerializedSize;
|
||||
if (size != -1)
|
||||
return size;
|
||||
|
||||
size = 0;
|
||||
if (((bitField0_ & 0x00000001) == 0x00000001)) {
|
||||
size += com.google.protobuf.CodedOutputStream.computeInt64Size(1, id_);
|
||||
}
|
||||
if (((bitField0_ & 0x00000002) == 0x00000002)) {
|
||||
size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, getNameBytes());
|
||||
}
|
||||
size += getUnknownFields().getSerializedSize();
|
||||
memoizedSerializedSize = size;
|
||||
return size;
|
||||
}
|
||||
|
||||
private static final long serialVersionUID = 0L;
|
||||
|
||||
@java.lang.Override
|
||||
protected java.lang.Object writeReplace() throws java.io.ObjectStreamException {
|
||||
return super.writeReplace();
|
||||
}
|
||||
|
||||
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException {
|
||||
return PARSER.parseFrom(data);
|
||||
}
|
||||
|
||||
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {
|
||||
return PARSER.parseFrom(data, extensionRegistry);
|
||||
}
|
||||
|
||||
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
|
||||
return PARSER.parseFrom(data);
|
||||
}
|
||||
|
||||
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {
|
||||
return PARSER.parseFrom(data, extensionRegistry);
|
||||
}
|
||||
|
||||
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException {
|
||||
return PARSER.parseFrom(input);
|
||||
}
|
||||
|
||||
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
|
||||
return PARSER.parseFrom(input, extensionRegistry);
|
||||
}
|
||||
|
||||
public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
|
||||
return PARSER.parseDelimitedFrom(input);
|
||||
}
|
||||
|
||||
public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
|
||||
return PARSER.parseDelimitedFrom(input, extensionRegistry);
|
||||
}
|
||||
|
||||
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
|
||||
return PARSER.parseFrom(input);
|
||||
}
|
||||
|
||||
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
|
||||
return PARSER.parseFrom(input, extensionRegistry);
|
||||
}
|
||||
|
||||
public static Builder newBuilder() {
|
||||
return Builder.create();
|
||||
}
|
||||
|
||||
public Builder newBuilderForType() {
|
||||
return newBuilder();
|
||||
}
|
||||
|
||||
public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) {
|
||||
return newBuilder().mergeFrom(prototype);
|
||||
}
|
||||
|
||||
public Builder toBuilder() {
|
||||
return newBuilder(this);
|
||||
}
|
||||
|
||||
@java.lang.Override
|
||||
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) {
|
||||
Builder builder = new Builder(parent);
|
||||
return builder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Protobuf type {@code baeldung.Foo}
|
||||
*/
|
||||
public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements
|
||||
// @@protoc_insertion_point(builder_implements:baeldung.Foo)
|
||||
org.baeldung.web.dto.FooProtos.FooOrBuilder {
|
||||
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
|
||||
return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor;
|
||||
}
|
||||
|
||||
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() {
|
||||
return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class);
|
||||
}
|
||||
|
||||
// Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder()
|
||||
private Builder() {
|
||||
maybeForceBuilderInitialization();
|
||||
}
|
||||
|
||||
private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) {
|
||||
super(parent);
|
||||
maybeForceBuilderInitialization();
|
||||
}
|
||||
|
||||
private void maybeForceBuilderInitialization() {
|
||||
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
|
||||
}
|
||||
}
|
||||
|
||||
private static Builder create() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
public Builder clear() {
|
||||
super.clear();
|
||||
id_ = 0L;
|
||||
bitField0_ = (bitField0_ & ~0x00000001);
|
||||
name_ = "";
|
||||
bitField0_ = (bitField0_ & ~0x00000002);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder clone() {
|
||||
return create().mergeFrom(buildPartial());
|
||||
}
|
||||
|
||||
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
|
||||
return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor;
|
||||
}
|
||||
|
||||
public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() {
|
||||
return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance();
|
||||
}
|
||||
|
||||
public org.baeldung.web.dto.FooProtos.Foo build() {
|
||||
org.baeldung.web.dto.FooProtos.Foo result = buildPartial();
|
||||
if (!result.isInitialized()) {
|
||||
throw newUninitializedMessageException(result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public org.baeldung.web.dto.FooProtos.Foo buildPartial() {
|
||||
org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this);
|
||||
int from_bitField0_ = bitField0_;
|
||||
int to_bitField0_ = 0;
|
||||
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
|
||||
to_bitField0_ |= 0x00000001;
|
||||
}
|
||||
result.id_ = id_;
|
||||
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
|
||||
to_bitField0_ |= 0x00000002;
|
||||
}
|
||||
result.name_ = name_;
|
||||
result.bitField0_ = to_bitField0_;
|
||||
onBuilt();
|
||||
return result;
|
||||
}
|
||||
|
||||
public Builder mergeFrom(com.google.protobuf.Message other) {
|
||||
if (other instanceof org.baeldung.web.dto.FooProtos.Foo) {
|
||||
return mergeFrom((org.baeldung.web.dto.FooProtos.Foo) other);
|
||||
} else {
|
||||
super.mergeFrom(other);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) {
|
||||
if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance())
|
||||
return this;
|
||||
if (other.hasId()) {
|
||||
setId(other.getId());
|
||||
}
|
||||
if (other.hasName()) {
|
||||
bitField0_ |= 0x00000002;
|
||||
name_ = other.name_;
|
||||
onChanged();
|
||||
}
|
||||
this.mergeUnknownFields(other.getUnknownFields());
|
||||
return this;
|
||||
}
|
||||
|
||||
public final boolean isInitialized() {
|
||||
if (!hasId()) {
|
||||
|
||||
return false;
|
||||
}
|
||||
if (!hasName()) {
|
||||
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
|
||||
org.baeldung.web.dto.FooProtos.Foo parsedMessage = null;
|
||||
try {
|
||||
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
|
||||
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
|
||||
parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage();
|
||||
throw e;
|
||||
} finally {
|
||||
if (parsedMessage != null) {
|
||||
mergeFrom(parsedMessage);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
private int bitField0_;
|
||||
|
||||
private long id_;
|
||||
|
||||
/**
|
||||
* <code>required int64 id = 1;</code>
|
||||
*/
|
||||
public boolean hasId() {
|
||||
return ((bitField0_ & 0x00000001) == 0x00000001);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>required int64 id = 1;</code>
|
||||
*/
|
||||
public long getId() {
|
||||
return id_;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>required int64 id = 1;</code>
|
||||
*/
|
||||
public Builder setId(long value) {
|
||||
bitField0_ |= 0x00000001;
|
||||
id_ = value;
|
||||
onChanged();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>required int64 id = 1;</code>
|
||||
*/
|
||||
public Builder clearId() {
|
||||
bitField0_ = (bitField0_ & ~0x00000001);
|
||||
id_ = 0L;
|
||||
onChanged();
|
||||
return this;
|
||||
}
|
||||
|
||||
private java.lang.Object name_ = "";
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
public boolean hasName() {
|
||||
return ((bitField0_ & 0x00000002) == 0x00000002);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
public java.lang.String getName() {
|
||||
java.lang.Object ref = name_;
|
||||
if (!(ref instanceof java.lang.String)) {
|
||||
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
|
||||
java.lang.String s = bs.toStringUtf8();
|
||||
if (bs.isValidUtf8()) {
|
||||
name_ = s;
|
||||
}
|
||||
return s;
|
||||
} else {
|
||||
return (java.lang.String) ref;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
public com.google.protobuf.ByteString getNameBytes() {
|
||||
java.lang.Object ref = name_;
|
||||
if (ref instanceof String) {
|
||||
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
|
||||
name_ = b;
|
||||
return b;
|
||||
} else {
|
||||
return (com.google.protobuf.ByteString) ref;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
public Builder setName(java.lang.String value) {
|
||||
if (value == null) {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
bitField0_ |= 0x00000002;
|
||||
name_ = value;
|
||||
onChanged();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
public Builder clearName() {
|
||||
bitField0_ = (bitField0_ & ~0x00000002);
|
||||
name_ = getDefaultInstance().getName();
|
||||
onChanged();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>required string name = 2;</code>
|
||||
*/
|
||||
public Builder setNameBytes(com.google.protobuf.ByteString value) {
|
||||
if (value == null) {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
bitField0_ |= 0x00000002;
|
||||
name_ = value;
|
||||
onChanged();
|
||||
return this;
|
||||
}
|
||||
|
||||
// @@protoc_insertion_point(builder_scope:baeldung.Foo)
|
||||
}
|
||||
|
||||
static {
|
||||
defaultInstance = new Foo(true);
|
||||
defaultInstance.initFields();
|
||||
}
|
||||
|
||||
// @@protoc_insertion_point(class_scope:baeldung.Foo)
|
||||
}
|
||||
|
||||
private static final com.google.protobuf.Descriptors.Descriptor internal_static_baeldung_Foo_descriptor;
|
||||
private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_baeldung_Foo_fieldAccessorTable;
|
||||
|
||||
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
|
||||
static {
|
||||
java.lang.String[] descriptorData = { "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024org.baeldung.web" + ".dtoB\tFooProtos" };
|
||||
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
|
||||
public com.google.protobuf.ExtensionRegistry assignDescriptors(com.google.protobuf.Descriptors.FileDescriptor root) {
|
||||
descriptor = root;
|
||||
return null;
|
||||
}
|
||||
};
|
||||
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner);
|
||||
internal_static_baeldung_Foo_descriptor = getDescriptor().getMessageTypes().get(0);
|
||||
internal_static_baeldung_Foo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(internal_static_baeldung_Foo_descriptor, new java.lang.String[] { "Id", "Name", });
|
||||
}
|
||||
|
||||
// @@protoc_insertion_point(outer_class_scope)
|
||||
}
|
||||
@@ -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 + "\"";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
server.port= 8082
|
||||
server.context-path=/spring-rest
|
||||
19
spring-rest-simple/src/main/resources/logback.xml
Normal file
19
spring-rest-simple/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
56
spring-rest-simple/src/main/webapp/WEB-INF/api-servlet.xml
Normal file
56
spring-rest-simple/src/main/webapp/WEB-INF/api-servlet.xml
Normal file
@@ -0,0 +1,56 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
|
||||
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"
|
||||
>
|
||||
|
||||
<context:component-scan base-package="org.baeldung.web" />
|
||||
|
||||
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" >
|
||||
<mvc:message-converters register-defaults="true">
|
||||
<!--
|
||||
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
|
||||
|
||||
<bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
|
||||
<property name="marshaller" ref="xstreamMarshaller" />
|
||||
<property name="unmarshaller" ref="xstreamMarshaller" />
|
||||
</bean>
|
||||
-->
|
||||
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
|
||||
<bean class="org.baeldung.config.converter.KryoHttpMessageConverter"/>
|
||||
<bean class="org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter"/>
|
||||
</mvc:message-converters>
|
||||
</mvc:annotation-driven>
|
||||
|
||||
<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller" />
|
||||
|
||||
<!-- -->
|
||||
|
||||
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
|
||||
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
|
||||
<property name="location">
|
||||
<value>/WEB-INF/spring-views.xml</value>
|
||||
</property>
|
||||
<property name="order" value="0" />
|
||||
</bean>
|
||||
|
||||
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
|
||||
<!-- max upload size in bytes -->
|
||||
<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
|
||||
|
||||
<!-- max size of file in memory (in bytes) -->
|
||||
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
|
||||
|
||||
</bean>
|
||||
|
||||
<bean id="contentNegotiationManager"
|
||||
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
|
||||
<property name="defaultContentType" value="application/json" />
|
||||
</bean>
|
||||
|
||||
|
||||
</beans>
|
||||
|
||||
|
||||
44
spring-rest-simple/src/main/webapp/WEB-INF/company.html
Normal file
44
spring-rest-simple/src/main/webapp/WEB-INF/company.html
Normal file
@@ -0,0 +1,44 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="ISO-8859-1">
|
||||
<title>Company Data</title>
|
||||
<script src="https://code.jquery.com/jquery-3.1.0.js"
|
||||
integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
|
||||
crossorigin="anonymous"></script>
|
||||
<script>
|
||||
$(document).ready(function(){
|
||||
$('#REST-button').click(function() {
|
||||
$.ajax({
|
||||
url: 'http://localhost:8080/spring-rest/companyRest?callback=getCompanyData',
|
||||
data: {
|
||||
format: 'json'
|
||||
},
|
||||
type: 'GET',
|
||||
jsonpCallback:'getCompanyData',
|
||||
dataType: 'jsonp',
|
||||
error: function() {
|
||||
$('#infoREST').html('<p>An error has occurred</p>');
|
||||
},
|
||||
success: function(data) {
|
||||
console.log("sucess");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function getCompanyData(data) {
|
||||
document.write("<b>ID:</b> "+data.id+"<br/>");
|
||||
document.write("<b>NAME:</b> "+data.name+"<br/>");
|
||||
document.write("<br/>");
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Using REST URL-->
|
||||
<button id="REST-button">Test REST JSON-P!</button>
|
||||
<div id="infoREST"></div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
10
spring-rest-simple/src/main/webapp/WEB-INF/spring-views.xml
Normal file
10
spring-rest-simple/src/main/webapp/WEB-INF/spring-views.xml
Normal file
@@ -0,0 +1,10 @@
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
|
||||
>
|
||||
|
||||
<bean id="RedirectedUrl" class="org.springframework.web.servlet.view.RedirectView">
|
||||
<property name="url" value="redirectedUrl" />
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
41
spring-rest-simple/src/main/webapp/WEB-INF/web.xml
Normal file
41
spring-rest-simple/src/main/webapp/WEB-INF/web.xml
Normal file
@@ -0,0 +1,41 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
xsi:schemaLocation="
|
||||
http://java.sun.com/xml/ns/javaee
|
||||
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
|
||||
>
|
||||
|
||||
<display-name>Spring MVC Application</display-name>
|
||||
|
||||
<!-- Spring root -->
|
||||
<context-param>
|
||||
<param-name>contextClass</param-name>
|
||||
<param-value>
|
||||
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
|
||||
</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>org.baeldung.config</param-value>
|
||||
</context-param>
|
||||
|
||||
<listener>
|
||||
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
|
||||
</listener>
|
||||
|
||||
<!-- Spring child -->
|
||||
<servlet>
|
||||
<servlet-name>api</servlet-name>
|
||||
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>api</servlet-name>
|
||||
<url-pattern>/</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<welcome-file-list>
|
||||
<welcome-file/>
|
||||
</welcome-file-list>
|
||||
|
||||
</web-app>
|
||||
@@ -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<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
|
||||
|
||||
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException {
|
||||
final ResponseEntity<String> 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<Foo> 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<Foo> 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<Foo> request = new HttpEntity<>(new Foo("bar"));
|
||||
|
||||
final ResponseEntity<Foo> 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<HttpMethod> 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<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
|
||||
|
||||
// Create Resource
|
||||
final ResponseEntity<Foo> 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<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers);
|
||||
template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
|
||||
|
||||
// Check that Resource was updated
|
||||
final ResponseEntity<Foo> 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<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
|
||||
|
||||
// Create entity
|
||||
ResponseEntity<Foo> 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<Foo> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
|
||||
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;
|
||||
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.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 BazzNewMappingsExampleIntegrationTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webApplicationContext;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingAllBazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(get("/bazz"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$", hasSize(4)))
|
||||
.andExpect(jsonPath("$[1].id", is("2")))
|
||||
.andExpect(jsonPath("$[1].name", is("Bazz2")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(get("/bazz/1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("1")))
|
||||
.andExpect(jsonPath("$.name", is("Bazz1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(post("/bazz").param("name", "Bazz5"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("5")))
|
||||
.andExpect(jsonPath("$.name", is("Bazz5")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpdatingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(put("/bazz/5").param("name", "Bazz6"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("5")))
|
||||
.andExpect(jsonPath("$.name", is("Bazz6")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeletingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(delete("/bazz/5"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("5")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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;
|
||||
|
||||
|
||||
public class RequestMappingLiveTest {
|
||||
private static String BASE_URI = "http://localhost:8082/spring-rest/ex/";
|
||||
|
||||
@Test
|
||||
public void givenSimplePath_whenGetFoos_thenOk() {
|
||||
RestAssured.given().accept("text/html").get(BASE_URI + "foos").then().assertThat().body(equalTo("Simple Get some Foos"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostFoos_thenOk() {
|
||||
RestAssured.given().accept("text/html").post(BASE_URI + "foos").then().assertThat().body(equalTo("Post some Foos"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneHeader_whenGetFoos_thenOk() {
|
||||
RestAssured.given().accept("text/html").header("key", "val").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleHeaders_whenGetFoos_thenOk() {
|
||||
RestAssured.given().accept("text/html").headers("key1", "val1", "key2", "val2").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAcceptHeader_whenGetFoos_thenOk() {
|
||||
RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(containsString("Get some Foos with Header New"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathVariable_whenGetFoos_thenOk() {
|
||||
RestAssured.given().accept("text/html").get(BASE_URI + "foos/1").then().assertThat().body(equalTo("Get a specific Foo with id=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplePathVariable_whenGetFoos_thenOk() {
|
||||
RestAssured.given().accept("text/html").get(BASE_URI + "foos/1/bar/2").then().assertThat().body(equalTo("Get a specific Bar with id=2 from a Foo with id=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathVariable_whenGetBars_thenOk() {
|
||||
RestAssured.given().accept("text/html").get(BASE_URI + "bars/1").then().assertThat().body(equalTo("Get a specific Bar with id=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParams_whenGetBars_thenOk() {
|
||||
RestAssured.given().accept("text/html").get(BASE_URI + "bars?id=100&second=something").then().assertThat().body(equalTo("Get a specific Bar with id=100"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFoosOrBars_thenOk() {
|
||||
RestAssured.given().accept("text/html").get(BASE_URI + "advanced/foos").then().assertThat().body(equalTo("Advanced - Get some Foos or Bars"));
|
||||
RestAssured.given().accept("text/html").get(BASE_URI + "advanced/bars").then().assertThat().body(equalTo("Advanced - Get some Foos or Bars"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package org.baeldung.web.test;
|
||||
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.baeldung.config.converter.KryoHttpMessageConverter;
|
||||
import org.baeldung.web.dto.Foo;
|
||||
import org.baeldung.web.dto.FooProtos;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
/**
|
||||
* Integration Test class. Tests methods hits the server's rest services.
|
||||
*/
|
||||
public class SpringHttpMessageConvertersLiveTest {
|
||||
|
||||
private static String BASE_URI = "http://localhost:8082/spring-rest/";
|
||||
|
||||
/**
|
||||
* Without specifying Accept Header, uses the default response from the
|
||||
* server (in this case json)
|
||||
*/
|
||||
@Test
|
||||
public void whenRetrievingAFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
final Foo resource = restTemplate.getForObject(URI, Foo.class, "1");
|
||||
|
||||
assertThat(resource, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConsumingXml_whenReadingTheFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
|
||||
final HttpEntity<String> entity = new HttpEntity<String>(headers);
|
||||
|
||||
final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
|
||||
final Foo resource = response.getBody();
|
||||
|
||||
assertThat(resource, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConsumingJson_whenReadingTheFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
|
||||
final HttpEntity<String> entity = new HttpEntity<String>(headers);
|
||||
|
||||
final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
|
||||
final Foo resource = response.getBody();
|
||||
|
||||
assertThat(resource, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConsumingXml_whenWritingTheFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
final Foo resource = new Foo(4, "jason");
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
|
||||
headers.setContentType((MediaType.APPLICATION_XML));
|
||||
final HttpEntity<Foo> entity = new HttpEntity<Foo>(resource, headers);
|
||||
|
||||
final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.PUT, entity, Foo.class, resource.getId());
|
||||
final Foo fooResponse = response.getBody();
|
||||
|
||||
Assert.assertEquals(resource.getId(), fooResponse.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConsumingProtobuf_whenReadingTheFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
restTemplate.setMessageConverters(Arrays.asList(new ProtobufHttpMessageConverter()));
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Arrays.asList(ProtobufHttpMessageConverter.PROTOBUF));
|
||||
final HttpEntity<String> entity = new HttpEntity<String>(headers);
|
||||
|
||||
final ResponseEntity<FooProtos.Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, FooProtos.Foo.class, "1");
|
||||
final FooProtos.Foo resource = response.getBody();
|
||||
|
||||
assertThat(resource, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConsumingKryo_whenReadingTheFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
restTemplate.setMessageConverters(Arrays.asList(new KryoHttpMessageConverter()));
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Arrays.asList(KryoHttpMessageConverter.KRYO));
|
||||
final HttpEntity<String> entity = new HttpEntity<String>(headers);
|
||||
|
||||
final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
|
||||
final Foo resource = response.getBody();
|
||||
|
||||
assertThat(resource, notNullValue());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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. <br>
|
||||
* https://api.github.com/users/steveklabnik/gists?page=2>; rel="next", <https://api.github.com/users/steveklabnik/gists?page=3>; rel="last"
|
||||
*/
|
||||
public static List<String> extractAllURIs(final String linkHeader) {
|
||||
Preconditions.checkNotNull(linkHeader);
|
||||
|
||||
final List<String> 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. <br>
|
||||
* 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);
|
||||
}
|
||||
|
||||
}
|
||||
13
spring-rest-simple/src/test/resources/.gitignore
vendored
Normal file
13
spring-rest-simple/src/test/resources/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
Reference in New Issue
Block a user