BAEL-2492 Rename WireMockScenario test class

This commit is contained in:
pcoates 2019-02-17 16:55:30 +00:00
commit 3c4a517b1d
106 changed files with 3477 additions and 772 deletions

View File

@ -0,0 +1,8 @@
package com.baeldung.traits
trait AnimalTrait {
String basicBehavior() {
return "Animalistic!!"
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.traits
class Dog implements WalkingTrait, SpeakingTrait {
String speakAndWalk() {
WalkingTrait.super.speakAndWalk()
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.traits
class Employee implements UserTrait {
String name() {
return 'Bob'
}
String lastName() {
return "Marley"
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.traits
interface Human {
String lastName()
}

View File

@ -0,0 +1,13 @@
package com.baeldung.traits
trait SpeakingTrait {
String basicAbility() {
return "Speaking!!"
}
String speakAndWalk() {
return "Speak and walk!!"
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.traits
trait UserTrait implements Human {
String sayHello() {
return "Hello!"
}
abstract String name()
String showName() {
return "Hello, ${name()}!"
}
private String greetingMessage() {
return 'Hello, from a private method!'
}
String greet() {
def msg = greetingMessage()
println msg
msg
}
def whoAmI() {
return this
}
String showLastName() {
return "Hello, ${lastName()}!"
}
String email
String address
}

View File

@ -0,0 +1,13 @@
package com.baeldung.traits
trait WalkingTrait {
String basicAbility() {
return "Walking!!"
}
String speakAndWalk() {
return "Walk and speak!!"
}
}

View File

@ -0,0 +1,19 @@
package groovy.com.baeldung.stringtypes
import org.junit.Assert
import org.junit.Test
class CharacterInGroovy {
@Test
void 'character'() {
char a = 'A' as char
char b = 'B' as char
char c = (char) 'C'
Assert.assertTrue(a instanceof Character)
Assert.assertTrue(b instanceof Character)
Assert.assertTrue(c instanceof Character)
}
}

View File

@ -0,0 +1,24 @@
package groovy.com.baeldung.stringtypes
import org.junit.Test
class DollarSlashyString {
@Test
void 'dollar slashy string'() {
def name = "John"
def dollarSlashy = $/
Hello $name!,
I can show you $ sign or escaped dollar sign: $$
Both slashes works: \ or /, but we can still escape it: $/
We have to escape opening and closing delimiter:
- $$$/
- $/$$
/$
print(dollarSlashy)
}
}

View File

@ -0,0 +1,67 @@
package groovy.com.baeldung.stringtypes
import org.junit.Assert
import org.junit.Test
class DoubleQuotedString {
@Test
void 'escape double quoted string'() {
def example = "Hello \"world\"!"
println(example)
}
@Test
void 'String ang GString'() {
def string = "example"
def stringWithExpression = "example${2}"
Assert.assertTrue(string instanceof String)
Assert.assertTrue(stringWithExpression instanceof GString)
Assert.assertTrue(stringWithExpression.toString() instanceof String)
}
@Test
void 'placeholder with variable'() {
def name = "John"
def helloName = "Hello $name!".toString()
Assert.assertEquals("Hello John!", helloName)
}
@Test
void 'placeholder with expression'() {
def result = "result is ${2 * 2}".toString()
Assert.assertEquals("result is 4", result)
}
@Test
void 'placeholder with dotted access'() {
def person = [name: 'John']
def myNameIs = "I'm $person.name, and you?".toString()
Assert.assertEquals("I'm John, and you?", myNameIs)
}
@Test
void 'placeholder with method call'() {
def name = 'John'
def result = "Uppercase name: ${name.toUpperCase()}".toString()
Assert.assertEquals("Uppercase name: JOHN", result)
}
@Test
void 'GString and String hashcode'() {
def string = "2+2 is 4"
def gstring = "2+2 is ${4}"
Assert.assertTrue(string.hashCode() != gstring.hashCode())
}
}

View File

@ -0,0 +1,15 @@
package groovy.com.baeldung.stringtypes
import org.junit.Assert
import org.junit.Test
class SingleQuotedString {
@Test
void 'single quoted string'() {
def example = 'Hello world'
Assert.assertEquals('Hello world!', 'Hello' + ' world!')
}
}

View File

@ -0,0 +1,31 @@
package groovy.com.baeldung.stringtypes
import org.junit.Assert
import org.junit.Test
class SlashyString {
@Test
void 'slashy string'() {
def pattern = /.*foobar.*\/hello.*/
Assert.assertTrue("I'm matching foobar /hello regexp pattern".matches(pattern))
}
void 'wont compile'() {
// if ('' == //) {
// println("I can't compile")
// }
}
@Test
void 'interpolate and multiline'() {
def name = 'John'
def example = /
Hello $name
second line
/
}
}

View File

@ -0,0 +1,26 @@
package groovy.com.baeldung.stringtypes
import org.junit.Assert
import org.junit.Test
class Strings {
@Test
void 'string interpolation '() {
def name = "Kacper"
def result = "Hello ${name}!"
Assert.assertEquals("Hello Kacper!", result.toString())
}
@Test
void 'string concatenation'() {
def first = "first"
def second = "second"
def concatenation = first + second
Assert.assertEquals("firstsecond", concatenation)
}
}

View File

@ -0,0 +1,19 @@
package groovy.com.baeldung.stringtypes
import org.junit.Test
class TripleDoubleQuotedString {
@Test
void 'triple-quoted strings with interpolation'() {
def name = "John"
def multiLine = """
I'm $name.
"This is quotation"
"""
println(multiLine)
}
}

View File

@ -0,0 +1,67 @@
package groovy.com.baeldung.stringtypes
import org.junit.Assert
import org.junit.Test
class TripleSingleQuotedString {
def 'formatted json'() {
def jsonContent = '''
{
"name": "John",
"age": 20,
"birthDate": null
}
'''
}
def 'triple single quoted'() {
def triple = '''im triple single quoted string'''
}
@Test
void 'triple single quoted with multiline string'() {
def triple = '''
firstline
secondline
'''
Assert.assertTrue(triple.startsWith("\n"))
}
@Test
void 'triple single quoted with multiline string with stripIndent() and removing newline characters'() {
def triple = '''\
firstline
secondline'''.stripIndent()
Assert.assertEquals("firstline\nsecondline", triple)
}
@Test
void 'triple single quoted with multiline string with last line with only whitespaces'() {
def triple = '''\
firstline
secondline\
'''.stripIndent()
println(triple)
}
@Test
void 'triple single quoted with multiline string with stripMargin(Character) and removing newline characters'() {
def triple = '''\
|firstline
|secondline'''.stripMargin()
println(triple)
}
@Test
void 'striple single quoted with special characters'() {
def specialCharacters = '''hello \'John\'. This is backslash - \\. \nSecond line starts here'''
println(specialCharacters)
}
}

View File

@ -0,0 +1,114 @@
package com.baeldung.traits
import spock.lang.Specification
class TraitsUnitTest extends Specification {
Employee employee
Dog dog
void setup () {
employee = new Employee()
dog = new Dog()
}
def 'Should return msg string when using Employee.sayHello method provided by UserTrait' () {
when:
def msg = employee.sayHello()
then:
msg
msg instanceof String
assert msg == "Hello!"
}
def 'Should return displayMsg string when using Employee.showName method' () {
when:
def displayMsg = employee.showName()
then:
displayMsg
displayMsg instanceof String
assert displayMsg == "Hello, Bob!"
}
def 'Should return greetMsg string when using Employee.greet method' () {
when:
def greetMsg = employee.greet()
then:
greetMsg
greetMsg instanceof String
assert greetMsg == "Hello, from a private method!"
}
def 'Should return MissingMethodException when using Employee.greetingMessage method' () {
when:
def exception
try {
employee.greetingMessage()
}catch(Exception e) {
exception = e
}
then:
exception
exception instanceof groovy.lang.MissingMethodException
assert exception.message == "No signature of method: com.baeldung.traits.Employee.greetingMessage()"+
" is applicable for argument types: () values: []"
}
def 'Should return employee instance when using Employee.whoAmI method' () {
when:
def emp = employee.whoAmI()
then:
emp
emp instanceof Employee
assert emp.is(employee)
}
def 'Should display lastName when using Employee.showLastName method' () {
when:
def lastNameMsg = employee.showLastName()
then:
lastNameMsg
lastNameMsg instanceof String
assert lastNameMsg == "Hello, Marley!"
}
def 'Should be able to define properties of UserTrait in Employee instance' () {
when:
employee = new Employee(email: "a@e.com", address: "baeldung.com")
then:
employee
employee instanceof Employee
assert employee.email == "a@e.com"
assert employee.address == "baeldung.com"
}
def 'Should execute basicAbility method from SpeakingTrait and return msg string' () {
when:
def speakMsg = dog.basicAbility()
then:
speakMsg
speakMsg instanceof String
assert speakMsg == "Speaking!!"
}
def 'Should verify multiple inheritance with traits and execute overridden traits method' () {
when:
def walkSpeakMsg = dog.speakAndWalk()
println walkSpeakMsg
then:
walkSpeakMsg
walkSpeakMsg instanceof String
assert walkSpeakMsg == "Walk and speak!!"
}
def 'Should implement AnimalTrait at runtime and access basicBehavior method' () {
when:
def dogInstance = new Dog() as AnimalTrait
def basicBehaviorMsg = dogInstance.basicBehavior()
then:
basicBehaviorMsg
basicBehaviorMsg instanceof String
assert basicBehaviorMsg == "Animalistic!!"
}
}

View File

@ -0,0 +1,132 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.java11.httpclient;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.http.HttpResponse.PushPromiseHandler;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
httpGetRequest();
httpPostRequest();
asynchronousGetRequest();
asynchronousMultipleRequests();
pushRequest();
}
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_2)
.uri(URI.create("http://jsonplaceholder.typicode.com/posts/1"))
.headers("Accept-Enconding", "gzip, deflate")
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
String responseBody = response.body();
int responseStatusCode = response.statusCode();
System.out.println("httpGetRequest: " + responseBody);
System.out.println("httpGetRequest status code: " + responseStatusCode);
}
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
.version(HttpClient.Version.HTTP_2)
.POST(BodyPublishers.ofString("Sample Post Request"))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
String responseBody = response.body();
System.out.println("httpPostRequest : " + responseBody);
}
public static void asynchronousGetRequest() throws URISyntaxException {
HttpClient client = HttpClient.newHttpClient();
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
HttpRequest request = HttpRequest.newBuilder(httpURI)
.version(HttpClient.Version.HTTP_2)
.build();
CompletableFuture<Void> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenAccept(resp -> {
System.out.println("Got pushed response " + resp.uri());
System.out.println("Response statuscode: " + resp.statusCode());
System.out.println("Response body: " + resp.body());
});
System.out.println("futureResponse" + futureResponse);
}
public static void asynchronousMultipleRequests() throws URISyntaxException {
HttpClient client = HttpClient.newHttpClient();
List<URI> uris = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
List<HttpRequest> requests = uris.stream()
.map(HttpRequest::newBuilder)
.map(reqBuilder -> reqBuilder.build())
.collect(Collectors.toList());
System.out.println("Got pushed response1 " + requests);
CompletableFuture.allOf(requests.stream()
.map(request -> client.sendAsync(request, BodyHandlers.ofString()))
.toArray(CompletableFuture<?>[]::new))
.thenAccept(System.out::println)
.join();
}
public static void pushRequest() throws URISyntaxException, InterruptedException {
System.out.println("Running HTTP/2 Server Push example...");
HttpClient httpClient = HttpClient.newBuilder()
.version(Version.HTTP_2)
.build();
HttpRequest pageRequest = HttpRequest.newBuilder()
.uri(URI.create("https://http2.golang.org/serverpush"))
.build();
// Interface HttpResponse.PushPromiseHandler<T>
// void applyPushPromise(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function<HttpResponse.BodyHandler<T>,CompletableFuture<HttpResponse<T>>> acceptor)
httpClient.sendAsync(pageRequest, BodyHandlers.ofString(), pushPromiseHandler())
.thenAccept(pageResponse -> {
System.out.println("Page response status code: " + pageResponse.statusCode());
System.out.println("Page response headers: " + pageResponse.headers());
String responseBody = pageResponse.body();
System.out.println(responseBody);
}).join();
Thread.sleep(1000); // waiting for full response
}
private static PushPromiseHandler<String> pushPromiseHandler() {
return (HttpRequest initiatingRequest,
HttpRequest pushPromiseRequest,
Function<HttpResponse.BodyHandler<String>,
CompletableFuture<HttpResponse<String>>> acceptor) -> {
acceptor.apply(BodyHandlers.ofString())
.thenAccept(resp -> {
System.out.println(" Pushed response: " + resp.uri() + ", headers: " + resp.headers());
});
System.out.println("Promise request: " + pushPromiseRequest.uri());
System.out.println("Promise request: " + pushPromiseRequest.headers());
};
}
}

View File

@ -0,0 +1,240 @@
package com.baeldung.java11.httpclient.test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.Authenticator;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
public class HttpClientTest {
@Test
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString("Sample body"))
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.proxy(ProxySelector.getDefault())
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample body"));
}
@Test
public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://stackoverflow.com"))
.version(HttpClient.Version.HTTP_1_1)
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
assertThat(response.body(), containsString("https://stackoverflow.com/"));
}
@Test
public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://stackoverflow.com"))
.version(HttpClient.Version.HTTP_1_1)
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.request()
.uri()
.toString(), equalTo("https://stackoverflow.com/"));
}
@Test
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/basic-auth"))
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("postman", "password".toCharArray());
}
})
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString("Sample body"))
.build();
CompletableFuture<HttpResponse<String>> response = HttpClient.newBuilder()
.build()
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
ExecutorService executorService = Executors.newFixedThreadPool(2);
CompletableFuture<HttpResponse<String>> response1 = HttpClient.newBuilder()
.executor(executorService)
.build()
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
CompletableFuture<HttpResponse<String>> response2 = HttpClient.newBuilder()
.executor(executorService)
.build()
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
CompletableFuture<HttpResponse<String>> response3 = HttpClient.newBuilder()
.executor(executorService)
.build()
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
CompletableFuture.allOf(response1, response2, response3)
.join();
assertThat(response1.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response2.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response3.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpClient httpClient = HttpClient.newBuilder()
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
.build();
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(httpClient.cookieHandler()
.isPresent());
}
@Test
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpClient httpClient = HttpClient.newBuilder()
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
.build();
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(httpClient.cookieHandler()
.isPresent());
}
@Test
public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));
HttpClient client = HttpClient.newHttpClient();
List<CompletableFuture<String>> futures = targets.stream()
.map(target -> client.sendAsync(HttpRequest.newBuilder(target)
.GET()
.build(), HttpResponse.BodyHandlers.ofString())
.thenApply(response -> response.body()))
.collect(Collectors.toList());
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.join();
if (futures.get(0)
.get()
.contains("foo1")) {
assertThat(futures.get(0)
.get(), containsString("bar1"));
assertThat(futures.get(1)
.get(), containsString("bar2"));
} else {
assertThat(futures.get(1)
.get(), containsString("bar2"));
assertThat(futures.get(1)
.get(), containsString("bar1"));
}
}
@Test
public void completeExceptionallyExample() {
CompletableFuture<String> cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase,
CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
CompletableFuture<String> exceptionHandler = cf.handle((s, th) -> { return (th != null) ? "message upon cancel" : ""; });
cf.completeExceptionally(new RuntimeException("completed exceptionally"));
assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally());
try {
cf.join();
fail("Should have thrown an exception");
} catch (CompletionException ex) { // just for testing
assertEquals("completed exceptionally", ex.getCause().getMessage());
}
assertEquals("message upon cancel", exceptionHandler.join());
}
}

View File

@ -0,0 +1,168 @@
package com.baeldung.java11.httpclient.test;
import static java.time.temporal.ChronoUnit.SECONDS;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import org.junit.Test;
public class HttpRequestTest {
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://stackoverflow.com"))
.version(HttpClient.Version.HTTP_2)
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
}
@Test
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.version(HttpClient.Version.HTTP_2)
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1));
}
@Test
public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.headers("key1", "value1", "key2", "value2")
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.timeout(Duration.of(10, SECONDS))
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.POST(HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString("Sample request body"))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample request body"));
}
@Test
public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException {
byte[] sampleData = "Sample request body".getBytes();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(sampleData)))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample request body"));
}
@Test
public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException {
byte[] sampleData = "Sample request body".getBytes();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofByteArray(sampleData))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample request body"));
}
@Test
public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofFile(Paths.get("src/test/resources/sample.txt")))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample file content"));
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.java11.httpclient.test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.junit.Test;
public class HttpResponseTest {
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.version(HttpClient.Version.HTTP_2)
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertNotNull(response.body());
}
@Test
public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://stackoverflow.com"))
.version(HttpClient.Version.HTTP_2)
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(request.uri()
.toString(), equalTo("http://stackoverflow.com"));
assertThat(response.uri()
.toString(), equalTo("https://stackoverflow.com/"));
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.customannotations;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(METHOD)
public @interface Init {
}

View File

@ -0,0 +1,13 @@
package com.baeldung.customannotations;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target({ FIELD })
public @interface JsonElement {
public String key() default "";
}

View File

@ -0,0 +1,13 @@
package com.baeldung.customannotations;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(TYPE)
public @interface JsonSerializable {
}

View File

@ -0,0 +1,10 @@
package com.baeldung.customannotations;
public class JsonSerializationException extends RuntimeException {
private static final long serialVersionUID = 1L;
public JsonSerializationException(String message) {
super(message);
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.customannotations;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
public class ObjectToJsonConverter {
public String convertToJson(Object object) throws JsonSerializationException {
try {
checkIfSerializable(object);
initializeObject(object);
return getJsonString(object);
} catch (Exception e) {
throw new JsonSerializationException(e.getMessage());
}
}
private void checkIfSerializable(Object object) {
if (Objects.isNull(object)) {
throw new JsonSerializationException("Can't serialize a null object");
}
Class<?> clazz = object.getClass();
if (!clazz.isAnnotationPresent(JsonSerializable.class)) {
throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable");
}
}
private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> clazz = object.getClass();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(Init.class)) {
method.setAccessible(true);
method.invoke(object);
}
}
}
private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
Class<?> clazz = object.getClass();
Map<String, String> jsonElementsMap = new HashMap<>();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
if (field.isAnnotationPresent(JsonElement.class)) {
jsonElementsMap.put(getKey(field), (String) field.get(object));
}
}
String jsonString = jsonElementsMap.entrySet()
.stream()
.map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
.collect(Collectors.joining(","));
return "{" + jsonString + "}";
}
private String getKey(Field field) {
String value = field.getAnnotation(JsonElement.class)
.key();
return value.isEmpty() ? field.getName() : value;
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.customannotations;
@JsonSerializable
public class Person {
@JsonElement
private String firstName;
@JsonElement
private String lastName;
@JsonElement(key = "personAge")
private String age;
private String address;
public Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public Person(String firstName, String lastName, String age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
@Init
private void initNames() {
this.firstName = this.firstName.substring(0, 1)
.toUpperCase() + this.firstName.substring(1);
this.lastName = this.lastName.substring(0, 1)
.toUpperCase() + this.lastName.substring(1);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

View File

@ -85,10 +85,16 @@ public class Java8CollectorsUnitTest {
}
@Test
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception {
final Map<String, Integer> result = listWithDuplicates.stream().collect(
toMap(
Function.identity(),
String::length,
(item, identicalItem) -> item
)
);
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("c", 1).containsEntry("d", 1);
}
@Test

View File

@ -0,0 +1,26 @@
package com.baeldung.customannotations;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class JsonSerializerUnitTest {
@Test
public void givenObjectNotSerializedThenExceptionThrown() throws JsonSerializationException {
Object object = new Object();
ObjectToJsonConverter serializer = new ObjectToJsonConverter();
assertThrows(JsonSerializationException.class, () -> {
serializer.convertToJson(object);
});
}
@Test
public void givenObjectSerializedThenTrueReturned() throws JsonSerializationException {
Person person = new Person("soufiane", "cheouati", "34");
ObjectToJsonConverter serializer = new ObjectToJsonConverter();
String jsonString = serializer.convertToJson(person);
assertEquals("{\"personAge\":\"34\",\"firstName\":\"Soufiane\",\"lastName\":\"Cheouati\"}", jsonString);
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.allequalelements;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import org.apache.commons.collections4.IterableUtils;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
public class VerifyAllEqualListElements {
public boolean verifyAllEqualUsingALoop(List<String> list) {
for (String s : list) {
if (!s.equals(list.get(0)))
return false;
}
return true;
}
public boolean verifyAllEqualUsingHashSet(List<String> list) {
return new HashSet<String>(list).size() <= 1;
}
public boolean verifyAllEqualUsingFrequency(List<String> list) {
return list.isEmpty() || Collections.frequency(list, list.get(0)) == list.size();
}
public boolean verifyAllEqualUsingStream(List<String> list) {
return list.stream()
.distinct()
.count() <= 1;
}
public boolean verifyAllEqualAnotherUsingStream(List<String> list) {
return list.isEmpty() || list.stream()
.allMatch(list.get(0)::equals);
}
public boolean verifyAllEqualUsingGuava(List<String> list) {
return Iterables.all(list, new Predicate<String>() {
public boolean apply(String s) {
return s.equals(list.get(0));
}
});
}
public boolean verifyAllEqualUsingApacheCommon(List<String> list) {
return IterableUtils.matchesAll(list, new org.apache.commons.collections4.Predicate<String>() {
public boolean evaluate(String s) {
return s.equals(list.get(0));
}
});
}
}

View File

@ -0,0 +1,172 @@
package com.baeldung.allequalelements;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class VerifyAllEqualListElementsUnitTest {
private static List<String> notAllEqualList = new ArrayList<>();
private static List<String> emptyList = new ArrayList<>();
private static List<String> allEqualList = new ArrayList<>();
static {
notAllEqualList = Arrays.asList("Jack", "James", "Sam", "James");
emptyList = Arrays.asList();
allEqualList = Arrays.asList("Jack", "Jack", "Jack", "Jack");
}
private static VerifyAllEqualListElements verifyAllEqualListElements = new VerifyAllEqualListElements();
@Test
public void givenNotAllEqualList_whenUsingALoop_thenReturnFalse() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(notAllEqualList);
assertFalse(allEqual);
}
@Test
public void givenEmptyList_whenUsingALoop_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(emptyList);
assertTrue(allEqual);
}
@Test
public void givenAllEqualList_whenUsingALoop_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(allEqualList);
assertTrue(allEqual);
}
@Test
public void givenNotAllEqualList_whenUsingHashSet_thenReturnFalse() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(notAllEqualList);
assertFalse(allEqual);
}
@Test
public void givenEmptyList_whenUsingHashSet_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(emptyList);
assertTrue(allEqual);
}
@Test
public void givenAllEqualList_whenUsingHashSet_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(allEqualList);
assertTrue(allEqual);
}
@Test
public void givenNotAllEqualList_whenUsingFrequency_thenReturnFalse() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(notAllEqualList);
assertFalse(allEqual);
}
@Test
public void givenEmptyList_whenUsingFrequency_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(emptyList);
assertTrue(allEqual);
}
@Test
public void givenAllEqualList_whenUsingFrequency_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(allEqualList);
assertTrue(allEqual);
}
@Test
public void givenNotAllEqualList_whenUsingStream_thenReturnFalse() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(notAllEqualList);
assertFalse(allEqual);
}
@Test
public void givenEmptyList_whenUsingStream_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(emptyList);
assertTrue(allEqual);
}
@Test
public void givenAllEqualList_whenUsingStream_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(allEqualList);
assertTrue(allEqual);
}
@Test
public void givenNotAllEqualList_whenUsingAnotherStream_thenReturnFalse() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(notAllEqualList);
assertFalse(allEqual);
}
@Test
public void givenEmptyList_whenUsingAnotherStream_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(emptyList);
assertTrue(allEqual);
}
@Test
public void givenAllEqualList_whenUsingAnotherStream_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(allEqualList);
assertTrue(allEqual);
}
@Test
public void givenNotAllEqualList_whenUsingGuava_thenReturnFalse() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(notAllEqualList);
assertFalse(allEqual);
}
@Test
public void givenEmptyList_whenUsingGuava_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(emptyList);
assertTrue(allEqual);
}
@Test
public void givenAllEqualList_whenUsingGuava_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(allEqualList);
assertTrue(allEqual);
}
@Test
public void givenNotAllEqualList_whenUsingApacheCommon_thenReturnFalse() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(notAllEqualList);
assertFalse(allEqual);
}
@Test
public void givenEmptyList_whenUsingApacheCommon_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(emptyList);
assertTrue(allEqual);
}
@Test
public void givenAllEqualList_whenUsingApacheCommon_thenReturnTrue() {
boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(allEqualList);
assertTrue(allEqual);
}
}

