Merge remote-tracking branch 'origin/master'
This commit is contained in:
commit
1736f681ef
|
@ -40,18 +40,22 @@ public class AsyncEchoClient {
|
|||
}
|
||||
}
|
||||
|
||||
public String sendMessage(String message) throws Exception {
|
||||
public String sendMessage(String message) {
|
||||
byte[] byteMsg = message.getBytes();
|
||||
ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
|
||||
Future<Integer> writeResult = client.write(buffer);
|
||||
|
||||
//run some code
|
||||
writeResult.get();
|
||||
try {
|
||||
writeResult.get();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
buffer.flip();
|
||||
Future<Integer> readResult = client.read(buffer);
|
||||
|
||||
//run some code
|
||||
readResult.get();
|
||||
try {
|
||||
readResult.get();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
String echo = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
return echo;
|
||||
|
|
|
@ -58,18 +58,19 @@ public class AsyncEchoServer2 {
|
|||
|
||||
@Override
|
||||
public void completed(Integer result, Map<String, Object> attachment) {
|
||||
String action = (String) attachment.get("action");
|
||||
Map<String, Object> actionInfo = attachment;
|
||||
String action = (String) actionInfo.get("action");
|
||||
if ("read".equals(action)) {
|
||||
ByteBuffer buffer = (ByteBuffer) attachment.get("buffer");
|
||||
ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer");
|
||||
buffer.flip();
|
||||
attachment.put("action", "write");
|
||||
clientChannel.write(buffer, attachment, this);
|
||||
actionInfo.put("action", "write");
|
||||
clientChannel.write(buffer, actionInfo, this);
|
||||
buffer.clear();
|
||||
} else if ("write".equals(action)) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||
attachment.put("action", "read");
|
||||
attachment.put("buffer", buffer);
|
||||
clientChannel.read(buffer, attachment, this);
|
||||
actionInfo.put("action", "read");
|
||||
actionInfo.put("buffer", buffer);
|
||||
clientChannel.read(buffer, actionInfo, this);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -81,6 +82,7 @@ public class AsyncEchoServer2 {
|
|||
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
new AsyncEchoServer2();
|
||||
}
|
||||
|
@ -95,4 +97,4 @@ public class AsyncEchoServer2 {
|
|||
|
||||
return builder.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,179 +1,173 @@
|
|||
package org.baeldung.java.collections;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class JoinSplitCollectionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenJoiningTwoArrays_thenJoined() {
|
||||
String[] animals1 = new String[] { "Dog", "Cat" };
|
||||
String[] animals2 = new String[] { "Bird", "Cow" };
|
||||
String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2))
|
||||
.toArray(String[]::new);
|
||||
@Test
|
||||
public void whenJoiningTwoArrays_thenJoined() {
|
||||
String[] animals1 = new String[]{"Dog", "Cat"};
|
||||
String[] animals2 = new String[]{"Bird", "Cow"};
|
||||
String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2))
|
||||
.toArray(String[]::new);
|
||||
|
||||
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningTwoCollections_thenJoined() {
|
||||
Collection<Integer> collection1 = Arrays.asList(7, 8, 9);
|
||||
Collection<Integer> collection2 = Arrays.asList(10, 11, 12);
|
||||
Collection<Integer> result = Stream.concat(collection1.stream(), collection2.stream())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(result.equals(Arrays.asList(7, 8, 9, 10, 11, 12)));
|
||||
}
|
||||
assertArrayEquals(result, new String[]{"Dog", "Cat", "Bird", "Cow"});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningTwoCollectionsWithFilter_thenJoined() {
|
||||
Collection<Integer> collection1 = Arrays.asList(7, 8, 11);
|
||||
Collection<Integer> collection2 = Arrays.asList(9, 12, 10);
|
||||
Collection<Integer> result = Stream.concat(collection1.stream(), collection2.stream())
|
||||
.filter(next -> next <= 10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(result.equals(Arrays.asList(7, 8, 9, 10)));
|
||||
}
|
||||
@Test
|
||||
public void whenJoiningTwoCollections_thenJoined() {
|
||||
Collection<Integer> collection1 = Arrays.asList(7, 8, 9);
|
||||
Collection<Integer> collection2 = Arrays.asList(10, 11, 12);
|
||||
Collection<Integer> result = Stream.concat(collection1.stream(), collection2.stream())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
@Test
|
||||
public void whenConvertArrayToString_thenConverted() {
|
||||
String[] colors = new String[] { "Red", "Blue", "Green", "Yellow" };
|
||||
String result = Arrays.stream(colors)
|
||||
.collect(Collectors.joining(", "));
|
||||
assertTrue(result.equals(Arrays.asList(7, 8, 9, 10, 11, 12)));
|
||||
}
|
||||
|
||||
assertEquals(result, "Red, Blue, Green, Yellow");
|
||||
}
|
||||
@Test
|
||||
public void whenJoiningTwoCollectionsWithFilter_thenJoined() {
|
||||
Collection<Integer> collection1 = Arrays.asList(7, 8, 11);
|
||||
Collection<Integer> collection2 = Arrays.asList(9, 12, 10);
|
||||
Collection<Integer> result = Stream.concat(collection1.stream(), collection2.stream())
|
||||
.filter(next -> next <= 10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
@Test
|
||||
public void whenConvertCollectionToString_thenConverted() {
|
||||
Collection<String> directions = Arrays.asList("Left", "Right", "Top", "Bottom");
|
||||
String result = directions.stream()
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
assertEquals(result, "Left, Right, Top, Bottom");
|
||||
}
|
||||
assertTrue(result.equals(Arrays.asList(7, 8, 9, 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertMapToString_thenConverted() {
|
||||
Map<Integer, String> users = new HashMap<>();
|
||||
users.put(1, "John Doe");
|
||||
users.put(2, "Paul Smith");
|
||||
users.put(3, "Susan Anderson");
|
||||
@Test
|
||||
public void whenConvertArrayToString_thenConverted() {
|
||||
String[] colors = new String[]{"Red", "Blue", "Green", "Yellow"};
|
||||
String result = Arrays.stream(colors)
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
String result = users.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue())
|
||||
.collect(Collectors.joining(", "));
|
||||
assertEquals(result, "Red, Blue, Green, Yellow");
|
||||
}
|
||||
|
||||
assertEquals(result, "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson");
|
||||
}
|
||||
@Test
|
||||
public void whenConvertCollectionToString_thenConverted() {
|
||||
Collection<String> directions = Arrays.asList("Left", "Right", "Top", "Bottom");
|
||||
String result = directions.stream()
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
@Test
|
||||
public void whenConvertNestedCollectionToString_thenConverted() {
|
||||
Collection<List<String>> nested = new ArrayList<>();
|
||||
nested.add(Arrays.asList("Left", "Right", "Top", "Bottom"));
|
||||
nested.add(Arrays.asList("Red", "Blue", "Green", "Yellow"));
|
||||
|
||||
String result = nested.stream()
|
||||
.map(nextList -> nextList.stream()
|
||||
.collect(Collectors.joining("-")))
|
||||
.collect(Collectors.joining("; "));
|
||||
|
||||
assertEquals(result, "Left-Right-Top-Bottom; Red-Blue-Green-Yellow");
|
||||
}
|
||||
assertEquals(result, "Left, Right, Top, Bottom");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertCollectionToStringAndSkipNull_thenConverted() {
|
||||
Collection<String> fruits = Arrays.asList("Apple", "Orange", null, "Grape");
|
||||
String result = fruits.stream()
|
||||
.filter(next -> next != null)
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
assertEquals(result, "Apple, Orange, Grape");
|
||||
}
|
||||
@Test
|
||||
public void whenConvertMapToString_thenConverted() {
|
||||
Map<Integer, String> users = new HashMap<>();
|
||||
users.put(1, "John Doe");
|
||||
users.put(2, "Paul Smith");
|
||||
users.put(3, "Susan Anderson");
|
||||
|
||||
@Test
|
||||
public void whenSplitCollectionHalf_thenConverted() {
|
||||
Collection<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
Collection<Integer> result1 = new ArrayList<>();
|
||||
Collection<Integer> result2 = new ArrayList<>();
|
||||
AtomicInteger count = new AtomicInteger();
|
||||
int midpoint = Math.round(numbers.size() / 2);
|
||||
|
||||
numbers.forEach(next -> {
|
||||
int index = count.getAndIncrement();
|
||||
if(index < midpoint){
|
||||
result1.add(next);
|
||||
}else{
|
||||
result2.add(next);
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue(result1.equals(Arrays.asList(1, 2, 3, 4, 5)));
|
||||
assertTrue(result2.equals(Arrays.asList(6, 7, 8, 9, 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSplitArrayByWordLength_thenConverted() {
|
||||
String[] words = new String[]{"bye", "cold", "it", "and", "my", "word"};
|
||||
Map<Integer, List<String>> result = Arrays.stream(words)
|
||||
.collect(Collectors.groupingBy(word -> word.length()));
|
||||
|
||||
assertTrue(result.get(2).equals(Arrays.asList("it", "my")));
|
||||
assertTrue(result.get(3).equals(Arrays.asList("bye", "and")));
|
||||
assertTrue(result.get(4).equals(Arrays.asList("cold", "word")));
|
||||
}
|
||||
String result = users.entrySet().stream()
|
||||
.map(entry -> entry.getKey() + " = " + entry.getValue())
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToArray_thenConverted() {
|
||||
String colors = "Red, Blue, Green, Yellow";
|
||||
String[] result = colors.split(", ");
|
||||
assertEquals(result, "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson");
|
||||
}
|
||||
|
||||
assertArrayEquals(result, new String[] { "Red", "Blue", "Green", "Yellow" });
|
||||
}
|
||||
@Test
|
||||
public void whenConvertNestedCollectionToString_thenConverted() {
|
||||
Collection<List<String>> nested = new ArrayList<>();
|
||||
nested.add(Arrays.asList("Left", "Right", "Top", "Bottom"));
|
||||
nested.add(Arrays.asList("Red", "Blue", "Green", "Yellow"));
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToCollection_thenConverted() {
|
||||
String colors = "Left, Right, Top, Bottom";
|
||||
Collection<String> result = Arrays.asList(colors.split(", "));
|
||||
String result = nested.stream()
|
||||
.map(nextList -> nextList.stream()
|
||||
.collect(Collectors.joining("-")))
|
||||
.collect(Collectors.joining("; "));
|
||||
|
||||
assertTrue(result.equals(Arrays.asList("Left", "Right", "Top", "Bottom")));
|
||||
}
|
||||
assertEquals(result, "Left-Right-Top-Bottom; Red-Blue-Green-Yellow");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToMap_thenConverted() {
|
||||
String users = "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson";
|
||||
@Test
|
||||
public void whenConvertCollectionToStringAndSkipNull_thenConverted() {
|
||||
Collection<String> fruits = Arrays.asList("Apple", "Orange", null, "Grape");
|
||||
String result = fruits.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
Map<Integer, String> result = Arrays.stream(users.split(", "))
|
||||
.map(next -> next.split(" = "))
|
||||
.collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1]));
|
||||
assertEquals(result, "Apple, Orange, Grape");
|
||||
}
|
||||
|
||||
assertEquals(result.get(1), "John Doe");
|
||||
assertEquals(result.get(2), "Paul Smith");
|
||||
assertEquals(result.get(3), "Susan Anderson");
|
||||
}
|
||||
@Test
|
||||
public void whenSplitCollectionHalf_thenConverted() {
|
||||
Collection<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
Collection<Integer> result1 = new ArrayList<>();
|
||||
Collection<Integer> result2 = new ArrayList<>();
|
||||
AtomicInteger count = new AtomicInteger();
|
||||
int midpoint = Math.round(numbers.size() / 2);
|
||||
|
||||
@Test
|
||||
public void whenConvertCollectionToStringMultipleSeparators_thenConverted() {
|
||||
String fruits = "Apple. , Orange, Grape. Lemon";
|
||||
numbers.forEach(next -> {
|
||||
int index = count.getAndIncrement();
|
||||
if (index < midpoint) {
|
||||
result1.add(next);
|
||||
} else {
|
||||
result2.add(next);
|
||||
}
|
||||
});
|
||||
|
||||
Collection<String> result = Arrays.stream(fruits.split("[,|.]"))
|
||||
.map(String::trim)
|
||||
.filter(next -> !next.isEmpty())
|
||||
.collect(Collectors.toList());
|
||||
assertTrue(result1.equals(Arrays.asList(1, 2, 3, 4, 5)));
|
||||
assertTrue(result2.equals(Arrays.asList(6, 7, 8, 9, 10)));
|
||||
}
|
||||
|
||||
assertTrue(result.equals(Arrays.asList("Apple", "Orange", "Grape", "Lemon")));
|
||||
}
|
||||
@Test
|
||||
public void whenSplitArrayByWordLength_thenConverted() {
|
||||
String[] words = new String[]{"bye", "cold", "it", "and", "my", "word"};
|
||||
Map<Integer, List<String>> result = Arrays.stream(words)
|
||||
.collect(Collectors.groupingBy(String::length));
|
||||
|
||||
assertTrue(result.get(2).equals(Arrays.asList("it", "my")));
|
||||
assertTrue(result.get(3).equals(Arrays.asList("bye", "and")));
|
||||
assertTrue(result.get(4).equals(Arrays.asList("cold", "word")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToArray_thenConverted() {
|
||||
String colors = "Red, Blue, Green, Yellow";
|
||||
String[] result = colors.split(", ");
|
||||
|
||||
assertArrayEquals(result, new String[]{"Red", "Blue", "Green", "Yellow"});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToCollection_thenConverted() {
|
||||
String colors = "Left, Right, Top, Bottom";
|
||||
Collection<String> result = Arrays.asList(colors.split(", "));
|
||||
|
||||
assertTrue(result.equals(Arrays.asList("Left", "Right", "Top", "Bottom")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToMap_thenConverted() {
|
||||
String users = "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson";
|
||||
|
||||
Map<Integer, String> result = Arrays.stream(users.split(", "))
|
||||
.map(next -> next.split(" = "))
|
||||
.collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1]));
|
||||
|
||||
assertEquals(result.get(1), "John Doe");
|
||||
assertEquals(result.get(2), "Paul Smith");
|
||||
assertEquals(result.get(3), "Susan Anderson");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertCollectionToStringMultipleSeparators_thenConverted() {
|
||||
String fruits = "Apple. , Orange, Grape. Lemon";
|
||||
|
||||
Collection<String> result = Arrays.stream(fruits.split("[,|.]"))
|
||||
.map(String::trim)
|
||||
.filter(next -> !next.isEmpty())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(result.equals(Arrays.asList("Apple", "Orange", "Grape", "Lemon")));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -463,46 +463,22 @@
|
|||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.40</mysql-connector-java.version>
|
||||
|
||||
<rsql.version>2.0.0</rsql.version>
|
||||
<querydsl.version>4.1.4</querydsl.version>
|
||||
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.7.8</jackson.version>
|
||||
<xml-apis.version>1.4.01</xml-apis.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
<rsql.version>2.1.0</rsql.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
|
||||
<xstream.version>1.4.8</xstream.version>
|
||||
<xstream.version>1.4.9</xstream.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
<httpclient.version>4.5</httpclient.version>
|
||||
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
|
||||
<!-- Maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
<apt-maven-plugin.version>1.1.3</apt-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -1,265 +0,0 @@
|
|||
package org.baeldung.client;
|
||||
|
||||
import static org.apache.commons.codec.binary.Base64.encodeBase64;
|
||||
import static org.baeldung.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
import org.baeldung.spring.ConfigTest;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
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.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
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;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class)
|
||||
@ActiveProfiles("test")
|
||||
public class RestTemplateLiveTest {
|
||||
|
||||
private RestTemplate restTemplate;
|
||||
private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/auth/foos";
|
||||
|
||||
@Before
|
||||
public void beforeTest() {
|
||||
restTemplate = new RestTemplate(getClientHttpRequestFactory());
|
||||
|
||||
ensureOneEntityExists();
|
||||
}
|
||||
|
||||
// GET
|
||||
|
||||
@Test
|
||||
public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException {
|
||||
final ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
|
||||
assertThat(response.getStatusCode(), is(HttpStatus.OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceUrl_whenSendGetForRestEntity_thenReceiveCorrectJson() 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");
|
||||
assertNotNull(name);
|
||||
|
||||
final JsonNode owner = root.path("id");
|
||||
assertThat(owner.asText(), is("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceUrl_whenSendGetForObject_thenReturnsRepoObject() {
|
||||
final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class);
|
||||
assertNotNull(foo.getName());
|
||||
assertThat(foo.getId(), is(1L));
|
||||
}
|
||||
|
||||
// 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_whenPostFor2Objects_thenNewObjectIsCreatedEachTime() {
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
|
||||
final Foo firstInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
|
||||
final Foo secondInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
|
||||
assertThat(firstInstance, notNullValue());
|
||||
assertThat(secondInstance, notNullValue());
|
||||
assertThat(firstInstance.getId(), not(secondInstance.getId()));
|
||||
}
|
||||
|
||||
// HEAD, OPTIONS
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
|
||||
final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
|
||||
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
|
||||
assertTrue(httpHeaders.get("bar").contains("baz"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() {
|
||||
final Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);
|
||||
final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE };
|
||||
assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
|
||||
}
|
||||
|
||||
// POST
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenPostResource_thenResourceIsCreated() {
|
||||
final RestTemplate template = new RestTemplate();
|
||||
|
||||
final HttpHeaders headers = prepareBasicAuthHeaders();
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
|
||||
|
||||
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"));
|
||||
}
|
||||
|
||||
// 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 void ensureOneEntityExists() {
|
||||
final Foo instance = new Foo("bar");
|
||||
instance.setId(1L);
|
||||
|
||||
try {
|
||||
restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class);
|
||||
} catch (final HttpClientErrorException ex) {
|
||||
if (ex.getStatusCode() == HttpStatus.NOT_FOUND) {
|
||||
restTemplate.postForEntity(fooResourceUrl, instance, Foo.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ClientHttpRequestFactory getClientHttpRequestFactory() {
|
||||
final int timeout = 5;
|
||||
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
||||
|
||||
final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
|
||||
credentialsProvider.setCredentials(new AuthScope("localhost", APPLICATION_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass"));
|
||||
|
||||
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).setDefaultCredentialsProvider(credentialsProvider).build();
|
||||
|
||||
return new HttpComponentsClientHttpRequestFactory(client);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -1,6 +1,5 @@
|
|||
package org.baeldung.web;
|
||||
|
||||
import org.baeldung.client.RestTemplateLiveTest;
|
||||
import org.baeldung.persistence.query.JPASpecificationLiveTest;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Suite;
|
||||
|
@ -12,7 +11,6 @@ import org.junit.runners.Suite;
|
|||
,FooDiscoverabilityLiveTest.class
|
||||
,FooLiveTest.class
|
||||
,MyUserLiveTest.class
|
||||
,RestTemplateLiveTest.class
|
||||
}) //
|
||||
public class LiveTestSuite {
|
||||
|
||||
|
|
|
@ -16,7 +16,7 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.0.RELEASE</version>
|
||||
<version>1.4.2.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
|
|
|
@ -11,7 +11,7 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.0.RELEASE</version>
|
||||
<version>1.4.2.RELEASE</version>
|
||||
<relativePath/>
|
||||
<!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
@ -61,7 +61,6 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
|
@ -70,7 +69,6 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*ControllerTest.java</exclude>
|
||||
|
@ -79,7 +77,4 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<properties>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -9,7 +9,7 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.0.RELEASE</version>
|
||||
<version>1.4.2.RELEASE</version>
|
||||
<relativePath></relativePath>
|
||||
</parent>
|
||||
|
||||
|
|
|
@ -8,26 +8,34 @@
|
|||
<artifactId>spel</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<hamcrest.version>1.3</hamcrest.version>
|
||||
<springframework.version>4.3.4.RELEASE</springframework.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<version>${junit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<version>1.3</version>
|
||||
<version>${hamcrest.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>4.0.6.RELEASE</version>
|
||||
<version>${springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>4.0.6.RELEASE</version>
|
||||
<version>${springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
@ -35,7 +43,7 @@
|
|||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<debug>true</debug>
|
||||
<optimize>true</optimize>
|
||||
|
@ -50,7 +58,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.19.1</version>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
|
|
Loading…
Reference in New Issue