work on initial state of the spring 5 project

This commit is contained in:
eugenp
2017-02-24 13:57:32 +02:00
parent 9f10890501
commit 07876a2855
53 changed files with 125 additions and 3087 deletions

View File

@@ -0,0 +1,16 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Spring5ApplicationTests {
@Test
public void contextLoads() {
}
}

View File

@@ -1,5 +0,0 @@
package org.baeldung.client;
public interface Consts {
int APPLICATION_PORT = 8082;
}

View File

@@ -1,216 +0,0 @@
package org.baeldung.client;
import static org.apache.commons.codec.binary.Base64.encodeBase64;
import static org.baeldung.client.Consts.APPLICATION_PORT;
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 = "http://localhost:" + APPLICATION_PORT + "/spring-rest/myfoos";
@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;
}
}

View File

@@ -1,24 +0,0 @@
package org.baeldung.okhttp;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class DefaultContentTypeInterceptor implements Interceptor {
private final String contentType;
public DefaultContentTypeInterceptor(String contentType) {
this.contentType = contentType;
}
public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
Request requestWithUserAgent = originalRequest.newBuilder().header("Content-Type", contentType).build();
return chain.proceed(requestWithUserAgent);
}
}

View File

@@ -1,65 +0,0 @@
package org.baeldung.okhttp;
import static org.baeldung.client.Consts.APPLICATION_PORT;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
public class OkHttpFileUploadingLiveTest {
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
OkHttpClient client;
@Before
public void init() {
client = new OkHttpClient();
}
@Test
public void whenUploadFile_thenCorrect() throws IOException {
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(requestBody).build();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@Test
public void whenGetUploadFileProgress_thenCorrect() throws IOException {
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
final ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> {
final float percentage = (100f * bytesWritten) / contentLength;
assertFalse(Float.compare(percentage, 100) > 0);
});
final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(countingBody).build();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
}

View File

@@ -1,77 +0,0 @@
package org.baeldung.okhttp;
import static org.baeldung.client.Consts.APPLICATION_PORT;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
public class OkHttpGetLiveTest {
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
OkHttpClient client;
@Before
public void init() {
client = new OkHttpClient();
}
@Test
public void whenGetRequest_thenCorrect() throws IOException {
final Request request = new Request.Builder().url(BASE_URL + "/date").build();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@Test
public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException {
final HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder();
urlBuilder.addQueryParameter("id", "1");
final String url = urlBuilder.build().toString();
final Request request = new Request.Builder().url(url).build();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@Test
public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException {
final Request request = new Request.Builder().url(BASE_URL + "/date").build();
final Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("OK");
}
@Override
public void onFailure(Call call, IOException e) {
fail();
}
});
Thread.sleep(3000);
}
}

View File

@@ -1,45 +0,0 @@
package org.baeldung.okhttp;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpHeaderLiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
OkHttpClient client;
@Before
public void init() {
client = new OkHttpClient();
}
@Test
public void whenSetHeader_thenCorrect() throws IOException {
Request request = new Request.Builder().url(SAMPLE_URL).addHeader("Content-Type", "application/json").build();
Call call = client.newCall(request);
Response response = call.execute();
response.close();
}
@Test
public void whenSetDefaultHeader_thenCorrect() throws IOException {
OkHttpClient clientWithInterceptor = new OkHttpClient.Builder().addInterceptor(new DefaultContentTypeInterceptor("application/json")).build();
Request request = new Request.Builder().url(SAMPLE_URL).build();
Call call = clientWithInterceptor.newCall(request);
Response response = call.execute();
response.close();
}
}

View File

@@ -1,99 +0,0 @@
package org.baeldung.okhttp;
import static org.baeldung.client.Consts.APPLICATION_PORT;
import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OkHttpMiscLiveTest {
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class);
OkHttpClient client;
@Before
public void init() {
client = new OkHttpClient();
}
@Test(expected = SocketTimeoutException.class)
public void whenSetRequestTimeout_thenFail() throws IOException {
final OkHttpClient clientWithTimeout = new OkHttpClient.Builder().readTimeout(1, TimeUnit.SECONDS).build();
final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
.build();
final Call call = clientWithTimeout.newCall(request);
final Response response = call.execute();
response.close();
}
@Test(expected = IOException.class)
public void whenCancelRequest_thenCorrect() throws IOException {
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
.build();
final int seconds = 1;
final long startNanos = System.nanoTime();
final Call call = client.newCall(request);
// Schedule a job to cancel the call in 1 second.
executor.schedule(() -> {
logger.debug("Canceling call: " + ((System.nanoTime() - startNanos) / 1e9f));
call.cancel();
logger.debug("Canceled call: " + ((System.nanoTime() - startNanos) / 1e9f));
}, seconds, TimeUnit.SECONDS);
logger.debug("Executing call: " + ((System.nanoTime() - startNanos) / 1e9f));
final Response response = call.execute();
logger.debug("Call completed: " + ((System.nanoTime() - startNanos) / 1e9f), response);
}
@Test
public void whenSetResponseCache_thenCorrect() throws IOException {
final int cacheSize = 10 * 1024 * 1024; // 10 MiB
final File cacheDirectory = new File("src/test/resources/cache");
final Cache cache = new Cache(cacheDirectory, cacheSize);
final OkHttpClient clientCached = new OkHttpClient.Builder().cache(cache).build();
final Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();
final Response response1 = clientCached.newCall(request).execute();
logResponse(response1);
final Response response2 = clientCached.newCall(request).execute();
logResponse(response2);
}
private void logResponse(Response response) throws IOException {
logger.debug("Response response: " + response);
logger.debug("Response cache response: " + response.cacheResponse());
logger.debug("Response network response: " + response.networkResponse());
logger.debug("Response responseBody: " + response.body().string());
}
}