View File

@ -2,6 +2,6 @@ package com.baeldung.reflection;
public class MonthEmployee extends Employee {
private double reward;
protected double reward;
}

View File

@ -2,7 +2,7 @@ package com.baeldung.reflection;
public class Person {
public String lastName;
protected String lastName;
private String firstName;
}

View File

@ -3,10 +3,13 @@ package com.baeldung.reflection;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.*;
@ -26,30 +29,14 @@ public class PersonAndEmployeeReflectionUnitTest {
// Then
assertEquals(2, allFields.length);
Field lastNameField = allFields[0];
assertEquals(LAST_NAME_FIELD, lastNameField.getName());
assertEquals(String.class, lastNameField.getType());
Field firstNameField = allFields[1];
assertEquals(FIRST_NAME_FIELD, firstNameField.getName());
assertEquals(String.class, firstNameField.getType());
}
@Test
public void givenEmployeeClass_whenSuperClassGetDeclaredFields_thenOneField() {
// When
Field[] allFields = Employee.class.getSuperclass().getDeclaredFields();
// Then
assertEquals(2, allFields.length);
Field lastNameField = allFields[0];
assertEquals(LAST_NAME_FIELD, lastNameField.getName());
assertEquals(String.class, lastNameField.getType());
Field firstNameField = allFields[1];
assertEquals(FIRST_NAME_FIELD, firstNameField.getName());
assertEquals(String.class, firstNameField.getType());
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(LAST_NAME_FIELD)
&& field.getType().equals(String.class))
);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(FIRST_NAME_FIELD)
&& field.getType().equals(String.class))
);
}
@Test
@ -60,9 +47,28 @@ public class PersonAndEmployeeReflectionUnitTest {
// Then
assertEquals(1, allFields.length);
Field employeeIdField = allFields[0];
assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName());
assertEquals(int.class, employeeIdField.getType());
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(EMPLOYEE_ID_FIELD)
&& field.getType().equals(int.class))
);
}
@Test
public void givenEmployeeClass_whenSuperClassGetDeclaredFields_thenOneField() {
// When
Field[] allFields = Employee.class.getSuperclass().getDeclaredFields();
// Then
assertEquals(2, allFields.length);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(LAST_NAME_FIELD)
&& field.getType().equals(String.class))
);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(FIRST_NAME_FIELD)
&& field.getType().equals(String.class))
);
}
@Test
@ -76,42 +82,56 @@ public class PersonAndEmployeeReflectionUnitTest {
// Then
assertEquals(3, allFields.length);
Field lastNameField = allFields[0];
assertEquals(LAST_NAME_FIELD, lastNameField.getName());
assertEquals(String.class, lastNameField.getType());
Field firstNameField = allFields[1];
assertEquals(FIRST_NAME_FIELD, firstNameField.getName());
assertEquals(String.class, firstNameField.getType());
Field employeeIdField = allFields[2];
assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName());
assertEquals(int.class, employeeIdField.getType());
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(LAST_NAME_FIELD)
&& field.getType().equals(String.class))
);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(FIRST_NAME_FIELD)
&& field.getType().equals(String.class))
);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(EMPLOYEE_ID_FIELD)
&& field.getType().equals(int.class))
);
}
@Test
public void givenMonthEmployeeClass_whenGetAllFields_thenFourFields() {
public void givenEmployeeClass_whenGetDeclaredFieldsOnEmployeeSuperclassWithModifiersFilter_thenOneFields() {
// When
List<Field> personFields = Arrays.stream(Employee.class.getSuperclass().getDeclaredFields())
.filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers()))
.collect(Collectors.toList());
// Then
assertEquals(1, personFields.size());
assertTrue(personFields.stream().anyMatch(field ->
field.getName().equals(LAST_NAME_FIELD)
&& field.getType().equals(String.class))
);
}
@Test
public void givenMonthEmployeeClass_whenGetAllFields_thenThreeFields() {
// When
List<Field> allFields = getAllFields(MonthEmployee.class);
// Then
assertEquals(4, allFields.size());
assertEquals(3, allFields.size());
Field lastNameField = allFields.get(0);
assertEquals(LAST_NAME_FIELD, lastNameField.getName());
assertEquals(String.class, lastNameField.getType());
Field firstNameField = allFields.get(1);
assertEquals(FIRST_NAME_FIELD, firstNameField.getName());
assertEquals(String.class, firstNameField.getType());
Field employeeIdField = allFields.get(2);
assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName());
assertEquals(int.class, employeeIdField.getType());
Field monthEmployeeRewardField = allFields.get(3);
assertEquals(MONTH_EMPLOYEE_REWARD_FIELD, monthEmployeeRewardField.getName());
assertEquals(double.class, monthEmployeeRewardField.getType());
assertTrue(allFields.stream().anyMatch(field ->
field.getName().equals(LAST_NAME_FIELD)
&& field.getType().equals(String.class))
);
assertTrue(allFields.stream().anyMatch(field ->
field.getName().equals(EMPLOYEE_ID_FIELD)
&& field.getType().equals(int.class))
);
assertTrue(allFields.stream().anyMatch(field ->
field.getName().equals(MONTH_EMPLOYEE_REWARD_FIELD)
&& field.getType().equals(double.class))
);
}
public List<Field> getAllFields(Class clazz) {
@ -119,9 +139,11 @@ public class PersonAndEmployeeReflectionUnitTest {
return Collections.emptyList();
}
List<Field> result = new ArrayList<>();
result.addAll(getAllFields(clazz.getSuperclass()));
result.addAll(Arrays.asList(clazz.getDeclaredFields()));
List<Field> result = new ArrayList<>(getAllFields(clazz.getSuperclass()));
List<Field> filteredFields = Arrays.stream(clazz.getDeclaredFields())
.filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers()))
.collect(Collectors.toList());
result.addAll(filteredFields);
return result;
}

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

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

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

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

