Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
46763c9afd
25
README.md
25
README.md
|
@ -1,12 +1,16 @@
|
|||
|
||||
The "REST with Spring" Classes
|
||||
The Courses
|
||||
==============================
|
||||
|
||||
Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material): <br/>
|
||||
**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
|
||||
And here's the Master Class of Learn Spring Security: <br/>
|
||||
**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||
Here's the new "Learn Spring" course: <br/>
|
||||
**[>> LEARN SPRING - THE MASTER CLASS](https://www.baeldung.com/learn-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=ls#master-class)**
|
||||
|
||||
Here's the Master Class of "REST With Spring" (along with the new announced Boot 2 material): <br/>
|
||||
**[>> THE REST WITH SPRING - MASTER CLASS](https://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
|
||||
And here's the Master Class of "Learn Spring Security": <br/>
|
||||
**[>> LEARN SPRING SECURITY - MASTER CLASS](https://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||
|
||||
|
||||
|
||||
|
@ -15,7 +19,7 @@ Java and Spring Tutorials
|
|||
|
||||
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
||||
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security.
|
||||
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
||||
In additional to Spring, the modules here are covering a number of aspects in Java.
|
||||
|
||||
|
||||
Building the project
|
||||
|
@ -32,8 +36,15 @@ Running a Spring Boot module
|
|||
====================
|
||||
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
|
||||
|
||||
###Running Tests
|
||||
|
||||
Working with the IDE
|
||||
====================
|
||||
This repo contains a large number of modules.
|
||||
When you're working with an individual module, there's no need to import all of them (or build all of them) - you can simply import that particular module in either Eclipse or IntelliJ.
|
||||
|
||||
|
||||
Running Tests
|
||||
=============
|
||||
The command `mvn clean install` will run the unit tests in a module.
|
||||
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
||||
|
||||
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
|
||||
|
|
|
@ -0,0 +1,25 @@
|
|||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,50 @@
|
|||
<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>core-java-arrays-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-arrays-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-arrays-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
<!-- testing -->
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -4,7 +4,7 @@ import org.junit.Test;
|
|||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class LoopDiagonallyTest {
|
||||
public class LoopDiagonallyUnitTest {
|
||||
|
||||
@Test
|
||||
public void twoArrayIsLoopedDiagonallyAsExpected() {
|
|
@ -1,3 +1,3 @@
|
|||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
||||
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.files;
|
||||
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner;
|
||||
|
||||
public class Main {
|
||||
|
||||
private static final String INPUT_FILE_NAME = "src/main/resources/input.txt";
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
System.out.printf("Total Number of Lines Using BufferedReader: %s%n", getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME));
|
||||
System.out.printf("Total Number of Lines Using LineNumberReader: %s%n", getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME));
|
||||
System.out.printf("Total Number of Lines Using Scanner: %s%n", getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME));
|
||||
System.out.printf("Total Number of Lines Using NIO Files: %s%n", getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME));
|
||||
System.out.printf("Total Number of Lines Using NIO FileChannel: %s%n", getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME));
|
||||
System.out.printf("Total Number of Lines Using Apache Commons IO: %s%n", getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME));
|
||||
System.out.printf("Total Number of Lines Using NIO Google Guava: %s%n", getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,112 @@
|
|||
package com.baeldung.files;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.LineNumberReader;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileChannel.MapMode;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.LineIterator;
|
||||
|
||||
public class NumberOfLineFinder {
|
||||
|
||||
public static int getTotalNumberOfLinesUsingBufferedReader(String fileName) {
|
||||
int lines = 0;
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
|
||||
while (reader.readLine() != null) {
|
||||
lines++;
|
||||
}
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
public static int getTotalNumberOfLinesUsingLineNumberReader(String fileName) {
|
||||
int lines = 0;
|
||||
try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) {
|
||||
reader.skip(Integer.MAX_VALUE);
|
||||
lines = reader.getLineNumber() + 1;
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
public static int getTotalNumberOfLinesUsingScanner(String fileName) {
|
||||
int lines = 0;
|
||||
try (Scanner scanner = new Scanner(new FileReader(fileName))) {
|
||||
while (scanner.hasNextLine()) {
|
||||
scanner.nextLine();
|
||||
lines++;
|
||||
}
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
public static int getTotalNumberOfLinesUsingNIOFiles(String fileName) {
|
||||
int lines = 0;
|
||||
try (Stream<String> fileStream = Files.lines(Paths.get(fileName))) {
|
||||
lines = (int) fileStream.count();
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
public static int getTotalNumberOfLinesUsingNIOFileChannel(String fileName) {
|
||||
int lines = 1;
|
||||
try (FileChannel channel = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ)) {
|
||||
ByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, channel.size());
|
||||
while (byteBuffer.hasRemaining()) {
|
||||
byte currentChar = byteBuffer.get();
|
||||
if (currentChar == '\n') {
|
||||
lines++;
|
||||
}
|
||||
}
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
public static int getTotalNumberOfLinesUsingApacheCommonsIO(String fileName) {
|
||||
int lines = 0;
|
||||
try {
|
||||
LineIterator lineIterator = FileUtils.lineIterator(new File(fileName));
|
||||
while (lineIterator.hasNext()) {
|
||||
lineIterator.nextLine();
|
||||
lines++;
|
||||
}
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
public static int getTotalNumberOfLinesUsingGoogleGuava(String fileName) {
|
||||
int lines = 0;
|
||||
try {
|
||||
List<String> lineItems = com.google.common.io.Files.readLines(Paths.get(fileName)
|
||||
.toFile(), Charset.defaultCharset());
|
||||
lines = lineItems.size();
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package com.baeldung.file;
|
||||
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles;
|
||||
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class NumberOfLineFinderUnitTest {
|
||||
private static final String INPUT_FILE_NAME = "src/main/resources/input.txt";
|
||||
private static final int ACTUAL_LINE_COUNT = 45;
|
||||
|
||||
@Test
|
||||
public void whenUsingBufferedReader_thenReturnTotalNumberOfLines() {
|
||||
int lines = getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME);
|
||||
assertEquals(ACTUAL_LINE_COUNT, lines);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingLineNumberReader_thenReturnTotalNumberOfLines() {
|
||||
int lines = getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME);
|
||||
assertEquals(ACTUAL_LINE_COUNT, lines);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingScanner_thenReturnTotalNumberOfLines() {
|
||||
int lines = getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME);
|
||||
assertEquals(ACTUAL_LINE_COUNT, lines);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingNIOFiles_thenReturnTotalNumberOfLines() {
|
||||
int lines = getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME);
|
||||
assertEquals(ACTUAL_LINE_COUNT, lines);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingNIOFileChannel_thenReturnTotalNumberOfLines() {
|
||||
int lines = getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME);
|
||||
assertEquals(ACTUAL_LINE_COUNT, lines);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingApacheCommonsIO_thenReturnTotalNumberOfLines() {
|
||||
int lines = getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME);
|
||||
assertEquals(ACTUAL_LINE_COUNT, lines);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingGoogleGuava_thenReturnTotalNumberOfLines() {
|
||||
int lines = getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME);
|
||||
assertEquals(ACTUAL_LINE_COUNT, lines);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.relationships.aggregation;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Car {
|
||||
|
||||
private List<Wheel> wheels;
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.relationships.aggregation;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class CarWithStaticInnerWheel {
|
||||
|
||||
private List<Wheel> wheels;
|
||||
|
||||
public static class Wheel {
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.relationships.aggregation;
|
||||
|
||||
public class Wheel {
|
||||
|
||||
private Car car;
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.relationships.association;
|
||||
|
||||
public class Child {
|
||||
|
||||
private Mother mother;
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.relationships.association;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Mother {
|
||||
|
||||
private List<Child> children;
|
||||
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.relationships.composition;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Building {
|
||||
|
||||
private String address;
|
||||
private List<Room> rooms;
|
||||
|
||||
public class Room {
|
||||
|
||||
public String getBuildingAddress() {
|
||||
return Building.this.address;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.relationships.composition;
|
||||
|
||||
public class BuildingWithDefinitionRoomInMethod {
|
||||
|
||||
public Room createAnonymousRoom() {
|
||||
return new Room() {
|
||||
@Override
|
||||
public void doInRoom() {}
|
||||
};
|
||||
}
|
||||
|
||||
public Room createInlineRoom() {
|
||||
class InlineRoom implements Room {
|
||||
@Override
|
||||
public void doInRoom() {}
|
||||
}
|
||||
return new InlineRoom();
|
||||
}
|
||||
|
||||
public Room createLambdaRoom() {
|
||||
return () -> {};
|
||||
}
|
||||
|
||||
public interface Room {
|
||||
void doInRoom();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.relationships.university;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Department {
|
||||
|
||||
private List<Professor> professors;
|
||||
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.relationships.university;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Professor {
|
||||
|
||||
private List<Department> department;
|
||||
private List<Professor> friends;
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.relationships.university;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class University {
|
||||
|
||||
private List<Department> department;
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.sasl;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.security.auth.callback.Callback;
|
||||
import javax.security.auth.callback.CallbackHandler;
|
||||
import javax.security.auth.callback.NameCallback;
|
||||
import javax.security.auth.callback.PasswordCallback;
|
||||
import javax.security.auth.callback.UnsupportedCallbackException;
|
||||
import javax.security.sasl.RealmCallback;
|
||||
|
||||
public class ClientCallbackHandler implements CallbackHandler {
|
||||
|
||||
@Override
|
||||
public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException {
|
||||
for (Callback cb : cbs) {
|
||||
if (cb instanceof NameCallback) {
|
||||
NameCallback nc = (NameCallback) cb;
|
||||
nc.setName("username");
|
||||
} else if (cb instanceof PasswordCallback) {
|
||||
PasswordCallback pc = (PasswordCallback) cb;
|
||||
pc.setPassword("password".toCharArray());
|
||||
} else if (cb instanceof RealmCallback) {
|
||||
RealmCallback rc = (RealmCallback) cb;
|
||||
rc.setText("myServer");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.sasl;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.security.auth.callback.Callback;
|
||||
import javax.security.auth.callback.CallbackHandler;
|
||||
import javax.security.auth.callback.NameCallback;
|
||||
import javax.security.auth.callback.PasswordCallback;
|
||||
import javax.security.auth.callback.UnsupportedCallbackException;
|
||||
import javax.security.sasl.AuthorizeCallback;
|
||||
import javax.security.sasl.RealmCallback;
|
||||
|
||||
public class ServerCallbackHandler implements CallbackHandler {
|
||||
|
||||
@Override
|
||||
public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException {
|
||||
for (Callback cb : cbs) {
|
||||
if (cb instanceof AuthorizeCallback) {
|
||||
AuthorizeCallback ac = (AuthorizeCallback) cb;
|
||||
ac.setAuthorized(true);
|
||||
} else if (cb instanceof NameCallback) {
|
||||
NameCallback nc = (NameCallback) cb;
|
||||
nc.setName("username");
|
||||
|
||||
} else if (cb instanceof PasswordCallback) {
|
||||
PasswordCallback pc = (PasswordCallback) cb;
|
||||
pc.setPassword("password".toCharArray());
|
||||
} else if (cb instanceof RealmCallback) {
|
||||
RealmCallback rc = (RealmCallback) cb;
|
||||
rc.setText("myServer");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
package com.baeldung.sasl;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.security.sasl.Sasl;
|
||||
import javax.security.sasl.SaslClient;
|
||||
import javax.security.sasl.SaslException;
|
||||
import javax.security.sasl.SaslServer;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SaslUnitTest {
|
||||
|
||||
private static final String MECHANISM = "DIGEST-MD5";
|
||||
private static final String SERVER_NAME = "myServer";
|
||||
private static final String PROTOCOL = "myProtocol";
|
||||
private static final String AUTHORIZATION_ID = null;
|
||||
private static final String QOP_LEVEL = "auth-conf";
|
||||
|
||||
private SaslServer saslServer;
|
||||
private SaslClient saslClient;
|
||||
|
||||
@Before
|
||||
public void setUp() throws SaslException {
|
||||
|
||||
ServerCallbackHandler serverHandler = new ServerCallbackHandler();
|
||||
ClientCallbackHandler clientHandler = new ClientCallbackHandler();
|
||||
|
||||
Map<String, String> props = new HashMap<>();
|
||||
props.put(Sasl.QOP, QOP_LEVEL);
|
||||
|
||||
saslServer = Sasl.createSaslServer(MECHANISM, PROTOCOL, SERVER_NAME, props, serverHandler);
|
||||
saslClient = Sasl.createSaslClient(new String[] { MECHANISM }, AUTHORIZATION_ID, PROTOCOL, SERVER_NAME, props, clientHandler);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHandlers_whenStarted_thenAutenticationWorks() throws SaslException {
|
||||
|
||||
byte[] challenge;
|
||||
byte[] response;
|
||||
|
||||
challenge = saslServer.evaluateResponse(new byte[0]);
|
||||
response = saslClient.evaluateChallenge(challenge);
|
||||
|
||||
challenge = saslServer.evaluateResponse(response);
|
||||
response = saslClient.evaluateChallenge(challenge);
|
||||
|
||||
assertTrue(saslServer.isComplete());
|
||||
assertTrue(saslClient.isComplete());
|
||||
|
||||
String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP);
|
||||
assertEquals("auth-conf", qop);
|
||||
|
||||
byte[] outgoing = "Baeldung".getBytes();
|
||||
byte[] secureOutgoing = saslClient.wrap(outgoing, 0, outgoing.length);
|
||||
|
||||
byte[] secureIncoming = secureOutgoing;
|
||||
byte[] incoming = saslServer.unwrap(secureIncoming, 0, secureIncoming.length);
|
||||
assertEquals("Baeldung", new String(incoming, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws SaslException {
|
||||
saslClient.dispose();
|
||||
saslServer.dispose();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant Articles
|
||||
|
||||
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
|
|
@ -0,0 +1,72 @@
|
|||
package com.baeldung.graph;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Stack;
|
||||
|
||||
public class Graph {
|
||||
|
||||
private Map<Integer, List<Integer>> adjVertices;
|
||||
|
||||
public Graph() {
|
||||
this.adjVertices = new HashMap<Integer, List<Integer>>();
|
||||
}
|
||||
|
||||
public void addVertex(int vertex) {
|
||||
adjVertices.putIfAbsent(vertex, new ArrayList<>());
|
||||
}
|
||||
|
||||
public void addEdge(int src, int dest) {
|
||||
adjVertices.get(src).add(dest);
|
||||
}
|
||||
|
||||
public void dfsWithoutRecursion(int start) {
|
||||
Stack<Integer> stack = new Stack<Integer>();
|
||||
boolean[] isVisited = new boolean[adjVertices.size()];
|
||||
stack.push(start);
|
||||
while (!stack.isEmpty()) {
|
||||
int current = stack.pop();
|
||||
isVisited[current] = true;
|
||||
System.out.print(" " + current);
|
||||
for (int dest : adjVertices.get(current)) {
|
||||
if (!isVisited[dest])
|
||||
stack.push(dest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void dfs(int start) {
|
||||
boolean[] isVisited = new boolean[adjVertices.size()];
|
||||
dfsRecursive(start, isVisited);
|
||||
}
|
||||
|
||||
private void dfsRecursive(int current, boolean[] isVisited) {
|
||||
isVisited[current] = true;
|
||||
System.out.print(" " + current);
|
||||
for (int dest : adjVertices.get(current)) {
|
||||
if (!isVisited[dest])
|
||||
dfsRecursive(dest, isVisited);
|
||||
}
|
||||
}
|
||||
|
||||
public void topologicalSort(int start) {
|
||||
Stack<Integer> result = new Stack<Integer>();
|
||||
boolean[] isVisited = new boolean[adjVertices.size()];
|
||||
topologicalSortRecursive(start, isVisited, result);
|
||||
while (!result.isEmpty()) {
|
||||
System.out.print(" " + result.pop());
|
||||
}
|
||||
}
|
||||
|
||||
private void topologicalSortRecursive(int current, boolean[] isVisited, Stack<Integer> result) {
|
||||
isVisited[current] = true;
|
||||
for (int dest : adjVertices.get(current)) {
|
||||
if (!isVisited[dest])
|
||||
topologicalSortRecursive(dest, isVisited, result);
|
||||
}
|
||||
result.push(current);
|
||||
}
|
||||
|
||||
}
|
|
@ -2,6 +2,7 @@ package com.baeldung.tree;
|
|||
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.Stack;
|
||||
|
||||
public class BinaryTree {
|
||||
|
||||
|
@ -147,6 +148,68 @@ public class BinaryTree {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
public void traverseInOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
while(! stack.isEmpty()) {
|
||||
while(current.left != null) {
|
||||
current = current.left;
|
||||
stack.push(current);
|
||||
}
|
||||
current = stack.pop();
|
||||
System.out.print(" " + current.value);
|
||||
if(current.right != null) {
|
||||
current = current.right;
|
||||
stack.push(current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePreOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
while(! stack.isEmpty()) {
|
||||
current = stack.pop();
|
||||
System.out.print(" " + current.value);
|
||||
|
||||
if(current.right != null)
|
||||
stack.push(current.right);
|
||||
|
||||
if(current.left != null)
|
||||
stack.push(current.left);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePostOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node prev = root;
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
|
||||
while (!stack.isEmpty()) {
|
||||
current = stack.peek();
|
||||
boolean hasChild = (current.left != null || current.right != null);
|
||||
boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null));
|
||||
|
||||
if (!hasChild || isPrevLastChild) {
|
||||
current = stack.pop();
|
||||
System.out.print(" " + current.value);
|
||||
prev = current;
|
||||
} else {
|
||||
if (current.right != null) {
|
||||
stack.push(current.right);
|
||||
}
|
||||
if (current.left != null) {
|
||||
stack.push(current.left);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class Node {
|
||||
int value;
|
||||
Node left;
|
||||
|
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.graph;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class GraphUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDirectedGraph_whenDFS_thenPrintAllValues() {
|
||||
Graph graph = createDirectedGraph();
|
||||
graph.dfs(0);
|
||||
System.out.println();
|
||||
graph.dfsWithoutRecursion(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() {
|
||||
Graph graph = createDirectedGraph();
|
||||
graph.topologicalSort(0);
|
||||
}
|
||||
|
||||
private Graph createDirectedGraph() {
|
||||
Graph graph = new Graph();
|
||||
graph.addVertex(0);
|
||||
graph.addVertex(1);
|
||||
graph.addVertex(2);
|
||||
graph.addVertex(3);
|
||||
graph.addVertex(4);
|
||||
graph.addVertex(5);
|
||||
graph.addEdge(0, 1);
|
||||
graph.addEdge(0, 2);
|
||||
graph.addEdge(1, 3);
|
||||
graph.addEdge(2, 3);
|
||||
graph.addEdge(3, 4);
|
||||
graph.addEdge(4, 5);
|
||||
return graph;
|
||||
}
|
||||
}
|
|
@ -87,6 +87,8 @@ public class BinaryTreeUnitTest {
|
|||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traverseInOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traverseInOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -95,6 +97,8 @@ public class BinaryTreeUnitTest {
|
|||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePreOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traversePreOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -103,6 +107,8 @@ public class BinaryTreeUnitTest {
|
|||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePostOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traversePostOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -0,0 +1,148 @@
|
|||
package com.baeldung.binarynumbers;
|
||||
|
||||
public class BinaryNumbers {
|
||||
|
||||
/**
|
||||
* This method takes a decimal number and convert it into a binary number.
|
||||
* example:- input:10, output:1010
|
||||
*
|
||||
* @param decimalNumber
|
||||
* @return binary number
|
||||
*/
|
||||
public Integer convertDecimalToBinary(Integer decimalNumber) {
|
||||
|
||||
if (decimalNumber == 0) {
|
||||
return decimalNumber;
|
||||
}
|
||||
|
||||
StringBuilder binaryNumber = new StringBuilder();
|
||||
|
||||
while (decimalNumber > 0) {
|
||||
|
||||
int remainder = decimalNumber % 2;
|
||||
int result = decimalNumber / 2;
|
||||
|
||||
binaryNumber.append(remainder);
|
||||
decimalNumber = result;
|
||||
}
|
||||
|
||||
binaryNumber = binaryNumber.reverse();
|
||||
|
||||
return Integer.valueOf(binaryNumber.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* This method takes a binary number and convert it into a decimal number.
|
||||
* example:- input:101, output:5
|
||||
*
|
||||
* @param binary number
|
||||
* @return decimal Number
|
||||
*/
|
||||
public Integer convertBinaryToDecimal(Integer binaryNumber) {
|
||||
|
||||
Integer result = 0;
|
||||
Integer base = 1;
|
||||
|
||||
while (binaryNumber > 0) {
|
||||
|
||||
int lastDigit = binaryNumber % 10;
|
||||
binaryNumber = binaryNumber / 10;
|
||||
|
||||
result += lastDigit * base;
|
||||
|
||||
base = base * 2;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method accepts two binary numbers and returns sum of input numbers.
|
||||
* Example:- firstNum: 101, secondNum: 100, output: 1001
|
||||
*
|
||||
* @param firstNum
|
||||
* @param secondNum
|
||||
* @return addition of input numbers
|
||||
*/
|
||||
public Integer addBinaryNumber(Integer firstNum, Integer secondNum) {
|
||||
|
||||
StringBuilder output = new StringBuilder();
|
||||
|
||||
int carry = 0;
|
||||
int temp;
|
||||
|
||||
while (firstNum != 0 || secondNum != 0) {
|
||||
|
||||
temp = (firstNum % 10 + secondNum % 10 + carry) % 2;
|
||||
output.append(temp);
|
||||
|
||||
carry = (firstNum % 10 + secondNum % 10 + carry) / 2;
|
||||
|
||||
firstNum = firstNum / 10;
|
||||
secondNum = secondNum / 10;
|
||||
}
|
||||
|
||||
if (carry != 0) {
|
||||
output.append(carry);
|
||||
}
|
||||
|
||||
return Integer.valueOf(output.reverse()
|
||||
.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* This method takes two binary number as input and subtract second number from the first number.
|
||||
* example:- firstNum: 1000, secondNum: 11, output: 101
|
||||
* @param firstNum
|
||||
* @param secondNum
|
||||
* @return Result of subtraction of secondNum from first
|
||||
*/
|
||||
public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) {
|
||||
|
||||
int onesComplement = Integer.valueOf(getOnesComplement(secondNum));
|
||||
|
||||
StringBuilder output = new StringBuilder();
|
||||
|
||||
int carry = 0;
|
||||
int temp;
|
||||
|
||||
while (firstNum != 0 || onesComplement != 0) {
|
||||
|
||||
temp = (firstNum % 10 + onesComplement % 10 + carry) % 2;
|
||||
output.append(temp);
|
||||
|
||||
carry = (firstNum % 10 + onesComplement % 10 + carry) / 2;
|
||||
|
||||
firstNum = firstNum / 10;
|
||||
onesComplement = onesComplement / 10;
|
||||
}
|
||||
|
||||
String additionOfFirstNumAndOnesComplement = output.reverse()
|
||||
.toString();
|
||||
|
||||
if (carry == 1) {
|
||||
return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry);
|
||||
} else {
|
||||
return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Integer getOnesComplement(Integer num) {
|
||||
|
||||
StringBuilder onesComplement = new StringBuilder();
|
||||
|
||||
while (num > 0) {
|
||||
int lastDigit = num % 10;
|
||||
if (lastDigit == 0) {
|
||||
onesComplement.append(1);
|
||||
} else {
|
||||
onesComplement.append(0);
|
||||
}
|
||||
num = num / 10;
|
||||
}
|
||||
|
||||
return Integer.valueOf(onesComplement.reverse()
|
||||
.toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
package com.baeldung.binarynumbers;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BinaryNumbersUnitTest {
|
||||
|
||||
private BinaryNumbers binaryNumbers = new BinaryNumbers();
|
||||
|
||||
@Test
|
||||
public void given_decimalNumber_then_returnBinaryNumber() {
|
||||
assertEquals(Integer.valueOf(1000), binaryNumbers.convertDecimalToBinary(8));
|
||||
assertEquals(Integer.valueOf(10100), binaryNumbers.convertDecimalToBinary(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_decimalNumber_then_convertToBinaryNumber() {
|
||||
assertEquals("1000", Integer.toBinaryString(8));
|
||||
assertEquals("10100", Integer.toBinaryString(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryNumber_then_ConvertToDecimalNumber() {
|
||||
assertEquals(8, Integer.parseInt("1000", 2));
|
||||
assertEquals(20, Integer.parseInt("10100", 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryNumber_then_returnDecimalNumber() {
|
||||
assertEquals(Integer.valueOf(8), binaryNumbers.convertBinaryToDecimal(1000));
|
||||
assertEquals(Integer.valueOf(20), binaryNumbers.convertBinaryToDecimal(10100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_twoBinaryNumber_then_returnAddition() {
|
||||
// adding 4 and 10
|
||||
assertEquals(Integer.valueOf(1110), binaryNumbers.addBinaryNumber(100, 1010));
|
||||
|
||||
// adding 26 and 14
|
||||
assertEquals(Integer.valueOf(101000), binaryNumbers.addBinaryNumber(11010, 1110));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_twoBinaryNumber_then_returnSubtraction() {
|
||||
// subtracting 16 from 25
|
||||
assertEquals(Integer.valueOf(1001), binaryNumbers.substractBinaryNumber(11001, 10000));
|
||||
|
||||
// subtracting 29 from 16, the output here is negative
|
||||
assertEquals(Integer.valueOf(1101), binaryNumbers.substractBinaryNumber(10000, 11101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryLiteral_thenReturnDecimalValue() {
|
||||
|
||||
byte five = 0b101;
|
||||
assertEquals((byte) 5, five);
|
||||
|
||||
short three = 0b11;
|
||||
assertEquals((short) 3, three);
|
||||
|
||||
int nine = 0B1001;
|
||||
assertEquals(9, nine);
|
||||
|
||||
long twentyNine = 0B11101;
|
||||
assertEquals(29, twentyNine);
|
||||
|
||||
int minusThirtySeven = -0B100101;
|
||||
assertEquals(-37, minusThirtySeven);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.string.changecase;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ToLowerCaseUnitTest {
|
||||
|
||||
private static final Locale TURKISH = new Locale("tr");
|
||||
private String name = "John Doe";
|
||||
private String foreignUppercase = "\u0049";
|
||||
|
||||
@Test
|
||||
public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() {
|
||||
assertEquals("john doe", name.toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() {
|
||||
assertEquals("\u0069", foreignUppercase.toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() {
|
||||
assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.string.changecase;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ToUpperCaseUnitTest {
|
||||
|
||||
private static final Locale TURKISH = new Locale("tr");
|
||||
private String name = "John Doe";
|
||||
private String foreignLowercase = "\u0069";
|
||||
|
||||
@Test
|
||||
public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() {
|
||||
assertEquals("JOHN DOE", name.toUpperCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() {
|
||||
assertEquals("\u0049", foreignLowercase.toUpperCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() {
|
||||
assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung.string.todouble;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.ParseException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringToDoubleConversionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenValidString_WhenParseDouble_ThenResultIsPrimitiveDouble() {
|
||||
assertEquals(1.23, Double.parseDouble("1.23"), 0.000001);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenNullString_WhenParseDouble_ThenNullPointerExceptionIsThrown() {
|
||||
Double.parseDouble(null);
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenInalidString_WhenParseDouble_ThenNumberFormatExceptionIsThrown() {
|
||||
Double.parseDouble("&");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidString_WhenValueOf_ThenResultIsPrimitiveDouble() {
|
||||
assertEquals(1.23, Double.valueOf("1.23"), 0.000001);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenNullString_WhenValueOf_ThenNullPointerExceptionIsThrown() {
|
||||
Double.valueOf(null);
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenInalidString_WhenValueOf_ThenNumberFormatExceptionIsThrown() {
|
||||
Double.valueOf("&");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidString_WhenDecimalFormat_ThenResultIsValidDouble() throws ParseException {
|
||||
assertEquals(1.23, new DecimalFormat("#").parse("1.23").doubleValue(), 0.000001);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenNullString_WhenDecimalFormat_ThenNullPointerExceptionIsThrown() throws ParseException {
|
||||
new DecimalFormat("#").parse(null);
|
||||
}
|
||||
|
||||
@Test(expected = ParseException.class)
|
||||
public void givenInvalidString_WhenDecimalFormat_ThenParseExceptionIsThrown() throws ParseException {
|
||||
new DecimalFormat("#").parse("&");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package org.baeldung.javabeanconstraints.bigdecimal;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import javax.validation.constraints.DecimalMin;
|
||||
import javax.validation.constraints.Digits;
|
||||
|
||||
public class Invoice {
|
||||
|
||||
@DecimalMin(value = "0.0", inclusive = false)
|
||||
@Digits(integer=3, fraction=2)
|
||||
private BigDecimal price;
|
||||
private String description;
|
||||
|
||||
public Invoice(BigDecimal price, String description) {
|
||||
this.price = price;
|
||||
this.description = description;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
package org.baeldung.javabeanconstraints.bigdecimal;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class InvoiceUnitTest {
|
||||
|
||||
private static Validator validator;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupValidatorInstance() {
|
||||
validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPriceIntegerDigitLessThanThreeWithDecimalValue_thenShouldGiveConstraintViolations() {
|
||||
Invoice invoice = new Invoice(new BigDecimal(10.21), "Book purchased");
|
||||
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPriceIntegerDigitLessThanThreeWithIntegerValue_thenShouldNotGiveConstraintViolations() {
|
||||
Invoice invoice = new Invoice(new BigDecimal(10), "Book purchased");
|
||||
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||
assertThat(violations.size()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPriceIntegerDigitGreaterThanThree_thenShouldGiveConstraintViolations() {
|
||||
Invoice invoice = new Invoice(new BigDecimal(1021.21), "Book purchased");
|
||||
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPriceIsZero_thenShouldGiveConstraintViolations() {
|
||||
Invoice invoice = new Invoice(new BigDecimal(000.00), "Book purchased");
|
||||
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("must be greater than 0.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPriceIsGreaterThanZero_thenShouldNotGiveConstraintViolations() {
|
||||
Invoice invoice = new Invoice(new BigDecimal(100.50), "Book purchased");
|
||||
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||
assertThat(violations.size()).isEqualTo(0);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant Articles
|
||||
|
||||
- [JHipster with a Microservice Architecture](https://www.baeldung.com/jhipster-microservices)
|
|
@ -1,4 +1,6 @@
|
|||
### Relevant articles
|
||||
## Relevant Articles
|
||||
|
||||
- [Intro to JHipster](https://www.baeldung.com/jhipster)
|
||||
|
||||
|
||||
# baeldung
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant Articles
|
||||
|
||||
- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service)
|
|
@ -121,8 +121,8 @@ public class AuthorizationEndpoint {
|
|||
String redirectUri = originalParams.getFirst("resolved_redirect_uri");
|
||||
StringBuilder sb = new StringBuilder(redirectUri);
|
||||
|
||||
String approbationStatus = params.getFirst("approbation_status");
|
||||
if ("NO".equals(approbationStatus)) {
|
||||
String approvalStatus = params.getFirst("approval_status");
|
||||
if ("NO".equals(approvalStatus)) {
|
||||
URI location = UriBuilder.fromUri(sb.toString())
|
||||
.queryParam("error", "User doesn't approved the request.")
|
||||
.queryParam("error_description", "User doesn't approved the request.")
|
||||
|
|
|
@ -15,15 +15,14 @@ import javax.ws.rs.core.HttpHeaders;
|
|||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Path("token")
|
||||
public class TokenEndpoint {
|
||||
|
||||
List<String> supportedGrantTypes = Collections.singletonList("authorization_code");
|
||||
List<String> supportedGrantTypes = Arrays.asList("authorization_code", "refresh_token");
|
||||
|
||||
@Inject
|
||||
private AppDataRepository appDataRepository;
|
||||
|
@ -39,36 +38,36 @@ public class TokenEndpoint {
|
|||
|
||||
//Check grant_type params
|
||||
String grantType = params.getFirst("grant_type");
|
||||
Objects.requireNonNull(grantType, "grant_type params is required");
|
||||
if (!supportedGrantTypes.contains(grantType)) {
|
||||
JsonObject error = Json.createObjectBuilder()
|
||||
.add("error", "unsupported_grant_type")
|
||||
.add("error_description", "grant type should be one of :" + supportedGrantTypes)
|
||||
.build();
|
||||
return Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(error).build();
|
||||
if (grantType == null || grantType.isEmpty())
|
||||
return responseError("Invalid_request", "grant_type is required", Response.Status.BAD_REQUEST);
|
||||
|
||||
if (!supportedGrantTypes.contains(grantType)) {
|
||||
return responseError("unsupported_grant_type", "grant_type should be one of :" + supportedGrantTypes, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
//Client Authentication
|
||||
String[] clientCredentials = extract(authHeader);
|
||||
if (clientCredentials.length != 2) {
|
||||
return responseError("Invalid_request", "Bad Credentials client_id/client_secret", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
String clientId = clientCredentials[0];
|
||||
String clientSecret = clientCredentials[1];
|
||||
Client client = appDataRepository.getClient(clientId);
|
||||
if (client == null || clientSecret == null || !clientSecret.equals(client.getClientSecret())) {
|
||||
JsonObject error = Json.createObjectBuilder()
|
||||
.add("error", "invalid_client")
|
||||
.build();
|
||||
return Response.status(Response.Status.UNAUTHORIZED)
|
||||
.entity(error).build();
|
||||
if (client == null) {
|
||||
return responseError("Invalid_request", "Invalid client_id", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
String clientSecret = clientCredentials[1];
|
||||
if (!clientSecret.equals(client.getClientSecret())) {
|
||||
return responseError("Invalid_request", "Invalid client_secret", Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get();
|
||||
JsonObject tokenResponse = null;
|
||||
try {
|
||||
tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params);
|
||||
} catch (WebApplicationException e) {
|
||||
return e.getResponse();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return responseError("Invalid_request", "Can't get token", Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
return Response.ok(tokenResponse)
|
||||
|
@ -81,6 +80,15 @@ public class TokenEndpoint {
|
|||
if (authHeader != null && authHeader.startsWith("Basic ")) {
|
||||
return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":");
|
||||
}
|
||||
return null;
|
||||
return new String[]{};
|
||||
}
|
||||
|
||||
private Response responseError(String error, String errorDescription, Response.Status status) {
|
||||
JsonObject errorResponse = Json.createObjectBuilder()
|
||||
.add("error", error)
|
||||
.add("error_description", errorDescription)
|
||||
.build();
|
||||
return Response.status(status)
|
||||
.entity(errorResponse).build();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,87 @@
|
|||
package com.baeldung.oauth2.authorization.server.handler;
|
||||
|
||||
import com.baeldung.oauth2.authorization.server.PEMKeyUtils;
|
||||
import com.nimbusds.jose.*;
|
||||
import com.nimbusds.jose.crypto.RSASSASigner;
|
||||
import com.nimbusds.jose.crypto.RSASSAVerifier;
|
||||
import com.nimbusds.jose.jwk.JWK;
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
import org.eclipse.microprofile.config.Config;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class AbstractGrantTypeHandler implements AuthorizationGrantTypeHandler {
|
||||
|
||||
//Always RSA 256, but could be parametrized
|
||||
protected JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
|
||||
|
||||
@Inject
|
||||
protected Config config;
|
||||
|
||||
//30 min
|
||||
protected Long expiresInMin = 30L;
|
||||
|
||||
protected JWSVerifier getJWSVerifier() throws Exception {
|
||||
String verificationkey = config.getValue("verificationkey", String.class);
|
||||
String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey);
|
||||
RSAKey rsaPublicKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey);
|
||||
return new RSASSAVerifier(rsaPublicKey);
|
||||
}
|
||||
|
||||
protected JWSSigner getJwsSigner() throws Exception {
|
||||
String signingkey = config.getValue("signingkey", String.class);
|
||||
String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey);
|
||||
RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey);
|
||||
return new RSASSASigner(rsaKey.toRSAPrivateKey());
|
||||
}
|
||||
|
||||
protected String getAccessToken(String clientId, String subject, String approvedScope) throws Exception {
|
||||
//4. Signing
|
||||
JWSSigner jwsSigner = getJwsSigner();
|
||||
|
||||
Instant now = Instant.now();
|
||||
//Long expiresInMin = 30L;
|
||||
Date expirationTime = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES));
|
||||
|
||||
//3. JWT Payload or claims
|
||||
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
|
||||
.issuer("http://localhost:9080")
|
||||
.subject(subject)
|
||||
.claim("upn", subject)
|
||||
.claim("client_id", clientId)
|
||||
.audience("http://localhost:9280")
|
||||
.claim("scope", approvedScope)
|
||||
.claim("groups", Arrays.asList(approvedScope.split(" ")))
|
||||
.expirationTime(expirationTime) // expires in 30 minutes
|
||||
.notBeforeTime(Date.from(now))
|
||||
.issueTime(Date.from(now))
|
||||
.jwtID(UUID.randomUUID().toString())
|
||||
.build();
|
||||
SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims);
|
||||
signedJWT.sign(jwsSigner);
|
||||
return signedJWT.serialize();
|
||||
}
|
||||
|
||||
protected String getRefreshToken(String clientId, String subject, String approvedScope) throws Exception {
|
||||
JWSSigner jwsSigner = getJwsSigner();
|
||||
Instant now = Instant.now();
|
||||
//6.Build refresh token
|
||||
JWTClaimsSet refreshTokenClaims = new JWTClaimsSet.Builder()
|
||||
.subject(subject)
|
||||
.claim("client_id", clientId)
|
||||
.claim("scope", approvedScope)
|
||||
//refresh token for 1 day.
|
||||
.expirationTime(Date.from(now.plus(1, ChronoUnit.DAYS)))
|
||||
.build();
|
||||
SignedJWT signedRefreshToken = new SignedJWT(jwsHeader, refreshTokenClaims);
|
||||
signedRefreshToken.sign(jwsSigner);
|
||||
return signedRefreshToken.serialize();
|
||||
}
|
||||
}
|
|
@ -1,18 +1,7 @@
|
|||
package com.baeldung.oauth2.authorization.server.handler;
|
||||
|
||||
import com.baeldung.oauth2.authorization.server.PEMKeyUtils;
|
||||
import com.baeldung.oauth2.authorization.server.model.AuthorizationCode;
|
||||
import com.nimbusds.jose.JOSEObjectType;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.JWSHeader;
|
||||
import com.nimbusds.jose.crypto.RSASSASigner;
|
||||
import com.nimbusds.jose.jwk.JWK;
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
import org.eclipse.microprofile.config.Config;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Named;
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonObject;
|
||||
|
@ -20,22 +9,14 @@ import javax.persistence.EntityManager;
|
|||
import javax.persistence.PersistenceContext;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
@Named("authorization_code")
|
||||
public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantTypeHandler {
|
||||
public class AuthorizationCodeGrantTypeHandler extends AbstractGrantTypeHandler {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Inject
|
||||
private Config config;
|
||||
|
||||
@Override
|
||||
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
|
||||
//1. code is required
|
||||
|
@ -58,42 +39,16 @@ public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantType
|
|||
throw new WebApplicationException("invalid_grant");
|
||||
}
|
||||
|
||||
//JWT Header
|
||||
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
|
||||
|
||||
Instant now = Instant.now();
|
||||
Long expiresInMin = 30L;
|
||||
Date expiresIn = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES));
|
||||
|
||||
//3. JWT Payload or claims
|
||||
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
|
||||
.issuer("http://localhost:9080")
|
||||
.subject(authorizationCode.getUserId())
|
||||
.claim("upn", authorizationCode.getUserId())
|
||||
.audience("http://localhost:9280")
|
||||
.claim("scope", authorizationCode.getApprovedScopes())
|
||||
.claim("groups", Arrays.asList(authorizationCode.getApprovedScopes().split(" ")))
|
||||
.expirationTime(expiresIn) // expires in 30 minutes
|
||||
.notBeforeTime(Date.from(now))
|
||||
.issueTime(Date.from(now))
|
||||
.jwtID(UUID.randomUUID().toString())
|
||||
.build();
|
||||
SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims);
|
||||
|
||||
//4. Signing
|
||||
String signingkey = config.getValue("signingkey", String.class);
|
||||
String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey);
|
||||
RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey);
|
||||
signedJWT.sign(new RSASSASigner(rsaKey.toRSAPrivateKey()));
|
||||
|
||||
//5. Finally the JWT access token
|
||||
String accessToken = signedJWT.serialize();
|
||||
String accessToken = getAccessToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
|
||||
String refreshToken = getRefreshToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
|
||||
|
||||
return Json.createObjectBuilder()
|
||||
.add("token_type", "Bearer")
|
||||
.add("access_token", accessToken)
|
||||
.add("expires_in", expiresInMin * 60)
|
||||
.add("scope", authorizationCode.getApprovedScopes())
|
||||
.add("refresh_token", refreshToken)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,72 @@
|
|||
package com.baeldung.oauth2.authorization.server.handler;
|
||||
|
||||
import com.nimbusds.jose.JWSVerifier;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
|
||||
import javax.inject.Named;
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Named("refresh_token")
|
||||
public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler {
|
||||
|
||||
@Override
|
||||
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
|
||||
String refreshToken = params.getFirst("refresh_token");
|
||||
if (refreshToken == null || "".equals(refreshToken)) {
|
||||
throw new WebApplicationException("invalid_grant");
|
||||
}
|
||||
|
||||
//Decode refresh token
|
||||
SignedJWT signedRefreshToken = SignedJWT.parse(refreshToken);
|
||||
JWSVerifier verifier = getJWSVerifier();
|
||||
|
||||
if (!signedRefreshToken.verify(verifier)) {
|
||||
throw new WebApplicationException("Invalid refresh token.");
|
||||
}
|
||||
if (!(new Date().before(signedRefreshToken.getJWTClaimsSet().getExpirationTime()))) {
|
||||
throw new WebApplicationException("Refresh token expired.");
|
||||
}
|
||||
String refreshTokenClientId = signedRefreshToken.getJWTClaimsSet().getStringClaim("client_id");
|
||||
if (!clientId.equals(refreshTokenClientId)) {
|
||||
throw new WebApplicationException("Invalid client_id.");
|
||||
}
|
||||
|
||||
//At this point, the refresh token is valid and not yet expired
|
||||
//So create a new access token from it.
|
||||
String subject = signedRefreshToken.getJWTClaimsSet().getSubject();
|
||||
String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope");
|
||||
|
||||
String requestedScopes = params.getFirst("scope");
|
||||
if (requestedScopes != null && !requestedScopes.isEmpty()) {
|
||||
Set<String> rScopes = new HashSet(Arrays.asList(requestedScopes.split(" ")));
|
||||
Set<String> aScopes = new HashSet(Arrays.asList(approvedScopes.split(" ")));
|
||||
if (!aScopes.containsAll(rScopes)) {
|
||||
JsonObject error = Json.createObjectBuilder()
|
||||
.add("error", "Invalid_request")
|
||||
.add("error_description", "Requested scopes should be a subset of the original scopes.")
|
||||
.build();
|
||||
Response response = Response.status(Response.Status.BAD_REQUEST).entity(error).build();
|
||||
throw new WebApplicationException(response);
|
||||
}
|
||||
} else {
|
||||
requestedScopes = approvedScopes;
|
||||
}
|
||||
|
||||
String accessToken = getAccessToken(clientId, subject, requestedScopes);
|
||||
return Json.createObjectBuilder()
|
||||
.add("token_type", "Bearer")
|
||||
.add("access_token", accessToken)
|
||||
.add("expires_in", expiresInMin * 60)
|
||||
.add("scope", requestedScopes)
|
||||
.add("refresh_token", refreshToken)
|
||||
.build();
|
||||
}
|
||||
}
|
|
@ -41,8 +41,8 @@
|
|||
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<input type="submit" name="approbation_status" value="YES"/>
|
||||
<input type="submit" name="approbation_status" value="NO"/>
|
||||
<input type="submit" name="approval_status" value="YES"/>
|
||||
<input type="submit" name="approval_status" value="NO"/>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.oauth2.client;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
public abstract class AbstractServlet extends HttpServlet {
|
||||
|
||||
protected void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
RequestDispatcher requestDispatcher = request.getRequestDispatcher(location);
|
||||
requestDispatcher.forward(request, response);
|
||||
}
|
||||
|
||||
protected String getAuthorizationHeaderValue(String clientId, String clientSecret) {
|
||||
String token = clientId + ":" + clientSecret;
|
||||
String encodedString = Base64.getEncoder().encodeToString(token.getBytes());
|
||||
return "Basic " + encodedString;
|
||||
}
|
||||
}
|
|
@ -4,10 +4,8 @@ import org.eclipse.microprofile.config.Config;
|
|||
|
||||
import javax.inject.Inject;
|
||||
import javax.json.JsonObject;
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.client.Client;
|
||||
|
@ -18,10 +16,9 @@ import javax.ws.rs.core.Form;
|
|||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
@WebServlet(urlPatterns = "/callback")
|
||||
public class CallbackServlet extends HttpServlet {
|
||||
public class CallbackServlet extends AbstractServlet {
|
||||
|
||||
@Inject
|
||||
private Config config;
|
||||
|
@ -29,6 +26,9 @@ public class CallbackServlet extends HttpServlet {
|
|||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
|
||||
String clientId = config.getValue("client.clientId", String.class);
|
||||
String clientSecret = config.getValue("client.clientSecret", String.class);
|
||||
|
||||
//Error:
|
||||
String error = request.getParameter("error");
|
||||
if (error != null) {
|
||||
|
@ -53,24 +53,15 @@ public class CallbackServlet extends HttpServlet {
|
|||
form.param("code", code);
|
||||
form.param("redirect_uri", config.getValue("client.redirectUri", String.class));
|
||||
|
||||
JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE)
|
||||
.header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue())
|
||||
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class);
|
||||
|
||||
request.getSession().setAttribute("tokenResponse", tokenResponse);
|
||||
try {
|
||||
JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE)
|
||||
.header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret))
|
||||
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class);
|
||||
request.getSession().setAttribute("tokenResponse", tokenResponse);
|
||||
} catch (Exception ex) {
|
||||
System.out.println(ex.getMessage());
|
||||
request.setAttribute("error", ex.getMessage());
|
||||
}
|
||||
dispatch("/", request, response);
|
||||
}
|
||||
|
||||
private void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
RequestDispatcher requestDispatcher = request.getRequestDispatcher(location);
|
||||
requestDispatcher.forward(request, response);
|
||||
}
|
||||
|
||||
private String getAuthorizationHeaderValue() {
|
||||
String clientId = config.getValue("client.clientId", String.class);
|
||||
String clientSecret = config.getValue("client.clientSecret", String.class);
|
||||
String token = clientId + ":" + clientSecret;
|
||||
String encodedString = Base64.getEncoder().encodeToString(token.getBytes());
|
||||
return "Basic " + encodedString;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.oauth2.client;
|
||||
|
||||
import org.eclipse.microprofile.config.Config;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.json.JsonObject;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.client.ClientBuilder;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.client.WebTarget;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet(urlPatterns = "/refreshtoken")
|
||||
public class RefreshTokenServlet extends AbstractServlet {
|
||||
|
||||
@Inject
|
||||
private Config config;
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
|
||||
String clientId = config.getValue("client.clientId", String.class);
|
||||
String clientSecret = config.getValue("client.clientSecret", String.class);
|
||||
|
||||
JsonObject actualTokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse");
|
||||
Client client = ClientBuilder.newClient();
|
||||
WebTarget target = client.target(config.getValue("provider.tokenUri", String.class));
|
||||
|
||||
Form form = new Form();
|
||||
form.param("grant_type", "refresh_token");
|
||||
form.param("refresh_token", actualTokenResponse.getString("refresh_token"));
|
||||
|
||||
String scope = request.getParameter("scope");
|
||||
if (scope != null && !scope.isEmpty()) {
|
||||
form.param("scope", scope);
|
||||
}
|
||||
|
||||
Response jaxrsResponse = target.request(MediaType.APPLICATION_JSON_TYPE)
|
||||
.header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret))
|
||||
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class);
|
||||
JsonObject tokenResponse = jaxrsResponse.readEntity(JsonObject.class);
|
||||
if (jaxrsResponse.getStatus() == 200) {
|
||||
request.getSession().setAttribute("tokenResponse", tokenResponse);
|
||||
} else {
|
||||
request.setAttribute("error", tokenResponse.getString("error_description", "error!"));
|
||||
}
|
||||
dispatch("/", request, response);
|
||||
}
|
||||
}
|
|
@ -10,6 +10,7 @@
|
|||
body {
|
||||
margin: 0px;
|
||||
}
|
||||
|
||||
input[type=text], input[type=password] {
|
||||
width: 75%;
|
||||
padding: 4px 0px;
|
||||
|
@ -17,6 +18,7 @@
|
|||
border: 1px solid #502bcc;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.container-error {
|
||||
padding: 16px;
|
||||
border: 1px solid #cc102a;
|
||||
|
@ -25,6 +27,7 @@
|
|||
margin-left: 25px;
|
||||
margin-bottom: 25px;
|
||||
}
|
||||
|
||||
.container {
|
||||
padding: 16px;
|
||||
border: 1px solid #130ecc;
|
||||
|
@ -81,8 +84,20 @@
|
|||
<li>access_token: ${tokenResponse.getString("access_token")}</li>
|
||||
<li>scope: ${tokenResponse.getString("scope")}</li>
|
||||
<li>Expires in (s): ${tokenResponse.getInt("expires_in")}</li>
|
||||
<li>refresh_token: ${tokenResponse.getString("refresh_token")}</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<span><h4>Refresh Token</h4></span>
|
||||
<hr>
|
||||
<ul>
|
||||
<li><a href="refreshtoken">Refresh token (original scope)</a></li>
|
||||
<li><a href="refreshtoken?scope=resource.read">Refresh token (scope: resource.read)</a></li>
|
||||
<li><a href="refreshtoken?scope=resource.write">Refresh token (scope: resource.write)</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<span><h4>OAuth2 Resource Server Call</h4></span>
|
||||
<hr>
|
||||
|
@ -90,7 +105,6 @@
|
|||
<li><a href="downstream?action=read">Read Protected Resource</a></li>
|
||||
<li><a href="downstream?action=write">Write Protected Resource</a></li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
|
||||
</body>
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
This is a parent module for projects that want to take advantage of the latest Spring Boot improvements/features.
|
|
@ -1,92 +0,0 @@
|
|||
<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>parent-boot-performance</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>parent-boot-performance</name>
|
||||
<packaging>pom</packaging>
|
||||
<description>Parent for all modules that want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2</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>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<configuration>
|
||||
<mainClass>${start-class}</mainClass>
|
||||
<!-- this is necessary as we're not using the Boot parent -->
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>thin-jar</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<dependencies>
|
||||
<!-- The following enables the "thin jar" deployment option. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot.experimental</groupId>
|
||||
<artifactId>spring-boot-thin-layout</artifactId>
|
||||
<version>${thin.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<rest-assured.version>3.1.0</rest-assured.version>
|
||||
<!-- plugins -->
|
||||
<thin.version>1.0.21.RELEASE</thin.version>
|
||||
<spring-boot.version>2.2.0.M3</spring-boot.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -1 +1 @@
|
|||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
|
|
@ -1 +1 @@
|
|||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
|
|
@ -1 +1 @@
|
|||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Better Retries with Exponential Backoff and Jitter](https://baeldung.com/retries-with-exponential-backoff-and-jitter)
|
|
@ -0,0 +1,54 @@
|
|||
<?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>backoff-jitter</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.resilience4j</groupId>
|
||||
<artifactId>resilience4j-retry</artifactId>
|
||||
<version>${resilience4j.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito-core.version>2.27.0</mockito-core.version>
|
||||
<slf4j.version>1.7.26</slf4j.version>
|
||||
<resilience4j.version>0.16.0</resilience4j.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,103 @@
|
|||
package com.baeldung.backoff.jitter;
|
||||
|
||||
import io.github.resilience4j.retry.IntervalFunction;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.github.resilience4j.retry.RetryConfig;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static com.baeldung.backoff.jitter.BackoffWithJitterTest.RetryProperties.*;
|
||||
import static io.github.resilience4j.retry.IntervalFunction.ofExponentialBackoff;
|
||||
import static io.github.resilience4j.retry.IntervalFunction.ofExponentialRandomBackoff;
|
||||
import static java.util.Collections.nCopies;
|
||||
import static java.util.concurrent.Executors.newFixedThreadPool;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class BackoffWithJitterTest {
|
||||
|
||||
static Logger log = LoggerFactory.getLogger(BackoffWithJitterTest.class);
|
||||
|
||||
interface PingPongService {
|
||||
|
||||
String call(String ping) throws PingPongServiceException;
|
||||
}
|
||||
|
||||
class PingPongServiceException extends RuntimeException {
|
||||
|
||||
public PingPongServiceException(String reason) {
|
||||
super(reason);
|
||||
}
|
||||
}
|
||||
|
||||
private PingPongService service;
|
||||
private static final int NUM_CONCURRENT_CLIENTS = 8;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
service = mock(PingPongService.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRetryExponentialBackoff_thenRetriedConfiguredNoOfTimes() {
|
||||
IntervalFunction intervalFn = ofExponentialBackoff(INITIAL_INTERVAL, MULTIPLIER);
|
||||
Function<String, String> pingPongFn = getRetryablePingPongFn(intervalFn);
|
||||
|
||||
when(service.call(anyString())).thenThrow(PingPongServiceException.class);
|
||||
try {
|
||||
pingPongFn.apply("Hello");
|
||||
} catch (PingPongServiceException e) {
|
||||
verify(service, times(MAX_RETRIES)).call(anyString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRetryExponentialBackoffWithoutJitter_thenThunderingHerdProblemOccurs() throws InterruptedException {
|
||||
IntervalFunction intervalFn = ofExponentialBackoff(INITIAL_INTERVAL, MULTIPLIER);
|
||||
test(intervalFn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRetryExponentialBackoffWithJitter_thenRetriesAreSpread() throws InterruptedException {
|
||||
IntervalFunction intervalFn = ofExponentialRandomBackoff(INITIAL_INTERVAL, MULTIPLIER, RANDOMIZATION_FACTOR);
|
||||
test(intervalFn);
|
||||
}
|
||||
|
||||
private void test(IntervalFunction intervalFn) throws InterruptedException {
|
||||
Function<String, String> pingPongFn = getRetryablePingPongFn(intervalFn);
|
||||
ExecutorService executors = newFixedThreadPool(NUM_CONCURRENT_CLIENTS);
|
||||
List<Callable<String>> tasks = nCopies(NUM_CONCURRENT_CLIENTS, () -> pingPongFn.apply("Hello"));
|
||||
|
||||
when(service.call(anyString())).thenThrow(PingPongServiceException.class);
|
||||
|
||||
executors.invokeAll(tasks);
|
||||
}
|
||||
|
||||
private Function<String, String> getRetryablePingPongFn(IntervalFunction intervalFn) {
|
||||
RetryConfig retryConfig = RetryConfig.custom()
|
||||
.maxAttempts(MAX_RETRIES)
|
||||
.intervalFunction(intervalFn)
|
||||
.retryExceptions(PingPongServiceException.class)
|
||||
.build();
|
||||
Retry retry = Retry.of("pingpong", retryConfig);
|
||||
return Retry.decorateFunction(retry, ping -> {
|
||||
log.info("Invoked at {}", LocalDateTime.now());
|
||||
return service.call(ping);
|
||||
});
|
||||
}
|
||||
|
||||
static class RetryProperties {
|
||||
static final Long INITIAL_INTERVAL = 1000L;
|
||||
static final Double MULTIPLIER = 2.0D;
|
||||
static final Double RANDOMIZATION_FACTOR = 0.6D;
|
||||
static final Integer MAX_RETRIES = 4;
|
||||
}
|
||||
}
|
|
@ -19,7 +19,8 @@
|
|||
<module>design-patterns</module>
|
||||
<module>design-patterns-2</module>
|
||||
<module>solid</module>
|
||||
<module>dip</module>
|
||||
<module>dip</module>
|
||||
<module>backoff-jitter</module>
|
||||
</modules>
|
||||
|
||||
<dependencyManagement>
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
# Relevant Articles
|
|
@ -0,0 +1,115 @@
|
|||
<?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>java-jpa-2</artifactId>
|
||||
<name>java-jpa-2</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-jpamodelgen</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Compile time JPA API-->
|
||||
<dependency>
|
||||
<groupId>javax.persistence</groupId>
|
||||
<artifactId>javax.persistence-api</artifactId>
|
||||
<version>${javax.persistence-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Runtime JPA implementation-->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.persistence</groupId>
|
||||
<artifactId>eclipselink</artifactId>
|
||||
<version>${eclipselink.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>${postgres.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<compilerArgument>-proc:none</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.bsc.maven</groupId>
|
||||
<artifactId>maven-processor-plugin</artifactId>
|
||||
<version>3.3.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>process</id>
|
||||
<goals>
|
||||
<goal>process</goal>
|
||||
</goals>
|
||||
<phase>generate-sources</phase>
|
||||
<configuration>
|
||||
<outputDirectory>target/metamodel</outputDirectory>
|
||||
<processors>
|
||||
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
|
||||
</processors>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add-source</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>target/metamodel</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.4.0.Final</hibernate.version>
|
||||
<eclipselink.version>2.7.4-RC1</eclipselink.version>
|
||||
<postgres.version>42.2.5</postgres.version>
|
||||
<javax.persistence-api.version>2.2</javax.persistence-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.jpa.entity;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity(name = "MyArticle")
|
||||
@Table(name = Article.TABLE_NAME)
|
||||
public class Article {
|
||||
|
||||
public static final String TABLE_NAME = "ARTICLES";
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [A Guide to Sql2o](http://www.baeldung.com/sql2o)
|
|
@ -0,0 +1,54 @@
|
|||
<?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>java-sql2o</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>8</source>
|
||||
<target>8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<name>java-sql2o</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>persistence-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.sql2o</groupId>
|
||||
<artifactId>sql2o</artifactId>
|
||||
<version>${sql2o.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>${hsqldb.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<sql2o.version>1.6.0</sql2o.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,340 @@
|
|||
package com.baeldung.persistence.sql2o;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.sql2o.Connection;
|
||||
import org.sql2o.Query;
|
||||
import org.sql2o.ResultSetIterable;
|
||||
import org.sql2o.Sql2o;
|
||||
import org.sql2o.data.Row;
|
||||
import org.sql2o.data.Table;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Sql2oIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenSql2oCreated_thenSuccess() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
java.sql.Connection jdbcConnection = connection.getJdbcConnection();
|
||||
assertFalse(jdbcConnection.isClosed());
|
||||
} catch (SQLException e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTableCreated_thenInsertIsPossible() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_1 (id integer identity, name varchar(50), url varchar(100))").executeUpdate();
|
||||
assertEquals(0, connection.getResult());
|
||||
connection.createQuery("INSERT INTO PROJECT_1 VALUES (1, 'tutorials', 'github.com/eugenp/tutorials')").executeUpdate();
|
||||
assertEquals(1, connection.getResult());
|
||||
connection.createQuery("drop table PROJECT_1").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIdentityColumn_thenInsertReturnsNewId() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
Query query = connection.createQuery(
|
||||
"INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')",
|
||||
true);
|
||||
assertEquals(0, query.executeUpdate().getKey());
|
||||
query = connection.createQuery("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')",
|
||||
true);
|
||||
assertEquals(1, query.executeUpdate().getKeys()[0]);
|
||||
connection.createQuery("drop table PROJECT_2").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSelect_thenResultsAreObjects() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
Query query = connection.createQuery("select * from PROJECT_3 order by id");
|
||||
List<Project> list = query.executeAndFetch(Project.class);
|
||||
|
||||
assertEquals("tutorials", list.get(0).getName());
|
||||
assertEquals("REST with Spring", list.get(1).getName());
|
||||
|
||||
connection.createQuery("drop table PROJECT_3").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSelectAlias_thenResultsAreObjects() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_4 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_4 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate();
|
||||
Query query = connection.createQuery("select NAME, URL, creation_date as creationDate from PROJECT_4 order by id");
|
||||
List<Project> list = query.executeAndFetch(Project.class);
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
assertEquals("2019-01-01", sdf.format(list.get(0).getCreationDate()));
|
||||
assertEquals("2019-02-01", sdf.format(list.get(1).getCreationDate()));
|
||||
|
||||
connection.createQuery("drop table PROJECT_4").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSelectMapping_thenResultsAreObjects() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate();
|
||||
Query query = connection.createQuery("select * from PROJECT_5 order by id")
|
||||
.addColumnMapping("CrEaTiOn_date", "creationDate");
|
||||
List<Project> list = query.executeAndFetch(Project.class);
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
assertEquals("2019-01-01", sdf.format(list.get(0).getCreationDate()));
|
||||
assertEquals("2019-02-01", sdf.format(list.get(1).getCreationDate()));
|
||||
|
||||
connection.createQuery("drop table PROJECT_5").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSelectCount_thenResultIsScalar() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_6 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_6 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate();
|
||||
Query query = connection.createQuery("select count(*) from PROJECT_6");
|
||||
assertEquals(2.0, query.executeScalar(Double.TYPE), 0.001);
|
||||
connection.createQuery("drop table PROJECT_6").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFetchTable_thenResultsAreMaps() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate();
|
||||
Query query = connection.createQuery("select * from PROJECT_5 order by id");
|
||||
Table table = query.executeAndFetchTable();
|
||||
List<Map<String, Object>> list = table.asList();
|
||||
|
||||
assertEquals("tutorials", list.get(0).get("name"));
|
||||
assertEquals("REST with Spring", list.get(1).get("name"));
|
||||
|
||||
connection.createQuery("drop table PROJECT_5").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFetchTable_thenResultsAreRows() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate();
|
||||
Query query = connection.createQuery("select * from PROJECT_5 order by id");
|
||||
Table table = query.executeAndFetchTable();
|
||||
List<Row> rows = table.rows();
|
||||
|
||||
assertEquals("tutorials", rows.get(0).getString("name"));
|
||||
assertEquals("REST with Spring", rows.get(1).getString("name"));
|
||||
|
||||
connection.createQuery("drop table PROJECT_5").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParameters_thenReplacement() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
Query query = connection.createQuery("INSERT INTO PROJECT_10 (NAME, URL) VALUES (:name, :url)")
|
||||
.addParameter("name", "REST with Spring")
|
||||
.addParameter("url", "github.com/eugenp/REST-With-Spring");
|
||||
assertEquals(1, query.executeUpdate().getResult());
|
||||
|
||||
List<Project> list = connection.createQuery("SELECT * FROM PROJECT_10 WHERE NAME = 'REST with Spring'").executeAndFetch(Project.class);
|
||||
assertEquals(1, list.size());
|
||||
|
||||
connection.createQuery("drop table PROJECT_10").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPOJOParameters_thenReplacement() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
|
||||
Project project = new Project();
|
||||
project.setName("REST with Spring");
|
||||
project.setUrl("github.com/eugenp/REST-With-Spring");
|
||||
connection.createQuery("INSERT INTO PROJECT_11 (NAME, URL) VALUES (:name, :url)")
|
||||
.bind(project).executeUpdate();
|
||||
assertEquals(1, connection.getResult());
|
||||
|
||||
List<Project> list = connection.createQuery("SELECT * FROM PROJECT_11 WHERE NAME = 'REST with Spring'").executeAndFetch(Project.class);
|
||||
assertEquals(1, list.size());
|
||||
|
||||
connection.createQuery("drop table PROJECT_11").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransactionRollback_thenNoDataInserted() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
connection.createQuery("create table PROJECT_12 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
connection.rollback();
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_12").executeAndFetchTable().asList();
|
||||
assertEquals(0, list.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransactionEnds_thenSubsequentStatementsNotRolledBack() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
connection.createQuery("create table PROJECT_13 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate();
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList();
|
||||
assertEquals(1, list.size());
|
||||
connection.rollback();
|
||||
list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList();
|
||||
assertEquals(0, list.size());
|
||||
connection.createQuery("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList();
|
||||
assertEquals(1, list.size());
|
||||
//No implicit rollback
|
||||
}
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList();
|
||||
assertEquals(1, list.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransactionRollbackThenCommit_thenOnlyLastInserted() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
connection.createQuery("create table PROJECT_14 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate();
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(1, list.size());
|
||||
connection.rollback(false);
|
||||
list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(0, list.size());
|
||||
connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(1, list.size());
|
||||
//Implicit rollback
|
||||
}
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(0, list.size());
|
||||
connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
connection.commit();
|
||||
list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(2, list.size());
|
||||
}
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(2, list.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBatch_thenMultipleInserts() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
connection.createQuery("create table PROJECT_15 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
Query query = connection.createQuery("INSERT INTO PROJECT_15 (NAME, URL) VALUES (:name, :url)");
|
||||
for(int i = 0; i < 1000; i++) {
|
||||
query.addParameter("name", "tutorials" + i);
|
||||
query.addParameter("url", "https://github.com/eugenp/tutorials" + i);
|
||||
query.addToBatch();
|
||||
}
|
||||
query.executeBatch();
|
||||
connection.commit();
|
||||
}
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
assertEquals(1000L, connection.createQuery("SELECT count(*) FROM PROJECT_15").executeScalar());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLazyFetch_thenResultsAreObjects() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_16 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_16 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_16 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
Query query = connection.createQuery("select * from PROJECT_16 order by id");
|
||||
try(ResultSetIterable<Project> projects = query.executeAndFetchLazy(Project.class)) {
|
||||
for(Project p : projects) {
|
||||
assertNotNull(p.getName());
|
||||
assertNotNull(p.getUrl());
|
||||
assertNull(p.getCreationDate());
|
||||
}
|
||||
}
|
||||
connection.createQuery("drop table PROJECT_16").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
static class Project {
|
||||
private long id;
|
||||
private String name;
|
||||
private String url;
|
||||
private Date creationDate;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public Date getCreationDate() {
|
||||
return creationDate;
|
||||
}
|
||||
|
||||
public void setCreationDate(Date creationDate) {
|
||||
this.creationDate = creationDate;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -2,10 +2,6 @@
|
|||
<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">
|
||||
<artifactId>jpa-hibernate-cascade-type</artifactId>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
@ -13,6 +9,10 @@
|
|||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<artifactId>jpa-hibernate-cascade-type</artifactId>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
|
|
|
@ -29,7 +29,9 @@
|
|||
<module>java-cockroachdb</module>
|
||||
<module>java-jdbi</module>
|
||||
<module>java-jpa</module>
|
||||
<module>java-jpa-2</module>
|
||||
<module>java-mongodb</module>
|
||||
<module>java-sql2o</module>
|
||||
<module>jnosql</module>
|
||||
<module>liquibase</module>
|
||||
<module>orientdb</module>
|
||||
|
|
|
@ -10,7 +10,6 @@
|
|||
- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8)
|
||||
- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging)
|
||||
- [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories)
|
||||
- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa)
|
||||
- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date)
|
||||
- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd)
|
||||
- [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save)
|
||||
|
|
|
@ -10,6 +10,7 @@
|
|||
- [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate)
|
||||
- [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading)
|
||||
- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
|
||||
- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa)
|
||||
|
||||
### Quick Start
|
||||
|
||||
|
|
|
@ -47,7 +47,7 @@ import com.google.common.base.Preconditions;
|
|||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager")
|
||||
@EnableJpaAuditing
|
||||
@PropertySource({ "classpath:persistence-mysql.properties" })
|
||||
@PropertySource({ "classpath:persistence-h2.properties" })
|
||||
@ComponentScan({ "com.baeldung.persistence" })
|
||||
public class PersistenceConfig {
|
||||
|
||||
|
|
|
@ -2,6 +2,7 @@ package com.baeldung.persistence.audit;
|
|||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
@ -17,6 +18,7 @@ import org.slf4j.Logger;
|
|||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
@ -29,6 +31,7 @@ import com.baeldung.spring.config.PersistenceTestConfig;
|
|||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
|
||||
public class EnversFooBarAuditIntegrationTest {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class);
|
||||
|
|
26
pom.xml
26
pom.xml
|
@ -10,10 +10,6 @@
|
|||
<name>parent-modules</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
<module>quarkus</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
|
@ -392,6 +388,7 @@
|
|||
<!--<module>core-java-modules/core-java-9</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
||||
<!--<module>core-java-modules/core-java-os</module> --> <!-- We haven't upgraded to java 9.-->
|
||||
<module>core-java-modules/core-java-arrays</module>
|
||||
<module>core-java-modules/core-java-arrays-2</module>
|
||||
<module>core-java-modules/core-java-collections</module>
|
||||
<module>core-java-modules/core-java-collections-list</module>
|
||||
<module>core-java-modules/core-java-collections-list-2</module>
|
||||
|
@ -482,7 +479,7 @@
|
|||
<module>jee-7</module> -->
|
||||
<module>jee-7-security</module>
|
||||
<module>jersey</module>
|
||||
<module>JGit</module>
|
||||
<module>jgit</module>
|
||||
<module>jgroups</module>
|
||||
<module>jhipster-5</module>
|
||||
<module>jib</module>
|
||||
|
@ -561,7 +558,7 @@
|
|||
<module>tensorflow-java</module>
|
||||
<module>spring-boot-flowable</module>
|
||||
<module>spring-security-kerberos</module>
|
||||
|
||||
<module>oauth2-framework-impl</module>
|
||||
</modules>
|
||||
|
||||
</profile>
|
||||
|
@ -743,7 +740,7 @@
|
|||
<module>spring-security-mvc-ldap</module>
|
||||
<module>spring-security-mvc-login</module>
|
||||
<module>spring-security-mvc-persisted-remember-me</module>
|
||||
<module>spring-security-mvc-session</module>
|
||||
<module>spring-security-mvc</module>
|
||||
<module>spring-security-mvc-socket</module>
|
||||
<module>spring-security-openid</module>
|
||||
<!--<module>spring-security-react</module> --> <!-- fails on Travis, fails intermittently on the new Jenkins (01.12.2018) BAEL-10834 -->
|
||||
|
@ -780,7 +777,7 @@
|
|||
<module>testing-modules</module>
|
||||
|
||||
<module>twilio</module>
|
||||
<module>Twitter4J</module>
|
||||
<module>twitter4j</module>
|
||||
|
||||
<module>undertow</module>
|
||||
|
||||
|
@ -919,7 +916,7 @@
|
|||
<module>spring-security-mvc-digest-auth</module>
|
||||
<module>spring-security-mvc-ldap</module>
|
||||
<module>spring-security-mvc-persisted-remember-me</module>
|
||||
<module>spring-security-mvc-session</module>
|
||||
<module>spring-security-mvc</module>
|
||||
<module>spring-security-mvc-socket</module>
|
||||
<module>spring-security-rest</module>
|
||||
<module>spring-security-sso</module>
|
||||
|
@ -1000,6 +997,7 @@
|
|||
<module>persistence-modules/hibernate5</module>
|
||||
<module>persistence-modules/hibernate-mapping</module>
|
||||
<module>persistence-modules/java-jpa</module>
|
||||
<module>persistence-modules/java-jpa-2</module>
|
||||
<module>persistence-modules/java-mongodb</module>
|
||||
<module>persistence-modules/jnosql</module>
|
||||
|
||||
|
@ -1088,6 +1086,7 @@
|
|||
<!--<module>core-java-modules/core-java-9</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
||||
<!--<module>core-java-modules/core-java-os</module> --> <!-- We haven't upgraded to java 9.-->
|
||||
<module>core-java-modules/core-java-arrays</module>
|
||||
<module>core-java-modules/core-java-arrays-2</module>
|
||||
<module>core-java-modules/core-java-collections</module>
|
||||
<module>core-java-modules/core-java-collections-list</module>
|
||||
<module>core-java-modules/core-java-collections-list-2</module>
|
||||
|
@ -1174,7 +1173,7 @@
|
|||
<module>jee-7</module> -->
|
||||
<module>jee-7-security</module>
|
||||
<module>jersey</module>
|
||||
<module>JGit</module>
|
||||
<module>jgit</module>
|
||||
<module>jgroups</module>
|
||||
<module>jhipster-5</module>
|
||||
<module>jib</module>
|
||||
|
@ -1244,6 +1243,7 @@
|
|||
<module>rsocket</module>
|
||||
<module>rxjava</module>
|
||||
<module>rxjava-2</module>
|
||||
<module>oauth2-framework-impl</module>
|
||||
|
||||
</modules>
|
||||
|
||||
|
@ -1411,7 +1411,7 @@
|
|||
<module>spring-security-mvc-ldap</module>
|
||||
<module>spring-security-mvc-login</module>
|
||||
<module>spring-security-mvc-persisted-remember-me</module>
|
||||
<module>spring-security-mvc-session</module>
|
||||
<module>spring-security-mvc</module>
|
||||
<module>spring-security-mvc-socket</module>
|
||||
<module>spring-security-openid</module>
|
||||
<!--<module>spring-security-react</module> --> <!-- fails on Travis, fails intermittently on the new Jenkins (01.12.2018) BAEL-10834 -->
|
||||
|
@ -1448,7 +1448,7 @@
|
|||
<module>testing-modules</module>
|
||||
|
||||
<module>twilio</module>
|
||||
<module>Twitter4J</module>
|
||||
<module>twitter4j</module>
|
||||
|
||||
<module>undertow</module>
|
||||
|
||||
|
@ -1508,6 +1508,7 @@
|
|||
|
||||
<module>persistence-modules/hibernate5</module>
|
||||
<module>persistence-modules/java-jpa</module>
|
||||
<module>persistence-modules/java-jpa-2</module>
|
||||
<module>persistence-modules/java-mongodb</module>
|
||||
<module>persistence-modules/jnosql</module>
|
||||
|
||||
|
@ -1586,4 +1587,5 @@
|
|||
<lombok.version>1.16.12</lombok.version>
|
||||
<h2.version>1.4.197</h2.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,3 +1,3 @@
|
|||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
||||
- [Guide to QuarkusIO](https://www.baeldung.com/quarkus-io)
|
||||
|
|
|
@ -1,6 +0,0 @@
|
|||
=========
|
||||
|
||||
## A Guide to RESTEasy
|
||||
|
||||
|
||||
### Relevant Articles:
|
|
@ -1,4 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin)
|
||||
- [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams)
|
||||
- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy)
|
||||
|
|
|
@ -23,10 +23,6 @@
|
|||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
|
|
|
@ -1,12 +1,8 @@
|
|||
package com.baeldung;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||
import org.springframework.web.filter.DelegatingFilterProxy;
|
||||
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
||||
|
||||
@SpringBootApplication( exclude = SecurityAutoConfiguration.class)
|
||||
public class Spring5Application {
|
||||
|
@ -14,32 +10,4 @@ public class Spring5Application {
|
|||
public static void main(String[] args) {
|
||||
SpringApplication.run(Spring5Application.class, args);
|
||||
}
|
||||
|
||||
public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected javax.servlet.Filter[] getServletFilters() {
|
||||
DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy();
|
||||
delegateFilterProxy.setTargetBeanName("loggingFilter");
|
||||
return new Filter[] { delegateFilterProxy };
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -16,14 +16,5 @@
|
|||
<servlet-name>functional</servlet-name>
|
||||
<url-pattern>/</url-pattern>
|
||||
</servlet-mapping>
|
||||
<filter>
|
||||
<filter-name>loggingFilter</filter-name>
|
||||
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
|
||||
</filter>
|
||||
|
||||
<filter-mapping>
|
||||
<filter-name>loggingFilter</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
|
||||
</web-app>
|
|
@ -4,3 +4,4 @@
|
|||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles
|
||||
|
||||
|
|
|
@ -0,0 +1,25 @@
|
|||
/target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/build/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Functional Controllers in Spring MVC]()
|
|
@ -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>
|
||||
<artifactId>spring-boot-mvc-2</artifactId>
|
||||
<name>spring-boot-mvc-2</name>
|
||||
<packaging>jar</packaging>
|
||||
<description>Module For Spring Boot MVC Web Fn</description>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.2.0.BUILD-SNAPSHOT</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.springbootmvc.SpringBootMvcFnApplication</mainClass>
|
||||
<layout>JAR</layout>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
<pluginRepository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
</project>
|
|
@ -0,0 +1,74 @@
|
|||
package com.baeldung.springbootmvc;
|
||||
|
||||
import static org.springframework.web.servlet.function.RouterFunctions.route;
|
||||
import static org.springframework.web.servlet.function.ServerResponse.notFound;
|
||||
import static org.springframework.web.servlet.function.ServerResponse.status;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.servlet.function.RequestPredicates;
|
||||
import org.springframework.web.servlet.function.RouterFunction;
|
||||
import org.springframework.web.servlet.function.ServerResponse;
|
||||
|
||||
import com.baeldung.springbootmvc.ctrl.ProductController;
|
||||
import com.baeldung.springbootmvc.svc.ProductService;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringBootMvcFnApplication {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SpringBootMvcFnApplication.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringBootMvcFnApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
RouterFunction<ServerResponse> productListing(ProductController pc, ProductService ps) {
|
||||
return pc.productListing(ps);
|
||||
}
|
||||
|
||||
@Bean
|
||||
RouterFunction<ServerResponse> allApplicationRoutes(ProductController pc, ProductService ps) {
|
||||
return route().add(pc.remainingProductRoutes(ps))
|
||||
.before(req -> {
|
||||
LOG.info("Found a route which matches " + req.uri()
|
||||
.getPath());
|
||||
return req;
|
||||
})
|
||||
.after((req, res) -> {
|
||||
if (res.statusCode() == HttpStatus.OK) {
|
||||
LOG.info("Finished processing request " + req.uri()
|
||||
.getPath());
|
||||
} else {
|
||||
LOG.info("There was an error while processing request" + req.uri());
|
||||
}
|
||||
return res;
|
||||
})
|
||||
.onError(Throwable.class, (e, res) -> {
|
||||
LOG.error("Fatal exception has occurred", e);
|
||||
return status(HttpStatus.INTERNAL_SERVER_ERROR).build();
|
||||
})
|
||||
.build()
|
||||
.and(route(RequestPredicates.all(), req -> notFound().build()));
|
||||
}
|
||||
|
||||
public static class Error {
|
||||
private String errorMessage;
|
||||
|
||||
public Error(String message) {
|
||||
this.errorMessage = message;
|
||||
}
|
||||
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setErrorMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.springbootmvc.ctrl;
|
||||
|
||||
import static org.springframework.web.servlet.function.RouterFunctions.route;
|
||||
import static org.springframework.web.servlet.function.ServerResponse.ok;
|
||||
import static org.springframework.web.servlet.function.ServerResponse.status;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.function.EntityResponse;
|
||||
import org.springframework.web.servlet.function.RequestPredicates;
|
||||
import org.springframework.web.servlet.function.RouterFunction;
|
||||
import org.springframework.web.servlet.function.ServerRequest;
|
||||
import org.springframework.web.servlet.function.ServerResponse;
|
||||
|
||||
import com.baeldung.springbootmvc.SpringBootMvcFnApplication.Error;
|
||||
import com.baeldung.springbootmvc.model.Product;
|
||||
import com.baeldung.springbootmvc.svc.ProductService;
|
||||
|
||||
@Component
|
||||
public class ProductController {
|
||||
|
||||
public RouterFunction<ServerResponse> productListing(ProductService ps) {
|
||||
return route().GET("/product", req -> ok().body(ps.findAll()))
|
||||
.build();
|
||||
}
|
||||
|
||||
public RouterFunction<ServerResponse> productSearch(ProductService ps) {
|
||||
return route().nest(RequestPredicates.path("/product"), builder -> {
|
||||
builder.GET("/name/{name}", req -> ok().body(ps.findByName(req.pathVariable("name"))))
|
||||
.GET("/id/{id}", req -> ok().body(ps.findById(Integer.parseInt(req.pathVariable("id")))));
|
||||
})
|
||||
.onError(ProductService.ItemNotFoundException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
public RouterFunction<ServerResponse> adminFunctions(ProductService ps) {
|
||||
return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class))))
|
||||
.filter((req, next) -> authenticate(req) ? next.handle(req) : status(HttpStatus.UNAUTHORIZED).build())
|
||||
.onError(IllegalArgumentException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
public RouterFunction<ServerResponse> remainingProductRoutes(ProductService ps) {
|
||||
return route().add(productSearch(ps))
|
||||
.add(adminFunctions(ps))
|
||||
.build();
|
||||
}
|
||||
|
||||
private boolean authenticate(ServerRequest req) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
package com.baeldung.springbootmvc.model;
|
||||
|
||||
public class Product {
|
||||
private String name;
|
||||
private double price;
|
||||
private int id;
|
||||
|
||||
public Product(String name, double price, int id) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.price = price;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + id;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
long temp;
|
||||
temp = Double.doubleToLongBits(price);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Product other = (Product) obj;
|
||||
if (id != other.id)
|
||||
return false;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.springbootmvc.svc;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.baeldung.springbootmvc.model.Product;
|
||||
|
||||
@Service
|
||||
public class ProductService {
|
||||
|
||||
private final Set<Product> products = new HashSet<>();
|
||||
|
||||
{
|
||||
products.add(new Product("Book", 23.90, 1));
|
||||
products.add(new Product("Pen", 44.34, 2));
|
||||
}
|
||||
|
||||
public Product findById(int id) {
|
||||
return products.stream()
|
||||
.filter(obj -> obj.getId() == id)
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new ItemNotFoundException("Product not found"));
|
||||
}
|
||||
|
||||
public Product findByName(String name) {
|
||||
return products.stream()
|
||||
.filter(obj -> obj.getName()
|
||||
.equalsIgnoreCase(name))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new ItemNotFoundException("Product not found"));
|
||||
}
|
||||
|
||||
public Set<Product> findAll() {
|
||||
return products;
|
||||
}
|
||||
|
||||
public Product save(Product product) {
|
||||
if (StringUtils.isEmpty(product.getName()) || product.getPrice() == 0.0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
int newId = products.stream()
|
||||
.mapToInt(Product::getId)
|
||||
.max()
|
||||
.getAsInt() + 1;
|
||||
product.setId(newId);
|
||||
products.add(product);
|
||||
return product;
|
||||
}
|
||||
|
||||
public static class ItemNotFoundException extends RuntimeException {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public ItemNotFoundException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
spring.main.allow-bean-definition-overriding=true
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue