Merge branch 'eugenp:master' into master

This commit is contained in:
Ashish Gupta 2021-09-12 13:18:26 +05:30 committed by GitHub
commit a0c85c2a5a
128 changed files with 6073 additions and 13393 deletions

View File

@ -12,6 +12,7 @@ This module contains articles about Apache Kafka.
- [Kafka Connect Example with MQTT and MongoDB](https://www.baeldung.com/kafka-connect-mqtt-mongodb)
- [Building a Data Pipeline with Flink and Kafka](https://www.baeldung.com/kafka-flink-data-pipeline)
- [Exactly Once Processing in Kafka with Java](https://www.baeldung.com/kafka-exactly-once)
- [Custom Serializers in Apache Kafka](https://www.baeldung.com/kafka-custom-serializer)
##### Building the project

View File

@ -133,6 +133,11 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>

File diff suppressed because it is too large Load Diff

View File

@ -10,7 +10,6 @@ import com.baeldung.apache.beam.intro.WordCount;
public class WordCountUnitTest {
@Test
// @Ignore
public void givenInputFile_whenWordCountRuns_thenJobFinishWithoutError() {
boolean jobDone = WordCount.wordCount("src/test/resources/wordcount.txt", "target/output");
assertTrue(jobDone);

View File

@ -2,3 +2,4 @@
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
- [New Features in Java 12](https://www.baeldung.com/java-12-new-features)
- [Compare the Content of Two Files in Java](https://www.baeldung.com/java-compare-files)

View File

@ -0,0 +1,49 @@
package com.baeldung.java_16_features.mapmulti;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
public class Album {
private String albumName;
private int albumCost;
private List<Artist> artists;
Album(String name, int albumCost, List<Artist> artists) {
this.albumName = name;
this.artists = artists;
this.albumCost = albumCost;
}
public void artistAlbumPairsToMajorLabels(Consumer<Pair<String, String>> consumer) {
for (Artist artist : artists) {
if (artist.isAssociatedMajorLabels()) {
String concatLabels = artist.getMajorLabels()
.stream()
.collect(Collectors.joining(","));
consumer.accept(new ImmutablePair<>(artist.getName() + ":" + albumName, concatLabels));
}
}
}
public String getAlbumName() {
return albumName;
}
public int getAlbumCost() {
return albumCost;
}
List<Artist> getArtists() {
return artists;
}
public String toString() {
return albumName;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.java_16_features.mapmulti;
import java.util.List;
import java.util.Objects;
public class Artist {
private final String name;
private boolean associatedMajorLabels;
private List<String> majorLabels;
Artist(String name, boolean associatedMajorLabels, List<String> majorLabels) {
this.name = name;
this.associatedMajorLabels = associatedMajorLabels;
this.majorLabels = majorLabels;
}
public String getName() {
return name;
}
public boolean isAssociatedMajorLabels() {
return associatedMajorLabels;
}
public List<String> getMajorLabels() {
return majorLabels;
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Artist other = (Artist) obj;
return Objects.equals(name, other.name);
}
public String toString() {
return name;
}
}

View File

@ -0,0 +1,134 @@
package com.baeldung.java_16_features.mapmulti;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.offset;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.Test;
public class JavaStreamMapMultiUnitTest {
private static final List<Album> albums = Arrays.asList(new Album("album1", 10, Arrays.asList(new Artist("bob", true, Arrays.asList("label1", "label3")), new Artist("tom", true, Arrays.asList("label2", "label3")))),
new Album("album2", 20, Arrays.asList(new Artist("bill", true, Arrays.asList("label2", "label3")), new Artist("tom", true, Arrays.asList("label2", "label4")))));
@Test
public void givenAListOfintegers_whenMapMulti_thenGetListOfOfEvenDoublesPlusPercentage() {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
double percentage = .01;
List<Double> evenDoubles = integers.stream()
.<Double> mapMulti((integer, consumer) -> {
if (integer % 2 == 0) {
consumer.accept((double) integer * (1 + percentage));
}
})
.collect(toList());
assertThat(evenDoubles).containsAll(Arrays.asList(2.02D, 4.04D));
}
@Test
public void givenAListOfintegers_whenFilterMap_thenGetListOfOfEvenDoublesPlusPercentage() {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
double percentage = .01;
List<Double> evenDoubles = integers.stream()
.filter(integer -> integer % 2 == 0)
.<Double> map(integer -> ((double) integer * (1 + percentage)))
.collect(toList());
assertThat(evenDoubles).containsAll(Arrays.asList(2.02D, 4.04D));
}
@Test
public void givenAListOfintegers_whenMapMultiToDouble_thenGetSumOfEvenNumbersAfterApplyPercentage() {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
double percentage = .01;
double sum = integers.stream()
.mapMultiToDouble((integer, consumer) -> {
if (integer % 2 == 0) {
consumer.accept(integer * (1 + percentage));
}
})
.sum();
assertThat(sum).isEqualTo(12.12, offset(0.001d));
}
@Test
public void givenAListOfAlbums_whenFlatMap_thenGetListOfArtistAlbumPairs() {
List<Pair<String, String>> artistAlbum = albums.stream()
.flatMap(album -> album.getArtists()
.stream()
.map(artist -> new ImmutablePair<String, String>(artist.getName(), album.getAlbumName())))
.collect(toList());
assertThat(artistAlbum).contains(new ImmutablePair<String, String>("bob", "album1"), new ImmutablePair<String,
String>("tom", "album1"), new ImmutablePair<String, String>("bill", "album2"), new ImmutablePair<String, String>("tom", "album2"));
}
@Test
public void givenAListOfAlbums_whenMapMulti_thenGetListOfPairsOfArtistAlbum() {
List<Pair<String, String>> artistAlbum = albums.stream()
.<Pair<String, String>> mapMulti((album, consumer) -> {
for (Artist artist : album.getArtists()) {
consumer.accept(new ImmutablePair<String, String>(artist.getName(), album.getAlbumName()));
}
})
.collect(toList());
assertThat(artistAlbum).contains(new ImmutablePair<String, String>("bob", "album1"), new ImmutablePair<String, String>("tom", "album1"),
new ImmutablePair<String, String>("bill", "album2"), new ImmutablePair<String, String>("tom", "album2"));
}
@Test
public void givenAListOfAlbums_whenFlatMap_thenGetListOfArtistAlbumjPairsBelowGivenCost() {
int upperCost = 9;
List<Pair<String, String>> artistAlbum = albums.stream()
.flatMap(album -> album.getArtists()
.stream()
.filter(artist -> upperCost > album.getAlbumCost())
.map(artist -> new ImmutablePair<String, String>(artist.getName(), album.getAlbumName())))
.collect(toList());
assertTrue(artistAlbum.isEmpty());
}
@Test
public void givenAListOfAlbums_whenMapMulti_thenGetListOfArtistAlbumPairsBelowGivenCost() {
int upperCost = 9;
List<Pair<String, String>> artistAlbum = albums.stream()
.<Pair<String, String>> mapMulti((album, consumer) -> {
if (album.getAlbumCost() < upperCost) {
for (Artist artist : album.getArtists()) {
consumer.accept(new ImmutablePair<String, String>(artist.getName(), album.getAlbumName()));
}
}
})
.collect(toList());
assertTrue(artistAlbum.isEmpty());
}
@Test
public void givenAListOfAlbums_whenMapMulti_thenGetPairsOfArtistMajorLabelsUsingMethodReference() {
List<Pair<String, String>> artistLabels = albums.stream()
.mapMulti(Album::artistAlbumPairsToMajorLabels)
.collect(toList());
assertThat(artistLabels).contains(new ImmutablePair<String, String>("bob:album1", "label1,label3"), new ImmutablePair<String, String>("tom:album1", "label2,label3"),
new ImmutablePair<String, String>("bill:album2", "label2,label3"), new ImmutablePair<String, String>("tom:album2", "label2,label4"));
}
}

View File

@ -11,3 +11,4 @@ This module contains articles about parsing and formatting Java date and time ob
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
- [Convert between String and Timestamp](https://www.baeldung.com/java-string-to-timestamp)
- [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date)
- [Format a Milliseconds Duration to HH:MM:SS](https://www.baeldung.com/java-ms-to-hhmmss)

View File

@ -75,7 +75,7 @@
<properties>
<commons-validator.version>1.6</commons-validator.version>
<joda-time.version>2.10</joda-time.version>
<joda-time.version>2.10.10</joda-time.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<maven.compiler.source>1.9</maven.compiler.source>

View File

@ -0,0 +1,54 @@
package com.baeldung.formatduration;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.joda.time.Period;
import org.junit.Test;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
public class FormatDurationUnitTest {
@Test
public void givenInterval_WhenFormatInterval_formatDuration() {
long HH = TimeUnit.MILLISECONDS.toHours(38114000);
long MM = TimeUnit.MILLISECONDS.toMinutes(38114000) % 60;
long SS = TimeUnit.MILLISECONDS.toSeconds(38114000) % 60;
String timeInHHMMSS = String.format("%02d:%02d:%02d", HH, MM, SS);
assertThat(timeInHHMMSS).isEqualTo("10:35:14");
}
@Test
public void givenInterval_WhenFormatUsingDuration_formatDuration() {
Duration duration = Duration.ofMillis(38114000);
long seconds = duration.getSeconds();
long HH = seconds / 3600;
long MM = (seconds % 3600) / 60;
long SS = seconds % 60;
String timeInHHMMSS = String.format("%02d:%02d:%02d", HH, MM, SS);
assertThat(timeInHHMMSS).isEqualTo("10:35:14");
}
@Test
public void givenInterval_WhenFormatDurationUsingApacheCommons_formatDuration() {
assertThat(DurationFormatUtils.formatDuration(38114000, "HH:mm:ss"))
.isEqualTo("10:35:14");
}
@Test
public void givenInterval_WhenFormatDurationUsingJodaTime_formatDuration() {
org.joda.time.Duration duration = new org.joda.time.Duration(38114000);
Period period = duration.toPeriod();
long HH = period.getHours();
long MM = period.getMinutes();
long SS = period.getSeconds();
String timeInHHMMSS = String.format("%02d:%02d:%02d", HH, MM, SS);
assertThat(timeInHHMMSS).isEqualTo("10:35:14");
}
}

View File

@ -8,4 +8,5 @@ This module contains articles about networking in Java
- [Downloading Email Attachments in Java](https://www.baeldung.com/java-download-email-attachments)
- [Connection Timeout vs. Read Timeout for Java Sockets](https://www.baeldung.com/java-socket-connection-read-timeout)
- [Find Whether an IP Address Is in the Specified Range or Not in Java](https://www.baeldung.com/java-check-ip-address-range)
- [Find the IP Address of a Client Connected to a Server](https://www.baeldung.com/java-client-get-ip-address)
- [[<-- Prev]](/core-java-modules/core-java-networking-2)

View File

@ -0,0 +1,39 @@
package com.baeldung.clientaddress;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ApplicationClient {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void connect(String ip, int port) throws IOException {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public void sendGreetings(String msg) throws IOException {
out.println(msg);
String reply = in.readLine();
System.out.println("Reply received from the server :: " + reply);
}
public void disconnect() throws IOException {
in.close();
out.close();
clientSocket.close();
}
public static void main(String[] args) throws IOException {
ApplicationClient client = new ApplicationClient();
client.connect(args[0], Integer.parseInt(args[1])); // IP address and port number of the server
client.sendGreetings(args[2]); // greetings message
client.disconnect();
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.clientaddress;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class ApplicationServer {
private ServerSocket serverSocket;
private Socket connectedSocket;
private PrintWriter out;
private BufferedReader in;
public void startServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
connectedSocket = serverSocket.accept();
InetSocketAddress socketAddress = (InetSocketAddress) connectedSocket.getRemoteSocketAddress();
String clientIpAddress = socketAddress.getAddress()
.getHostAddress();
System.out.println("IP address of the connected client :: " + clientIpAddress);
out = new PrintWriter(connectedSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(connectedSocket.getInputStream()));
String msg = in.readLine();
System.out.println("Message received from the client :: " + msg);
out.println("Hello Client !!");
closeIO();
stopServer();
}
private void closeIO() throws IOException {
in.close();
out.close();
}
private void stopServer() throws IOException {
connectedSocket.close();
serverSocket.close();
}
public static void main(String[] args) throws IOException {
ApplicationServer server = new ApplicationServer();
server.startServer(5000);
}
}

View File

@ -0,0 +1,101 @@
package com.baeldung.java9.process;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProcessAPIEnhancements {
static Logger log = LoggerFactory.getLogger(ProcessAPIEnhancements.class);
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
infoOfCurrentProcess();
infoOfLiveProcesses();
infoOfSpawnProcess();
infoOfExitCallback();
infoOfChildProcess();
}
private static void infoOfCurrentProcess() {
ProcessHandle processHandle = ProcessHandle.current();
ProcessHandle.Info processInfo = processHandle.info();
log.info("PID: " + processHandle.pid());
log.info("Arguments: " + processInfo.arguments());
log.info("Command: " + processInfo.command());
log.info("Instant: " + processInfo.startInstant());
log.info("Total CPU duration: " + processInfo.totalCpuDuration());
log.info("User: " + processInfo.user());
}
private static void infoOfSpawnProcess() throws IOException {
String javaCmd = ProcessUtils.getJavaCmd().getAbsolutePath();
ProcessBuilder processBuilder = new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO().start();
ProcessHandle processHandle = process.toHandle();
ProcessHandle.Info processInfo = processHandle.info();
log.info("PID: " + processHandle.pid());
log.info("Arguments: " + processInfo.arguments());
log.info("Command: " + processInfo.command());
log.info("Instant: " + processInfo.startInstant());
log.info("Total CPU duration: " + processInfo.totalCpuDuration());
log.info("User: " + processInfo.user());
}
private static void infoOfLiveProcesses() {
Stream<ProcessHandle> liveProcesses = ProcessHandle.allProcesses();
liveProcesses.filter(ProcessHandle::isAlive)
.forEach(ph -> {
log.info("PID: " + ph.pid());
log.info("Instance: " + ph.info().startInstant());
log.info("User: " + ph.info().user());
});
}
private static void infoOfChildProcess() throws IOException {
int childProcessCount = 5;
for (int i = 0; i < childProcessCount; i++) {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
processBuilder.inheritIO().start();
}
Stream<ProcessHandle> children = ProcessHandle.current()
.children();
children.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
Stream<ProcessHandle> descendants = ProcessHandle.current()
.descendants();
descendants.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
}
private static void infoOfExitCallback() throws IOException, InterruptedException, ExecutionException {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO()
.start();
ProcessHandle processHandle = process.toHandle();
log.info("PID: {} has started", processHandle.pid());
CompletableFuture<ProcessHandle> onProcessExit = processHandle.onExit();
onProcessExit.get();
log.info("Alive: " + processHandle.isAlive());
onProcessExit.thenAccept(ph -> {
log.info("PID: {} has stopped", ph.pid());
});
}
}

View File

@ -1,132 +0,0 @@
package com.baeldung.java9.process;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by sanaulla on 2/23/2017.
*/
public class ProcessAPIEnhancementsUnitTest {
Logger log = LoggerFactory.getLogger(ProcessAPIEnhancementsUnitTest.class);
// @Test
// OS / Java version dependent
public void givenCurrentProcess_whenInvokeGetInfo_thenSuccess() throws IOException {
ProcessHandle processHandle = ProcessHandle.current();
ProcessHandle.Info processInfo = processHandle.info();
assertNotNull(processHandle.pid());
assertEquals(true, processInfo.arguments()
.isPresent());
assertEquals(true, processInfo.command()
.isPresent());
assertTrue(processInfo.command()
.get()
.contains("java"));
assertEquals(true, processInfo.startInstant()
.isPresent());
assertEquals(true, processInfo.totalCpuDuration()
.isPresent());
assertEquals(true, processInfo.user()
.isPresent());
}
// @Test
// OS / Java version dependent
public void givenSpawnProcess_whenInvokeGetInfo_thenSuccess() throws IOException {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder = new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO()
.start();
ProcessHandle processHandle = process.toHandle();
ProcessHandle.Info processInfo = processHandle.info();
assertNotNull(processHandle.pid());
assertEquals(true, processInfo.arguments()
.isPresent());
assertEquals(true, processInfo.command()
.isPresent());
assertTrue(processInfo.command()
.get()
.contains("java"));
assertEquals(true, processInfo.startInstant()
.isPresent());
assertEquals(false, processInfo.totalCpuDuration()
.isPresent());
assertEquals(true, processInfo.user()
.isPresent());
}
// @Test
// OS / Java version dependent
public void givenLiveProcesses_whenInvokeGetInfo_thenSuccess() {
Stream<ProcessHandle> liveProcesses = ProcessHandle.allProcesses();
liveProcesses.filter(ProcessHandle::isAlive)
.forEach(ph -> {
assertNotNull(ph.pid());
assertEquals(true, ph.info()
.startInstant()
.isPresent());
assertEquals(true, ph.info()
.user()
.isPresent());
});
}
// @Test
// OS / Java version dependent
public void givenProcess_whenGetChildProcess_thenSuccess() throws IOException {
int childProcessCount = 5;
for (int i = 0; i < childProcessCount; i++) {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
processBuilder.inheritIO().start();
}
Stream<ProcessHandle> children = ProcessHandle.current()
.children();
children.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
Stream<ProcessHandle> descendants = ProcessHandle.current()
.descendants();
descendants.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
}
// @Test
// OS / Java version dependent
public void givenProcess_whenAddExitCallback_thenSuccess() throws Exception {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO()
.start();
ProcessHandle processHandle = process.toHandle();
log.info("PID: {} has started", processHandle.pid());
CompletableFuture<ProcessHandle> onProcessExit = processHandle.onExit();
onProcessExit.get();
assertEquals(false, processHandle.isAlive());
onProcessExit.thenAccept(ph -> {
log.info("PID: {} has stopped", ph.pid());
});
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.cryptography;
import org.junit.Test;
import java.security.NoSuchAlgorithmException;
import static org.assertj.core.api.Assertions.assertThat;
public class CryptographyStrengthUnitTest {
private static final int UNLIMITED_KEY_SIZE = 2147483647;
@Test
public void whenDefaultCheck_thenUnlimitedReturned() throws NoSuchAlgorithmException {
int maxKeySize = javax.crypto.Cipher.getMaxAllowedKeyLength("AES");
assertThat(maxKeySize).isEqualTo(UNLIMITED_KEY_SIZE);
}
}

View File

@ -24,7 +24,7 @@
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-datatype.version}</version>
<version>${jackson.version}</version>
</dependency>
<!-- CSV -->
<dependency>
@ -52,7 +52,6 @@
<properties>
<assertj.version>3.11.0</assertj.version>
<jackson-datatype.version>2.9.8</jackson-datatype.version>
</properties>
</project>

View File

@ -3,5 +3,6 @@
This module contains articles about JavaFX.
### Relevant Articles:
-[Introduction to JavaFX](https://www.baeldung.com/javafx)
- [Introduction to JavaFX](https://www.baeldung.com/javafx)
- [Display Custom Items in JavaFX ListView](https://www.baeldung.com/javafx-listview-display-custom-items)

View File

@ -17,7 +17,6 @@
</prerequisites>
<properties>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
<argLine>-Djava.security.egd=file:/dev/./urandom -Xmx256m</argLine>
<assertj.version>3.6.2</assertj.version>
<awaitility.version>2.0.0</awaitility.version>
@ -31,6 +30,7 @@
<jcache.version>1.0.0</jcache.version>
<jhipster.server.version>1.1.0</jhipster.server.version>
<jjwt.version>0.7.0</jjwt.version>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
<liquibase-slf4j.version>2.0.0</liquibase-slf4j.version>
<liquibase.version>3.6.2</liquibase.version>
@ -349,7 +349,6 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -365,11 +364,6 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
@ -580,14 +574,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!-- Force alphabetical order to have a reproducible build -->
<runOrder>alphabetical</runOrder>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>

View File

@ -21,6 +21,8 @@ eureka:
instanceId: carapp:${spring.application.instance_id:${random.value}}
spring:
main:
banner-mode: "off"
application:
name: carapp
jackson:
@ -37,7 +39,7 @@ spring:
database-platform: io.github.jhipster.domain.util.FixedH2Dialect
database: H2
open-in-view: false
show-sql: true
show-sql: false
hibernate:
ddl-auto: none
naming:

View File

@ -3,7 +3,7 @@
<configuration scan="true">
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="com.car.app" level="DEBUG"/>
<logger name="com.car.app" level="INFO"/>
<logger name="org.hibernate" level="WARN"/>
<logger name="org.hibernate.ejb.HibernatePersistence" level="OFF"/>
<logger name="org.apache.catalina.startup.DigesterFactory" level="OFF"/>

View File

@ -29,6 +29,7 @@
<jcache.version>1.0.0</jcache.version>
<jhipster.server.version>1.1.0</jhipster.server.version>
<jjwt.version>0.7.0</jjwt.version>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
<liquibase-slf4j.version>2.0.0</liquibase-slf4j.version>
<liquibase.version>3.6.2</liquibase.version>
@ -90,7 +91,6 @@
<undertow.version>1.4.10.Final</undertow.version>
<validation-api.version>1.1.0.Final</validation-api.version>
<yarn.version>v0.21.3</yarn.version>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
</properties>
<dependencyManagement>
@ -345,6 +345,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
@ -359,11 +363,6 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
@ -574,14 +573,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!-- Force alphabetical order to have a reproducible build -->
<runOrder>alphabetical</runOrder>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>

View File

@ -21,6 +21,8 @@ eureka:
instanceId: dealerapp:${spring.application.instance_id:${random.value}}
spring:
main:
banner-mode: "off"
application:
name: dealerapp
jackson:
@ -37,7 +39,7 @@ spring:
database-platform: io.github.jhipster.domain.util.FixedH2Dialect
database: H2
open-in-view: false
show-sql: true
show-sql: false
hibernate:
ddl-auto: none
naming:

View File

@ -3,7 +3,7 @@
<configuration scan="true">
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="com.dealer.app" level="DEBUG"/>
<logger name="com.dealer.app" level="INFO"/>
<logger name="org.hibernate" level="WARN"/>
<logger name="org.hibernate.ejb.HibernatePersistence" level="OFF"/>
<logger name="org.apache.catalina.startup.DigesterFactory" level="OFF"/>

View File

@ -32,6 +32,7 @@
<jcache.version>1.0.0</jcache.version>
<jhipster.server.version>1.1.0</jhipster.server.version>
<jjwt.version>0.7.0</jjwt.version>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
<liquibase-slf4j.version>2.0.0</liquibase-slf4j.version>
<liquibase.version>3.6.2</liquibase.version>
@ -94,7 +95,6 @@
<undertow.version>1.4.10.Final</undertow.version>
<validation-api.version>1.1.0.Final</validation-api.version>
<yarn.version>v0.21.3</yarn.version>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
</properties>
<dependencyManagement>
@ -383,6 +383,10 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
@ -397,11 +401,6 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
@ -632,14 +631,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!-- Force alphabetical order to have a reproducible build -->
<runOrder>alphabetical</runOrder>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>

View File

@ -49,7 +49,7 @@ public class LogsResourceIntegrationTest {
public void changeLogs()throws Exception {
LoggerVM logger = new LoggerVM();
logger.setLevel("INFO");
logger.setName("ROOT");
logger.setName("some.test.logger");
restLogsMockMvc.perform(put("/management/logs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)

View File

@ -21,6 +21,8 @@ eureka:
instanceId: gateway:${spring.application.instance_id:${random.value}}
spring:
main:
banner-mode: "off"
application:
name: gateway
autoconfigure:
@ -39,7 +41,7 @@ spring:
database-platform: io.github.jhipster.domain.util.FixedH2Dialect
database: H2
open-in-view: false
show-sql: true
show-sql: false
hibernate:
ddl-auto: none
naming:

View File

@ -3,7 +3,7 @@
<configuration scan="true">
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="com.gateway" level="DEBUG"/>
<logger name="com.gateway" level="INFO"/>
<logger name="org.hibernate" level="WARN"/>
<logger name="org.hibernate.ejb.HibernatePersistence" level="OFF"/>
<logger name="org.apache.catalina.startup.DigesterFactory" level="OFF"/>

View File

@ -277,8 +277,7 @@
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- security -->
<dependency>

View File

@ -49,7 +49,7 @@ public class LogsResourceIntegrationTest {
public void changeLogs()throws Exception {
LoggerVM logger = new LoggerVM();
logger.setLevel("INFO");
logger.setName("ROOT");
logger.setName("some.test.logger");
restLogsMockMvc.perform(put("/management/logs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)

View File

@ -15,6 +15,8 @@
spring:
main:
banner-mode: "off"
application:
name: baeldung
jackson:
@ -31,7 +33,7 @@ spring:
database-platform: io.github.jhipster.domain.util.FixedH2Dialect
database: H2
open-in-view: false
show-sql: true
show-sql: false
hibernate:
ddl-auto: none
naming:

View File

@ -3,7 +3,7 @@
<configuration scan="true">
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="com.baeldung" level="DEBUG"/>
<logger name="com.baeldung" level="INFO"/>
<logger name="org.hibernate" level="WARN"/>
<logger name="org.hibernate.ejb.HibernatePersistence" level="OFF"/>
<logger name="org.apache.catalina.startup.DigesterFactory" level="OFF"/>

View File

@ -1,6 +1,13 @@
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>jhipster-uaa</artifactId>
<groupId>com.baeldung.jhipster</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>com.baeldung.jhipster.gateway</groupId>
<artifactId>gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
@ -415,15 +422,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<!-- Force alphabetical order to have a reproducible build -->
<runOrder>alphabetical</runOrder>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>

View File

@ -40,7 +40,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
*
* @see WebConfigurer
*/
public class WebConfigurerTest {
public class WebConfigurerUnitTest {
private WebConfigurer webConfigurer;

View File

@ -18,7 +18,7 @@ import static springfox.documentation.swagger2.web.Swagger2Controller.DEFAULT_UR
/**
* Tests SwaggerBasePathRewritingFilter class.
*/
public class SwaggerBasePathRewritingFilterTest {
public class SwaggerBasePathRewritingFilterUnitTest {
private SwaggerBasePathRewritingFilter filter = new SwaggerBasePathRewritingFilter();

View File

@ -16,7 +16,7 @@ import java.util.List;
*
* @see CookieCollection
*/
public class CookieCollectionTest {
public class CookieCollectionUnitTest {
public static final String COOKIE_NAME = "chocolate";
public static final String COOKIE_VALUE = "yummy";
public static final String BROWNIE_NAME = "brownie";

View File

@ -12,7 +12,7 @@ import org.springframework.security.oauth2.common.OAuth2AccessToken;
* Test whether the CookieTokenExtractor can properly extract access tokens from
* Cookies and Headers.
*/
public class CookieTokenExtractorTest {
public class CookieTokenExtractorUnitTest {
private CookieTokenExtractor cookieTokenExtractor;
@Before
@ -22,24 +22,24 @@ public class CookieTokenExtractorTest {
@Test
public void testExtractTokenCookie() {
MockHttpServletRequest request = OAuth2AuthenticationServiceTest.createMockHttpServletRequest();
MockHttpServletRequest request = OAuth2AuthenticationServiceUnitTest.createMockHttpServletRequest();
Authentication authentication = cookieTokenExtractor.extract(request);
Assert.assertEquals(OAuth2AuthenticationServiceTest.ACCESS_TOKEN_VALUE, authentication.getPrincipal().toString());
Assert.assertEquals(OAuth2AuthenticationServiceUnitTest.ACCESS_TOKEN_VALUE, authentication.getPrincipal().toString());
}
@Test
public void testExtractTokenHeader() {
MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "http://www.test.com");
request.addHeader("Authorization", OAuth2AccessToken.BEARER_TYPE + " " + OAuth2AuthenticationServiceTest.ACCESS_TOKEN_VALUE);
request.addHeader("Authorization", OAuth2AccessToken.BEARER_TYPE + " " + OAuth2AuthenticationServiceUnitTest.ACCESS_TOKEN_VALUE);
Authentication authentication = cookieTokenExtractor.extract(request);
Assert.assertEquals(OAuth2AuthenticationServiceTest.ACCESS_TOKEN_VALUE, authentication.getPrincipal().toString());
Assert.assertEquals(OAuth2AuthenticationServiceUnitTest.ACCESS_TOKEN_VALUE, authentication.getPrincipal().toString());
}
@Test
public void testExtractTokenParam() {
MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "http://www.test.com");
request.addParameter(OAuth2AccessToken.ACCESS_TOKEN, OAuth2AuthenticationServiceTest.ACCESS_TOKEN_VALUE);
request.addParameter(OAuth2AccessToken.ACCESS_TOKEN, OAuth2AuthenticationServiceUnitTest.ACCESS_TOKEN_VALUE);
Authentication authentication = cookieTokenExtractor.extract(request);
Assert.assertEquals(OAuth2AuthenticationServiceTest.ACCESS_TOKEN_VALUE, authentication.getPrincipal().toString());
Assert.assertEquals(OAuth2AuthenticationServiceUnitTest.ACCESS_TOKEN_VALUE, authentication.getPrincipal().toString());
}
}

View File

@ -39,7 +39,7 @@ import static org.mockito.Mockito.when;
* @see OAuth2AuthenticationService
*/
@RunWith(MockitoJUnitRunner.class)
public class OAuth2AuthenticationServiceTest {
public class OAuth2AuthenticationServiceUnitTest {
public static final String CLIENT_AUTHORIZATION = "Basic d2ViX2FwcDpjaGFuZ2VpdA==";
public static final String ACCESS_TOKEN_VALUE = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0OTQyNzI4NDQsInVzZXJfbmFtZSI6InVzZXIiLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiNzc1ZTJkYWUtYWYzZi00YTdhLWExOTktNzNiZTU1MmIxZDVkIiwiY2xpZW50X2lkIjoid2ViX2FwcCIsInNjb3BlIjpbIm9wZW5pZCJdfQ.gEK0YcX2IpkpxnkxXXHQ4I0xzTjcy7edqb89ukYE0LPe7xUcZVwkkCJF_nBxsGJh2jtA6NzNLfY5zuL6nP7uoAq3fmvsyrcyR2qPk8JuuNzGtSkICx3kPDRjAT4ST8SZdeh7XCbPVbySJ7ZmPlRWHyedzLA1wXN0NUf8yZYS4ELdUwVBYIXSjkNoKqfWm88cwuNr0g0teypjPtjDqCnXFt1pibwdfIXn479Y1neNAdvSpHcI4Ost-c7APCNxW2gqX-0BItZQearxRgKDdBQ7CGPAIky7dA0gPuKUpp_VCoqowKCXqkE9yKtRQGIISewtj2UkDRZePmzmYrUBXRzfYw";
public static final String REFRESH_TOKEN_VALUE = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ1c2VyIiwic2NvcGUiOlsib3BlbmlkIl0sImF0aSI6Ijc3NWUyZGFlLWFmM2YtNGE3YS1hMTk5LTczYmU1NTJiMWQ1ZCIsImV4cCI6MTQ5Njg2NDc0MywiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6IjhmYjI2YTllLTdjYzQtNDFlMi1hNzBjLTk4MDc0N2U2YWFiOSIsImNsaWVudF9pZCI6IndlYl9hcHAifQ.q1-Df9_AFO6TJNiLKV2YwTjRbnd7qcXv52skXYnog5siHYRoR6cPtm6TNQ04iDAoIHljTSTNnD6DS3bHk41mV55gsSVxGReL8VCb_R8ZmhVL4-5yr90sfms0wFp6lgD2bPmZ-TXiS2Oe9wcbNWagy5RsEplZ-sbXu3tjmDao4FN35ojPsXmUs84XnNQH3Y_-PY9GjZG0JEfLQIvE0J5BkXS18Z015GKyA6GBIoLhAGBQQYyG9m10ld_a9fD5SmCyCF72Jad_pfP1u8Z_WyvO-wrlBvm2x-zBthreVrXU5mOb9795wJEP-xaw3dXYGjht_grcW4vKUFtj61JgZk98CQ";

View File

@ -12,7 +12,7 @@ import org.springframework.test.util.ReflectionTestUtils;
*
* @see OAuth2CookieHelper
*/
public class OAuth2CookieHelperTest {
public class OAuth2CookieHelperUnitTest {
public static final String GET_COOKIE_DOMAIN_METHOD = "getCookieDomain";
private OAuth2Properties oAuth2Properties;
private OAuth2CookieHelper cookieHelper;

View File

@ -51,7 +51,7 @@ public class LogsResourceIntTest {
public void changeLogs() throws Exception {
LoggerVM logger = new LoggerVM();
logger.setLevel("INFO");
logger.setName("ROOT");
logger.setName("some.test.logger");
restLogsMockMvc.perform(put("/management/logs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)

View File

@ -21,6 +21,8 @@ eureka:
instanceId: gateway:${spring.application.instance-id:${random.value}}
spring:
main:
banner-mode: "off"
application:
name: gateway
cache:

View File

@ -1,6 +1,13 @@
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>jhipster-uaa</artifactId>
<groupId>com.baeldung.jhipster</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>com.baeldung.jhipster.quotes</groupId>
<artifactId>quotes</artifactId>
<version>0.0.1-SNAPSHOT</version>
@ -399,15 +406,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<!-- Force alphabetical order to have a reproducible build -->
<runOrder>alphabetical</runOrder>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>

View File

@ -38,7 +38,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
*
* @see WebConfigurer
*/
public class WebConfigurerTest {
public class WebConfigurerUnitTest {
private WebConfigurer webConfigurer;

View File

@ -51,7 +51,7 @@ public class LogsResourceIntTest {
public void changeLogs() throws Exception {
LoggerVM logger = new LoggerVM();
logger.setLevel("INFO");
logger.setName("ROOT");
logger.setName("some.test.logger");
restLogsMockMvc.perform(put("/management/logs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)

View File

@ -21,6 +21,8 @@ eureka:
instanceId: quotes:${spring.application.instance-id:${random.value}}
spring:
main:
banner-mode: "off"
application:
name: quotes
cache:

View File

@ -1,6 +1,12 @@
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>jhipster-uaa</artifactId>
<groupId>com.baeldung.jhipster</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>com.baeldung.jhipster.uaa</groupId>
<artifactId>uaa</artifactId>
<version>0.0.1-SNAPSHOT</version>
@ -399,15 +405,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<!-- Force alphabetical order to have a reproducible build -->
<runOrder>alphabetical</runOrder>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>

View File

@ -38,7 +38,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
*
* @see WebConfigurer
*/
public class WebConfigurerTest {
public class WebConfigurerUnitTest {
private WebConfigurer webConfigurer;

View File

@ -51,7 +51,7 @@ public class LogsResourceIntTest {
public void changeLogs() throws Exception {
LoggerVM logger = new LoggerVM();
logger.setLevel("INFO");
logger.setName("ROOT");
logger.setName("some.test.logger");
restLogsMockMvc.perform(put("/management/logs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)

View File

@ -21,6 +21,8 @@ eureka:
instanceId: uaa:${spring.application.instance-id:${random.value}}
spring:
main:
banner-mode: "off"
application:
name: uaa
cache:

View File

@ -17,11 +17,39 @@
<relativePath>../parent-boot-1</relativePath>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
<exclusion>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</exclusion>
</exclusions>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>${byte-buddy.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<modules>

View File

@ -17,7 +17,22 @@ import com.sun.codemodel.JCodeModel;
public class JsonToJavaClassConversion {
public Object convertJsonToJavaClass(URL inputJson, File outputJavaClassDirectory, String packageName, String className) throws IOException {
public static void main(String[] args) {
String packageName = "com.baeldung.jsontojavaclass.pojo";
String basePath = "src/main/resources";
File inputJson = new File(basePath + File.separator + "input.json");
File outputPojoDirectory = new File(basePath + File.separator + "convertedPojo");
outputPojoDirectory.mkdirs();
try {
new JsonToJavaClassConversion().convertJsonToJavaClass(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));
} catch (IOException e) {
System.out.println("Encountered issue while converting to pojo: " + e.getMessage());
e.printStackTrace();
}
}
public void convertJsonToJavaClass(URL inputJsonUrl, File outputJavaClassDirectory, String packageName, String javaClassName) throws IOException {
JCodeModel jcodeModel = new JCodeModel();
GenerationConfig config = new DefaultGenerationConfig() {
@ -33,10 +48,9 @@ public class JsonToJavaClassConversion {
};
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(jcodeModel, className, packageName, inputJson);
mapper.generate(jcodeModel, javaClassName, packageName, inputJsonUrl);
jcodeModel.build(outputJavaClassDirectory);
return mapper;
}
}

View File

@ -5,9 +5,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@ -16,7 +14,14 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "name", "area", "author", "id", "salary", "topics" })
@JsonPropertyOrder({
"name",
"area",
"author",
"id",
"salary",
"topics"
})
@Generated("jsonschema2pojo")
public class SamplePojo {
@ -143,40 +148,37 @@ public class SamplePojo {
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(SamplePojo.class.getName())
.append('@')
.append(Integer.toHexString(System.identityHashCode(this)))
.append('[');
sb.append(SamplePojo.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("name");
sb.append('=');
sb.append(((this.name == null) ? "<null>" : this.name));
sb.append(((this.name == null)?"<null>":this.name));
sb.append(',');
sb.append("area");
sb.append('=');
sb.append(((this.area == null) ? "<null>" : this.area));
sb.append(((this.area == null)?"<null>":this.area));
sb.append(',');
sb.append("author");
sb.append('=');
sb.append(((this.author == null) ? "<null>" : this.author));
sb.append(((this.author == null)?"<null>":this.author));
sb.append(',');
sb.append("id");
sb.append('=');
sb.append(((this.id == null) ? "<null>" : this.id));
sb.append(((this.id == null)?"<null>":this.id));
sb.append(',');
sb.append("salary");
sb.append('=');
sb.append(((this.salary == null) ? "<null>" : this.salary));
sb.append(((this.salary == null)?"<null>":this.salary));
sb.append(',');
sb.append("topics");
sb.append('=');
sb.append(((this.topics == null) ? "<null>" : this.topics));
sb.append(((this.topics == null)?"<null>":this.topics));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null) ? "<null>" : this.additionalProperties));
sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length() - 1)) == ',') {
sb.setCharAt((sb.length() - 1), ']');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
@ -186,13 +188,13 @@ public class SamplePojo {
@Override
public int hashCode() {
int result = 1;
result = ((result * 31) + ((this.area == null) ? 0 : this.area.hashCode()));
result = ((result * 31) + ((this.author == null) ? 0 : this.author.hashCode()));
result = ((result * 31) + ((this.topics == null) ? 0 : this.topics.hashCode()));
result = ((result * 31) + ((this.name == null) ? 0 : this.name.hashCode()));
result = ((result * 31) + ((this.id == null) ? 0 : this.id.hashCode()));
result = ((result * 31) + ((this.additionalProperties == null) ? 0 : this.additionalProperties.hashCode()));
result = ((result * 31) + ((this.salary == null) ? 0 : this.salary.hashCode()));
result = ((result* 31)+((this.area == null)? 0 :this.area.hashCode()));
result = ((result* 31)+((this.author == null)? 0 :this.author.hashCode()));
result = ((result* 31)+((this.topics == null)? 0 :this.topics.hashCode()));
result = ((result* 31)+((this.name == null)? 0 :this.name.hashCode()));
result = ((result* 31)+((this.id == null)? 0 :this.id.hashCode()));
result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));
result = ((result* 31)+((this.salary == null)? 0 :this.salary.hashCode()));
return result;
}
@ -205,10 +207,7 @@ public class SamplePojo {
return false;
}
SamplePojo rhs = ((SamplePojo) other);
return ((((((((this.area == rhs.area) || ((this.area != null) && this.area.equals(rhs.area))) && ((this.author == rhs.author) || ((this.author != null) && this.author.equals(rhs.author))))
&& ((this.topics == rhs.topics) || ((this.topics != null) && this.topics.equals(rhs.topics)))) && ((this.name == rhs.name) || ((this.name != null) && this.name.equals(rhs.name))))
&& ((this.id == rhs.id) || ((this.id != null) && this.id.equals(rhs.id)))) && ((this.additionalProperties == rhs.additionalProperties) || ((this.additionalProperties != null) && this.additionalProperties.equals(rhs.additionalProperties))))
&& ((this.salary == rhs.salary) || ((this.salary != null) && this.salary.equals(rhs.salary))));
return ((((((((this.area == rhs.area)||((this.area!= null)&&this.area.equals(rhs.area)))&&((this.author == rhs.author)||((this.author!= null)&&this.author.equals(rhs.author))))&&((this.topics == rhs.topics)||((this.topics!= null)&&this.topics.equals(rhs.topics))))&&((this.name == rhs.name)||((this.name!= null)&&this.name.equals(rhs.name))))&&((this.id == rhs.id)||((this.id!= null)&&this.id.equals(rhs.id))))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))))&&((this.salary == rhs.salary)||((this.salary!= null)&&this.salary.equals(rhs.salary))));
}
}

View File

@ -0,0 +1,119 @@
package com.baeldung.jsontojavaclass.pojo;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"city",
"country"
})
@Generated("jsonschema2pojo")
public class Address {
@JsonProperty("city")
private String city;
@JsonProperty("country")
private String country;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("city")
public String getCity() {
return city;
}
@JsonProperty("city")
public void setCity(String city) {
this.city = city;
}
public Address withCity(String city) {
this.city = city;
return this;
}
@JsonProperty("country")
public String getCountry() {
return country;
}
@JsonProperty("country")
public void setCountry(String country) {
this.country = country;
}
public Address withCountry(String country) {
this.country = country;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public Address withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(Address.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("city");
sb.append('=');
sb.append(((this.city == null)?"<null>":this.city));
sb.append(',');
sb.append("country");
sb.append('=');
sb.append(((this.country == null)?"<null>":this.country));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
@Override
public int hashCode() {
int result = 1;
result = ((result* 31)+((this.country == null)? 0 :this.country.hashCode()));
result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));
result = ((result* 31)+((this.city == null)? 0 :this.city.hashCode()));
return result;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Address) == false) {
return false;
}
Address rhs = ((Address) other);
return ((((this.country == rhs.country)||((this.country!= null)&&this.country.equals(rhs.country)))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))))&&((this.city == rhs.city)||((this.city!= null)&&this.city.equals(rhs.city))));
}
}

View File

@ -0,0 +1,213 @@
package com.baeldung.jsontojavaclass.pojo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name",
"area",
"author",
"id",
"topics",
"address"
})
@Generated("jsonschema2pojo")
public class Input {
@JsonProperty("name")
private String name;
@JsonProperty("area")
private String area;
@JsonProperty("author")
private String author;
@JsonProperty("id")
private Integer id;
@JsonProperty("topics")
private List<String> topics = new ArrayList<String>();
@JsonProperty("address")
private Address address;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
public Input withName(String name) {
this.name = name;
return this;
}
@JsonProperty("area")
public String getArea() {
return area;
}
@JsonProperty("area")
public void setArea(String area) {
this.area = area;
}
public Input withArea(String area) {
this.area = area;
return this;
}
@JsonProperty("author")
public String getAuthor() {
return author;
}
@JsonProperty("author")
public void setAuthor(String author) {
this.author = author;
}
public Input withAuthor(String author) {
this.author = author;
return this;
}
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
public Input withId(Integer id) {
this.id = id;
return this;
}
@JsonProperty("topics")
public List<String> getTopics() {
return topics;
}
@JsonProperty("topics")
public void setTopics(List<String> topics) {
this.topics = topics;
}
public Input withTopics(List<String> topics) {
this.topics = topics;
return this;
}
@JsonProperty("address")
public Address getAddress() {
return address;
}
@JsonProperty("address")
public void setAddress(Address address) {
this.address = address;
}
public Input withAddress(Address address) {
this.address = address;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public Input withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(Input.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("name");
sb.append('=');
sb.append(((this.name == null)?"<null>":this.name));
sb.append(',');
sb.append("area");
sb.append('=');
sb.append(((this.area == null)?"<null>":this.area));
sb.append(',');
sb.append("author");
sb.append('=');
sb.append(((this.author == null)?"<null>":this.author));
sb.append(',');
sb.append("id");
sb.append('=');
sb.append(((this.id == null)?"<null>":this.id));
sb.append(',');
sb.append("topics");
sb.append('=');
sb.append(((this.topics == null)?"<null>":this.topics));
sb.append(',');
sb.append("address");
sb.append('=');
sb.append(((this.address == null)?"<null>":this.address));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
@Override
public int hashCode() {
int result = 1;
result = ((result* 31)+((this.area == null)? 0 :this.area.hashCode()));
result = ((result* 31)+((this.address == null)? 0 :this.address.hashCode()));
result = ((result* 31)+((this.author == null)? 0 :this.author.hashCode()));
result = ((result* 31)+((this.topics == null)? 0 :this.topics.hashCode()));
result = ((result* 31)+((this.name == null)? 0 :this.name.hashCode()));
result = ((result* 31)+((this.id == null)? 0 :this.id.hashCode()));
result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));
return result;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Input) == false) {
return false;
}
Input rhs = ((Input) other);
return ((((((((this.area == rhs.area)||((this.area!= null)&&this.area.equals(rhs.area)))&&((this.address == rhs.address)||((this.address!= null)&&this.address.equals(rhs.address))))&&((this.author == rhs.author)||((this.author!= null)&&this.author.equals(rhs.author))))&&((this.topics == rhs.topics)||((this.topics!= null)&&this.topics.equals(rhs.topics))))&&((this.name == rhs.name)||((this.name!= null)&&this.name.equals(rhs.name))))&&((this.id == rhs.id)||((this.id!= null)&&this.id.equals(rhs.id))))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))));
}
}

View File

@ -0,0 +1,16 @@
{
"name": "Baeldung",
"area": "tech blogs",
"author": "Eugen",
"id": 32134,
"topics": [
"java",
"kotlin",
"cs",
"linux"
],
"address": {
"city": "Bucharest",
"country": "Romania"
}
}

View File

@ -3,6 +3,7 @@ package com.baeldung.jsontojavaclass;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -21,17 +22,16 @@ class JsonToJavaClassConversionUnitTest {
File inputJson = new File(jsonPath + "sample_input.json");
// create the local directory for generating the Java Class file
String outputPath = "src/main/java/";
String outputPath = "src/test/resources/";
File outputJavaClassDirectory = new File(outputPath);
outputJavaClassDirectory.mkdirs();
String className = "SamplePojo";
String javaClassName = "SamplePojo";
Object object = jsonToJavaConversion.convertJsonToJavaClass(inputJson.toURI()
.toURL(), outputJavaClassDirectory, packageName, className);
System.out.println(object);
jsonToJavaConversion.convertJsonToJavaClass(inputJson.toURI()
.toURL(), outputJavaClassDirectory, packageName, javaClassName);
Assertions.assertNotNull(object);
File outputJavaClassPath = new File(outputPath + packageName.replace(".", "/"));
Assertions.assertTrue(Arrays.stream(outputJavaClassPath.listFiles()).peek(System.out::println).anyMatch(file -> (javaClassName+".java").equalsIgnoreCase(file.getName())));
}

View File

@ -0,0 +1,213 @@
package com.baeldung.jsontojavaclass.pojo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name",
"area",
"author",
"id",
"salary",
"topics"
})
@Generated("jsonschema2pojo")
public class SamplePojo {
@JsonProperty("name")
private String name;
@JsonProperty("area")
private String area;
@JsonProperty("author")
private String author;
@JsonProperty("id")
private Integer id;
@JsonProperty("salary")
private Integer salary;
@JsonProperty("topics")
private List<String> topics = new ArrayList<String>();
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
public SamplePojo withName(String name) {
this.name = name;
return this;
}
@JsonProperty("area")
public String getArea() {
return area;
}
@JsonProperty("area")
public void setArea(String area) {
this.area = area;
}
public SamplePojo withArea(String area) {
this.area = area;
return this;
}
@JsonProperty("author")
public String getAuthor() {
return author;
}
@JsonProperty("author")
public void setAuthor(String author) {
this.author = author;
}
public SamplePojo withAuthor(String author) {
this.author = author;
return this;
}
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
public SamplePojo withId(Integer id) {
this.id = id;
return this;
}
@JsonProperty("salary")
public Integer getSalary() {
return salary;
}
@JsonProperty("salary")
public void setSalary(Integer salary) {
this.salary = salary;
}
public SamplePojo withSalary(Integer salary) {
this.salary = salary;
return this;
}
@JsonProperty("topics")
public List<String> getTopics() {
return topics;
}
@JsonProperty("topics")
public void setTopics(List<String> topics) {
this.topics = topics;
}
public SamplePojo withTopics(List<String> topics) {
this.topics = topics;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public SamplePojo withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(SamplePojo.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("name");
sb.append('=');
sb.append(((this.name == null)?"<null>":this.name));
sb.append(',');
sb.append("area");
sb.append('=');
sb.append(((this.area == null)?"<null>":this.area));
sb.append(',');
sb.append("author");
sb.append('=');
sb.append(((this.author == null)?"<null>":this.author));
sb.append(',');
sb.append("id");
sb.append('=');
sb.append(((this.id == null)?"<null>":this.id));
sb.append(',');
sb.append("salary");
sb.append('=');
sb.append(((this.salary == null)?"<null>":this.salary));
sb.append(',');
sb.append("topics");
sb.append('=');
sb.append(((this.topics == null)?"<null>":this.topics));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
@Override
public int hashCode() {
int result = 1;
result = ((result* 31)+((this.area == null)? 0 :this.area.hashCode()));
result = ((result* 31)+((this.author == null)? 0 :this.author.hashCode()));
result = ((result* 31)+((this.topics == null)? 0 :this.topics.hashCode()));
result = ((result* 31)+((this.name == null)? 0 :this.name.hashCode()));
result = ((result* 31)+((this.id == null)? 0 :this.id.hashCode()));
result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));
result = ((result* 31)+((this.salary == null)? 0 :this.salary.hashCode()));
return result;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof SamplePojo) == false) {
return false;
}
SamplePojo rhs = ((SamplePojo) other);
return ((((((((this.area == rhs.area)||((this.area!= null)&&this.area.equals(rhs.area)))&&((this.author == rhs.author)||((this.author!= null)&&this.author.equals(rhs.author))))&&((this.topics == rhs.topics)||((this.topics!= null)&&this.topics.equals(rhs.topics))))&&((this.name == rhs.name)||((this.name!= null)&&this.name.equals(rhs.name))))&&((this.id == rhs.id)||((this.id!= null)&&this.id.equals(rhs.id))))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))))&&((this.salary == rhs.salary)||((this.salary!= null)&&this.salary.equals(rhs.salary))));
}
}

3
ksqldb/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to ksqlDB](https://www.baeldung.com/ksqldb)

View File

@ -1,3 +1,4 @@
## Relevant Articles:
- [Creating a Kubertes Admission Controller in Java](https://www.baeldung.com/java-kubernetes-admission-controller)
- [Access Control Models](https://www.baeldung.com/java-access-control-models)

View File

@ -78,6 +78,29 @@
<artifactId>sshd-core</artifactId>
<version>${apache-mina.version}</version>
</dependency>
<dependency>
<groupId>org.xacml4j</groupId>
<artifactId>xacml-core</artifactId>
<version>${xacml4j.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.xacml4j</groupId>
<artifactId>xacml-test</artifactId>
<version>${xacml4j.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
@ -90,6 +113,7 @@
<jsch.version>0.1.55</jsch.version>
<apache-mina.version>2.5.1</apache-mina.version>
<spring-security-oauth2.version>2.4.0.RELEASE</spring-security-oauth2.version>
<xacml4j.version>1.4.0</xacml4j.version>
</properties>
</project>

View File

@ -2,9 +2,11 @@ package com.baeldung.scribejava;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan
public class ScribejavaApplication {
public static void main(String[] args) {

View File

@ -0,0 +1,27 @@
package com.baeldung.scribejava.controller;
import java.io.IOException;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="rbac", urlPatterns = {"/protected"})
@DeclareRoles("USER")
@ServletSecurity(
@HttpConstraint(rolesAllowed = "USER")
)
public class RBACController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("Hello, USER");
}
}

View File

@ -0,0 +1,233 @@
package com.baeldung.xacml4j;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.xacml4j.v20.Xacml20TestUtility;
import org.xacml4j.v30.Attribute;
import org.xacml4j.v30.Categories;
import org.xacml4j.v30.Category;
import org.xacml4j.v30.CompositeDecisionRule;
import org.xacml4j.v30.Decision;
import org.xacml4j.v30.Entity;
import org.xacml4j.v30.RequestContext;
import org.xacml4j.v30.ResponseContext;
import org.xacml4j.v30.Result;
import org.xacml4j.v30.XacmlPolicyTestSupport;
import org.xacml4j.v30.pdp.PolicyDecisionPoint;
import org.xacml4j.v30.pdp.PolicyDecisionPointBuilder;
import org.xacml4j.v30.spi.combine.DecisionCombiningAlgorithmProviderBuilder;
import org.xacml4j.v30.spi.function.FunctionProviderBuilder;
import org.xacml4j.v30.spi.pip.PolicyInformationPointBuilder;
import org.xacml4j.v30.spi.repository.InMemoryPolicyRepository;
import org.xacml4j.v30.spi.repository.PolicyRepository;
import org.xacml4j.v30.types.DoubleExp;
import org.xacml4j.v30.types.StringExp;
import org.xacml4j.v30.types.TimeExp;
public class NightlyWithdrawalPolicyUnitTest extends XacmlPolicyTestSupport {
private static final String POLICY_SET = "xacml4j/NightlyWithdrawalsPolicy.xml";
@Test
public void testWhenNightlyWithdrawalOver500_thenFail() throws Exception {
PolicyDecisionPoint pdp = buildPDP(POLICY_SET);
// Action category
Attribute actionAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:action:action-id")
.value(StringExp.of("withdrawal"))
.build();
Entity actionEntity = Entity.builder()
.attribute(actionAttribute)
.build();
Category actionCategory = Category.builder(Categories.ACTION)
.entity(actionEntity)
.build();
// Environment Category
Attribute timeAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:environment:current-time")
.includeInResult(false)
.value(TimeExp.of("21:00:00"))
.build();
Entity timeEntity = Entity.builder()
.attribute(timeAttribute)
.build();
Category environmentCategory = Category.builder(Categories.ENVIRONMENT)
.entity(timeEntity)
.build();
// ATM category
Attribute amountAttribute = Attribute.builder("urn:baeldung:atm:withdrawal:amount")
.value(DoubleExp.of("1200.00"))
.build();
Entity atmEntity = Entity.builder()
.attribute(amountAttribute)
.build();
Category atmCategory = Category.builder(Categories.parse("urn:baeldung:atm:withdrawal"))
.entity(atmEntity)
.build();
RequestContext request = RequestContext.builder()
.attributes(actionCategory, environmentCategory, atmCategory)
.build();
ResponseContext response = pdp.decide(request);
assertNotNull(response);
assertTrue("Shoud have at least one result", response.getResults() != null && !response.getResults()
.isEmpty());
Result result = response.getResults()
.iterator()
.next();
assertTrue("Evaluation should succeed", result.getStatus()
.isSuccess());
assertEquals("Should DENY withdrawal", Decision.DENY, result.getDecision());
}
@Test
public void testWhenNightlyWithdrawalUnder500_thenSuccess() throws Exception {
PolicyDecisionPoint pdp = buildPDP(POLICY_SET);
// Action category
Attribute actionAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:action:action-id")
.includeInResult(false)
.value(StringExp.of("withdrawal"))
.build();
Entity actionEntity = Entity.builder()
.attribute(actionAttribute)
.build();
Category actionCategory = Category.builder(Categories.ACTION)
.entity(actionEntity)
.build();
// Environment Category
Attribute timeAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:environment:current-time")
.includeInResult(false)
.value(TimeExp.of("21:00:00"))
.build();
Entity timeEntity = Entity.builder()
.attribute(timeAttribute)
.build();
Category environmentCategory = Category.builder(Categories.ENVIRONMENT)
.entity(timeEntity)
.build();
// ATM category
Attribute amountAttribute = Attribute.builder("urn:baeldung:atm:withdrawal:amount")
.value(DoubleExp.of("499.00"))
.build();
Entity atmEntity = Entity.builder()
.attribute(amountAttribute)
.build();
Category atmCategory = Category.builder(Categories.parse("urn:baeldung:atm:withdrawal"))
.entity(atmEntity)
.build();
RequestContext request = RequestContext.builder()
.attributes(actionCategory, environmentCategory, atmCategory)
.build();
ResponseContext response = pdp.decide(request);
assertNotNull(response);
assertTrue("Shoud have at least one result",
response.getResults() != null && !response.getResults().isEmpty());
Result result = response.getResults().iterator().next();
assertTrue("Evaluation should succeed", result.getStatus().isSuccess());
assertEquals("Should PERMIT withdrawal", Decision.PERMIT, result.getDecision());
}
@Test
public void testWhenBusinessHoursWithdrawalOver500_thenSuccess() throws Exception {
PolicyDecisionPoint pdp = buildPDP(POLICY_SET);
// Action category
Attribute actionAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:action:action-id")
.includeInResult(false)
.value(StringExp.of("withdrawal"))
.build();
Entity actionEntity = Entity.builder()
.attribute(actionAttribute)
.build();
Category actionCategory = Category.builder(Categories.ACTION)
.entity(actionEntity)
.build();
// Environment Category
Attribute timeAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:environment:current-time")
.includeInResult(false)
.value(TimeExp.of("12:00:00"))
.build();
Entity timeEntity = Entity.builder()
.attribute(timeAttribute)
.build();
Category environmentCategory = Category.builder(Categories.ENVIRONMENT)
.entity(timeEntity)
.build();
// ATM category
Attribute amountAttribute = Attribute.builder("urn:baeldung:atm:withdrawal:amount")
.value(DoubleExp.of("2000.00"))
.build();
Entity atmEntity = Entity.builder()
.attribute(amountAttribute)
.build();
Category atmCategory = Category.builder(Categories.parse("urn:baeldung:atm:withdrawal"))
.entity(atmEntity)
.build();
RequestContext request = RequestContext.builder()
.attributes(actionCategory, environmentCategory, atmCategory)
.build();
ResponseContext response = pdp.decide(request);
assertNotNull(response);
assertTrue("Shoud have at least one result", response.getResults() != null && !response.getResults()
.isEmpty());
Result result = response.getResults()
.iterator()
.next();
assertTrue("Evaluation should succeed", result.getStatus().isSuccess());
assertEquals("Should PERMIT withdrawal", Decision.PERMIT, result.getDecision());
}
private PolicyDecisionPoint buildPDP(String... policyResources) throws Exception {
PolicyRepository repository = new InMemoryPolicyRepository("tes-repository", FunctionProviderBuilder.builder()
.defaultFunctions()
.build(),
DecisionCombiningAlgorithmProviderBuilder.builder()
.withDefaultAlgorithms()
.create());
List<CompositeDecisionRule> policies = new ArrayList<CompositeDecisionRule>(policyResources.length);
for (String policyResource : policyResources) {
CompositeDecisionRule policy = repository.importPolicy(Xacml20TestUtility.getClasspathResource(policyResource));
log.info("Policy: {}", policy);
policies.add(policy);
}
return PolicyDecisionPointBuilder.builder("testPdp")
.policyRepository(repository)
.pip(PolicyInformationPointBuilder.builder("testPip")
.defaultResolvers()
.build())
.rootPolicy(policies.get(0))
.build();
}
}

View File

@ -0,0 +1,137 @@
<?xml version="1.0" encoding="UTF-8"?>
<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17 http://docs.oasis-open.org/xacml/3.0/xacml-core-v3-schema-wd-17.xsd"
PolicyId="urn:baeldung:atm:WithdrawalPolicy"
Version="1.0"
RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:deny-overrides">
<Description>
Withdrawal policy example
</Description>
<Target/>
<Rule RuleId="urn:oasis:names:tc:baeldung:WithDrawalPolicy:Rule1" Effect="Deny">
<Description>
Deny withdrawals over $500 between 20:00 and 08:00
</Description>
<Target>
<AnyOf>
<AllOf>
<Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">withdrawal</AttributeValue>
<AttributeDesignator
DataType="http://www.w3.org/2001/XMLSchema#string"
MustBePresent="true"
Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action"
AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"/>
</Match>
</AllOf>
</AnyOf>
</Target>
<Condition>
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not">
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-in-range">
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only">
<AttributeDesignator
DataType="http://www.w3.org/2001/XMLSchema#time"
MustBePresent="true"
Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment"
AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time"/>
</Apply>
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">08:00:00</AttributeValue>
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">20:00:00</AttributeValue>
</Apply>
</Apply>
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:double-greater-than">
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:double-one-and-only">
<AttributeDesignator
DataType="http://www.w3.org/2001/XMLSchema#double"
MustBePresent="true"
Category="urn:baeldung:atm:withdrawal"
AttributeId="urn:baeldung:atm:withdrawal:amount"/>
</Apply>
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#double">500.00</AttributeValue>
</Apply>
</Apply>
</Condition>
</Rule>
<Rule RuleId="urn:oasis:names:tc:baeldung:WithDrawalPolicy:Rule2" Effect="Permit">
<Description>
Permit withdrawals under $500 between 20:00 and 08:00
</Description>
<Target>
<AnyOf>
<AllOf>
<Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">withdrawal</AttributeValue>
<AttributeDesignator
DataType="http://www.w3.org/2001/XMLSchema#string"
MustBePresent="true"
Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action"
AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"/>
</Match>
</AllOf>
</AnyOf>
</Target>
<Condition>
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not">
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-in-range">
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only">
<AttributeDesignator
DataType="http://www.w3.org/2001/XMLSchema#time"
MustBePresent="true"
Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment"
AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time"/>
</Apply>
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">08:00:00</AttributeValue>
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">20:00:00</AttributeValue>
</Apply>
</Apply>
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:double-less-than-or-equal">
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:double-one-and-only">
<AttributeDesignator
DataType="http://www.w3.org/2001/XMLSchema#double"
MustBePresent="true"
Category="urn:baeldung:atm:withdrawal"
AttributeId="urn:baeldung:atm:withdrawal:amount"/>
</Apply>
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#double">500.00</AttributeValue>
</Apply>
</Apply>
</Condition>
</Rule>
<Rule RuleId="urn:oasis:names:tc:baeldung:WithDrawalPolicy:Rule3" Effect="Permit">
<Description>
Permit withdrawals of any value between 08:00 and 20:00
</Description>
<Target>
<AnyOf>
<AllOf>
<Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">withdrawal</AttributeValue>
<AttributeDesignator
DataType="http://www.w3.org/2001/XMLSchema#string"
MustBePresent="true"
Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action"
AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"/>
</Match>
</AllOf>
</AnyOf>
</Target>
<Condition>
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-in-range">
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only">
<AttributeDesignator
DataType="http://www.w3.org/2001/XMLSchema#time"
MustBePresent="true"
Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment"
AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time"/>
</Apply>
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">08:00:00</AttributeValue>
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">20:00:00</AttributeValue>
</Apply>
</Condition>
</Rule>
</Policy>

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<Request
xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17 http://docs.oasis-open.org/xacml/3.0/xacml-core-v3-schema-wd-17.xsd"
CombinedDecision="true"
ReturnPolicyIdList="false">
<Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action">
<Attribute
IncludeInResult="false"
AttributeId="urn:oasis:names:tc:xacml:3.0:attribute-category:action">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">withdrawal</AttributeValue>
</Attribute>
</Attributes>
<Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action">
<Attribute
IncludeInResult="false"
AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">21:00:00</AttributeValue>
</Attribute>
</Attributes>
<Attributes Category="urn:baeldung:atm:withdrawal">
<Attribute
IncludeInResult="false"
AttributeId="urn:baeldung:atm:withdrawal:amount">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#decimal">1200</AttributeValue>
</Attribute>
</Attributes>
</Request>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<Response xmlns="urn:oasis:names:tc:xacml:2.0:context:schema:os" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:tc:xacml:2.0:context:schema:os http://docs.oasis-open.org/xacml/access_control-xacml-2.0-context-schema-os.xsd">
<Result>
<Decision>NotApplicable</Decision>
<Status>
<StatusCode Value="urn:oasis:names:tc:xacml:1.0:status:ok"/>
</Status>
</Result>
</Response>

View File

@ -40,6 +40,11 @@
<artifactId>javatuples</artifactId>
<version>${javatuples.version}</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javaassist.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.assertj/assertj-core -->
<dependency>
<groupId>org.assertj</groupId>
@ -51,42 +56,6 @@
<artifactId>javers-core</artifactId>
<version>${javers.version}</version>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-core</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-junit</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-jbehave</artifactId>
<version>${serenity.jbehave.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-rest-assured</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-jira-requirements-provider</artifactId>
<version>${serenity.jira.version}</version>
<scope>test</scope>
</dependency>
<!-- JDO -->
<dependency>
<groupId>org.datanucleus</groupId>
@ -139,30 +108,6 @@
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-spring</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-screenplay</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-screenplay-webdriver</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<!-- JetS3t -->
<dependency>
<groupId>org.lucee</groupId>
@ -253,29 +198,6 @@
<build>
<plugins>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<configuration>
<systemProperties>
<webdriver.chrome.driver>chromedriver</webdriver.chrome.driver>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>net.serenity-bdd.maven.plugins</groupId>
<artifactId>serenity-maven-plugin</artifactId>
<version>${serenity.plugin.version}</version>
<executions>
<execution>
<id>serenity-reports</id>
<phase>post-integration-test</phase>
<goals>
<goal>aggregate</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- JDO Plugin -->
<plugin>
<groupId>org.datanucleus</groupId>
@ -380,6 +302,7 @@
<spring.version>4.3.8.RELEASE</spring.version>
<spring-mock-mvc.version>3.0.3</spring-mock-mvc.version>
<quartz.version>2.3.0</quartz.version>
<javaassist.version>3.21.0-GA</javaassist.version>
<jool.version>0.9.12</jool.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<commons-net.version>3.6</commons-net.version>

View File

@ -1,4 +0,0 @@
jira.url=<jira-url>
jira.project=<jira-project>
jira.username=<jira-username>
jira.password=<jira-password>

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Understanding the "relativePath" Tag - Maven Parent POM Resolution At A Glance](https://www.baeldung.com/maven-relativepath)

View File

@ -0,0 +1,15 @@
<?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>module1</artifactId>
<parent>
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
<artifactId>aggregator</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!-- The parent pom is resolved to project a's pom.xml -->
</parent>
<packaging>pom</packaging>
</project>

View File

@ -0,0 +1,17 @@
<?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>module3</artifactId>
<parent>
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
<artifactId>aggregator</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!-- removing relativePath won't work even if project-a is the aggregator project -->
<!-- it only works in IntelliJ IDEA when project-a is registered as a Maven Project -->
<relativePath>../../pom.xml</relativePath>
</parent>
<packaging>pom</packaging>
</project>

View File

@ -0,0 +1,20 @@
<?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>module2</artifactId>
<parent>
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
<artifactId>module1</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../module1/pom.xml</relativePath>
<!-- The parent pom is resolved to project a's pom.xml -->
</parent>
<packaging>pom</packaging>
<modules>
<module>module3</module>
</modules>
</project>

View File

@ -0,0 +1,21 @@
<?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.maven-parent-pom-resolution</groupId>
<artifactId>aggregator</artifactId>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>maven-parent-pom-resolution</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!-- The parent pom is resolved to ../pom.xml -->
</parent>
<packaging>pom</packaging>
<modules>
<module>module1</module>
<module>module2</module>
</modules>
</project>

View File

@ -0,0 +1,28 @@
<?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>maven-parent-pom-resolution</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>aggregator</module>
</modules>
<!-- to detect the POM hierarchy, just type "mvn dependency:display-ancestors" -->
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.2.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -18,7 +18,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<version>${junit.version}</version>
</dependency>
</dependencies>
@ -46,6 +46,7 @@
<properties>
<name>${project.name}</name>
<my.awesome.property>property-from-pom</my.awesome.property>
<junit.version>4.13</junit.version>
</properties>
</project>

View File

@ -0,0 +1,3 @@
## Relevant Articles:
- [Running a Single Test or Method With Maven](https://www.baeldung.com/maven-run-single-test)

View File

@ -36,6 +36,7 @@
<module>host-maven-repo-example</module>
<module>plugin-management</module>
<module>maven-surefire-plugin</module>
<module>maven-parent-pom-resolution</module>
</modules>
</project>

View File

@ -30,7 +30,7 @@
</dependencies>
<properties>
<spring.version>5.3.7</spring.version>
<spring.version>5.3.9</spring.version>
<spring-security.version>5.2.3.RELEASE</spring-security.version>
<spring-boot-starter-test.version>1.5.10.RELEASE</spring-boot-starter-test.version>
</properties>

View File

@ -3,3 +3,4 @@
- [The DAO Pattern in Java](https://www.baeldung.com/java-dao-pattern)
- [DAO vs Repository Patterns](https://www.baeldung.com/java-dao-vs-repository)
- [Difference Between MVC and MVP Patterns](https://www.baeldung.com/mvc-vs-mvp-pattern)
- [The DTO Pattern (Data Transfer Object)](https://www.baeldung.com/java-dto-pattern)

View File

@ -15,6 +15,21 @@
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@ -38,6 +53,9 @@
<assertj-core.version>3.9.1</assertj-core.version>
<hibernate-core.version>5.2.16.Final</hibernate-core.version>
<mysql-connector.version>6.0.6</mysql-connector.version>
<spring-boot.version>2.5.3</spring-boot.version>
<rest-assured.version>3.3.0</rest-assured.version>
</properties>
</project>

View File

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

View File

@ -0,0 +1,28 @@
package com.baeldung.dtopattern.api;
import com.baeldung.dtopattern.domain.Role;
import com.baeldung.dtopattern.domain.User;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
@Component
class Mapper {
public UserDTO toDto(User user) {
String name = user.getName();
List<String> roles = user
.getRoles()
.stream()
.map(Role::getName)
.collect(toList());
return new UserDTO(name, roles);
}
public User toUser(UserCreationDTO userDTO) {
return new User(userDTO.getName(), userDTO.getPassword(), new ArrayList<>());
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.dtopattern.api;
import com.baeldung.dtopattern.domain.RoleService;
import com.baeldung.dtopattern.domain.User;
import com.baeldung.dtopattern.domain.UserService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static java.util.stream.Collectors.toList;
@RestController
@RequestMapping("/users")
class UserController {
private UserService userService;
private RoleService roleService;
private Mapper mapper;
public UserController(UserService userService, RoleService roleService, Mapper mapper) {
this.userService = userService;
this.roleService = roleService;
this.mapper = mapper;
}
@GetMapping
@ResponseBody
public List<UserDTO> getUsers() {
return userService.getAll()
.stream()
.map(mapper::toDto)
.collect(toList());
}
@PostMapping
@ResponseBody
public UserIdDTO create(@RequestBody UserCreationDTO userDTO) {
User user = mapper.toUser(userDTO);
userDTO.getRoles()
.stream()
.map(role -> roleService.getOrCreate(role))
.forEach(user::addRole);
userService.save(user);
return new UserIdDTO(user.getId());
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.dtopattern.api;
import java.util.List;
public class UserCreationDTO {
private String name;
private String password;
private List<String> roles;
UserCreationDTO() {}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public List<String> getRoles() {
return roles;
}
void setName(String name) {
this.name = name;
}
void setPassword(String password) {
this.password = password;
}
void setRoles(List<String> roles) {
this.roles = roles;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.dtopattern.api;
import java.util.List;
public class UserDTO {
private String name;
private List<String> roles;
public UserDTO(String name, List<String> roles) {
this.name = name;
this.roles = roles;
}
public String getName() {
return name;
}
public List<String> getRoles() {
return roles;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.dtopattern.api;
public class UserIdDTO {
private String id;
public UserIdDTO(String id) {
this.id = id;
}
public String getId() {
return id;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.dtopattern.domain;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
class InMemoryRepository implements UserRepository, RoleRepository {
private Map<String, User> users = new LinkedHashMap<>();
private Map<String, Role> roles = new LinkedHashMap<>();
@Override
public List<User> getAll() {
return new ArrayList<>(users.values());
}
@Override
public void save(User user) {
user.setId(UUID.randomUUID().toString());
users.put(user.getId(), user);
}
@Override
public void save(Role role) {
role.setId(UUID.randomUUID().toString());
roles.put(role.getId(), role);
}
@Override
public Role getRoleById(String id) {
return roles.get(id);
}
@Override
public Role getRoleByName(String name) {
return roles.values()
.stream()
.filter(role -> role.getName().equalsIgnoreCase(name))
.findFirst()
.orElse(null);
}
@Override
public void deleteAll() {
users.clear();
roles.clear();
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.dtopattern.domain;
import java.util.Objects;
public class Role {
private String id;
private String name;
public Role(String name) {
this.name = Objects.requireNonNull(name);
}
public String getId() {
return id;
}
void setId(String id) {
this.id = Objects.requireNonNull(id);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = Objects.requireNonNull(name);
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.dtopattern.domain;
public interface RoleRepository {
Role getRoleById(String id);
Role getRoleByName(String name);
void save(Role role);
}

View File

@ -0,0 +1,32 @@
package com.baeldung.dtopattern.domain;
import org.springframework.stereotype.Service;
import java.util.Objects;
@Service
public class RoleService {
private RoleRepository repository;
public RoleService(RoleRepository repository) {
this.repository = repository;
}
public Role getOrCreate(String name) {
Role role = repository.getRoleByName(name);
if (role == null) {
role = new Role(name);
repository.save(role);
}
return role;
}
public void save(Role role) {
Objects.requireNonNull(role);
repository.save(role);
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.dtopattern.domain;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class User {
private static SecretKeySpec KEY = initKey();
static SecretKeySpec initKey(){
try {
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
return new SecretKeySpec(secretKey.getEncoded(), "AES");
} catch (NoSuchAlgorithmException ex) {
return null;
}
}
private String id;
private String name;
private String password;
private List<Role> roles;
public User(String name, String password, List<Role> roles) {
this.name = Objects.requireNonNull(name);
this.password = this.encrypt(password);
this.roles = Objects.requireNonNull(roles);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void addRole(Role role) {
roles.add(role);
}
public List<Role> getRoles() {
return Collections.unmodifiableList(roles);
}
public String getId() {
return id;
}
void setId(String id) {
this.id = id;
}
String encrypt(String password) {
Objects.requireNonNull(password);
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, KEY);
final byte[] encryptedBytes = cipher.doFinal(password.getBytes(StandardCharsets.UTF_8));
return new String(encryptedBytes, StandardCharsets.UTF_8);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
// do nothing
return "";
}
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.dtopattern.domain;
import java.util.List;
public interface UserRepository {
List<User> getAll();
void save(User user);
void deleteAll();
}

View File

@ -0,0 +1,25 @@
package com.baeldung.dtopattern.domain;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
@Service
public class UserService {
private UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
public List<User> getAll() {
return repository.getAll();
}
public void save(User user) {
Objects.requireNonNull(user);
repository.save(user);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.dtopattern.api;
import com.baeldung.dtopattern.domain.Role;
import com.baeldung.dtopattern.domain.User;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class MapperUnitTest {
@Test
void toDto_shouldMapFromDomainToDTO() {
String name = "Test";
String password = "test";
Role admin = new Role("admin");
List<String> expectedRoles = Collections.singletonList("admin");
List<Role> roles = new ArrayList<>();
roles.add(admin);
User user = new User(name, password, roles);
Mapper mapper = new Mapper();
UserDTO dto = mapper.toDto(user);
assertEquals(name, dto.getName());
assertEquals(expectedRoles, dto.getRoles());
}
@Test
void toUser_shouldMapFromDTOToDomain() {
String name = "Test";
String password = "test";
String role = "admin";
UserCreationDTO dto = new UserCreationDTO();
dto.setName(name);
dto.setPassword(password);
dto.setRoles(Collections.singletonList("admin"));
User expectedUser = new User(name, password, new ArrayList<>());
Mapper mapper = new Mapper();
User user = mapper.toUser(dto);
assertEquals(name, user.getName());
assertEquals(expectedUser.getPassword(), user.getPassword());
assertEquals(Collections.emptyList(), user.getRoles());
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.dtopattern.api;
import com.baeldung.dtopattern.domain.Role;
import com.baeldung.dtopattern.domain.RoleRepository;
import com.baeldung.dtopattern.domain.User;
import com.baeldung.dtopattern.domain.UserRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import java.util.Collections;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.*;
import static org.springframework.http.HttpStatus.OK;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class UserControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@LocalServerPort
int port;
@Autowired
private ObjectMapper objectMapper;
@Test
void create_shouldReturnUseId() throws Exception {
UserCreationDTO request = new UserCreationDTO();
request.setName("User 1");
request.setPassword("Test@123456");
request.setRoles(Collections.singletonList("admin"));
given()
.contentType(ContentType.JSON)
.body(objectMapper.writeValueAsString(request))
.when()
.port(port)
.post("/users")
.then()
.statusCode(OK.value())
.body("id", notNullValue());
}
@Test
void getAll_shouldReturnUseDTO() {
userRepository.deleteAll();
String roleName = "admin";
Role admin = new Role(roleName);
roleRepository.save(admin);
String name = "User 1";
User user = new User(name, "Test@123456", Collections.singletonList(admin));
userRepository.save(user);
given()
.port(port)
.when()
.get("/users")
.then()
.statusCode(OK.value())
.body("size()", is(1))
.body("[0].name", equalTo(name))
.body("[0].roles", hasItem(roleName));
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.dtopattern.domain;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class InMemoryRepositoryUnitTest {
@Test
void getAll_shouldReturnAllUsers() {
String name = "Test";
String password = "test123";
List<Role> roles = new ArrayList<>();
User user = new User(name, password, roles);
List<User> expectedUsers = Collections.singletonList(user);
InMemoryRepository repository = new InMemoryRepository();
repository.save(user);
List<User> users = repository.getAll();
assertEquals(expectedUsers, users);
}
@Test
void save_whenSavingUser_shouldSetId() {
String name = "Test";
String password = "test123";
List<Role> roles = new ArrayList<>();
User user = new User(name, password, roles);
InMemoryRepository repository = new InMemoryRepository();
repository.save(user);
assertNotNull(user.getId());
}
@Test
void save_whenSavingRole_shouldSetId() {
String name = "Test";
Role role = new Role(name);
InMemoryRepository repository = new InMemoryRepository();
repository.save(role);
assertNotNull(role.getId());
}
@Test
void getRoleById_shouldReturnRoleById() {
String name = "Test";
Role expectedRole = new Role(name);
InMemoryRepository repository = new InMemoryRepository();
repository.save(expectedRole);
Role role = repository.getRoleById(expectedRole.getId());
assertEquals(expectedRole, role);
}
@Test
void getRoleByName_shouldReturnRoleByName() {
String name = "Test";
Role expectedRole = new Role(name);
InMemoryRepository repository = new InMemoryRepository();
repository.save(expectedRole);
Role role = repository.getRoleByName(name);
assertEquals(expectedRole, role);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.dtopattern.domain;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class UserUnitTest {
@Test
void whenUserIsCreated_shouldEncryptPassword() {
User user = new User("Test", "test", new ArrayList<>());
assertEquals(user.encrypt("test"), user.getPassword());
assertNotEquals(user.encrypt("Test"), user.getPassword());
}
@Test
void whenUserIsCreated_shouldFailIfNameIsNull() {
assertThrows(NullPointerException.class, () ->
new User(null, "test", new ArrayList<>()));
}
@Test
void whenUserIsCreated_shouldFailIfPasswordIsNull() {
assertThrows(NullPointerException.class, () ->
new User("Test", null, new ArrayList<>()));
}
@Test
void whenUserIsCreated_shouldFailIfRolesIsNull() {
assertThrows(NullPointerException.class, () ->
new User("Test", "Test", null));
}
}

View File

@ -13,3 +13,5 @@ This module contains articles about the Java Persistence API (JPA) in Java.
- [Returning an Auto-Generated Id with JPA](https://www.baeldung.com/jpa-get-auto-generated-id)
- [How to Return Multiple Entities In JPA Query](https://www.baeldung.com/jpa-return-multiple-entities)
- [Defining Unique Constraints in JPA](https://www.baeldung.com/jpa-unique-constraints)
- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists)
- [Connecting to a Specific Schema in JDBC](https://www.baeldung.com/jdbc-connect-to-schema)

View File

@ -8,5 +8,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles
- [Spring Data Reactive Repositories with MongoDB](https://www.baeldung.com/spring-data-mongodb-reactive)
- [Spring Data MongoDB Tailable Cursors](https://www.baeldung.com/spring-data-mongodb-tailable-cursors)
- [A Quick Look at R2DBC with Spring Data](https://www.baeldung.com/spring-data-r2dbc)
- [Spring Data Reactive Repositories with Couchbase](https://www.baeldung.com/spring-data-reactive-couchbase)

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