BAEL-2492 Rename WireMockScenario test class
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
trait AnimalTrait {
|
||||
|
||||
String basicBehavior() {
|
||||
return "Animalistic!!"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
class Dog implements WalkingTrait, SpeakingTrait {
|
||||
|
||||
String speakAndWalk() {
|
||||
WalkingTrait.super.speakAndWalk()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
class Employee implements UserTrait {
|
||||
|
||||
String name() {
|
||||
return 'Bob'
|
||||
}
|
||||
|
||||
String lastName() {
|
||||
return "Marley"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
interface Human {
|
||||
|
||||
String lastName()
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
trait SpeakingTrait {
|
||||
|
||||
String basicAbility() {
|
||||
return "Speaking!!"
|
||||
}
|
||||
|
||||
String speakAndWalk() {
|
||||
return "Speak and walk!!"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
trait UserTrait implements Human {
|
||||
|
||||
String sayHello() {
|
||||
return "Hello!"
|
||||
}
|
||||
|
||||
abstract String name()
|
||||
|
||||
String showName() {
|
||||
return "Hello, ${name()}!"
|
||||
}
|
||||
|
||||
private String greetingMessage() {
|
||||
return 'Hello, from a private method!'
|
||||
}
|
||||
|
||||
String greet() {
|
||||
def msg = greetingMessage()
|
||||
println msg
|
||||
msg
|
||||
}
|
||||
|
||||
def whoAmI() {
|
||||
return this
|
||||
}
|
||||
|
||||
String showLastName() {
|
||||
return "Hello, ${lastName()}!"
|
||||
}
|
||||
|
||||
String email
|
||||
String address
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
trait WalkingTrait {
|
||||
|
||||
String basicAbility() {
|
||||
return "Walking!!"
|
||||
}
|
||||
|
||||
String speakAndWalk() {
|
||||
return "Walk and speak!!"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class CharacterInGroovy {
|
||||
|
||||
@Test
|
||||
void 'character'() {
|
||||
char a = 'A' as char
|
||||
char b = 'B' as char
|
||||
char c = (char) 'C'
|
||||
|
||||
Assert.assertTrue(a instanceof Character)
|
||||
Assert.assertTrue(b instanceof Character)
|
||||
Assert.assertTrue(c instanceof Character)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
class DollarSlashyString {
|
||||
|
||||
@Test
|
||||
void 'dollar slashy string'() {
|
||||
def name = "John"
|
||||
|
||||
def dollarSlashy = $/
|
||||
Hello $name!,
|
||||
|
||||
I can show you $ sign or escaped dollar sign: $$
|
||||
Both slashes works: \ or /, but we can still escape it: $/
|
||||
|
||||
We have to escape opening and closing delimiter:
|
||||
- $$$/
|
||||
- $/$$
|
||||
/$
|
||||
|
||||
print(dollarSlashy)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class DoubleQuotedString {
|
||||
|
||||
@Test
|
||||
void 'escape double quoted string'() {
|
||||
def example = "Hello \"world\"!"
|
||||
|
||||
println(example)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'String ang GString'() {
|
||||
def string = "example"
|
||||
def stringWithExpression = "example${2}"
|
||||
|
||||
Assert.assertTrue(string instanceof String)
|
||||
Assert.assertTrue(stringWithExpression instanceof GString)
|
||||
Assert.assertTrue(stringWithExpression.toString() instanceof String)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'placeholder with variable'() {
|
||||
def name = "John"
|
||||
def helloName = "Hello $name!".toString()
|
||||
|
||||
Assert.assertEquals("Hello John!", helloName)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'placeholder with expression'() {
|
||||
def result = "result is ${2 * 2}".toString()
|
||||
|
||||
Assert.assertEquals("result is 4", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'placeholder with dotted access'() {
|
||||
def person = [name: 'John']
|
||||
|
||||
def myNameIs = "I'm $person.name, and you?".toString()
|
||||
|
||||
Assert.assertEquals("I'm John, and you?", myNameIs)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'placeholder with method call'() {
|
||||
def name = 'John'
|
||||
|
||||
def result = "Uppercase name: ${name.toUpperCase()}".toString()
|
||||
|
||||
Assert.assertEquals("Uppercase name: JOHN", result)
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void 'GString and String hashcode'() {
|
||||
def string = "2+2 is 4"
|
||||
def gstring = "2+2 is ${4}"
|
||||
|
||||
Assert.assertTrue(string.hashCode() != gstring.hashCode())
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class SingleQuotedString {
|
||||
|
||||
@Test
|
||||
void 'single quoted string'() {
|
||||
def example = 'Hello world'
|
||||
|
||||
Assert.assertEquals('Hello world!', 'Hello' + ' world!')
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class SlashyString {
|
||||
|
||||
@Test
|
||||
void 'slashy string'() {
|
||||
def pattern = /.*foobar.*\/hello.*/
|
||||
|
||||
Assert.assertTrue("I'm matching foobar /hello regexp pattern".matches(pattern))
|
||||
}
|
||||
|
||||
void 'wont compile'() {
|
||||
// if ('' == //) {
|
||||
// println("I can't compile")
|
||||
// }
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'interpolate and multiline'() {
|
||||
def name = 'John'
|
||||
|
||||
def example = /
|
||||
Hello $name
|
||||
second line
|
||||
/
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class Strings {
|
||||
|
||||
@Test
|
||||
void 'string interpolation '() {
|
||||
def name = "Kacper"
|
||||
|
||||
def result = "Hello ${name}!"
|
||||
|
||||
Assert.assertEquals("Hello Kacper!", result.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'string concatenation'() {
|
||||
def first = "first"
|
||||
def second = "second"
|
||||
|
||||
def concatenation = first + second
|
||||
|
||||
Assert.assertEquals("firstsecond", concatenation)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
class TripleDoubleQuotedString {
|
||||
|
||||
@Test
|
||||
void 'triple-quoted strings with interpolation'() {
|
||||
def name = "John"
|
||||
|
||||
def multiLine = """
|
||||
I'm $name.
|
||||
"This is quotation"
|
||||
"""
|
||||
|
||||
println(multiLine)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class TripleSingleQuotedString {
|
||||
|
||||
def 'formatted json'() {
|
||||
def jsonContent = '''
|
||||
{
|
||||
"name": "John",
|
||||
"age": 20,
|
||||
"birthDate": null
|
||||
}
|
||||
'''
|
||||
}
|
||||
|
||||
def 'triple single quoted'() {
|
||||
def triple = '''im triple single quoted string'''
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'triple single quoted with multiline string'() {
|
||||
def triple = '''
|
||||
firstline
|
||||
secondline
|
||||
'''
|
||||
|
||||
Assert.assertTrue(triple.startsWith("\n"))
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'triple single quoted with multiline string with stripIndent() and removing newline characters'() {
|
||||
def triple = '''\
|
||||
firstline
|
||||
secondline'''.stripIndent()
|
||||
|
||||
Assert.assertEquals("firstline\nsecondline", triple)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'triple single quoted with multiline string with last line with only whitespaces'() {
|
||||
def triple = '''\
|
||||
firstline
|
||||
secondline\
|
||||
'''.stripIndent()
|
||||
|
||||
println(triple)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'triple single quoted with multiline string with stripMargin(Character) and removing newline characters'() {
|
||||
def triple = '''\
|
||||
|firstline
|
||||
|secondline'''.stripMargin()
|
||||
|
||||
println(triple)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'striple single quoted with special characters'() {
|
||||
def specialCharacters = '''hello \'John\'. This is backslash - \\. \nSecond line starts here'''
|
||||
|
||||
println(specialCharacters)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
class TraitsUnitTest extends Specification {
|
||||
|
||||
Employee employee
|
||||
Dog dog
|
||||
|
||||
void setup () {
|
||||
employee = new Employee()
|
||||
dog = new Dog()
|
||||
}
|
||||
|
||||
def 'Should return msg string when using Employee.sayHello method provided by UserTrait' () {
|
||||
when:
|
||||
def msg = employee.sayHello()
|
||||
then:
|
||||
msg
|
||||
msg instanceof String
|
||||
assert msg == "Hello!"
|
||||
}
|
||||
|
||||
def 'Should return displayMsg string when using Employee.showName method' () {
|
||||
when:
|
||||
def displayMsg = employee.showName()
|
||||
then:
|
||||
displayMsg
|
||||
displayMsg instanceof String
|
||||
assert displayMsg == "Hello, Bob!"
|
||||
}
|
||||
|
||||
def 'Should return greetMsg string when using Employee.greet method' () {
|
||||
when:
|
||||
def greetMsg = employee.greet()
|
||||
then:
|
||||
greetMsg
|
||||
greetMsg instanceof String
|
||||
assert greetMsg == "Hello, from a private method!"
|
||||
}
|
||||
|
||||
def 'Should return MissingMethodException when using Employee.greetingMessage method' () {
|
||||
when:
|
||||
def exception
|
||||
try {
|
||||
employee.greetingMessage()
|
||||
}catch(Exception e) {
|
||||
exception = e
|
||||
}
|
||||
|
||||
then:
|
||||
exception
|
||||
exception instanceof groovy.lang.MissingMethodException
|
||||
assert exception.message == "No signature of method: com.baeldung.traits.Employee.greetingMessage()"+
|
||||
" is applicable for argument types: () values: []"
|
||||
}
|
||||
|
||||
def 'Should return employee instance when using Employee.whoAmI method' () {
|
||||
when:
|
||||
def emp = employee.whoAmI()
|
||||
then:
|
||||
emp
|
||||
emp instanceof Employee
|
||||
assert emp.is(employee)
|
||||
}
|
||||
|
||||
def 'Should display lastName when using Employee.showLastName method' () {
|
||||
when:
|
||||
def lastNameMsg = employee.showLastName()
|
||||
then:
|
||||
lastNameMsg
|
||||
lastNameMsg instanceof String
|
||||
assert lastNameMsg == "Hello, Marley!"
|
||||
}
|
||||
|
||||
def 'Should be able to define properties of UserTrait in Employee instance' () {
|
||||
when:
|
||||
employee = new Employee(email: "[email protected]", address: "baeldung.com")
|
||||
then:
|
||||
employee
|
||||
employee instanceof Employee
|
||||
assert employee.email == "[email protected]"
|
||||
assert employee.address == "baeldung.com"
|
||||
}
|
||||
|
||||
def 'Should execute basicAbility method from SpeakingTrait and return msg string' () {
|
||||
when:
|
||||
def speakMsg = dog.basicAbility()
|
||||
then:
|
||||
speakMsg
|
||||
speakMsg instanceof String
|
||||
assert speakMsg == "Speaking!!"
|
||||
}
|
||||
|
||||
def 'Should verify multiple inheritance with traits and execute overridden traits method' () {
|
||||
when:
|
||||
def walkSpeakMsg = dog.speakAndWalk()
|
||||
println walkSpeakMsg
|
||||
then:
|
||||
walkSpeakMsg
|
||||
walkSpeakMsg instanceof String
|
||||
assert walkSpeakMsg == "Walk and speak!!"
|
||||
}
|
||||
|
||||
def 'Should implement AnimalTrait at runtime and access basicBehavior method' () {
|
||||
when:
|
||||
def dogInstance = new Dog() as AnimalTrait
|
||||
def basicBehaviorMsg = dogInstance.basicBehavior()
|
||||
then:
|
||||
basicBehaviorMsg
|
||||
basicBehaviorMsg instanceof String
|
||||
assert basicBehaviorMsg == "Animalistic!!"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/*
|
||||
* To change this license header, choose License Headers in Project Properties.
|
||||
* To change this template file, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
package com.baeldung.java11.httpclient;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpClient.Version;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpRequest.BodyPublishers;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
import java.net.http.HttpResponse.PushPromiseHandler;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class HttpClientExample {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
httpGetRequest();
|
||||
httpPostRequest();
|
||||
asynchronousGetRequest();
|
||||
asynchronousMultipleRequests();
|
||||
pushRequest();
|
||||
}
|
||||
|
||||
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.uri(URI.create("http://jsonplaceholder.typicode.com/posts/1"))
|
||||
.headers("Accept-Enconding", "gzip, deflate")
|
||||
.build();
|
||||
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
|
||||
|
||||
String responseBody = response.body();
|
||||
int responseStatusCode = response.statusCode();
|
||||
|
||||
System.out.println("httpGetRequest: " + responseBody);
|
||||
System.out.println("httpGetRequest status code: " + responseStatusCode);
|
||||
}
|
||||
|
||||
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpClient client = HttpClient.newBuilder()
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.build();
|
||||
HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.POST(BodyPublishers.ofString("Sample Post Request"))
|
||||
.build();
|
||||
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
|
||||
String responseBody = response.body();
|
||||
System.out.println("httpPostRequest : " + responseBody);
|
||||
}
|
||||
|
||||
public static void asynchronousGetRequest() throws URISyntaxException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
|
||||
HttpRequest request = HttpRequest.newBuilder(httpURI)
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.build();
|
||||
CompletableFuture<Void> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenAccept(resp -> {
|
||||
System.out.println("Got pushed response " + resp.uri());
|
||||
System.out.println("Response statuscode: " + resp.statusCode());
|
||||
System.out.println("Response body: " + resp.body());
|
||||
});
|
||||
System.out.println("futureResponse" + futureResponse);
|
||||
|
||||
}
|
||||
|
||||
public static void asynchronousMultipleRequests() throws URISyntaxException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
List<URI> uris = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
|
||||
List<HttpRequest> requests = uris.stream()
|
||||
.map(HttpRequest::newBuilder)
|
||||
.map(reqBuilder -> reqBuilder.build())
|
||||
.collect(Collectors.toList());
|
||||
System.out.println("Got pushed response1 " + requests);
|
||||
CompletableFuture.allOf(requests.stream()
|
||||
.map(request -> client.sendAsync(request, BodyHandlers.ofString()))
|
||||
.toArray(CompletableFuture<?>[]::new))
|
||||
.thenAccept(System.out::println)
|
||||
.join();
|
||||
}
|
||||
|
||||
public static void pushRequest() throws URISyntaxException, InterruptedException {
|
||||
System.out.println("Running HTTP/2 Server Push example...");
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.version(Version.HTTP_2)
|
||||
.build();
|
||||
|
||||
HttpRequest pageRequest = HttpRequest.newBuilder()
|
||||
.uri(URI.create("https://http2.golang.org/serverpush"))
|
||||
.build();
|
||||
|
||||
// Interface HttpResponse.PushPromiseHandler<T>
|
||||
// void applyPushPromise(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function<HttpResponse.BodyHandler<T>,CompletableFuture<HttpResponse<T>>> acceptor)
|
||||
httpClient.sendAsync(pageRequest, BodyHandlers.ofString(), pushPromiseHandler())
|
||||
.thenAccept(pageResponse -> {
|
||||
System.out.println("Page response status code: " + pageResponse.statusCode());
|
||||
System.out.println("Page response headers: " + pageResponse.headers());
|
||||
String responseBody = pageResponse.body();
|
||||
System.out.println(responseBody);
|
||||
}).join();
|
||||
|
||||
Thread.sleep(1000); // waiting for full response
|
||||
}
|
||||
|
||||
private static PushPromiseHandler<String> pushPromiseHandler() {
|
||||
return (HttpRequest initiatingRequest,
|
||||
HttpRequest pushPromiseRequest,
|
||||
Function<HttpResponse.BodyHandler<String>,
|
||||
CompletableFuture<HttpResponse<String>>> acceptor) -> {
|
||||
acceptor.apply(BodyHandlers.ofString())
|
||||
.thenAccept(resp -> {
|
||||
System.out.println(" Pushed response: " + resp.uri() + ", headers: " + resp.headers());
|
||||
});
|
||||
System.out.println("Promise request: " + pushPromiseRequest.uri());
|
||||
System.out.println("Promise request: " + pushPromiseRequest.headers());
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package com.baeldung.java11.httpclient.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Authenticator;
|
||||
import java.net.CookieManager;
|
||||
import java.net.CookiePolicy;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.PasswordAuthentication;
|
||||
import java.net.ProxySelector;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class HttpClientTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("Sample body"))
|
||||
.build();
|
||||
|
||||
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.proxy(ProxySelector.getDefault())
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
|
||||
assertThat(response.body(), containsString("https://stackoverflow.com/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.ALWAYS)
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.request()
|
||||
.uri()
|
||||
.toString(), equalTo("https://stackoverflow.com/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/basic-auth"))
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.authenticator(new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication("postman", "password".toCharArray());
|
||||
}
|
||||
})
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("Sample body"))
|
||||
.build();
|
||||
CompletableFuture<HttpResponse<String>> response = HttpClient.newBuilder()
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response1 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response2 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response3 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
CompletableFuture.allOf(response1, response2, response3)
|
||||
.join();
|
||||
|
||||
assertThat(response1.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response2.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response3.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
|
||||
.build();
|
||||
|
||||
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertTrue(httpClient.cookieHandler()
|
||||
.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
|
||||
.build();
|
||||
|
||||
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertTrue(httpClient.cookieHandler()
|
||||
.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
|
||||
List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));
|
||||
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
List<CompletableFuture<String>> futures = targets.stream()
|
||||
.map(target -> client.sendAsync(HttpRequest.newBuilder(target)
|
||||
.GET()
|
||||
.build(), HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(response -> response.body()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
|
||||
.join();
|
||||
|
||||
if (futures.get(0)
|
||||
.get()
|
||||
.contains("foo1")) {
|
||||
assertThat(futures.get(0)
|
||||
.get(), containsString("bar1"));
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar2"));
|
||||
} else {
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar2"));
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar1"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void completeExceptionallyExample() {
|
||||
CompletableFuture<String> cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase,
|
||||
CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
|
||||
CompletableFuture<String> exceptionHandler = cf.handle((s, th) -> { return (th != null) ? "message upon cancel" : ""; });
|
||||
cf.completeExceptionally(new RuntimeException("completed exceptionally"));
|
||||
assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally());
|
||||
try {
|
||||
cf.join();
|
||||
fail("Should have thrown an exception");
|
||||
} catch (CompletionException ex) { // just for testing
|
||||
assertEquals("completed exceptionally", ex.getCause().getMessage());
|
||||
}
|
||||
|
||||
assertEquals("message upon cancel", exceptionHandler.join());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.baeldung.java11.httpclient.test;
|
||||
|
||||
import static java.time.temporal.ChronoUnit.SECONDS;
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class HttpRequestTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.headers("key1", "value1", "key2", "value2")
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.timeout(Duration.of(10, SECONDS))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.POST(HttpRequest.BodyPublishers.noBody())
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("Sample request body"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
byte[] sampleData = "Sample request body".getBytes();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(sampleData)))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
byte[] sampleData = "Sample request body".getBytes();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(sampleData))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofFile(Paths.get("src/test/resources/sample.txt")))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample file content"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.java11.httpclient.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class HttpResponseTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertNotNull(response.body());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(request.uri()
|
||||
.toString(), equalTo("http://stackoverflow.com"));
|
||||
assertThat(response.uri()
|
||||
.toString(), equalTo("https://stackoverflow.com/"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
import static java.lang.annotation.ElementType.METHOD;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RUNTIME)
|
||||
@Target(METHOD)
|
||||
public @interface Init {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
import static java.lang.annotation.ElementType.FIELD;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RUNTIME)
|
||||
@Target({ FIELD })
|
||||
public @interface JsonElement {
|
||||
public String key() default "";
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
import static java.lang.annotation.ElementType.TYPE;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RUNTIME)
|
||||
@Target(TYPE)
|
||||
public @interface JsonSerializable {
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
public class JsonSerializationException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public JsonSerializationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ObjectToJsonConverter {
|
||||
public String convertToJson(Object object) throws JsonSerializationException {
|
||||
try {
|
||||
|
||||
checkIfSerializable(object);
|
||||
initializeObject(object);
|
||||
return getJsonString(object);
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new JsonSerializationException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void checkIfSerializable(Object object) {
|
||||
if (Objects.isNull(object)) {
|
||||
throw new JsonSerializationException("Can't serialize a null object");
|
||||
}
|
||||
|
||||
Class<?> clazz = object.getClass();
|
||||
if (!clazz.isAnnotationPresent(JsonSerializable.class)) {
|
||||
throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable");
|
||||
}
|
||||
}
|
||||
|
||||
private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
|
||||
Class<?> clazz = object.getClass();
|
||||
for (Method method : clazz.getDeclaredMethods()) {
|
||||
if (method.isAnnotationPresent(Init.class)) {
|
||||
method.setAccessible(true);
|
||||
method.invoke(object);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
|
||||
Class<?> clazz = object.getClass();
|
||||
Map<String, String> jsonElementsMap = new HashMap<>();
|
||||
for (Field field : clazz.getDeclaredFields()) {
|
||||
field.setAccessible(true);
|
||||
if (field.isAnnotationPresent(JsonElement.class)) {
|
||||
jsonElementsMap.put(getKey(field), (String) field.get(object));
|
||||
}
|
||||
}
|
||||
|
||||
String jsonString = jsonElementsMap.entrySet()
|
||||
.stream()
|
||||
.map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
|
||||
.collect(Collectors.joining(","));
|
||||
return "{" + jsonString + "}";
|
||||
}
|
||||
|
||||
private String getKey(Field field) {
|
||||
String value = field.getAnnotation(JsonElement.class)
|
||||
.key();
|
||||
return value.isEmpty() ? field.getName() : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
@JsonSerializable
|
||||
public class Person {
|
||||
@JsonElement
|
||||
private String firstName;
|
||||
@JsonElement
|
||||
private String lastName;
|
||||
@JsonElement(key = "personAge")
|
||||
private String age;
|
||||
|
||||
private String address;
|
||||
|
||||
public Person(String firstName, String lastName) {
|
||||
super();
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Person(String firstName, String lastName, String age) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Init
|
||||
private void initNames() {
|
||||
this.firstName = this.firstName.substring(0, 1)
|
||||
.toUpperCase() + this.firstName.substring(1);
|
||||
this.lastName = this.lastName.substring(0, 1)
|
||||
.toUpperCase() + this.lastName.substring(1);
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(String age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -85,10 +85,16 @@ public class Java8CollectorsUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||
public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception {
|
||||
final Map<String, Integer> result = listWithDuplicates.stream().collect(
|
||||
toMap(
|
||||
Function.identity(),
|
||||
String::length,
|
||||
(item, identicalItem) -> item
|
||||
)
|
||||
);
|
||||
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("c", 1).containsEntry("d", 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class JsonSerializerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenObjectNotSerializedThenExceptionThrown() throws JsonSerializationException {
|
||||
Object object = new Object();
|
||||
ObjectToJsonConverter serializer = new ObjectToJsonConverter();
|
||||
assertThrows(JsonSerializationException.class, () -> {
|
||||
serializer.convertToJson(object);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObjectSerializedThenTrueReturned() throws JsonSerializationException {
|
||||
Person person = new Person("soufiane", "cheouati", "34");
|
||||
ObjectToJsonConverter serializer = new ObjectToJsonConverter();
|
||||
String jsonString = serializer.convertToJson(person);
|
||||
assertEquals("{\"personAge\":\"34\",\"firstName\":\"Soufiane\",\"lastName\":\"Cheouati\"}", jsonString);
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.allequalelements;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import org.apache.commons.collections4.IterableUtils;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.collect.Iterables;
|
||||
|
||||
public class VerifyAllEqualListElements {
|
||||
|
||||
public boolean verifyAllEqualUsingALoop(List<String> list) {
|
||||
for (String s : list) {
|
||||
if (!s.equals(list.get(0)))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean verifyAllEqualUsingHashSet(List<String> list) {
|
||||
return new HashSet<String>(list).size() <= 1;
|
||||
}
|
||||
|
||||
public boolean verifyAllEqualUsingFrequency(List<String> list) {
|
||||
return list.isEmpty() || Collections.frequency(list, list.get(0)) == list.size();
|
||||
}
|
||||
|
||||
public boolean verifyAllEqualUsingStream(List<String> list) {
|
||||
return list.stream()
|
||||
.distinct()
|
||||
.count() <= 1;
|
||||
}
|
||||
|
||||
public boolean verifyAllEqualAnotherUsingStream(List<String> list) {
|
||||
return list.isEmpty() || list.stream()
|
||||
.allMatch(list.get(0)::equals);
|
||||
}
|
||||
|
||||
public boolean verifyAllEqualUsingGuava(List<String> list) {
|
||||
return Iterables.all(list, new Predicate<String>() {
|
||||
public boolean apply(String s) {
|
||||
return s.equals(list.get(0));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public boolean verifyAllEqualUsingApacheCommon(List<String> list) {
|
||||
return IterableUtils.matchesAll(list, new org.apache.commons.collections4.Predicate<String>() {
|
||||
public boolean evaluate(String s) {
|
||||
return s.equals(list.get(0));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package com.baeldung.allequalelements;
|
||||
|
||||
import org.junit.Test;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class VerifyAllEqualListElementsUnitTest {
|
||||
|
||||
private static List<String> notAllEqualList = new ArrayList<>();
|
||||
|
||||
private static List<String> emptyList = new ArrayList<>();
|
||||
|
||||
private static List<String> allEqualList = new ArrayList<>();
|
||||
|
||||
static {
|
||||
notAllEqualList = Arrays.asList("Jack", "James", "Sam", "James");
|
||||
emptyList = Arrays.asList();
|
||||
allEqualList = Arrays.asList("Jack", "Jack", "Jack", "Jack");
|
||||
}
|
||||
|
||||
private static VerifyAllEqualListElements verifyAllEqualListElements = new VerifyAllEqualListElements();
|
||||
|
||||
@Test
|
||||
public void givenNotAllEqualList_whenUsingALoop_thenReturnFalse() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(notAllEqualList);
|
||||
|
||||
assertFalse(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenUsingALoop_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(emptyList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllEqualList_whenUsingALoop_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(allEqualList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNotAllEqualList_whenUsingHashSet_thenReturnFalse() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(notAllEqualList);
|
||||
|
||||
assertFalse(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenUsingHashSet_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(emptyList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllEqualList_whenUsingHashSet_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(allEqualList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNotAllEqualList_whenUsingFrequency_thenReturnFalse() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(notAllEqualList);
|
||||
|
||||
assertFalse(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenUsingFrequency_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(emptyList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllEqualList_whenUsingFrequency_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(allEqualList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNotAllEqualList_whenUsingStream_thenReturnFalse() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(notAllEqualList);
|
||||
|
||||
assertFalse(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenUsingStream_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(emptyList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllEqualList_whenUsingStream_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(allEqualList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNotAllEqualList_whenUsingAnotherStream_thenReturnFalse() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(notAllEqualList);
|
||||
|
||||
assertFalse(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenUsingAnotherStream_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(emptyList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllEqualList_whenUsingAnotherStream_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(allEqualList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNotAllEqualList_whenUsingGuava_thenReturnFalse() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(notAllEqualList);
|
||||
|
||||
assertFalse(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenUsingGuava_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(emptyList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllEqualList_whenUsingGuava_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(allEqualList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNotAllEqualList_whenUsingApacheCommon_thenReturnFalse() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(notAllEqualList);
|
||||
|
||||
assertFalse(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenUsingApacheCommon_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(emptyList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllEqualList_whenUsingApacheCommon_thenReturnTrue() {
|
||||
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(allEqualList);
|
||||
|
||||
assertTrue(allEqual);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user