View File

@@ -1,85 +0,0 @@
package org.baeldung.okhttp;
import static org.baeldung.client.Consts.APPLICATION_PORT;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Credentials;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
public class OkHttpPostingLiveTest {
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
OkHttpClient client;
@Before
public void init() {
client = new OkHttpClient();
}
@Test
public void whenSendPostRequest_thenCorrect() throws IOException {
final RequestBody formBody = new FormBody.Builder().add("username", "test").add("password", "test").build();
final Request request = new Request.Builder().url(BASE_URL + "/users").post(formBody).build();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@Test
public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException {
final String postBody = "test post";
final Request request = new Request.Builder().url(URL_SECURED_BY_BASIC_AUTHENTICATION).addHeader("Authorization", Credentials.basic("test", "test")).post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), "test post")).build();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@Test
public void whenPostJson_thenCorrect() throws IOException {
final String json = "{\"id\":1,\"name\":\"John\"}";
final RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"id\":1,\"name\":\"John\"}");
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@Test
public void whenSendMultipartRequest_thenCorrect() throws IOException {
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("username", "test").addFormDataPart("password", "test")
.addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
final Request request = new Request.Builder().url(BASE_URL + "/users/multipart").post(requestBody).build();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
}

View File

@@ -1,29 +0,0 @@
package org.baeldung.okhttp;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import org.junit.Test;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpRedirectLiveTest {
@Test
public void whenSetFollowRedirects_thenNotRedirected() throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder().followRedirects(false).build();
Request request = new Request.Builder().url("http://t.co/I5YYd9tddw").build();
Call call = client.newCall(request);
Response response = call.execute();
assertThat(response.code(), equalTo(301));
}
}

View File

@@ -1,73 +0,0 @@
package org.baeldung.okhttp;
import okhttp3.RequestBody;
import okhttp3.MediaType;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
public class ProgressRequestWrapper extends RequestBody {
protected RequestBody delegate;
protected ProgressListener listener;
protected CountingSink countingSink;
public ProgressRequestWrapper(RequestBody delegate, ProgressListener listener) {
this.delegate = delegate;
this.listener = listener;
}
@Override
public MediaType contentType() {
return delegate.contentType();
}
@Override
public long contentLength() throws IOException {
return delegate.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink bufferedSink;
countingSink = new CountingSink(sink);
bufferedSink = Okio.buffer(countingSink);
delegate.writeTo(bufferedSink);
bufferedSink.flush();
}
protected final class CountingSink extends ForwardingSink {
private long bytesWritten = 0;
public CountingSink(Sink delegate) {
super(delegate);
}
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
bytesWritten += byteCount;
listener.onRequestProgress(bytesWritten, contentLength());
}
}
public interface ProgressListener {
void onRequestProgress(long bytesWritten, long contentLength);
}
}

View File

@@ -1,49 +0,0 @@
package org.baeldung.uribuilder;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import org.junit.Test;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
public class SpringUriBuilderTest {
@Test
public void constructUri() {
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/junit-5").build();
assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString());
}
@Test
public void constructUriEncoded() {
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/junit 5").build().encode();
assertEquals("http://www.baeldung.com/junit%205", uriComponents.toUriString());
}
@Test
public void constructUriFromTemplate() {
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/{article-name}").buildAndExpand("junit-5");
assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString());
}
@Test
public void constructUriWithQueryParameter() {
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.google.com").path("/").query("q={keyword}").buildAndExpand("baeldung");
assertEquals("http://www.google.com/?q=baeldung", uriComponents.toUriString());
}
@Test
public void expandWithRegexVar() {
String template = "/myurl/{name:[a-z]{1,5}}/show";
UriComponents uriComponents = UriComponentsBuilder.fromUriString(template).build();
uriComponents = uriComponents.expand(Collections.singletonMap("name", "test"));
assertEquals("/myurl/test/show", uriComponents.getPath());
}
}