View File

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

Binary file not shown.

View File

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

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

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

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

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -22,107 +22,122 @@ public class MultiValuedMapUnitTest {
public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutMethod_thenReturningAllValues() {
MultiValuedMap<String, String> 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<String>) map.get("fruits")).containsExactly("apple", "orange");
assertThat((Collection<String>) map.get("key")).containsExactly("value1", "value2", "value2");
}
@Test
public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutAllMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.putAll("key", Arrays.asList("value1", "value2", "value2"));
map.putAll("vehicles", Arrays.asList("car", "bike"));
assertThat((Collection<String>) map.get("vehicles")).containsExactly("car", "bike");
assertThat((Collection<String>) map.get("key")).containsExactly("value1", "value2", "value2");
}
@Test
public void givenMultiValuesMap_whenGettingValueUsingGetMethod_thenReturningValue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
assertThat((Collection<String>) map.get("key")).containsExactly("value");
map.put("fruits", "apple");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple");
}
@Test
public void givenMultiValuesMap_whenUsingEntriesMethod_thenReturningMappings() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value1");
map.put("key", "value2");
map.put("fruits", "apple");
map.put("fruits", "orange");
Collection<Entry<String, String>> entries = (Collection<Entry<String, String>>) map.entries();
for(Map.Entry<String,String> 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<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.keys())).contains("key", "key1", "key2");
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.keys())).contains("fruits", "vehicles");
}
@Test
public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat((Collection<String>) map.keySet()).contains("key", "key1", "key2");
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat((Collection<String>) map.keySet()).contains("fruits", "vehicles");
}
@Test
public void givenMultiValuesMap_whenUsingValuesMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2");
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
}
@Test
public void givenMultiValuesMap_whenUsingRemoveMethod_thenReturningUpdatedMap() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2");
map.remove("key");
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
map.remove("fruits");
assertThat(((Collection<String>) map.values())).contains("car", "bike");
assertThat(((Collection<String>) map.values())).contains("value1", "value2");
}
@Test
public void givenMultiValuesMap_whenUsingRemoveMappingMethod_thenReturningUpdatedMapAfterMappingRemoved() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2");
map.removeMapping("key", "value");
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
assertThat(((Collection<String>) map.values())).contains("value1", "value2");
map.removeMapping("fruits", "apple");
assertThat(((Collection<String>) map.values())).contains("orange", "car", "bike");
}
@Test
public void givenMultiValuesMap_whenUsingClearMethod_thenReturningEmptyMap() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2");
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
map.clear();
@ -132,29 +147,32 @@ public class MultiValuedMapUnitTest {
@Test
public void givenMultiValuesMap_whenUsingContainsKeyMethod_thenReturningTrue() {
MultiValuedMap<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String>) map.get("key")).containsExactly("value1", "value2", "value2");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple", "orange", "orange");
}
@Test
public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() {
MultiValuedMap<String, String> map = new HashSetValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "apple");
map.put("key1", "value1");
map.put("key1", "value1");
assertThat((Collection<String>) map.get("key1")).containsExactly("value1");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple");
}
@Test(expected = UnsupportedOperationException.class)
public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value1");
map.put("key", "value2");
map.put("fruits", "apple");
map.put("fruits", "orange");
MultiValuedMap<String, String> immutableMap = MultiMapUtils.unmodifiableMultiValuedMap(map);
immutableMap.put("key", "value3");
immutableMap.put("fruits", "banana");
}

