diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy new file mode 100644 index 0000000000..c043723d95 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy @@ -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) + } + +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/DollarSlashyString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/DollarSlashyString.groovy new file mode 100644 index 0000000000..db8ba68c8f --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/DollarSlashyString.groovy @@ -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) + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy new file mode 100644 index 0000000000..a730244d0a --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy @@ -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()) + } + +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy new file mode 100644 index 0000000000..569991b788 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy @@ -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!') + } + +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/SlashyString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/SlashyString.groovy new file mode 100644 index 0000000000..09ba35e17e --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/SlashyString.groovy @@ -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 + / + } + +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy new file mode 100644 index 0000000000..e45f352285 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy @@ -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) + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleDoubleQuotedString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleDoubleQuotedString.groovy new file mode 100644 index 0000000000..cbbb1a4665 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleDoubleQuotedString.groovy @@ -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) + } + +} diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleSingleQuotedString.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleSingleQuotedString.groovy new file mode 100644 index 0000000000..24d55b8a2a --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtypes/TripleSingleQuotedString.groovy @@ -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) + } + +} diff --git a/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java b/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java new file mode 100644 index 0000000000..fb4abd3bb6 --- /dev/null +++ b/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java @@ -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 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 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 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 uris = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2")); + List 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 + // void applyPushPromise​(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function,​CompletableFuture>> 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 pushPromiseHandler() { + return (HttpRequest initiatingRequest, + HttpRequest pushPromiseRequest, + Function, + CompletableFuture>> 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()); + }; + } + +} diff --git a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientTest.java b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientTest.java new file mode 100644 index 0000000000..bade666636 --- /dev/null +++ b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientTest.java @@ -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 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 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 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 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> 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> response1 = HttpClient.newBuilder() + .executor(executorService) + .build() + .sendAsync(request, HttpResponse.BodyHandlers.ofString()); + + CompletableFuture> response2 = HttpClient.newBuilder() + .executor(executorService) + .build() + .sendAsync(request, HttpResponse.BodyHandlers.ofString()); + + CompletableFuture> 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 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> 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 cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase, + CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS)); + CompletableFuture 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()); + } + +} diff --git a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestTest.java b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestTest.java new file mode 100644 index 0000000000..7d138bd8d5 --- /dev/null +++ b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestTest.java @@ -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 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 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 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 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 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 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 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 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 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 response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response.body(), containsString("Sample file content")); + } + +} diff --git a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseTest.java b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseTest.java new file mode 100644 index 0000000000..78d86fbf4e --- /dev/null +++ b/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseTest.java @@ -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 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 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/")); + } + +} diff --git a/core-kotlin-2/.gitignore b/core-kotlin-2/.gitignore new file mode 100644 index 0000000000..0c017e8f8c --- /dev/null +++ b/core-kotlin-2/.gitignore @@ -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 diff --git a/core-kotlin-2/README.md b/core-kotlin-2/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/core-kotlin-2/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/core-kotlin-2/build.gradle b/core-kotlin-2/build.gradle new file mode 100644 index 0000000000..b058e0ecad --- /dev/null +++ b/core-kotlin-2/build.gradle @@ -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' +} \ No newline at end of file diff --git a/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar b/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..01b8bf6b1f Binary files /dev/null and b/core-kotlin-2/gradle/wrapper/gradle-wrapper.jar differ diff --git a/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties b/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..933b6473ce --- /dev/null +++ b/core-kotlin-2/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/core-kotlin-2/gradlew b/core-kotlin-2/gradlew new file mode 100644 index 0000000000..cccdd3d517 --- /dev/null +++ b/core-kotlin-2/gradlew @@ -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" "$@" diff --git a/core-kotlin-2/gradlew.bat b/core-kotlin-2/gradlew.bat new file mode 100644 index 0000000000..f9553162f1 --- /dev/null +++ b/core-kotlin-2/gradlew.bat @@ -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 diff --git a/core-kotlin-2/pom.xml b/core-kotlin-2/pom.xml new file mode 100644 index 0000000000..81df3cee81 --- /dev/null +++ b/core-kotlin-2/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + core-kotlin-2 + core-kotlin-2 + jar + + + com.baeldung + parent-kotlin + 1.0.0-SNAPSHOT + ../parent-kotlin + + + diff --git a/core-kotlin-2/resources/logback.xml b/core-kotlin-2/resources/logback.xml new file mode 100644 index 0000000000..9452207268 --- /dev/null +++ b/core-kotlin-2/resources/logback.xml @@ -0,0 +1,11 @@ + + + + %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + \ No newline at end of file diff --git a/core-kotlin-2/settings.gradle b/core-kotlin-2/settings.gradle new file mode 100644 index 0000000000..c91c993971 --- /dev/null +++ b/core-kotlin-2/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'KtorWithKotlin' + diff --git a/core-kotlin-2/src/main/resources/logback.xml b/core-kotlin-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-kotlin-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/voidtypes/VoidTypesUnitTest.kt b/core-kotlin-2/src/test/kotlin/voidtypes/VoidTypesUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/voidtypes/VoidTypesUnitTest.kt rename to core-kotlin-2/src/test/kotlin/voidtypes/VoidTypesUnitTest.kt diff --git a/core-kotlin-2/src/test/resources/Kotlin.in b/core-kotlin-2/src/test/resources/Kotlin.in new file mode 100644 index 0000000000..d140d4429e --- /dev/null +++ b/core-kotlin-2/src/test/resources/Kotlin.in @@ -0,0 +1,5 @@ +Hello to Kotlin. Its: +1. Concise +2. Safe +3. Interoperable +4. Tool-friendly \ No newline at end of file diff --git a/core-kotlin-2/src/test/resources/Kotlin.out b/core-kotlin-2/src/test/resources/Kotlin.out new file mode 100644 index 0000000000..63d15d2528 --- /dev/null +++ b/core-kotlin-2/src/test/resources/Kotlin.out @@ -0,0 +1,2 @@ +Kotlin +Concise, Safe, Interoperable, Tool-friendly \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt b/core-kotlin/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt new file mode 100644 index 0000000000..23c7cfb11a --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt @@ -0,0 +1,10 @@ +package com.baeldung.static + +class ConsoleUtils { + companion object { + @JvmStatic + fun debug(debugMessage : String) { + println("[DEBUG] $debugMessage") + } + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/static/LoggingUtils.kt b/core-kotlin/src/main/kotlin/com/baeldung/static/LoggingUtils.kt new file mode 100644 index 0000000000..e67addc9ea --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/static/LoggingUtils.kt @@ -0,0 +1,5 @@ +package com.baeldung.static + +fun debug(debugMessage : String) { + println("[DEBUG] $debugMessage") +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt new file mode 100644 index 0000000000..8abed144eb --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt @@ -0,0 +1,10 @@ +package com.baeldung.static + +import org.junit.Test + +class ConsoleUtilsUnitTest { + @Test + fun givenAStaticMethod_whenCalled_thenNoErrorIsThrown() { + ConsoleUtils.debug("test message") + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt new file mode 100644 index 0000000000..59587ff009 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt @@ -0,0 +1,10 @@ +package com.baeldung.static + +import org.junit.Test + +class LoggingUtilsUnitTest { + @Test + fun givenAPackageMethod_whenCalled_thenNoErrorIsThrown() { + debug("test message") + } +} \ No newline at end of file diff --git a/java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java index 67e4a5b0a0..b02b67f685 100644 --- a/java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java +++ b/java-collections-maps/src/test/java/com/baeldung/java/map/MultiValuedMapUnitTest.java @@ -22,139 +22,157 @@ public class MultiValuedMapUnitTest { public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutMethod_thenReturningAllValues() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value1"); - map.put("key", "value2"); - map.put("key", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); - assertThat((Collection) map.get("key")).containsExactly("value1", "value2", "value2"); + assertThat((Collection) map.get("fruits")).containsExactly("apple", "orange"); + } @Test public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutAllMethod_thenReturningAllValues() { MultiValuedMap map = new ArrayListValuedHashMap<>(); + + map.putAll("vehicles", Arrays.asList("car", "bike")); - map.putAll("key", Arrays.asList("value1", "value2", "value2")); - - assertThat((Collection) map.get("key")).containsExactly("value1", "value2", "value2"); + assertThat((Collection) map.get("vehicles")).containsExactly("car", "bike"); + } @Test public void givenMultiValuesMap_whenGettingValueUsingGetMethod_thenReturningValue() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); + + map.put("fruits", "apple"); - assertThat((Collection) map.get("key")).containsExactly("value"); + assertThat((Collection) map.get("fruits")).containsExactly("apple"); } @Test public void givenMultiValuesMap_whenUsingEntriesMethod_thenReturningMappings() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value1"); - map.put("key", "value2"); - + map.put("fruits", "apple"); + map.put("fruits", "orange"); + Collection> entries = (Collection>) map.entries(); for(Map.Entry entry : entries) { - assertThat(entry.getKey()).contains("key"); - assertTrue(entry.getValue().equals("value1") || entry.getValue().equals("value2") ); + assertThat(entry.getKey()).contains("fruits"); + assertTrue(entry.getValue().equals("apple") || entry.getValue().equals("orange") ); } } @Test public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertThat(((Collection) map.keys())).contains("key", "key1", "key2"); + assertThat(((Collection) map.keys())).contains("fruits", "vehicles"); } @Test public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertThat((Collection) map.keySet()).contains("key", "key1", "key2"); + assertThat((Collection) map.keySet()).contains("fruits", "vehicles"); + } @Test public void givenMultiValuesMap_whenUsingValuesMethod_thenReturningAllValues() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); } @Test public void givenMultiValuesMap_whenUsingRemoveMethod_thenReturningUpdatedMap() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); - assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); - map.remove("key"); + map.remove("fruits"); - assertThat(((Collection) map.values())).contains("value1", "value2"); + assertThat(((Collection) map.values())).contains("car", "bike"); + } @Test public void givenMultiValuesMap_whenUsingRemoveMappingMethod_thenReturningUpdatedMapAfterMappingRemoved() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); - assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); - map.removeMapping("key", "value"); + map.removeMapping("fruits", "apple"); - assertThat(((Collection) map.values())).contains("value1", "value2"); + assertThat(((Collection) map.values())).contains("orange", "car", "bike"); } @Test public void givenMultiValuesMap_whenUsingClearMethod_thenReturningEmptyMap() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); - assertThat(((Collection) map.values())).contains("value", "value1", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); map.clear(); - + assertTrue(map.isEmpty()); } @Test public void givenMultiValuesMap_whenUsingContainsKeyMethod_thenReturningTrue() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertTrue(map.containsKey("key")); + assertTrue(map.containsKey("fruits")); } @Test public void givenMultiValuesMap_whenUsingContainsValueMethod_thenReturningTrue() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertTrue(map.containsValue("value")); + assertTrue(map.containsValue("orange")); } @Test public void givenMultiValuesMap_whenUsingIsEmptyMethod_thenReturningFalse() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); assertFalse(map.isEmpty()); } @@ -162,42 +180,42 @@ public class MultiValuedMapUnitTest { @Test public void givenMultiValuesMap_whenUsingSizeMethod_thenReturningElementCount() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value"); - map.put("key1", "value1"); - map.put("key2", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); - assertEquals(3, map.size()); + assertEquals(4, map.size()); } @Test public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() { MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("fruits", "orange"); - map.put("key", "value1"); - map.put("key", "value2"); - map.put("key", "value2"); - - assertThat((Collection) map.get("key")).containsExactly("value1", "value2", "value2"); + assertThat((Collection) map.get("fruits")).containsExactly("apple", "orange", "orange"); } @Test public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() { MultiValuedMap map = new HashSetValuedHashMap<>(); - - map.put("key1", "value1"); - map.put("key1", "value1"); - - assertThat((Collection) map.get("key1")).containsExactly("value1"); + map.put("fruits", "apple"); + map.put("fruits", "apple"); + + assertThat((Collection) map.get("fruits")).containsExactly("apple"); } @Test(expected = UnsupportedOperationException.class) public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() { MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key", "value1"); - map.put("key", "value2"); + map.put("fruits", "apple"); + map.put("fruits", "orange"); MultiValuedMap immutableMap = MultiMapUtils.unmodifiableMultiValuedMap(map); - immutableMap.put("key", "value3"); + immutableMap.put("fruits", "banana"); + } diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml index 786e587734..401f4877ac 100644 --- a/persistence-modules/spring-data-jpa/pom.xml +++ b/persistence-modules/spring-data-jpa/pom.xml @@ -27,11 +27,27 @@ org.hibernate hibernate-envers + com.h2database h2 + + + org.testcontainers + postgresql + 1.10.6 + test + + + + org.postgresql + postgresql + 42.2.5 + + + org.springframework.security spring-security-test diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java index 2bdd4e5451..891624443b 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java @@ -1,14 +1,11 @@ package com.baeldung.config; -import java.util.Properties; - -import javax.sql.DataSource; - +import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; +import com.baeldung.services.IBarService; +import com.baeldung.services.impl.BarSpringDataJpaService; +import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.*; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; 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.annotation.EnableTransactionManagement; -import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; -import com.baeldung.services.IBarService; -import com.baeldung.services.impl.BarSpringDataJpaService; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.Properties; @Configuration @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) @EnableJpaAuditing @PropertySource("classpath:persistence.properties") +@Profile("!tc") public class PersistenceConfiguration { @Autowired diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java index 207fba9bc5..ecaee82ae5 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java @@ -4,6 +4,7 @@ import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @@ -19,6 +20,7 @@ import java.util.HashMap; @Configuration @PropertySource({"classpath:persistence-multiple-db.properties"}) @EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") +@Profile("!tc") public class PersistenceProductConfiguration { @Autowired private Environment env; diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java index dd32477755..6893d889e6 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java @@ -2,10 +2,7 @@ package com.baeldung.config; import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.*; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -20,6 +17,7 @@ import java.util.HashMap; @Configuration @PropertySource({"classpath:persistence-multiple-db.properties"}) @EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") +@Profile("!tc") public class PersistenceUserConfiguration { @Autowired private Environment env; diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java index 7f54254832..c291f93e2c 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java @@ -1,7 +1,6 @@ package com.baeldung.dao.repositories.user; import com.baeldung.domain.user.User; - import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -21,13 +20,13 @@ public interface UserRepository extends JpaRepository , UserRepos @Query("SELECT u FROM User u WHERE u.status = 1") Collection 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 findAllActiveUsersNative(); @Query("SELECT u FROM User u WHERE u.status = ?1") 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); @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") @@ -36,7 +35,7 @@ public interface UserRepository extends JpaRepository , UserRepos @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :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); @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") @@ -48,7 +47,7 @@ public interface UserRepository extends JpaRepository , UserRepos @Query("SELECT u FROM User u WHERE u.name like :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); @Query(value = "SELECT u FROM User u") @@ -57,7 +56,7 @@ public interface UserRepository extends JpaRepository , UserRepos @Query(value = "SELECT u FROM User u ORDER BY id") Page 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 findAllUsersWithPaginationNative(Pageable pageable); @Modifying @@ -65,6 +64,10 @@ public interface UserRepository extends JpaRepository , UserRepos int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); @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); + + @Modifying + @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true) + int updateUserSetStatusForNameNativePostgres(Integer status, String name); } diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java index 614e13df36..b1427c0270 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java @@ -1,13 +1,9 @@ package com.baeldung.domain.user; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import javax.persistence.*; @Entity -@Table(schema = "users") +@Table public class Possession { @Id diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java index 3a8b617d9a..28c52140c7 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java @@ -4,7 +4,7 @@ import javax.persistence.*; import java.util.List; @Entity -@Table(name = "users", schema = "users") +@Table(name = "users") public class User { @Id diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryCommon.java new file mode 100644 index 0000000000..8c4e8073b7 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryCommon.java @@ -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 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 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 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 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 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 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 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 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 emails = new HashSet<>(); + emails.add(USER_EMAIL2); + emails.add(USER_EMAIL3); + + Collection usersWithEmails = userRepository.findUserByEmails(emails); + + assertThat(usersWithEmails.size()).isEqualTo(2); + } + + @After + public void cleanUp() { + userRepository.deleteAll(); + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java index b05086d00e..6bcbb6dcaa 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java @@ -1,28 +1,14 @@ package com.baeldung.dao.repositories; import com.baeldung.config.PersistenceConfiguration; -import com.baeldung.dao.repositories.user.UserRepository; import com.baeldung.domain.user.User; -import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; 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.context.junit4.SpringRunner; 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; /** @@ -31,327 +17,7 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(classes = PersistenceConfiguration.class) @DirtiesContext -public class UserRepositoryIntegrationTest { - - 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 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 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 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 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 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 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 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 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); - } +public class UserRepositoryIntegrationTest extends UserRepositoryCommon { @Test @Transactional @@ -366,34 +32,4 @@ public class UserRepositoryIntegrationTest { 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 emails = new HashSet<>(); - emails.add(USER_EMAIL2); - emails.add(USER_EMAIL3); - - Collection usersWithEmails = userRepository.findUserByEmails(emails); - - assertThat(usersWithEmails.size()).isEqualTo(2); - } - - @After - public void cleanUp() { - userRepository.deleteAll(); - } - } diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCAutoIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCAutoIntegrationTest.java new file mode 100644 index 0000000000..4b58be487c --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCAutoIntegrationTest.java @@ -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); + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCIntegrationTest.java new file mode 100644 index 0000000000..ccbc3b3fe2 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryTCIntegrationTest.java @@ -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 { + 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()); + } + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java new file mode 100644 index 0000000000..e5ad2dd448 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java @@ -0,0 +1,35 @@ +package com.baeldung.util; + +import org.testcontainers.containers.PostgreSQLContainer; + +public class BaeldungPostgresqlContainer extends PostgreSQLContainer { + + 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 + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties b/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties new file mode 100644 index 0000000000..c3005d861f --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties @@ -0,0 +1,4 @@ +# configuration for test containers testing +spring.datasource.url=${DB_URL} +spring.datasource.username=${DB_USERNAME} +spring.datasource.password=${DB_PASSWORD} diff --git a/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties b/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties new file mode 100644 index 0000000000..3bf8693d53 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties @@ -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 diff --git a/pom.xml b/pom.xml index 58d57ade05..1c016a2ea9 100644 --- a/pom.xml +++ b/pom.xml @@ -750,6 +750,7 @@ spring-security-x509 spring-session spring-sleuth + spring-soap spring-social-login spring-spel spring-state-machine @@ -1003,6 +1004,7 @@ core-java-concurrency-advanced core-kotlin + core-kotlin-2 jenkins/hello-world jhipster @@ -1459,6 +1461,7 @@ spring-security-x509 spring-session spring-sleuth + spring-soap spring-social-login spring-spel spring-state-machine @@ -1554,6 +1557,7 @@ core-java core-java-concurrency-advanced core-kotlin + core-kotlin-2 jenkins/hello-world jhipster diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java b/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java index 7b4cbac7f7..18df103733 100644 --- a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java +++ b/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/advice/ExceptionHandler.java @@ -5,5 +5,12 @@ import org.zalando.problem.spring.web.advice.ProblemHandling; @ControllerAdvice 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; + } } diff --git a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java b/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java index 209ff553c7..f5e6a6b99a 100644 --- a/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java +++ b/spring-boot-libraries/src/main/java/com/baeldung/boot/problem/configuration/ProblemDemoConfiguration.java @@ -12,6 +12,8 @@ public class ProblemDemoConfiguration { @Bean 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()); } } diff --git a/spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java b/spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java index 3b7e43a565..5ced1034c4 100644 --- a/spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java +++ b/spring-boot-libraries/src/test/java/com/baeldung/boot/problem/controller/ProblemDemoControllerIntegrationTest.java @@ -1,6 +1,8 @@ package com.baeldung.boot.problem.controller; +import static org.hamcrest.CoreMatchers.containsString; 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.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; @@ -71,5 +73,29 @@ public class ProblemDemoControllerIntegrationTest { .andExpect(jsonPath("$.detail", equalTo("You can't delete this task"))) .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()); + } } diff --git a/spring-soap/.gitignore b/spring-soap/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/spring-soap/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml new file mode 100644 index 0000000000..2865a4c3bc --- /dev/null +++ b/spring-soap/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + com.baeldung + spring-soap + 1.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.1.2.RELEASE + + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web-services + + + wsdl4j + wsdl4j + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + org.codehaus.mojo + jaxb2-maven-plugin + 1.6 + + + xjc + + xjc + + + + + ${project.basedir}/src/main/resources/ + ${project.basedir}/src/main/java + false + + + + + + + diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/Application.java b/spring-soap/src/main/java/com/baeldung/springsoap/Application.java new file mode 100644 index 0000000000..ad9258447c --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/Application.java @@ -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); + } +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java b/spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java new file mode 100644 index 0000000000..745131767a --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java @@ -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; + } +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java b/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java new file mode 100644 index 0000000000..8a0f58a64e --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java @@ -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 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); + } +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java b/spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java new file mode 100644 index 0000000000..930a961208 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java @@ -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")); + } +} diff --git a/spring-soap/src/main/resources/countries.xsd b/spring-soap/src/main/resources/countries.xsd new file mode 100644 index 0000000000..524e5ac2d5 --- /dev/null +++ b/spring-soap/src/main/resources/countries.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java b/spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..3b071c286f --- /dev/null +++ b/spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java @@ -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(); + } +} diff --git a/spring-soap/src/test/resources/request.xml b/spring-soap/src/test/resources/request.xml new file mode 100644 index 0000000000..7a94aeeee6 --- /dev/null +++ b/spring-soap/src/test/resources/request.xml @@ -0,0 +1,23 @@ + + + + + Spain + + + + + + + + + + Spain + 46704314 + Madrid + EUR + + + + \ No newline at end of file