11package org .baeldung .client ;
22
3+ import static org .apache .commons .codec .binary .Base64 .encodeBase64 ;
34import static org .baeldung .client .Consts .APPLICATION_PORT ;
45import static org .hamcrest .CoreMatchers .equalTo ;
56import static org .hamcrest .CoreMatchers .is ;
67import static org .hamcrest .CoreMatchers .notNullValue ;
78import 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
1012import java .io .IOException ;
13+ import java .net .URI ;
14+ import java .util .Arrays ;
15+ import java .util .Set ;
1116
1217import org .baeldung .web .dto .Foo ;
1318import org .junit .Before ;
1419import org .junit .Test ;
20+ import org .springframework .http .HttpEntity ;
21+ import org .springframework .http .HttpHeaders ;
22+ import org .springframework .http .HttpMethod ;
1523import org .springframework .http .HttpStatus ;
24+ import org .springframework .http .MediaType ;
1625import 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 ;
1730import org .springframework .web .client .RestTemplate ;
1831
1932import com .fasterxml .jackson .databind .JsonNode ;
2033import com .fasterxml .jackson .databind .ObjectMapper ;
34+ import com .google .common .base .Charsets ;
2135
2236public 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