View File

@ -0,0 +1,83 @@
package com.baeldung.stream;
import org.junit.Before;
import org.junit.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class StreamMapUnitTest {
private Map<String, String> books;
@Before
public void setup() {
books = new HashMap<>();
books.put("978-0201633610", "Design patterns : elements of reusable object-oriented software");
books.put("978-1617291999", "Java 8 in Action: Lambdas, Streams, and functional-style programming");
books.put("978-0134685991", "Effective Java");
}
@Test
public void whenOptionalVersionCalledForExistingTitle_thenReturnOptionalWithISBN() {
Optional<String> optionalIsbn = books.entrySet().stream()
.filter(e -> "Effective Java".equals(e.getValue()))
.map(Map.Entry::getKey).findFirst();
assertEquals("978-0134685991", optionalIsbn.get());
}
@Test
public void whenOptionalVersionCalledForNonExistingTitle_thenReturnEmptyOptionalForISBN() {
Optional<String> optionalIsbn = books.entrySet().stream()
.filter(e -> "Non Existent Title".equals(e.getValue()))
.map(Map.Entry::getKey).findFirst();
assertEquals(false, optionalIsbn.isPresent());
}
@Test
public void whenMultipleResultsVersionCalledForExistingTitle_aCollectionWithMultipleValuesIsReturned() {
books.put("978-0321356680", "Effective Java: Second Edition");
List<String> isbnCodes = books.entrySet().stream()
.filter(e -> e.getValue().startsWith("Effective Java"))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
assertTrue(isbnCodes.contains("978-0321356680"));
assertTrue(isbnCodes.contains("978-0134685991"));
}
@Test
public void whenMultipleResultsVersionCalledForNonExistingTitle_aCollectionWithNoValuesIsReturned() {
List<String> isbnCodes = books.entrySet().stream()
.filter(e -> e.getValue().startsWith("Spring"))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
assertTrue(isbnCodes.isEmpty());
}
@Test
public void whenKeysFollowingPatternReturnsAllValuesForThoseKeys() {
List<String> titlesForKeyPattern = books.entrySet().stream()
.filter(e -> e.getKey().startsWith("978-0"))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
assertEquals(2, titlesForKeyPattern.size());
assertTrue(titlesForKeyPattern.contains("Design patterns : elements of reusable object-oriented software"));
assertTrue(titlesForKeyPattern.contains("Effective Java"));
}
}

View File

@ -73,6 +73,16 @@
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk-jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk-jmh.version}</version>
</dependency>
</dependencies>
<build>
@ -92,6 +102,7 @@
<h2database.version>1.4.196</h2database.version>
<assertj-core.version>3.8.0</assertj-core.version>
<jackson.version>2.9.7</jackson.version>
<openjdk-jmh.version>1.21</openjdk-jmh.version>
</properties>
</project>

View File

@ -68,6 +68,11 @@ public class HibernateUtil {
return sessionFactory;
}
public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException {
ServiceRegistry serviceRegistry = configureServiceRegistry(properties);
return makeSessionFactory(serviceRegistry);
}
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
@ -119,12 +124,15 @@ public class HibernateUtil {
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return configureServiceRegistry(getProperties());
}
private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException {
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
public static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()

View File

@ -0,0 +1,106 @@
package com.baeldung.hibernate.queryplancache;
import com.baeldung.hibernate.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.jpa.QueryHints;
import org.hibernate.query.Query;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.RunnerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
public class QueryPlanCacheBenchmark {
private static final Logger LOGGER = LoggerFactory.getLogger(QueryPlanCacheBenchmark.class);
@State(Scope.Thread)
public static class QueryPlanCacheBenchMarkState {
@Param({"1", "2", "3"})
public int planCacheSize;
public Session session;
@Setup
public void stateSetup() throws IOException {
LOGGER.info("State - Setup");
session = initSession(planCacheSize);
LOGGER.info("State - Setup Complete");
}
private Session initSession(int planCacheSize) throws IOException {
Properties properties = HibernateUtil.getProperties();
properties.put("hibernate.query.plan_cache_max_size", planCacheSize);
properties.put("hibernate.query.plan_parameter_metadata_max_size", planCacheSize);
SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties);
return sessionFactory.openSession();
}
@TearDown
public void tearDownState() {
LOGGER.info("State - Teardown");
SessionFactory sessionFactory = session.getSessionFactory();
session.close();
sessionFactory.close();
LOGGER.info("State - Teardown complete");
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(1)
@Warmup(iterations = 2)
@Measurement(iterations = 5)
public void givenQueryPlanCacheSize_thenCompileQueries(QueryPlanCacheBenchMarkState state, Blackhole blackhole) {
Query query1 = findEmployeesByDepartmentNameQuery(state.session);
Query query2 = findEmployeesByDesignationQuery(state.session);
Query query3 = findDepartmentOfAnEmployeeQuery(state.session);
blackhole.consume(query1);
blackhole.consume(query2);
blackhole.consume(query3);
}
private Query findEmployeesByDepartmentNameQuery(Session session) {
return session.createQuery("SELECT e FROM DeptEmployee e " +
"JOIN e.department WHERE e.department.name = :deptName")
.setMaxResults(30)
.setHint(QueryHints.HINT_FETCH_SIZE, 30);
}
private Query findEmployeesByDesignationQuery(Session session) {
return session.createQuery("SELECT e FROM DeptEmployee e " +
"WHERE e.title = :designation")
.setHint(QueryHints.SPEC_HINT_TIMEOUT, 1000);
}
private Query findDepartmentOfAnEmployeeQuery(Session session) {
return session.createQuery("SELECT e.department FROM DeptEmployee e " +
"JOIN e.department WHERE e.employeeNumber = :empId");
}
public static void main(String... args) throws IOException, RunnerException {
//main-class to run the benchmark
org.openjdk.jmh.Main.main(args);
}
}

View File

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

View File

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

View File

@ -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;

View File

@ -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;

View File

@ -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<User, Integer> , UserRepos
@Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();
@Query(value = "SELECT * FROM USERS.USERS u WHERE u.status = 1", nativeQuery = true)
@Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
Collection<User> findAllActiveUsersNative();
@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<User, Integer> , 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<User, Integer> , 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<User, Integer> , UserRepos
@Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable);
@Query(value = "SELECT * FROM USERS.Users ORDER BY id", countQuery = "SELECT count(*) FROM USERS.Users", nativeQuery = true)
@Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
Page<User> findAllUsersWithPaginationNative(Pageable pageable);
@Modifying
@ -65,6 +64,13 @@ public interface UserRepository extends JpaRepository<User, Integer> , 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);
@Query(value = "SELECT u FROM User u WHERE u.name IN :names")
List<User> findUserByNameList(@Param("names") Collection<String> names);
}