View File

@@ -1,37 +0,0 @@
package org.baeldung.web.controller.mediatypes;
import com.jayway.restassured.http.ContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static com.jayway.restassured.RestAssured.given;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class)
public class CustomMediaTypeControllerLiveTest {
private static final String URL_PREFIX = "http://localhost:8082/spring-rest";
@Test
public void givenServiceEndpoint_whenGetRequestFirstAPIVersion_thenShouldReturn200() {
given()
.accept("application/vnd.baeldung.api.v1+json")
.when()
.get(URL_PREFIX + "/public/api/items/1")
.then()
.contentType(ContentType.JSON).and().statusCode(200);
}
@Test
public void givenServiceEndpoint_whenGetRequestSecondAPIVersion_thenShouldReturn200() {
given()
.accept("application/vnd.baeldung.api.v2+json")
.when()
.get(URL_PREFIX + "/public/api/items/2")
.then()
.contentType(ContentType.JSON).and().statusCode(200);
}
}

View File

@@ -1,42 +0,0 @@
package org.baeldung.web.controller.mediatypes;
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;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = WebConfig.class)
@WebAppConfiguration
public class CustomMediaTypeControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void givenServiceUrl_whenGetWithProperAcceptHeaderFirstAPIVersion_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/items/1").accept("application/vnd.baeldung.api.v1+json")).andExpect(status().isOk());
}
@Test
public void givenServiceUrl_whenGetWithProperAcceptHeaderSecondVersion_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/items/2").accept("application/vnd.baeldung.api.v2+json")).andExpect(status().isOk());
}
}

View File

@@ -1,11 +0,0 @@
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 {
}

View File

@@ -1,66 +0,0 @@
package org.baeldung.web.controller.redirect;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
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.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/api-servlet.xml")
@WebAppConfiguration
public class RedirectControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
protected WebApplicationContext wac;
@Before
public void setup() {
mockMvc = webAppContextSetup(wac).build();
}
@Test
public void whenRedirectOnUrlWithUsingXMLConfig_thenStatusRedirectionAndRedirectedOnUrl() throws Exception {
mockMvc.perform(get("/redirectWithXMLConfig")).andExpect(status().is3xxRedirection()).andExpect(view().name("RedirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithXMLConfig")))
.andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithXMLConfig"));
}
@Test
public void whenRedirectOnUrlWithUsingRedirectPrefix_thenStatusRedirectionAndRedirectedOnUrl() throws Exception {
mockMvc.perform(get("/redirectWithRedirectPrefix")).andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectPrefix")))
.andExpect(redirectedUrl("/redirectedUrl?attribute=redirectWithRedirectPrefix"));
}
@Test
public void whenRedirectOnUrlWithUsingRedirectAttributes_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception {
mockMvc.perform(get("/redirectWithRedirectAttributes")).andExpect(status().is3xxRedirection()).andExpect(flash().attribute("flashAttribute", equalTo("redirectWithRedirectAttributes")))
.andExpect(model().attribute("attribute", equalTo("redirectWithRedirectAttributes"))).andExpect(model().attribute("flashAttribute", equalTo(null))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectAttributes"));
}
@Test
public void whenRedirectOnUrlWithUsingRedirectView_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception {
mockMvc.perform(get("/redirectWithRedirectView")).andExpect(status().is3xxRedirection()).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectView"))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectView"));
}
@Test
public void whenRedirectOnUrlWithUsingForwardPrefix_thenStatusOkAndForwardedOnUrl() throws Exception {
mockMvc.perform(get("/forwardWithForwardPrefix")).andExpect(status().isOk()).andExpect(view().name("forward:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithForwardPrefix"))).andExpect(forwardedUrl("/redirectedUrl"));
}
}

View File

@@ -1,42 +0,0 @@
package org.baeldung.web.controller.status;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.baeldung.config.WebConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.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 ExampleControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void whenGetRequestSentToController_thenReturnsStatusNotAcceptable() throws Exception {
mockMvc.perform(get("/controller")).andExpect(status().isNotAcceptable());
}
@Test
public void whenGetRequestSentToException_thenReturnsStatusForbidden() throws Exception {
mockMvc.perform(get("/exception")).andExpect(status().isForbidden());
}
}

View File

@@ -1,63 +0,0 @@
package org.baeldung.web.test;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;
import com.jayway.restassured.RestAssured;
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"));
}
}

View File

@@ -1,123 +0,0 @@
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());
}
}