Merge pull request #19 from eugenp/master

update from eugenp/master
This commit is contained in:
pandachris 2019-02-13 21:50:50 +07:00 committed by GitHub
commit 8d6a3be475
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
58 changed files with 2248 additions and 467 deletions

View File

@ -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)
}
}

View File

@ -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)
}
}

View File

@ -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())
}
}

View File

@ -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!')
}
}

View File

@ -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
/
}
}

View File

@ -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)
}
}

View File

@ -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)
}
}

View File

@ -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)
}
}

View File

@ -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());
};
}
}

View File

@ -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());
}
}

View File

@ -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"));
}
}

View File

@ -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/"));
}
}

14
core-kotlin-2/.gitignore vendored Normal file
View File

@ -0,0 +1,14 @@
/bin/
#ignore gradle
.gradle/
#ignore build and generated files
build/
node/
out/
#ignore installed node modules and package lock file
node_modules/
package-lock.json

1
core-kotlin-2/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -0,0 +1,48 @@
group 'com.baeldung.ktor'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.2.41'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName = 'APIServer.kt'
sourceCompatibility = 1.8
compileKotlin { kotlinOptions.jvmTarget = "1.8" }
compileTestKotlin { kotlinOptions.jvmTarget = "1.8" }
kotlin { experimental { coroutines "enable" } }
repositories {
mavenCentral()
jcenter()
maven { url "https://dl.bintray.com/kotlin/ktor" }
}
sourceSets {
main{
kotlin{
srcDirs 'com/baeldung/ktor'
}
}
}
dependencies {
compile "ch.qos.logback:logback-classic:1.2.1"
testCompile group: 'junit', name: 'junit', version: '4.12'
}

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip

172
core-kotlin-2/gradlew vendored Normal file
View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
core-kotlin-2/gradlew.bat vendored Normal file
View File

@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

16
core-kotlin-2/pom.xml Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-kotlin-2</artifactId>
<name>core-kotlin-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-kotlin</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../parent-kotlin</relativePath>
</parent>
</project>

View File

@ -0,0 +1,11 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>

View File

@ -0,0 +1,2 @@
rootProject.name = 'KtorWithKotlin'

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,5 @@
Hello to Kotlin. Its:
1. Concise
2. Safe
3. Interoperable
4. Tool-friendly

View File

@ -0,0 +1,2 @@
Kotlin
Concise, Safe, Interoperable, Tool-friendly

View File

