Skip to content

Commit 6e6c3e6

Browse files
committed
move rest template test
1 parent 602e98c commit 6e6c3e6

5 files changed

Lines changed: 262 additions & 9 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package org.baeldung.web.controller;
2+
3+
import java.util.Collection;
4+
import java.util.HashMap;
5+
import java.util.Map;
6+
7+
import javax.servlet.http.HttpServletResponse;
8+
9+
import org.baeldung.web.dto.Foo;
10+
import org.baeldung.web.exception.ResourceNotFoundException;
11+
import org.springframework.http.HttpStatus;
12+
import org.springframework.stereotype.Controller;
13+
import org.springframework.web.bind.annotation.PathVariable;
14+
import org.springframework.web.bind.annotation.RequestBody;
15+
import org.springframework.web.bind.annotation.RequestMapping;
16+
import org.springframework.web.bind.annotation.RequestMethod;
17+
import org.springframework.web.bind.annotation.ResponseBody;
18+
import org.springframework.web.bind.annotation.ResponseStatus;
19+
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
20+
21+
@Controller
22+
@RequestMapping(value = "/myfoos")
23+
public class MyFooController {
24+
25+
private final Map<Long, Foo> myfoos;
26+
27+
public MyFooController() {
28+
super();
29+
myfoos = new HashMap<Long, Foo>();
30+
myfoos.put(1L, new Foo(1L, "sample foo"));
31+
}
32+
33+
// API - read
34+
35+
@RequestMapping(method = RequestMethod.GET)
36+
@ResponseBody
37+
public Collection<Foo> findAll() {
38+
return myfoos.values();
39+
}
40+
41+
@RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = { "application/json" })
42+
@ResponseBody
43+
public Foo findById(@PathVariable final long id) {
44+
final Foo foo = myfoos.get(id);
45+
if (foo == null) {
46+
throw new ResourceNotFoundException();
47+
}
48+
return foo;
49+
}
50+
51+
// API - write
52+
53+
@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
54+
@ResponseStatus(HttpStatus.OK)
55+
@ResponseBody
56+
public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) {
57+
myfoos.put(id, foo);
58+
return foo;
59+
}
60+
61+
@RequestMapping(method = RequestMethod.POST)
62+
@ResponseStatus(HttpStatus.CREATED)
63+
@ResponseBody
64+
public Foo createFoo(@RequestBody final Foo foo, HttpServletResponse response) {
65+
myfoos.put(foo.getId(), foo);
66+
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentRequest().path("/" + foo.getId()).toUriString());
67+
return foo;
68+
}
69+
70+
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
71+
@ResponseStatus(HttpStatus.OK)
72+
public void deleteById(@PathVariable final long id) {
73+
myfoos.remove(id);
74+
}
75+
76+
}

‎spring-rest/src/main/java/org/baeldung/web/dto/Foo.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ public Foo() {
1111
super();
1212
}
1313