View File

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

View File

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

View File

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

View File

@ -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<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
assertThat(foundUsersStream.count()).isEqualTo(3l);
}
}
@Test
public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLike("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNative("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
List<User> usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
assertThat(usersSortByName.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test(expected = PropertyReferenceException.class)
public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
List<User> usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAllUsers(new Sort("name"));
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3));
assertThat(usersPage.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3));
assertThat(usersSortByNameLength.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@Test
@Transactional
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
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<String> emails = new HashSet<>();
emails.add(USER_EMAIL2);
emails.add(USER_EMAIL3);
Collection<User> usersWithEmails = userRepository.findUserByEmails(emails);
assertThat(usersWithEmails.size()).isEqualTo(2);
}
@After
public void cleanUp() {
userRepository.deleteAll();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,8 +4,8 @@
### Relevant Articles:
- [Spring 3 and JPA with Hibernate](http://www.baeldung.com/2011/12/13/the-persistence-layer-with-spring-3-1-and-jpa/)
- [Transactions with Spring 3 and JPA](http://www.baeldung.com/2011/12/26/transaction-configuration-with-jpa-and-spring-3-1/)
- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
- [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa)
- [JPA Pagination](http://www.baeldung.com/jpa-pagination)
- [Sorting with JPA](http://www.baeldung.com/jpa-sort)
@ -21,6 +21,7 @@
- [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries)
- [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many)
### Eclipse Config
After importing the project into Eclipse, you may see the following error:
"No persistence xml file found in project"

View File

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

View File

@ -1,66 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-boot-mvc</artifactId>
<name>spring-boot-mvc</name>
<packaging>jar</packaging>
<description>Module For Spring Boot MVC</description>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-boot-mvc</artifactId>
<name>spring-boot-mvc</name>
<packaging>jar</packaging>
<description>Module For Spring Boot MVC</description>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--JSF -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.3.7</version>
</dependency>
<!--Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--JSF -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.3.7</version>
</dependency>
<!-- ROME for RSS -->
<dependency>
<groupId>com.rometools</groupId>
<artifactId>rome</artifactId>
<version>${rome.version}</version>
</dependency>
<!--Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Validation -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- ROME for RSS -->
<dependency>
<groupId>com.rometools</groupId>
<artifactId>rome</artifactId>
<version>${rome.version}</version>
</dependency>
<!-- Spring Fox 2 -->
<!--Validation -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Spring Fox 2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
@ -77,31 +88,27 @@
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.springbootmvc.SpringBootMvcApplication</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>
</plugins>
</build>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.springbootmvc.SpringBootMvcApplication</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring.fox.version>2.9.2</spring.fox.version>
<!-- ROME for RSS -->
<rome.version>1.10.0</rome.version>
<start-class>com.baeldung.springbootmvc.SpringBootMvcApplication</start-class>
</properties>
<properties>
<spring.fox.version>2.9.2</spring.fox.version>
<!-- ROME for RSS -->
<rome.version>1.10.0</rome.version>
<start-class>com.baeldung.springbootmvc.SpringBootMvcApplication</start-class>
</properties>
</project>

View File

@ -9,5 +9,4 @@ public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

View File

@ -23,10 +23,10 @@ public class Controller {
* @return
*/
@RequestMapping("/index")
public ModelAndView index(Map<String, Object> model) {
public ModelAndView thymeleafView(Map<String, Object> model) {
model.put("number", 1234);
model.put("message", "Hello from Spring MVC");
return new ModelAndView("/index");
return new ModelAndView("thymeleaf/index");
}
}

View File

@ -1,3 +1,2 @@
spring.main.allow-bean-definition-overriding=true
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.thymeleaf.view-names=thymeleaf/*

View File

@ -0,0 +1,29 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Access Spring MVC params</title>
<script src="/js/jquery.js"></script>
<script src="/js/script-async.js"></script>
<script src="/js/script-async-jquery.js"></script>
<script>
var number = [[${number}]];
var message = "[[${message}]]";
</script>
</head>
<body>
Number=
<span th:text="${number}" th:remove="tag"></span>
<br /> Message=
<span th:text="${message}" th:remove="tag"></span>
<h2>Data from the external JS file (due to loading order)</h2>
<div id="number-ext"></div>
<div id="message-ext"></div>
<h2>Asynchronous loading from external JS file (plain JS)</h2>
<div id="number-async"></div>
<div id="message-async"></div>
<h2>Asynchronous loading from external JS file (jQuery)</h2>
<div id="number-async-jquery"></div>
<div id="message-async-jquery"></div>
</body>
<script src="/js/script.js"></script>
</html>

View File

@ -1,27 +0,0 @@
<!DOCTYPE html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html lang="en">
<head>
<title>Access Spring MVC params</title>
<script src="/js/jquery.js"></script>
<script src="/js/script-async.js"></script>
<script src="/js/script-async-jquery.js"></script>
<script>
var number = <c:out value="${number}"></c:out>;
var message = "<c:out value="${message}"></c:out>";
</script>
</head>
<body>
<h2>Data from the external JS file (due to loading order)</h2>
<div id="number-ext"></div>
<div id="message-ext"></div>
<h2>Asynchronous loading from external JS file (plain JS)</h2>
<div id="number-async"></div>
<div id="message-async"></div>
<h2>Asynchronous loading from external JS file (jQuery)</h2>
<div id="number-async-jquery"></div>
<div id="message-async-jquery"></div>
</body>
<script src="/js/script.js"></script>
</html>

View File

@ -20,9 +20,10 @@ public class ControllerUnitTest {
private MockMvc mvc;
@Test
public void whenRequestIndex_thenStatusOk() throws Exception {
public void whenRequestThymeleaf_thenStatusOk() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/index")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}

View File

@ -4,3 +4,5 @@ Module for the articles that are part of the Spring REST E-book:
2. [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring)
3. [REST Pagination in Spring](http://www.baeldung.com/rest-api-pagination-in-spring)
4. [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration)
5. [HATEOAS for a Spring REST Service](http://www.baeldung.com/rest-api-discoverability-with-spring)
6. [REST API Discoverability and HATEOAS](http://www.baeldung.com/restful-web-service-discoverability)

View File

@ -1,4 +1,4 @@
package org.baeldung.common.web;
package com.baeldung.common.web;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.containsString;
@ -8,8 +8,8 @@ import static org.junit.Assert.assertThat;
import java.io.Serializable;
import org.baeldung.persistence.model.Foo;
import org.baeldung.web.util.HTTPLinkHeaderUtil;
import com.baeldung.persistence.model.Foo;
import com.baeldung.web.util.HTTPLinkHeaderUtil;
import org.hamcrest.core.AnyOf;
import org.junit.Test;
import org.springframework.http.MediaType;

View File

@ -1,10 +1,10 @@
package org.baeldung.web;
package com.baeldung.web;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.baeldung.common.web.AbstractDiscoverabilityLiveTest;
import org.baeldung.persistence.model.Foo;
import org.baeldung.spring.ConfigIntegrationTest;
import com.baeldung.common.web.AbstractDiscoverabilityLiveTest;
import com.baeldung.persistence.model.Foo;
import com.baeldung.spring.ConfigIntegrationTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;

View File

@ -1,11 +1,13 @@
package com.baeldung.web;
import com.baeldung.web.FooDiscoverabilityLiveTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
// @formatter:off
FooDiscoverabilityLiveTest.class,
FooLiveTest.class
,FooPageableLiveTest.class
}) //

View File

@ -8,8 +8,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
### Relevant Articles:
- [HATEOAS for a Spring REST Service](http://www.baeldung.com/rest-api-discoverability-with-spring)
- [REST API Discoverability and HATEOAS](http://www.baeldung.com/restful-web-service-discoverability)
- [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring)
- [Integration Testing with the Maven Cargo plugin](http://www.baeldung.com/integration-testing-with-the-maven-cargo-plugin)
- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)

View File

@ -7,7 +7,6 @@ import javax.servlet.http.HttpServletResponse;
import org.baeldung.persistence.model.Foo;
import org.baeldung.persistence.service.IFooService;
import org.baeldung.web.hateoas.event.ResourceCreatedEvent;
import org.baeldung.web.hateoas.event.SingleResourceRetrievedEvent;
import org.baeldung.web.util.RestPreconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
@ -53,7 +52,6 @@ public class FooController {
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
return resourceById;
}

View File

@ -1,22 +1,14 @@
package org.baeldung.web.controller;
import java.net.URI;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.baeldung.web.metric.IActuatorMetricService;
import org.baeldung.web.metric.IMetricService;
import org.baeldung.web.util.LinkUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.util.UriTemplate;
@Controller
@RequestMapping(value = "/auth/")
@ -34,18 +26,6 @@ public class RootController {
// API
// discover
@RequestMapping(value = "admin", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
final String rootUri = request.getRequestURL().toString();
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
response.addHeader("Link", linkToFoo);
}
@RequestMapping(value = "/metric", method = RequestMethod.GET)
@ResponseBody
public Map getMetric() {

View File

@ -1,22 +0,0 @@
package org.baeldung.web.hateoas.event;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEvent;
public class SingleResourceRetrievedEvent extends ApplicationEvent {
private final HttpServletResponse response;
public SingleResourceRetrievedEvent(final Object source, final HttpServletResponse response) {
super(source);
this.response = response;
}
// API
public HttpServletResponse getResponse() {
return response;
}
}

View File

@ -1,34 +0,0 @@
package org.baeldung.web.hateoas.listener;
import javax.servlet.http.HttpServletResponse;
import org.baeldung.web.hateoas.event.SingleResourceRetrievedEvent;
import org.baeldung.web.util.LinkUtil;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
@Component
class SingleResourceRetrievedDiscoverabilityListener implements ApplicationListener<SingleResourceRetrievedEvent> {
@Override
public void onApplicationEvent(final SingleResourceRetrievedEvent resourceRetrievedEvent) {
Preconditions.checkNotNull(resourceRetrievedEvent);
final HttpServletResponse response = resourceRetrievedEvent.getResponse();
addLinkHeaderOnSingleResourceRetrieval(response);
}
void addLinkHeaderOnSingleResourceRetrieval(final HttpServletResponse response) {
final String requestURL = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri().toASCIIString();
final int positionOfLastSlash = requestURL.lastIndexOf("/");
final String uriForResourceCreation = requestURL.substring(0, positionOfLastSlash);
final String linkHeaderValue = LinkUtil.createLinkHeader(uriForResourceCreation, "collection");
response.addHeader(HttpHeaders.LINK, linkHeaderValue);
}
}

View File

@ -6,8 +6,7 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
// @formatter:off
FooDiscoverabilityLiveTest.class
,FooLiveTest.class
FooLiveTest.class
}) //
public class LiveTestSuiteLiveTest {

View File

@ -1,36 +0,0 @@
package org.baeldung.web.util;
public final class HTTPLinkHeaderUtil {
private HTTPLinkHeaderUtil() {
throw new AssertionError();
}
//
public static String extractURIByRel(final String linkHeader, final String rel) {
if (linkHeader == null) {
return null;
}
String uriWithSpecifiedRel = null;
final String[] links = linkHeader.split(", ");
String linkRelation;
for (final String link : links) {
final int positionOfSeparator = link.indexOf(';');
linkRelation = link.substring(positionOfSeparator + 1, link.length()).trim();
if (extractTypeOfRelation(linkRelation).equals(rel)) {
uriWithSpecifiedRel = link.substring(1, positionOfSeparator - 1);
break;
}
}
return uriWithSpecifiedRel;
}
private static Object extractTypeOfRelation(final String linkRelation) {
final int positionOfEquals = linkRelation.indexOf('=');
return linkRelation.substring(positionOfEquals + 2, linkRelation.length() - 1).trim();
}
}

View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-cors</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-security-cors</name>
<description>Spring Security CORS</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.springbootsecuritycors.basicauth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecuritycors")
@EnableAutoConfiguration
public class SpringBootSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSecurityApplication.class, args);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.springbootsecuritycors.basicauth.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
http.cors(); //disable this line to reproduce the CORS 401
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.springbootsecuritycors.controller;
import java.security.Principal;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin("http://localhost:4200")
public class ResourceController {
@GetMapping("/user")
public String user(Principal principal) {
return principal.getName();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.springbootsecuritycors;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
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.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.springbootsecuritycors.basicauth.SpringBootSecurityApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SpringBootSecurityApplication.class })
public class ResourceControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
@Test
public void givenPreFlightRequest_whenPerfomed_shouldReturnOK() throws Exception {
mockMvc.perform(options("/user")
.header("Access-Control-Request-Method", "GET")
.header("Origin", "http://localhost:4200"))
.andExpect(status().isOk());
}
}

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

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

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

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

View File

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

View File

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

View File

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

Some files were not shown because too many files have changed in this diff Show More