@ -0,0 +1,10 @@
package com.baeldung.static
class ConsoleUtils {
companion object {
@JvmStatic
fun debug(debugMessage : String) {
println("[DEBUG] $debugMessage")
}
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.static
fun debug(debugMessage : String) {
println("[DEBUG] $debugMessage")
}

View File

@ -0,0 +1,10 @@
package com.baeldung.static
import org.junit.Test
class ConsoleUtilsUnitTest {
@Test
fun givenAStaticMethod_whenCalled_thenNoErrorIsThrown() {
ConsoleUtils.debug("test message")
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.static
import org.junit.Test
class LoggingUtilsUnitTest {
@Test
fun givenAPackageMethod_whenCalled_thenNoErrorIsThrown() {
debug("test message")
}
}

View File

@ -22,107 +22,122 @@ public class MultiValuedMapUnitTest {
public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutMethod_thenReturningAllValues() { public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value1"); map.put("fruits", "apple");
map.put("key", "value2"); map.put("fruits", "orange");
map.put("key", "value2");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple", "orange");
assertThat((Collection<String>) map.get("key")).containsExactly("value1", "value2", "value2");
} }
@Test @Test
public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutAllMethod_thenReturningAllValues() { public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutAllMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.putAll("key", Arrays.asList("value1", "value2", "value2")); map.putAll("vehicles", Arrays.asList("car", "bike"));
assertThat((Collection<String>) map.get("vehicles")).containsExactly("car", "bike");
assertThat((Collection<String>) map.get("key")).containsExactly("value1", "value2", "value2");
} }
@Test @Test
public void givenMultiValuesMap_whenGettingValueUsingGetMethod_thenReturningValue() { public void givenMultiValuesMap_whenGettingValueUsingGetMethod_thenReturningValue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
assertThat((Collection<String>) map.get("key")).containsExactly("value"); map.put("fruits", "apple");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple");
} }
@Test @Test
public void givenMultiValuesMap_whenUsingEntriesMethod_thenReturningMappings() { public void givenMultiValuesMap_whenUsingEntriesMethod_thenReturningMappings() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value1"); map.put("fruits", "apple");
map.put("key", "value2"); map.put("fruits", "orange");
Collection<Entry<String, String>> entries = (Collection<Entry<String, String>>) map.entries(); Collection<Entry<String, String>> entries = (Collection<Entry<String, String>>) map.entries();
for(Map.Entry<String,String> entry : entries) { for(Map.Entry<String,String> entry : entries) {
assertThat(entry.getKey()).contains("key"); assertThat(entry.getKey()).contains("fruits");
assertTrue(entry.getValue().equals("value1") || entry.getValue().equals("value2") ); assertTrue(entry.getValue().equals("apple") || entry.getValue().equals("orange") );
} }
} }
@Test @Test
public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() { public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.keys())).contains("key", "key1", "key2"); map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.keys())).contains("fruits", "vehicles");
} }
@Test @Test
public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() { public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat((Collection<String>) map.keySet()).contains("key", "key1", "key2"); map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat((Collection<String>) map.keySet()).contains("fruits", "vehicles");
} }
@Test @Test
public void givenMultiValuesMap_whenUsingValuesMethod_thenReturningAllValues() { public void givenMultiValuesMap_whenUsingValuesMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2"); map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
} }
@Test @Test
public void givenMultiValuesMap_whenUsingRemoveMethod_thenReturningUpdatedMap() { public void givenMultiValuesMap_whenUsingRemoveMethod_thenReturningUpdatedMap() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2");
map.remove("key"); map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
map.remove("fruits");
assertThat(((Collection<String>) map.values())).contains("car", "bike");
assertThat(((Collection<String>) map.values())).contains("value1", "value2");
} }
@Test @Test
public void givenMultiValuesMap_whenUsingRemoveMappingMethod_thenReturningUpdatedMapAfterMappingRemoved() { public void givenMultiValuesMap_whenUsingRemoveMappingMethod_thenReturningUpdatedMapAfterMappingRemoved() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2");
map.removeMapping("key", "value"); map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
assertThat(((Collection<String>) map.values())).contains("value1", "value2"); map.removeMapping("fruits", "apple");
assertThat(((Collection<String>) map.values())).contains("orange", "car", "bike");
} }
@Test @Test
public void givenMultiValuesMap_whenUsingClearMethod_thenReturningEmptyMap() { public void givenMultiValuesMap_whenUsingClearMethod_thenReturningEmptyMap() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value"); map.put("fruits", "apple");
map.put("key1", "value1"); map.put("fruits", "orange");
map.put("key2", "value2"); map.put("vehicles", "car");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2"); map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
map.clear(); map.clear();
@ -132,29 +147,32 @@ public class MultiValuedMapUnitTest {
@Test @Test
public void givenMultiValuesMap_whenUsingContainsKeyMethod_thenReturningTrue() { public void givenMultiValuesMap_whenUsingContainsKeyMethod_thenReturningTrue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value"); map.put("fruits", "apple");
map.put("key1", "value1"); map.put("fruits", "orange");
map.put("key2", "value2"); map.put("vehicles", "car");
map.put("vehicles", "bike");
assertTrue(map.containsKey("key")); assertTrue(map.containsKey("fruits"));
} }
@Test @Test
public void givenMultiValuesMap_whenUsingContainsValueMethod_thenReturningTrue() { public void givenMultiValuesMap_whenUsingContainsValueMethod_thenReturningTrue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value"); map.put("fruits", "apple");
map.put("key1", "value1"); map.put("fruits", "orange");
map.put("key2", "value2"); map.put("vehicles", "car");
map.put("vehicles", "bike");
assertTrue(map.containsValue("value")); assertTrue(map.containsValue("orange"));
} }
@Test @Test
public void givenMultiValuesMap_whenUsingIsEmptyMethod_thenReturningFalse() { public void givenMultiValuesMap_whenUsingIsEmptyMethod_thenReturningFalse() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value"); map.put("fruits", "apple");
map.put("key1", "value1"); map.put("fruits", "orange");
map.put("key2", "value2"); map.put("vehicles", "car");
map.put("vehicles", "bike");
assertFalse(map.isEmpty()); assertFalse(map.isEmpty());
} }
@ -162,42 +180,42 @@ public class MultiValuedMapUnitTest {
@Test @Test
public void givenMultiValuesMap_whenUsingSizeMethod_thenReturningElementCount() { public void givenMultiValuesMap_whenUsingSizeMethod_thenReturningElementCount() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value"); map.put("fruits", "apple");
map.put("key1", "value1"); map.put("fruits", "orange");
map.put("key2", "value2"); map.put("vehicles", "car");
map.put("vehicles", "bike");
assertEquals(3, map.size()); assertEquals(4, map.size());
} }
@Test @Test
public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() { public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("fruits", "orange");
map.put("key", "value1"); assertThat((Collection<String>) map.get("fruits")).containsExactly("apple", "orange", "orange");
map.put("key", "value2");
map.put("key", "value2");
assertThat((Collection<String>) map.get("key")).containsExactly("value1", "value2", "value2");
} }
@Test @Test
public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() { public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() {
MultiValuedMap<String, String> map = new HashSetValuedHashMap<>(); MultiValuedMap<String, String> map = new HashSetValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "apple");
map.put("key1", "value1"); assertThat((Collection<String>) map.get("fruits")).containsExactly("apple");
map.put("key1", "value1");
assertThat((Collection<String>) map.get("key1")).containsExactly("value1");
} }
@Test(expected = UnsupportedOperationException.class) @Test(expected = UnsupportedOperationException.class)
public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() { public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value1"); map.put("fruits", "apple");
map.put("key", "value2"); map.put("fruits", "orange");
MultiValuedMap<String, String> immutableMap = MultiMapUtils.unmodifiableMultiValuedMap(map); MultiValuedMap<String, String> immutableMap = MultiMapUtils.unmodifiableMultiValuedMap(map);
immutableMap.put("key", "value3"); immutableMap.put("fruits", "banana");
} }