14+
public Foo(final String name) {
15+
super();
16+
17+
this.name = name;
18+
}
19+
1420
public Foo(final long id, final String name) {
1521
super();
1622

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package org.baeldung.web.exception;
2+
3+
import org.springframework.http.HttpStatus;
4+
import org.springframework.web.bind.annotation.ResponseStatus;
5+
6+
@ResponseStatus(value = HttpStatus.NOT_FOUND)
7+
public class ResourceNotFoundException extends RuntimeException {
8+
}

‎spring-rest/src/main/webapp/WEB-INF/api-servlet.xml‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
<context:component-scan base-package="org.baeldung.web" />
1010

11-
<mvc:annotation-driven>
11+
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" >
1212
<mvc:message-converters register-defaults="true">
1313
<!--
1414
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
@@ -18,6 +18,7 @@
1818
<property name="unmarshaller" ref="xstreamMarshaller" />
1919
</bean>
2020
-->
21+
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
2122
<bean class="org.baeldung.config.converter.KryoHttpMessageConverter"/>
2223
<bean class="org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter"/>
2324
</mvc:message-converters>
@@ -43,6 +44,11 @@
4344
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
4445

4546
</bean>
47+
48+
<bean id="contentNegotiationManager"
49+
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
50+
<property name="defaultContentType" value="application/json" />
51+
</bean>
4652

4753

4854
</beans>
Lines changed: 165 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,42 @@
11
package org.baeldung.client;
22

3+
import static org.apache.commons.codec.binary.Base64.encodeBase64;
34
import static org.baeldung.client.Consts.APPLICATION_PORT;
45
import static org.hamcrest.CoreMatchers.equalTo;
56
import static org.hamcrest.CoreMatchers.is;
67
import static org.hamcrest.CoreMatchers.notNullValue;
78
import static org.hamcrest.MatcherAssert.assertThat;
8-
import static org.mockito.Matchers.notNull;
9+
import static org.junit.Assert.assertTrue;
10+
import static org.junit.Assert.fail;
911

1012
import java.io.IOException;
13+
import java.net.URI;
14+
import java.util.Arrays;
15+
import java.util.Set;
1116

1217
import org.baeldung.web.dto.Foo;
1318
import org.junit.Before;
1419
import org.junit.Test;
20+
import org.springframework.http.HttpEntity;
21+
import org.springframework.http.HttpHeaders;
22+
import org.springframework.http.HttpMethod;
1523
import org.springframework.http.HttpStatus;
24+
import org.springframework.http.MediaType;
1625
import org.springframework.http.ResponseEntity;
26+
import org.springframework.http.client.ClientHttpRequestFactory;
27+
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
28+
import org.springframework.web.client.HttpClientErrorException;
29+
import org.springframework.web.client.RequestCallback;
1730
import org.springframework.web.client.RestTemplate;
1831

1932
import com.fasterxml.jackson.databind.JsonNode;
2033
import com.fasterxml.jackson.databind.ObjectMapper;
34+
import com.google.common.base.Charsets;
2135

2236
public class RestTemplateBasicLiveTest {
2337

2438
private RestTemplate restTemplate;
25-
private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos";
39+
private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/myfoos";
2640

2741
@Before
2842
public void beforeTest() {
@@ -33,19 +47,19 @@ public void beforeTest() {
3347

3448
@Test
3549
public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException {
36-
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
50+
final ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
3751

3852
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
3953
}
4054

4155
@Test
4256
public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException {
43-
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
57+
final ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
4458

45-
ObjectMapper mapper = new ObjectMapper();
46-
JsonNode root = mapper.readTree(response.getBody());
47-
JsonNode name = root.path("name");
48-
assertThat(name.asText(), is(notNull()));
59+
final ObjectMapper mapper = new ObjectMapper();
60+
final JsonNode root = mapper.readTree(response.getBody());
61+
final JsonNode name = root.path("name");
62+
assertThat(name.asText(), notNullValue());
4963
}
5064

5165
@Test
@@ -56,4 +70,147 @@ public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOExcep
5670
assertThat(foo.getId(), is(1L));
5771
}
5872

73+
// HEAD, OPTIONS
74+
75+
@Test
76+
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
77+
final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
78+
79+
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
80+
}
81+
82+
// POST
83+
84+
@Test
85+
public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() {
86+
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
87+
final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
88+
assertThat(foo, notNullValue());
89+
assertThat(foo.getName(), is("bar"));
90+
}
91+
92+
@Test
93+
public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() {
94+
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
95+
final URI location = restTemplate.postForLocation(fooResourceUrl, request);
96+
assertThat(location, notNullValue());
97+
}
98+
99+
@Test
100+
public void givenFooService_whenPostResource_thenResourceIsCreated() {
101+
final RestTemplate template = new RestTemplate();
102+
103+
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
104+
105+
final ResponseEntity<Foo> response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
106+
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
107+
final Foo foo = response.getBody();
108+
assertThat(foo, notNullValue());
109+
assertThat(foo.getName(), is("bar"));
110+
}
111+
112+
@Test
113+
public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() {
114+
final Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);
115+
final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD };
116+
117+
assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
118+
}
119+
120+
// PUT
121+
122+
@Test
123+
public void givenFooService_whenPutExistingEntity_thenItIsUpdated() {
124+
final RestTemplate template = new RestTemplate();
125+
final HttpHeaders headers = prepareBasicAuthHeaders();
126+
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
127+
128+
// Create Resource
129+
final ResponseEntity<Foo> createResponse = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
130+
131+
// Update Resource
132+
final Foo updatedInstance = new Foo("newName");
133+
updatedInstance.setId(createResponse.getBody().getId());
134+
final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody().getId();
135+
final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers);
136+
template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
137+
138+
// Check that Resource was updated
139+
final ResponseEntity<Foo> updateResponse = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
140+
final Foo foo = updateResponse.getBody();
141+
assertThat(foo.getName(), is(updatedInstance.getName()));
142+
}
143+
144+
@Test
145+
public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() {
146+
final RestTemplate template = new RestTemplate();
147+
final HttpHeaders headers = prepareBasicAuthHeaders();
148+
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
149+
150+
// Create entity
151+
ResponseEntity<Foo> response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
152+
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
153+
154+
// Update entity
155+
final Foo updatedInstance = new Foo("newName");
156+
updatedInstance.setId(response.getBody().getId());
157+
final String resourceUrl = fooResourceUrl + '/' + response.getBody().getId();
158+
template.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null);
159+
160+
// Check that entity was updated
161+
response = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
162+
final Foo foo = response.getBody();
163+
assertThat(foo.getName(), is(updatedInstance.getName()));
164+
}
165+
166+
// DELETE
167+
168+
@Test
169+
public void givenFooService_whenCallDelete_thenEntityIsRemoved() {
170+
final Foo foo = new Foo("remove me");
171+
final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class);
172+
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
173+
174+
final String entityUrl = fooResourceUrl + "/" + response.getBody().getId();
175+
restTemplate.delete(entityUrl);
176+
try {
177+
restTemplate.getForEntity(entityUrl, Foo.class);
178+
fail();
179+
} catch (final HttpClientErrorException ex) {
180+
assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND));
181+
}
182+
}
183+
184+
//
185+
186+
private HttpHeaders prepareBasicAuthHeaders() {
187+
final HttpHeaders headers = new HttpHeaders();
188+
final String encodedLogPass = getBase64EncodedLogPass();
189+
headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass);
190+
return headers;
191+
}
192+
193+
private String getBase64EncodedLogPass() {
194+
final String logPass = "user1:user1Pass";
195+
final byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII));
196+
return new String(authHeaderBytes, Charsets.US_ASCII);
197+
}
198+
199+
private RequestCallback requestCallback(final Foo updatedInstance) {
200+
return clientHttpRequest -> {
201+
final ObjectMapper mapper = new ObjectMapper();
202+
mapper.writeValue(clientHttpRequest.getBody(), updatedInstance);
203+
clientHttpRequest.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
204+
clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass());
205+
};
206+
}
207+
208+
// Simply setting restTemplate timeout using ClientHttpRequestFactory
209+
210+
ClientHttpRequestFactory getSimpleClientHttpRequestFactory() {
211+
final int timeout = 5;
212+
final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
213+
clientHttpRequestFactory.setConnectTimeout(timeout * 1000);
214+
return clientHttpRequestFactory;
215+
}
59216
}

0 commit comments

Comments
 (0)