View File

@ -27,11 +27,27 @@
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId> <artifactId>hibernate-envers</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.h2database</groupId> <groupId>com.h2database</groupId>
<artifactId>h2</artifactId> <artifactId>h2</artifactId>
</dependency> </dependency>
<!-- Test containers only dependencies -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.10.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>
<!-- Test containers only dependencies -->
<dependency> <dependency>
<groupId>org.springframework.security</groupId> <groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId> <artifactId>spring-security-test</artifactId>

View File

@ -1,14 +1,11 @@
package com.baeldung.config; package com.baeldung.config;
import java.util.Properties; import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl;
import com.baeldung.services.IBarService;
import javax.sql.DataSource; import com.baeldung.services.impl.BarSpringDataJpaService;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.*;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@ -21,10 +18,8 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; import javax.sql.DataSource;
import com.baeldung.services.IBarService; import java.util.Properties;
import com.baeldung.services.impl.BarSpringDataJpaService;
import com.google.common.base.Preconditions;
@Configuration @Configuration
@ComponentScan({ "com.baeldung.dao", "com.baeldung.services" }) @ComponentScan({ "com.baeldung.dao", "com.baeldung.services" })
@ -32,6 +27,7 @@ import com.google.common.base.Preconditions;
@EnableJpaRepositories(basePackages = { "com.baeldung.dao" }, repositoryBaseClass = ExtendedRepositoryImpl.class) @EnableJpaRepositories(basePackages = { "com.baeldung.dao" }, repositoryBaseClass = ExtendedRepositoryImpl.class)
@EnableJpaAuditing @EnableJpaAuditing
@PropertySource("classpath:persistence.properties") @PropertySource("classpath:persistence.properties")
@Profile("!tc")
public class PersistenceConfiguration { public class PersistenceConfiguration {
@Autowired @Autowired

View File

@ -4,6 +4,7 @@ import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@ -19,6 +20,7 @@ import java.util.HashMap;
@Configuration @Configuration
@PropertySource({"classpath:persistence-multiple-db.properties"}) @PropertySource({"classpath:persistence-multiple-db.properties"})
@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") @EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager")
@Profile("!tc")
public class PersistenceProductConfiguration { public class PersistenceProductConfiguration {
@Autowired @Autowired
private Environment env; private Environment env;

View File

@ -2,10 +2,7 @@ package com.baeldung.config;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.DriverManagerDataSource;
@ -20,6 +17,7 @@ import java.util.HashMap;
@Configuration @Configuration
@PropertySource({"classpath:persistence-multiple-db.properties"}) @PropertySource({"classpath:persistence-multiple-db.properties"})
@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") @EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager")
@Profile("!tc")
public class PersistenceUserConfiguration { public class PersistenceUserConfiguration {
@Autowired @Autowired
private Environment env; private Environment env;

View File

@ -1,7 +1,6 @@
package com.baeldung.dao.repositories.user; package com.baeldung.dao.repositories.user;
import com.baeldung.domain.user.User; import com.baeldung.domain.user.User;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
@ -21,13 +20,13 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
@Query("SELECT u FROM User u WHERE u.status = 1") @Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers(); Collection<User> findAllActiveUsers();
@Query(value = "SELECT * FROM USERS.USERS u WHERE u.status = 1", nativeQuery = true) @Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
Collection<User> findAllActiveUsersNative(); Collection<User> findAllActiveUsersNative();
@Query("SELECT u FROM User u WHERE u.status = ?1") @Query("SELECT u FROM User u WHERE u.status = ?1")
User findUserByStatus(Integer status); User findUserByStatus(Integer status);
@Query(value = "SELECT * FROM USERS.Users u WHERE u.status = ?1", nativeQuery = true) @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
User findUserByStatusNative(Integer status); User findUserByStatusNative(Integer status);
@Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
@ -36,7 +35,7 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
@Query(value = "SELECT * FROM USERS.Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
@ -48,7 +47,7 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
@Query("SELECT u FROM User u WHERE u.name like :name%") @Query("SELECT u FROM User u WHERE u.name like :name%")
User findUserByNameLikeNamedParam(@Param("name") String name); User findUserByNameLikeNamedParam(@Param("name") String name);
@Query(value = "SELECT * FROM USERS.users u WHERE u.name LIKE ?1%", nativeQuery = true) @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
User findUserByNameLikeNative(String name); User findUserByNameLikeNative(String name);
@Query(value = "SELECT u FROM User u") @Query(value = "SELECT u FROM User u")
@ -57,7 +56,7 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
@Query(value = "SELECT u FROM User u ORDER BY id") @Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable); Page<User> findAllUsersWithPagination(Pageable pageable);
@Query(value = "SELECT * FROM USERS.Users ORDER BY id", countQuery = "SELECT count(*) FROM USERS.Users", nativeQuery = true) @Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
Page<User> findAllUsersWithPaginationNative(Pageable pageable); Page<User> findAllUsersWithPaginationNative(Pageable pageable);
@Modifying @Modifying
@ -65,6 +64,10 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
@Modifying @Modifying
@Query(value = "UPDATE USERS.Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNative(Integer status, String name); int updateUserSetStatusForNameNative(Integer status, String name);
@Modifying
@Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNativePostgres(Integer status, String name);
} }

View File

@ -1,13 +1,9 @@
package com.baeldung.domain.user; package com.baeldung.domain.user;
import javax.persistence.Entity; import javax.persistence.*;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity @Entity
@Table(schema = "users") @Table
public class Possession { public class Possession {
@Id @Id

View File

@ -4,7 +4,7 @@ import javax.persistence.*;
import java.util.List; import java.util.List;
@Entity @Entity
@Table(name = "users", schema = "users") @Table(name = "users")
public class User { public class User {
@Id @Id

View File

@ -0,0 +1,371 @@
package com.baeldung.dao.repositories;
import com.baeldung.dao.repositories.user.UserRepository;
import com.baeldung.domain.user.User;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
class UserRepositoryCommon {
final String USER_EMAIL = "email@example.com";
final String USER_EMAIL2 = "email2@example.com";
final String USER_EMAIL3 = "email3@example.com";
final String USER_EMAIL4 = "email4@example.com";
final Integer INACTIVE_STATUS = 0;
final Integer ACTIVE_STATUS = 1;
private final String USER_EMAIL5 = "email5@example.com";
private final String USER_EMAIL6 = "email6@example.com";
private final String USER_NAME_ADAM = "Adam";
private final String USER_NAME_PETER = "Peter";
@Autowired
protected UserRepository userRepository;
@Test
@Transactional
public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
userRepository.save(user3);
User user4 = new User();
user4.setName("SAMPLE");
user4.setEmail(USER_EMAIL4);
userRepository.save(user4);
try (Stream<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
assertThat(foundUsersStream.count()).isEqualTo(3l);
}
}
@Test
public void givenUsersInDB_WhenFindAllWithQueryAnnotation_ThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUsersInDB_WhenFindAllWithQueryAnnotationNative_ThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotation_ThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotationNative_ThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationIndexedParams_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParams_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParams_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNames_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationIndexedParams_ThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLike("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNamedParams_ThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNative_ThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNative("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
List<User> usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
assertThat(usersSortByName.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test(expected = PropertyReferenceException.class)
public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
List<User> usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindAllSortWithFunctionQueryAnnotationJPQL_ThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAllUsers(new Sort("name"));
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationJPQL_ThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3));
assertThat(usersPage.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@Test
public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationNative_ThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3));
assertThat(usersSortByNameLength.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@Test
@Transactional
public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationJPQL_ThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
@Test
public void givenUsersInDB_WhenFindByEmailsWithDynamicQuery_ThenReturnCollection() {
User user1 = new User();
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
User user3 = new User();
user3.setEmail(USER_EMAIL3);
userRepository.save(user3);
Set<String> emails = new HashSet<>();
emails.add(USER_EMAIL2);
emails.add(USER_EMAIL3);
Collection<User> usersWithEmails = userRepository.findUserByEmails(emails);
assertThat(usersWithEmails.size()).isEqualTo(2);
}
@After
public void cleanUp() {
userRepository.deleteAll();
}
}

View File

@ -1,28 +1,14 @@
package com.baeldung.dao.repositories; package com.baeldung.dao.repositories;
import com.baeldung.config.PersistenceConfiguration; import com.baeldung.config.PersistenceConfiguration;
import com.baeldung.dao.repositories.user.UserRepository;
import com.baeldung.domain.user.User; import com.baeldung.domain.user.User;
import org.junit.After;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
/** /**
@ -31,327 +17,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = PersistenceConfiguration.class) @SpringBootTest(classes = PersistenceConfiguration.class)
@DirtiesContext @DirtiesContext
public class UserRepositoryIntegrationTest { public class UserRepositoryIntegrationTest extends UserRepositoryCommon {
private final String USER_NAME_ADAM = "Adam";
private final String USER_NAME_PETER = "Peter";
private final String USER_EMAIL = "email@example.com";
private final String USER_EMAIL2 = "email2@example.com";
private final String USER_EMAIL3 = "email3@example.com";
private final String USER_EMAIL4 = "email4@example.com";
private final String USER_EMAIL5 = "email5@example.com";
private final String USER_EMAIL6 = "email6@example.com";
private final Integer INACTIVE_STATUS = 0;
private final Integer ACTIVE_STATUS = 1;
@Autowired
private UserRepository userRepository;
@Test
@Transactional
public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
userRepository.save(user3);
User user4 = new User();
user4.setName("SAMPLE");
user4.setEmail(USER_EMAIL4);
userRepository.save(user4);
try (Stream<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
assertThat(foundUsersStream.count()).isEqualTo(3l);
}
}
@Test
public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLike("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNative("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
List<User> usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
assertThat(usersSortByName.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test(expected = PropertyReferenceException.class)
public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
List<User> usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAllUsers(new Sort("name"));
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3));
assertThat(usersPage.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3));
assertThat(usersSortByNameLength.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@Test
@Transactional
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
@Test @Test
@Transactional @Transactional
@ -366,34 +32,4 @@ public class UserRepositoryIntegrationTest {
assertThat(updatedUsersSize).isEqualTo(2); assertThat(updatedUsersSize).isEqualTo(2);
} }
@Test
public void givenUsersInDBWhenFindByEmailsWithDynamicQueryThenReturnCollection() {
User user1 = new User();
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
User user3 = new User();
user3.setEmail(USER_EMAIL3);
userRepository.save(user3);
Set<String> emails = new HashSet<>();
emails.add(USER_EMAIL2);
emails.add(USER_EMAIL3);
Collection<User> usersWithEmails = userRepository.findUserByEmails(emails);
assertThat(usersWithEmails.size()).isEqualTo(2);
}
@After
public void cleanUp() {
userRepository.deleteAll();
}
} }

View File

@ -0,0 +1,40 @@
package com.baeldung.dao.repositories;
import com.baeldung.domain.user.User;
import com.baeldung.util.BaeldungPostgresqlContainer;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import org.testcontainers.containers.PostgreSQLContainer;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by adam.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"tc", "tc-auto"})
public class UserRepositoryTCAutoIntegrationTest extends UserRepositoryCommon {
@ClassRule
public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance();
@Test
@Transactional
public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNativePostgres_ThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
userRepository.flush();
int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.dao.repositories;
import com.baeldung.domain.user.User;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import org.testcontainers.containers.PostgreSQLContainer;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("tc")
@ContextConfiguration(initializers = {UserRepositoryTCIntegrationTest.Initializer.class})
public class UserRepositoryTCIntegrationTest extends UserRepositoryCommon {
@ClassRule
public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1")
.withDatabaseName("integration-tests-db")
.withUsername("sa")
.withPassword("sa");
@Test
@Transactional
public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNative_ThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
userRepository.flush();
int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
static class Initializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
TestPropertyValues.of(
"spring.datasource.url=" + postgreSQLContainer.getJdbcUrl(),
"spring.datasource.username=" + postgreSQLContainer.getUsername(),
"spring.datasource.password=" + postgreSQLContainer.getPassword()
).applyTo(configurableApplicationContext.getEnvironment());
}
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.util;
import org.testcontainers.containers.PostgreSQLContainer;
public class BaeldungPostgresqlContainer extends PostgreSQLContainer<BaeldungPostgresqlContainer> {
private static final String IMAGE_VERSION = "postgres:11.1";
private static BaeldungPostgresqlContainer container;
private BaeldungPostgresqlContainer() {
super(IMAGE_VERSION);
}
public static BaeldungPostgresqlContainer getInstance() {
if (container == null) {
container = new BaeldungPostgresqlContainer();
}
return container;
}
@Override
public void start() {
super.start();
System.setProperty("DB_URL", container.getJdbcUrl());
System.setProperty("DB_USERNAME", container.getUsername());
System.setProperty("DB_PASSWORD", container.getPassword());
}
@Override
public void stop() {
//do nothing, JVM handles shut down
}
}

View File

@ -0,0 +1,4 @@
# configuration for test containers testing
spring.datasource.url=${DB_URL}
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}

View File

@ -0,0 +1,4 @@
# configuration for Test Containers testing
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false

View File

@ -750,6 +750,7 @@
<module>spring-security-x509</module> <module>spring-security-x509</module>
<module>spring-session</module> <module>spring-session</module>
<module>spring-sleuth</module> <module>spring-sleuth</module>
<module>spring-soap</module>
<module>spring-social-login</module> <module>spring-social-login</module>
<module>spring-spel</module> <module>spring-spel</module>
<module>spring-state-machine</module> <module>spring-state-machine</module>
@ -1003,6 +1004,7 @@
<module>core-java-concurrency-advanced</module> <!-- very long running? --> <module>core-java-concurrency-advanced</module> <!-- very long running? -->
<module>core-kotlin</module> <!-- long running? --> <module>core-kotlin</module> <!-- long running? -->
<module>core-kotlin-2</module>
<module>jenkins/hello-world</module> <module>jenkins/hello-world</module>
<module>jhipster</module> <module>jhipster</module>
@ -1459,6 +1461,7 @@
<module>spring-security-x509</module> <module>spring-security-x509</module>
<module>spring-session</module> <module>spring-session</module>
<module>spring-sleuth</module> <module>spring-sleuth</module>
<module>spring-soap</module>
<module>spring-social-login</module> <module>spring-social-login</module>
<module>spring-spel</module> <module>spring-spel</module>
<module>spring-state-machine</module> <module>spring-state-machine</module>
@ -1554,6 +1557,7 @@
<module>core-java</module> <module>core-java</module>
<module>core-java-concurrency-advanced</module> <!-- very long running? --> <module>core-java-concurrency-advanced</module> <!-- very long running? -->
<module>core-kotlin</module> <!-- long running? --> <module>core-kotlin</module> <!-- long running? -->
<module>core-kotlin-2</module>
<module>jenkins/hello-world</module> <module>jenkins/hello-world</module>
<module>jhipster</module> <module>jhipster</module>

View File

@ -6,4 +6,11 @@ import org.zalando.problem.spring.web.advice.ProblemHandling;
@ControllerAdvice @ControllerAdvice
public class ExceptionHandler implements ProblemHandling { public class ExceptionHandler implements ProblemHandling {
// The causal chain of causes is disabled by default,
// but we can easily enable it by overriding the behavior:
@Override
public boolean isCausalChainsEnabled() {
return true;
}
} }

View File

@ -12,6 +12,8 @@ public class ProblemDemoConfiguration {
@Bean @Bean
public ObjectMapper objectMapper() { public ObjectMapper objectMapper() {
return new ObjectMapper().registerModules(new ProblemModule(), new ConstraintViolationProblemModule()); // In this example, stack traces support is enabled by default.
// If you want to disable stack traces just use new ProblemModule() instead of new ProblemModule().withStackTraces()
return new ObjectMapper().registerModules(new ProblemModule().withStackTraces(), new ConstraintViolationProblemModule());
} }
} }

View File

@ -1,6 +1,8 @@
package com.baeldung.boot.problem.controller; package com.baeldung.boot.problem.controller;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
@ -72,4 +74,28 @@ public class ProblemDemoControllerIntegrationTest {
.andExpect(status().isForbidden()); .andExpect(status().isForbidden());
} }
@Test
public void whenMakeGetCallWithInvalidIdFormat_thenReturnBadRequestResponseWithStackTrace() throws Exception {
mockMvc.perform(get("/tasks/invalid-id").contentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE))
.andDo(print())
.andExpect(jsonPath("$.title", equalTo("Bad Request")))
.andExpect(jsonPath("$.status", equalTo(400)))
.andExpect(jsonPath("$.stacktrace", notNullValue()))
.andExpect(status().isBadRequest());
}
@Test
public void whenMakeGetCallWithInvalidIdFormat_thenReturnBadRequestResponseWithCause() throws Exception {
mockMvc.perform(get("/tasks/invalid-id").contentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE))
.andDo(print())
.andExpect(jsonPath("$.title", equalTo("Bad Request")))
.andExpect(jsonPath("$.status", equalTo(400)))
.andExpect(jsonPath("$.cause", notNullValue()))
.andExpect(jsonPath("$.cause.title", equalTo("Internal Server Error")))
.andExpect(jsonPath("$.cause.status", equalTo(500)))
.andExpect(jsonPath("$.cause.detail", containsString("For input string:")))
.andExpect(jsonPath("$.cause.stacktrace", notNullValue()))
.andExpect(status().isBadRequest());
}
} }

1
spring-soap/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target/

68
spring-soap/pom.xml Normal file
View File

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-soap</artifactId>
<version>1.0.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- tag::springws[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
<!-- end::springws[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- tag::xsd[] -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>${project.basedir}/src/main/resources/</schemaDirectory>
<outputDirectory>${project.basedir}/src/main/java</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</plugin>
<!-- end::xsd[] -->
</plugins>
</build>
</project>

View File

@ -0,0 +1,12 @@
package com.baeldung.springsoap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.springsoap;
import com.baeldung.springsoap.gen.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
@Endpoint
public class CountryEndpoint {
private static final String NAMESPACE_URI = "http://www.baeldung.com/springsoap/gen";
private CountryRepository countryRepository;
@Autowired
public CountryEndpoint(CountryRepository countryRepository) {
this.countryRepository = countryRepository;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest")
@ResponsePayload
public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request) {
GetCountryResponse response = new GetCountryResponse();
response.setCountry(countryRepository.findCountry(request.getName()));
return response;
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.springsoap;
import com.baeldung.springsoap.gen.*;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
@Component
public class CountryRepository {
private static final Map<String, Country> countries = new HashMap<>();
@PostConstruct
public void initData() {
Country spain = new Country();
spain.setName("Spain");
spain.setCapital("Madrid");
spain.setCurrency(Currency.EUR);
spain.setPopulation(46704314);
countries.put(spain.getName(), spain);
Country poland = new Country();
poland.setName("Poland");
poland.setCapital("Warsaw");
poland.setCurrency(Currency.PLN);
poland.setPopulation(38186860);
countries.put(poland.getName(), poland);
Country uk = new Country();
uk.setName("United Kingdom");
uk.setCapital("London");
uk.setCurrency(Currency.GBP);
uk.setPopulation(63705000);
countries.put(uk.getName(), uk);
}
public Country findCountry(String name) {
Assert.notNull(name, "The country's name must not be null");
return countries.get(name);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.springsoap;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
@Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
@Bean(name = "countries")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CountriesPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://www.baeldung.com/springsoap/gen");
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
@Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
}
}

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.baeldung.com/springsoap/gen"
targetNamespace="http://www.baeldung.com/springsoap/gen" elementFormDefault="qualified">
<xs:element name="getCountryRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="getCountryResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="country" type="tns:country"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="country">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="population" type="xs:int"/>
<xs:element name="capital" type="xs:string"/>
<xs:element name="currency" type="tns:currency"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="currency">
<xs:restriction base="xs:string">
<xs:enumeration value="GBP"/>
<xs:enumeration value="EUR"/>
<xs:enumeration value="PLN"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>

View File

@ -0,0 +1,39 @@
package com.baeldung.springsoap;
import com.baeldung.springsoap.gen.GetCountryRequest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ClassUtils;
import org.springframework.ws.client.core.WebServiceTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationIntegrationTest {
private Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
@LocalServerPort private int port = 0;
@Before
public void init() throws Exception {
marshaller.setPackagesToScan(ClassUtils.getPackageName(GetCountryRequest.class));
marshaller.afterPropertiesSet();
}
@Test
public void whenSendRequest_thenResponseIsNotNull() {
WebServiceTemplate ws = new WebServiceTemplate(marshaller);
GetCountryRequest request = new GetCountryRequest();
request.setName("Spain");
assertThat(ws.marshalSendAndReceive("http://localhost:" + port + "/ws", request)).isNotNull();
}
}

View File

@ -0,0 +1,23 @@
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:gs="http://www.baeldung.com/springsoap/gen">
<soapenv:Header/>
<soapenv:Body>
<gs:getCountryRequest>
<gs:name>Spain</gs:name>
</gs:getCountryRequest>
</soapenv:Body>
</soapenv:Envelope>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns2:getCountryResponse xmlns:ns2="http://www.baeldung.com/springsoap/gen">
<ns2:country>
<ns2:name>Spain</ns2:name>
<ns2:population>46704314</ns2:population>
<ns2:capital>Madrid</ns2:capital>
<ns2:currency>EUR</ns2:currency>
</ns2:country>
</ns2:getCountryResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>