commit
6c4cceb9f5
25
README.md
25
README.md
|
@ -1,12 +1,16 @@
|
||||||
|
|
||||||
The "REST with Spring" Classes
|
The Courses
|
||||||
==============================
|
==============================
|
||||||
|
|
||||||
Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material): <br/>
|
|
||||||
**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
|
||||||
|
|
||||||
And here's the Master Class of Learn Spring Security: <br/>
|
Here's the new "Learn Spring" course: <br/>
|
||||||
**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
**[>> LEARN SPRING - THE MASTER CLASS](https://www.baeldung.com/learn-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=ls#master-class)**
|
||||||
|
|
||||||
|
Here's the Master Class of "REST With Spring" (along with the new announced Boot 2 material): <br/>
|
||||||
|
**[>> THE REST WITH SPRING - MASTER CLASS](https://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||||
|
|
||||||
|
And here's the Master Class of "Learn Spring Security": <br/>
|
||||||
|
**[>> LEARN SPRING SECURITY - MASTER CLASS](https://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -15,7 +19,7 @@ Java and Spring Tutorials
|
||||||
|
|
||||||
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
||||||
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security.
|
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security.
|
||||||
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
In additional to Spring, the modules here are covering a number of aspects in Java.
|
||||||
|
|
||||||
|
|
||||||
Building the project
|
Building the project
|
||||||
|
@ -32,8 +36,15 @@ Running a Spring Boot module
|
||||||
====================
|
====================
|
||||||
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
|
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
|
||||||
|
|
||||||
#Running Tests
|
|
||||||
|
|
||||||
|
Working with the IDE
|
||||||
|
====================
|
||||||
|
This repo contains a large number of modules.
|
||||||
|
When you're working with an individual module, there's no need to import all of them (or build all of them) - you can simply import that particular module in either Eclipse or IntelliJ.
|
||||||
|
|
||||||
|
|
||||||
|
Running Tests
|
||||||
|
=============
|
||||||
The command `mvn clean install` will run the unit tests in a module.
|
The command `mvn clean install` will run the unit tests in a module.
|
||||||
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`
|
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.algorithms.stringsortingbynumber;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
|
||||||
|
public final class NaturalOrderComparators {
|
||||||
|
|
||||||
|
private static final String DIGIT_AND_DECIMAL_REGEX = "[^\\d.]";
|
||||||
|
|
||||||
|
private NaturalOrderComparators() {
|
||||||
|
throw new AssertionError("Let's keep this static");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Comparator<String> createNaturalOrderRegexComparator() {
|
||||||
|
return Comparator.comparingDouble(NaturalOrderComparators::parseStringToNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double parseStringToNumber(String input){
|
||||||
|
|
||||||
|
final String digitsOnly = input.replaceAll(DIGIT_AND_DECIMAL_REGEX, "");
|
||||||
|
|
||||||
|
if("".equals(digitsOnly)) return 0;
|
||||||
|
|
||||||
|
try{
|
||||||
|
return Double.parseDouble(digitsOnly);
|
||||||
|
}catch (NumberFormatException nfe){
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,79 @@
|
||||||
|
package com.baeldung.algorithms.stringsortingbynumber;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class NaturalOrderComparatorsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() {
|
||||||
|
|
||||||
|
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d");
|
||||||
|
|
||||||
|
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||||
|
|
||||||
|
List<String> expected = Arrays.asList("a1", "d2.2", "d2.3d", "d2.4", "b3", "c4");
|
||||||
|
|
||||||
|
assertEquals(expected, testStrings);
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() {
|
||||||
|
|
||||||
|
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d");
|
||||||
|
|
||||||
|
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||||
|
|
||||||
|
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.4", "b3", "c4");
|
||||||
|
|
||||||
|
assertEquals(expected, testStrings);
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() {
|
||||||
|
|
||||||
|
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d");
|
||||||
|
|
||||||
|
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||||
|
|
||||||
|
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.f4", "b3", "c4");
|
||||||
|
|
||||||
|
assertEquals(expected, testStrings);
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() {
|
||||||
|
|
||||||
|
List<String> testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5
|
||||||
|
|
||||||
|
List<String> expected = Arrays.asList("b3ght3.2", "something65.thensomething5", "a1b2c5" );
|
||||||
|
|
||||||
|
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||||
|
|
||||||
|
assertEquals(expected, testStrings);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() {
|
||||||
|
|
||||||
|
List<String> testStrings = Arrays.asList("a", "c", "d", "e");
|
||||||
|
List<String> expected = new ArrayList<>(testStrings);
|
||||||
|
|
||||||
|
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||||
|
|
||||||
|
assertEquals(expected, testStrings);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.algorithms.shellsort;
|
||||||
|
|
||||||
|
public class ShellSort {
|
||||||
|
|
||||||
|
public static void sort(int arrayToSort[]) {
|
||||||
|
int n = arrayToSort.length;
|
||||||
|
|
||||||
|
for (int gap = n / 2; gap > 0; gap /= 2) {
|
||||||
|
for (int i = gap; i < n; i++) {
|
||||||
|
int key = arrayToSort[i];
|
||||||
|
int j = i;
|
||||||
|
while (j >= gap && arrayToSort[j - gap] > key) {
|
||||||
|
arrayToSort[j] = arrayToSort[j - gap];
|
||||||
|
j -= gap;
|
||||||
|
}
|
||||||
|
arrayToSort[j] = key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.algorithms.shellsort;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class ShellSortUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedArray_whenShellSort_thenSortedAsc() {
|
||||||
|
int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8};
|
||||||
|
ShellSort.sort(input);
|
||||||
|
int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82};
|
||||||
|
assertArrayEquals("the two arrays are not equal", expected, input);
|
||||||
|
}
|
||||||
|
}
|
|
@ -18,12 +18,6 @@
|
||||||
<groupId>org.axonframework</groupId>
|
<groupId>org.axonframework</groupId>
|
||||||
<artifactId>axon-spring-boot-starter</artifactId>
|
<artifactId>axon-spring-boot-starter</artifactId>
|
||||||
<version>${axon.version}</version>
|
<version>${axon.version}</version>
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<groupId>org.axonframework</groupId>
|
|
||||||
<artifactId>axon-server-connector</artifactId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -58,7 +52,7 @@
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<axon.version>4.0.3</axon.version>
|
<axon.version>4.1.2</axon.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -13,6 +13,7 @@ import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
|
||||||
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
||||||
import com.baeldung.axon.coreapi.events.OrderPlacedEvent;
|
import com.baeldung.axon.coreapi.events.OrderPlacedEvent;
|
||||||
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
|
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
|
||||||
|
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
|
||||||
|
|
||||||
@Aggregate
|
@Aggregate
|
||||||
public class OrderAggregate {
|
public class OrderAggregate {
|
||||||
|
@ -34,7 +35,7 @@ public class OrderAggregate {
|
||||||
@CommandHandler
|
@CommandHandler
|
||||||
public void handle(ShipOrderCommand command) {
|
public void handle(ShipOrderCommand command) {
|
||||||
if (!orderConfirmed) {
|
if (!orderConfirmed) {
|
||||||
throw new IllegalStateException("Cannot ship an order which has not been confirmed yet.");
|
throw new UnconfirmedOrderException();
|
||||||
}
|
}
|
||||||
|
|
||||||
apply(new OrderShippedEvent(orderId));
|
apply(new OrderShippedEvent(orderId));
|
||||||
|
@ -43,12 +44,12 @@ public class OrderAggregate {
|
||||||
@EventSourcingHandler
|
@EventSourcingHandler
|
||||||
public void on(OrderPlacedEvent event) {
|
public void on(OrderPlacedEvent event) {
|
||||||
this.orderId = event.getOrderId();
|
this.orderId = event.getOrderId();
|
||||||
orderConfirmed = false;
|
this.orderConfirmed = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventSourcingHandler
|
@EventSourcingHandler
|
||||||
public void on(OrderConfirmedEvent event) {
|
public void on(OrderConfirmedEvent event) {
|
||||||
orderConfirmed = true;
|
this.orderConfirmed = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected OrderAggregate() {
|
protected OrderAggregate() {
|
||||||
|
|
|
@ -0,0 +1,8 @@
|
||||||
|
package com.baeldung.axon.coreapi.exceptions;
|
||||||
|
|
||||||
|
public class UnconfirmedOrderException extends IllegalStateException {
|
||||||
|
|
||||||
|
public UnconfirmedOrderException() {
|
||||||
|
super("Cannot ship an order which has not been confirmed yet.");
|
||||||
|
}
|
||||||
|
}
|
|
@ -5,6 +5,7 @@ import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.axonframework.config.ProcessingGroup;
|
||||||
import org.axonframework.eventhandling.EventHandler;
|
import org.axonframework.eventhandling.EventHandler;
|
||||||
import org.axonframework.queryhandling.QueryHandler;
|
import org.axonframework.queryhandling.QueryHandler;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
@ -16,6 +17,7 @@ import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
|
||||||
import com.baeldung.axon.coreapi.queries.OrderedProduct;
|
import com.baeldung.axon.coreapi.queries.OrderedProduct;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
|
@ProcessingGroup("ordered-products")
|
||||||
public class OrderedProductsEventHandler {
|
public class OrderedProductsEventHandler {
|
||||||
|
|
||||||
private final Map<String, OrderedProduct> orderedProducts = new HashMap<>();
|
private final Map<String, OrderedProduct> orderedProducts = new HashMap<>();
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
spring.application.name=Order Management Service
|
|
@ -2,6 +2,7 @@ package com.baeldung.axon.commandmodel;
|
||||||
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
|
||||||
import org.axonframework.test.aggregate.AggregateTestFixture;
|
import org.axonframework.test.aggregate.AggregateTestFixture;
|
||||||
import org.axonframework.test.aggregate.FixtureConfiguration;
|
import org.axonframework.test.aggregate.FixtureConfiguration;
|
||||||
import org.junit.*;
|
import org.junit.*;
|
||||||
|
@ -41,12 +42,12 @@ public class OrderAggregateUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowIllegalStateException() {
|
public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowUnconfirmedOrderException() {
|
||||||
String orderId = UUID.randomUUID().toString();
|
String orderId = UUID.randomUUID().toString();
|
||||||
String product = "Deluxe Chair";
|
String product = "Deluxe Chair";
|
||||||
fixture.given(new OrderPlacedEvent(orderId, product))
|
fixture.given(new OrderPlacedEvent(orderId, product))
|
||||||
.when(new ShipOrderCommand(orderId))
|
.when(new ShipOrderCommand(orderId))
|
||||||
.expectException(IllegalStateException.class);
|
.expectException(UnconfirmedOrderException.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
## Relevant articles:
|
## Relevant Articles:
|
||||||
|
|
||||||
|
|
||||||
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
|
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
|
||||||
|
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.java_8_features.groupingby;
|
||||||
|
|
||||||
|
public class Tuple {
|
||||||
|
|
||||||
|
private BlogPostType type;
|
||||||
|
private String author;
|
||||||
|
|
||||||
|
public Tuple(BlogPostType type, String author) {
|
||||||
|
super();
|
||||||
|
this.type = type;
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BlogPostType getType() {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setType(BlogPostType type) {
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthor() {
|
||||||
|
return author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAuthor(String author) {
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Tuple [type=" + type + ", author=" + author + ", getType()=" + getType() + ", getAuthor()=" + getAuthor() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
*.class
|
||||||
|
|
||||||
|
0.*
|
||||||
|
|
||||||
|
#folders#
|
||||||
|
/target
|
||||||
|
/neoDb*
|
||||||
|
/data
|
||||||
|
/src/main/webapp/WEB-INF/classes
|
||||||
|
*/META-INF/*
|
||||||
|
.resourceCache
|
||||||
|
|
||||||
|
# Packaged files #
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.ear
|
||||||
|
|
||||||
|
# Files generated by integration tests
|
||||||
|
backup-pom.xml
|
||||||
|
/bin/
|
||||||
|
/temp
|
||||||
|
|
||||||
|
#IntelliJ specific
|
||||||
|
.idea/
|
||||||
|
*.iml
|
|
@ -0,0 +1,50 @@
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>core-java-arrays-2</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>core-java-arrays-2</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-java</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-java</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- test scoped -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj-core.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-arrays-2</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
|
||||||
|
<!-- util -->
|
||||||
|
<commons-lang3.version>3.9</commons-lang3.version>
|
||||||
|
<!-- testing -->
|
||||||
|
<assertj-core.version>3.10.0</assertj-core.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,45 @@
|
||||||
|
package com.baeldung.array.looping;
|
||||||
|
|
||||||
|
public class LoopDiagonally {
|
||||||
|
|
||||||
|
|
||||||
|
public String loopDiagonally(String[][] twoDArray) {
|
||||||
|
|
||||||
|
int length = twoDArray.length;
|
||||||
|
int diagonalLines = (length + length) - 1;
|
||||||
|
int itemsInDiagonal = 0;
|
||||||
|
int midPoint = (diagonalLines / 2) + 1;
|
||||||
|
StringBuilder output = new StringBuilder();
|
||||||
|
|
||||||
|
for (int i = 1; i <= diagonalLines; i++) {
|
||||||
|
|
||||||
|
StringBuilder items = new StringBuilder();
|
||||||
|
int rowIndex;
|
||||||
|
int columnIndex;
|
||||||
|
|
||||||
|
if (i <= midPoint) {
|
||||||
|
itemsInDiagonal++;
|
||||||
|
for (int j = 0; j < itemsInDiagonal; j++) {
|
||||||
|
rowIndex = (i - j) - 1;
|
||||||
|
columnIndex = j;
|
||||||
|
items.append(twoDArray[rowIndex][columnIndex]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
itemsInDiagonal--;
|
||||||
|
for (int j = 0; j < itemsInDiagonal; j++) {
|
||||||
|
rowIndex = (length - 1) - j;
|
||||||
|
columnIndex = (i - length) + j;
|
||||||
|
items.append(twoDArray[rowIndex][columnIndex]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i != diagonalLines) {
|
||||||
|
output.append(items).append(" ");
|
||||||
|
} else {
|
||||||
|
output.append(items);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output.toString();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.array.looping;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class LoopDiagonallyUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void twoArrayIsLoopedDiagonallyAsExpected() {
|
||||||
|
|
||||||
|
LoopDiagonally loopDiagonally = new LoopDiagonally();
|
||||||
|
String[][] twoDArray = {{"a", "b", "c"},
|
||||||
|
{"d", "e", "f"},
|
||||||
|
{"g", "h", "i"}};
|
||||||
|
|
||||||
|
String output = loopDiagonally.loopDiagonally(twoDArray);
|
||||||
|
assertEquals("a db gec hf i", output);
|
||||||
|
}
|
||||||
|
}
|
|
@ -2,7 +2,10 @@ package com.baeldung.array;
|
||||||
|
|
||||||
import com.baeldung.arraycopy.model.Employee;
|
import com.baeldung.arraycopy.model.Employee;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
|
||||||
public class SortedArrayChecker {
|
public class SortedArrayChecker {
|
||||||
|
|
||||||
boolean isSorted(int[] array, int length) {
|
boolean isSorted(int[] array, int length) {
|
||||||
if (array == null || length < 2)
|
if (array == null || length < 2)
|
||||||
return true;
|
return true;
|
||||||
|
@ -22,7 +25,7 @@ public class SortedArrayChecker {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean isSorted(String[] array, int length) {
|
boolean isSorted(Comparable[] array, int length) {
|
||||||
if (array == null || length < 2)
|
if (array == null || length < 2)
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
|
@ -32,40 +35,31 @@ public class SortedArrayChecker {
|
||||||
return isSorted(array, length - 1);
|
return isSorted(array, length - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean isSorted(String[] array) {
|
boolean isSorted(Comparable[] array) {
|
||||||
for (int i = 0; i < array.length - 1; ++i) {
|
for (int i = 0; i < array.length - 1; ++i) {
|
||||||
if (array[i].compareTo(array[i + 1]) > 0)
|
if (array[i].compareTo(array[i + 1]) > 0)
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean isSortedByName(Employee[] array) {
|
boolean isSorted(Object[] array, Comparator comparator) {
|
||||||
for (int i = 0; i < array.length - 1; ++i) {
|
for (int i = 0; i < array.length - 1; ++i) {
|
||||||
if (array[i].getName().compareTo(array[i + 1].getName()) > 0)
|
if (comparator.compare(array[i], (array[i + 1])) > 0)
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean isSortedByAge(Employee[] array) {
|
boolean isSorted(Object[] array, Comparator comparator, int length) {
|
||||||
for (int i = 0; i < array.length - 1; ++i) {
|
|
||||||
if (array[i].getAge() > (array[i + 1].getAge()))
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean isSortedByAge(Employee[] array, int length) {
|
|
||||||
if (array == null || length < 2)
|
if (array == null || length < 2)
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
if (array[length - 2].getAge() > array[length - 1].getAge())
|
if (comparator.compare(array[length - 2], array[length - 1]) > 0)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
return isSortedByAge(array, length - 1);
|
return isSorted(array, comparator, length - 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,32 +4,33 @@ import com.baeldung.arraycopy.model.Employee;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
class SortedArrayCheckerUnitTest {
|
public class SortedArrayCheckerUnitTest {
|
||||||
|
|
||||||
private static final int[] INTEGER_SORTED = {1, 3, 5, 7, 9};
|
private static final int[] INTEGER_SORTED = {1, 3, 5, 7, 9};
|
||||||
private static final int[] INTEGER_NOT_SORTED = {1, 3, 11, 7};
|
private static final int[] INTEGER_NOT_SORTED = {1, 3, 11, 7};
|
||||||
|
|
||||||
private static final String[] STRING_SORTED = {"abc", "cde", "fgh"};
|
private static final String[] STRING_SORTED = {"abc", "cde", "fgh"};
|
||||||
private static final String[] STRING_NOT_SORTED = {"abc", "fgh", "cde", "ijk"};
|
private static final String[] STRING_NOT_SORTED = {"abc", "fgh", "cde", "ijk"};
|
||||||
|
|
||||||
private final Employee[] EMPLOYEES_SORTED_BY_NAME = {
|
private static final Employee[] EMPLOYEES_SORTED_BY_NAME = {
|
||||||
new Employee(1, "Carlos", 26),
|
new Employee(1, "Carlos", 26),
|
||||||
new Employee(2, "Daniel", 31),
|
new Employee(2, "Daniel", 31),
|
||||||
new Employee(3, "Marta", 27)};
|
new Employee(3, "Marta", 27)};
|
||||||
|
|
||||||
private final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = {
|
private static final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = {
|
||||||
new Employee(1, "Daniel", 31),
|
new Employee(1, "Daniel", 31),
|
||||||
new Employee(2, "Carlos", 26),
|
new Employee(2, "Carlos", 26),
|
||||||
new Employee(3, "Marta", 27)};
|
new Employee(3, "Marta", 27)};
|
||||||
|
|
||||||
private final Employee[] EMPLOYEES_SORTED_BY_AGE = {
|
private static final Employee[] EMPLOYEES_SORTED_BY_AGE = {
|
||||||
new Employee(1, "Carlos", 26),
|
new Employee(1, "Carlos", 26),
|
||||||
new Employee(2, "Marta", 27),
|
new Employee(2, "Marta", 27),
|
||||||
new Employee(3, "Daniel", 31)};
|
new Employee(3, "Daniel", 31)};
|
||||||
|
|
||||||
private final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = {
|
private static final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = {
|
||||||
new Employee(1, "Marta", 27),
|
new Employee(1, "Marta", 27),
|
||||||
new Employee(2, "Carlos", 26),
|
new Employee(2, "Carlos", 26),
|
||||||
new Employee(3, "Daniel", 31)};
|
new Employee(3, "Daniel", 31)};
|
||||||
|
@ -61,13 +62,18 @@ class SortedArrayCheckerUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenEmployeeArray_thenReturnIfItIsSortedOrNot() {
|
public void givenEmployeeArray_thenReturnIfItIsSortedOrNot() {
|
||||||
assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_SORTED_BY_NAME)).isEqualTo(true);
|
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(true);
|
||||||
assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_NOT_SORTED_BY_NAME)).isEqualTo(false);
|
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(false);
|
||||||
|
|
||||||
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE)).isEqualTo(true);
|
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).isEqualTo(true);
|
||||||
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE)).isEqualTo(false);
|
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).isEqualTo(false);
|
||||||
|
|
||||||
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE, EMPLOYEES_SORTED_BY_AGE.length)).isEqualTo(true);
|
assertThat(sortedArrayChecker
|
||||||
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE, EMPLOYEES_NOT_SORTED_BY_AGE.length)).isEqualTo(false);
|
.isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), EMPLOYEES_SORTED_BY_AGE.length))
|
||||||
|
.isEqualTo(true);
|
||||||
|
assertThat(sortedArrayChecker
|
||||||
|
.isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), EMPLOYEES_NOT_SORTED_BY_AGE.length))
|
||||||
|
.isEqualTo(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -42,7 +42,7 @@ public class CoreJavaCollectionsUnitTest {
|
||||||
@Test(expected = UnsupportedOperationException.class)
|
@Test(expected = UnsupportedOperationException.class)
|
||||||
public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() {
|
public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() {
|
||||||
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
|
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
|
||||||
final ImmutableList<Object> unmodifiableList = ImmutableList.builder().addAll(list).build();
|
final ImmutableList<String> unmodifiableList = ImmutableList.<String>builder().addAll(list).build();
|
||||||
unmodifiableList.add("four");
|
unmodifiableList.add("four");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,3 +1,3 @@
|
||||||
## Relevant articles:
|
## Relevant Articles:
|
||||||
|
|
||||||
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)
|
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)
|
||||||
|
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.baeldung.relationships.aggregation;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Car {
|
||||||
|
|
||||||
|
private List<Wheel> wheels;
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.relationships.aggregation;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class CarWithStaticInnerWheel {
|
||||||
|
|
||||||
|
private List<Wheel> wheels;
|
||||||
|
|
||||||
|
public static class Wheel {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,7 @@
|
||||||
|
package com.baeldung.relationships.aggregation;
|
||||||
|
|
||||||
|
public class Wheel {
|
||||||
|
|
||||||
|
private Car car;
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,7 @@
|
||||||
|
package com.baeldung.relationships.association;
|
||||||
|
|
||||||
|
public class Child {
|
||||||
|
|
||||||
|
private Mother mother;
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.baeldung.relationships.association;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Mother {
|
||||||
|
|
||||||
|
private List<Child> children;
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.relationships.composition;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Building {
|
||||||
|
|
||||||
|
private String address;
|
||||||
|
private List<Room> rooms;
|
||||||
|
|
||||||
|
public class Room {
|
||||||
|
|
||||||
|
public String getBuildingAddress() {
|
||||||
|
return Building.this.address;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.relationships.composition;
|
||||||
|
|
||||||
|
public class BuildingWithDefinitionRoomInMethod {
|
||||||
|
|
||||||
|
public Room createAnonymousRoom() {
|
||||||
|
return new Room() {
|
||||||
|
@Override
|
||||||
|
public void doInRoom() {}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public Room createInlineRoom() {
|
||||||
|
class InlineRoom implements Room {
|
||||||
|
@Override
|
||||||
|
public void doInRoom() {}
|
||||||
|
}
|
||||||
|
return new InlineRoom();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Room createLambdaRoom() {
|
||||||
|
return () -> {};
|
||||||
|
}
|
||||||
|
|
||||||
|
public interface Room {
|
||||||
|
void doInRoom();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.baeldung.relationships.university;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Department {
|
||||||
|
|
||||||
|
private List<Professor> professors;
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,10 @@
|
||||||
|
package com.baeldung.relationships.university;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Professor {
|
||||||
|
|
||||||
|
private List<Department> department;
|
||||||
|
private List<Professor> friends;
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.baeldung.relationships.university;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class University {
|
||||||
|
|
||||||
|
private List<Department> department;
|
||||||
|
|
||||||
|
}
|
|
@ -54,3 +54,15 @@ class BankAccountCopyConstructor extends BankAccount {
|
||||||
this.balance = 0.0f;
|
this.balance = 0.0f;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class BankAccountChainedConstructors extends BankAccount {
|
||||||
|
public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) {
|
||||||
|
this.name = name;
|
||||||
|
this.opened = opened;
|
||||||
|
this.balance = balance;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BankAccountChainedConstructors(String name) {
|
||||||
|
this(name, LocalDateTime.now(), 0.0f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -1,15 +1,14 @@
|
||||||
package com.baeldung.constructors;
|
package com.baeldung.constructors;
|
||||||
|
|
||||||
import com.baeldung.constructors.*;
|
import com.google.common.collect.Comparators;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.logging.Logger;
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.Month;
|
import java.time.Month;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
import org.junit.Test;
|
import static org.assertj.core.api.Assertions.*;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
|
||||||
|
|
||||||
public class ConstructorUnitTest {
|
public class ConstructorUnitTest {
|
||||||
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
|
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
|
||||||
|
@ -17,7 +16,9 @@ public class ConstructorUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenNoExplicitContructor_whenUsed_thenFails() {
|
public void givenNoExplicitContructor_whenUsed_thenFails() {
|
||||||
BankAccount account = new BankAccount();
|
BankAccount account = new BankAccount();
|
||||||
assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class);
|
assertThatThrownBy(() -> {
|
||||||
|
account.toString();
|
||||||
|
}).isInstanceOf(Exception.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -50,4 +51,13 @@ public class ConstructorUnitTest {
|
||||||
|
|
||||||
assertThat(newAccount.getBalance()).isEqualTo(0.0f);
|
assertThat(newAccount.getBalance()).isEqualTo(0.0f);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenChainedConstructor_whenUsed_thenMaintainsLogic() {
|
||||||
|
BankAccountChainedConstructors account = new BankAccountChainedConstructors("Tim");
|
||||||
|
BankAccountChainedConstructors newAccount = new BankAccountChainedConstructors("Tim", LocalDateTime.now(), 0.0f);
|
||||||
|
|
||||||
|
assertThat(account.getName()).isEqualTo(newAccount.getName());
|
||||||
|
assertThat(account.getBalance()).isEqualTo(newAccount.getBalance());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,7 +18,6 @@
|
||||||
- [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces)
|
- [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces)
|
||||||
- [Recursion In Java](http://www.baeldung.com/java-recursion)
|
- [Recursion In Java](http://www.baeldung.com/java-recursion)
|
||||||
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
|
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
|
||||||
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
|
|
||||||
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
|
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
|
||||||
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
|
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
|
||||||
- [Using Java Assertions](http://www.baeldung.com/java-assert)
|
- [Using Java Assertions](http://www.baeldung.com/java-assert)
|
||||||
|
|
|
@ -0,0 +1,25 @@
|
||||||
|
*.class
|
||||||
|
|
||||||
|
0.*
|
||||||
|
|
||||||
|
#folders#
|
||||||
|
/target
|
||||||
|
/neoDb*
|
||||||
|
/data
|
||||||
|
/src/main/webapp/WEB-INF/classes
|
||||||
|
*/META-INF/*
|
||||||
|
.resourceCache
|
||||||
|
|
||||||
|
# Packaged files #
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.ear
|
||||||
|
|
||||||
|
# Files generated by integration tests
|
||||||
|
backup-pom.xml
|
||||||
|
/bin/
|
||||||
|
/temp
|
||||||
|
|
||||||
|
#IntelliJ specific
|
||||||
|
.idea/
|
||||||
|
*.iml
|
|
@ -0,0 +1,20 @@
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>core-java-networking-2</artifactId>
|
||||||
|
<name>core-java-networking-2</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
<artifactId>core-java-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-networking-2</finalName>
|
||||||
|
</build>
|
||||||
|
</project>
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.url;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
public class UrlChecker {
|
||||||
|
|
||||||
|
public int getResponseCodeForURL(String address) throws IOException {
|
||||||
|
return getResponseCodeForURLUsing(address, "GET");
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getResponseCodeForURLUsingHead(String address) throws IOException {
|
||||||
|
return getResponseCodeForURLUsing(address, "HEAD");
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getResponseCodeForURLUsing(String address, String method) throws IOException {
|
||||||
|
HttpURLConnection.setFollowRedirects(false); // Set follow redirects to false
|
||||||
|
final URL url = new URL(address);
|
||||||
|
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
|
||||||
|
huc.setRequestMethod(method);
|
||||||
|
return huc.getResponseCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.url;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class UrlCheckerUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidUrl_WhenUsingHEAD_ThenReturn200() throws IOException {
|
||||||
|
UrlChecker tester = new UrlChecker();
|
||||||
|
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com");
|
||||||
|
assertEquals(200, responseCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInvalidIUrl_WhenUsingHEAD_ThenReturn404() throws IOException {
|
||||||
|
UrlChecker tester = new UrlChecker();
|
||||||
|
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com/unkownurl");
|
||||||
|
assertEquals(404, responseCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidUrl_WhenUsingGET_ThenReturn200() throws IOException {
|
||||||
|
UrlChecker tester = new UrlChecker();
|
||||||
|
int responseCode = tester.getResponseCodeForURL("http://www.example.com");
|
||||||
|
assertEquals(200, responseCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInvalidIUrl_WhenUsingGET_ThenReturn404() throws IOException {
|
||||||
|
UrlChecker tester = new UrlChecker();
|
||||||
|
int responseCode = tester.getResponseCodeForURL("http://www.example.com/unkownurl");
|
||||||
|
assertEquals(404, responseCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,40 @@
|
||||||
|
package com.baeldung.core.pwd;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.nio.file.FileSystems;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
public final class CurrentDirectoryFetcher {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.printf("Current Directory Using Java System API: %s%n", currentDirectoryUsingSystemProperties());
|
||||||
|
|
||||||
|
System.out.printf("Current Directory Using Java IO File API: %s%n", currentDirectoryUsingFile());
|
||||||
|
|
||||||
|
System.out.printf("Current Directory Using Java NIO FileSystems API: %s%n", currentDirectoryUsingFileSystems());
|
||||||
|
|
||||||
|
System.out.printf("Current Directory Using Java NIO Paths API: %s%n", currentDirectoryUsingPaths());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String currentDirectoryUsingSystemProperties() {
|
||||||
|
return System.getProperty("user.dir");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String currentDirectoryUsingPaths() {
|
||||||
|
return Paths.get("")
|
||||||
|
.toAbsolutePath()
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String currentDirectoryUsingFileSystems() {
|
||||||
|
return FileSystems.getDefault()
|
||||||
|
.getPath("")
|
||||||
|
.toAbsolutePath()
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String currentDirectoryUsingFile() {
|
||||||
|
return new File("").getAbsolutePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.core.pwd;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CurrentDirectoryFetcherTest {
|
||||||
|
|
||||||
|
private static final String CURRENT_DIR = "core-java-os";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingSystemProperties_thenReturnCurrentDirectory() {
|
||||||
|
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingSystemProperties()
|
||||||
|
.endsWith(CURRENT_DIR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingJavaNioPaths_thenReturnCurrentDirectory() {
|
||||||
|
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingPaths()
|
||||||
|
.endsWith(CURRENT_DIR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingJavaNioFileSystems_thenReturnCurrentDirectory() {
|
||||||
|
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFileSystems()
|
||||||
|
.endsWith(CURRENT_DIR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingJavaIoFile_thenReturnCurrentDirectory() {
|
||||||
|
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFile()
|
||||||
|
.endsWith(CURRENT_DIR));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.sasl;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import javax.security.auth.callback.Callback;
|
||||||
|
import javax.security.auth.callback.CallbackHandler;
|
||||||
|
import javax.security.auth.callback.NameCallback;
|
||||||
|
import javax.security.auth.callback.PasswordCallback;
|
||||||
|
import javax.security.auth.callback.UnsupportedCallbackException;
|
||||||
|
import javax.security.sasl.RealmCallback;
|
||||||
|
|
||||||
|
public class ClientCallbackHandler implements CallbackHandler {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException {
|
||||||
|
for (Callback cb : cbs) {
|
||||||
|
if (cb instanceof NameCallback) {
|
||||||
|
NameCallback nc = (NameCallback) cb;
|
||||||
|
nc.setName("username");
|
||||||
|
} else if (cb instanceof PasswordCallback) {
|
||||||
|
PasswordCallback pc = (PasswordCallback) cb;
|
||||||
|
pc.setPassword("password".toCharArray());
|
||||||
|
} else if (cb instanceof RealmCallback) {
|
||||||
|
RealmCallback rc = (RealmCallback) cb;
|
||||||
|
rc.setText("myServer");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.sasl;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import javax.security.auth.callback.Callback;
|
||||||
|
import javax.security.auth.callback.CallbackHandler;
|
||||||
|
import javax.security.auth.callback.NameCallback;
|
||||||
|
import javax.security.auth.callback.PasswordCallback;
|
||||||
|
import javax.security.auth.callback.UnsupportedCallbackException;
|
||||||
|
import javax.security.sasl.AuthorizeCallback;
|
||||||
|
import javax.security.sasl.RealmCallback;
|
||||||
|
|
||||||
|
public class ServerCallbackHandler implements CallbackHandler {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException {
|
||||||
|
for (Callback cb : cbs) {
|
||||||
|
if (cb instanceof AuthorizeCallback) {
|
||||||
|
AuthorizeCallback ac = (AuthorizeCallback) cb;
|
||||||
|
ac.setAuthorized(true);
|
||||||
|
} else if (cb instanceof NameCallback) {
|
||||||
|
NameCallback nc = (NameCallback) cb;
|
||||||
|
nc.setName("username");
|
||||||
|
|
||||||
|
} else if (cb instanceof PasswordCallback) {
|
||||||
|
PasswordCallback pc = (PasswordCallback) cb;
|
||||||
|
pc.setPassword("password".toCharArray());
|
||||||
|
} else if (cb instanceof RealmCallback) {
|
||||||
|
RealmCallback rc = (RealmCallback) cb;
|
||||||
|
rc.setText("myServer");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,76 @@
|
||||||
|
package com.baeldung.sasl;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import javax.security.sasl.Sasl;
|
||||||
|
import javax.security.sasl.SaslClient;
|
||||||
|
import javax.security.sasl.SaslException;
|
||||||
|
import javax.security.sasl.SaslServer;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class SaslUnitTest {
|
||||||
|
|
||||||
|
private static final String MECHANISM = "DIGEST-MD5";
|
||||||
|
private static final String SERVER_NAME = "myServer";
|
||||||
|
private static final String PROTOCOL = "myProtocol";
|
||||||
|
private static final String AUTHORIZATION_ID = null;
|
||||||
|
private static final String QOP_LEVEL = "auth-conf";
|
||||||
|
|
||||||
|
private SaslServer saslServer;
|
||||||
|
private SaslClient saslClient;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws SaslException {
|
||||||
|
|
||||||
|
ServerCallbackHandler serverHandler = new ServerCallbackHandler();
|
||||||
|
ClientCallbackHandler clientHandler = new ClientCallbackHandler();
|
||||||
|
|
||||||
|
Map<String, String> props = new HashMap<>();
|
||||||
|
props.put(Sasl.QOP, QOP_LEVEL);
|
||||||
|
|
||||||
|
saslServer = Sasl.createSaslServer(MECHANISM, PROTOCOL, SERVER_NAME, props, serverHandler);
|
||||||
|
saslClient = Sasl.createSaslClient(new String[] { MECHANISM }, AUTHORIZATION_ID, PROTOCOL, SERVER_NAME, props, clientHandler);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHandlers_whenStarted_thenAutenticationWorks() throws SaslException {
|
||||||
|
|
||||||
|
byte[] challenge;
|
||||||
|
byte[] response;
|
||||||
|
|
||||||
|
challenge = saslServer.evaluateResponse(new byte[0]);
|
||||||
|
response = saslClient.evaluateChallenge(challenge);
|
||||||
|
|
||||||
|
challenge = saslServer.evaluateResponse(response);
|
||||||
|
response = saslClient.evaluateChallenge(challenge);
|
||||||
|
|
||||||
|
assertTrue(saslServer.isComplete());
|
||||||
|
assertTrue(saslClient.isComplete());
|
||||||
|
|
||||||
|
String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP);
|
||||||
|
assertEquals("auth-conf", qop);
|
||||||
|
|
||||||
|
byte[] outgoing = "Baeldung".getBytes();
|
||||||
|
byte[] secureOutgoing = saslClient.wrap(outgoing, 0, outgoing.length);
|
||||||
|
|
||||||
|
byte[] secureIncoming = secureOutgoing;
|
||||||
|
byte[] incoming = saslServer.unwrap(secureIncoming, 0, secureIncoming.length);
|
||||||
|
assertEquals("Baeldung", new String(incoming, StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws SaslException {
|
||||||
|
saslClient.dispose();
|
||||||
|
saslServer.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -37,7 +37,6 @@
|
||||||
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
|
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
|
||||||
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
||||||
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
||||||
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
|
||||||
- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
|
- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
|
||||||
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
|
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
|
||||||
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
|
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
## Relevant Articles
|
||||||
|
|
||||||
|
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
|
|
@ -17,6 +17,7 @@
|
||||||
<module>pre-jpms</module>
|
<module>pre-jpms</module>
|
||||||
<module>core-java-exceptions</module>
|
<module>core-java-exceptions</module>
|
||||||
<module>core-java-optional</module>
|
<module>core-java-optional</module>
|
||||||
|
<module>core-java-networking-2</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
Binary file not shown.
|
@ -22,6 +22,10 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule {
|
||||||
String className = node.getImage();
|
String className = node.getImage();
|
||||||
Objects.requireNonNull(className);
|
Objects.requireNonNull(className);
|
||||||
|
|
||||||
|
if (className.endsWith("SpringContextTest")) {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
if (className.endsWith("Tests")
|
if (className.endsWith("Tests")
|
||||||
|| (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) {
|
|| (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) {
|
||||||
addViolation(data, node);
|
addViolation(data, node);
|
||||||
|
|
|
@ -0,0 +1,72 @@
|
||||||
|
package com.baeldung.graph;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Stack;
|
||||||
|
|
||||||
|
public class Graph {
|
||||||
|
|
||||||
|
private Map<Integer, List<Integer>> adjVertices;
|
||||||
|
|
||||||
|
public Graph() {
|
||||||
|
this.adjVertices = new HashMap<Integer, List<Integer>>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addVertex(int vertex) {
|
||||||
|
adjVertices.putIfAbsent(vertex, new ArrayList<>());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addEdge(int src, int dest) {
|
||||||
|
adjVertices.get(src).add(dest);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void dfsWithoutRecursion(int start) {
|
||||||
|
Stack<Integer> stack = new Stack<Integer>();
|
||||||
|
boolean[] isVisited = new boolean[adjVertices.size()];
|
||||||
|
stack.push(start);
|
||||||
|
while (!stack.isEmpty()) {
|
||||||
|
int current = stack.pop();
|
||||||
|
isVisited[current] = true;
|
||||||
|
System.out.print(" " + current);
|
||||||
|
for (int dest : adjVertices.get(current)) {
|
||||||
|
if (!isVisited[dest])
|
||||||
|
stack.push(dest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void dfs(int start) {
|
||||||
|
boolean[] isVisited = new boolean[adjVertices.size()];
|
||||||
|
dfsRecursive(start, isVisited);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void dfsRecursive(int current, boolean[] isVisited) {
|
||||||
|
isVisited[current] = true;
|
||||||
|
System.out.print(" " + current);
|
||||||
|
for (int dest : adjVertices.get(current)) {
|
||||||
|
if (!isVisited[dest])
|
||||||
|
dfsRecursive(dest, isVisited);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void topologicalSort(int start) {
|
||||||
|
Stack<Integer> result = new Stack<Integer>();
|
||||||
|
boolean[] isVisited = new boolean[adjVertices.size()];
|
||||||
|
topologicalSortRecursive(start, isVisited, result);
|
||||||
|
while (!result.isEmpty()) {
|
||||||
|
System.out.print(" " + result.pop());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void topologicalSortRecursive(int current, boolean[] isVisited, Stack<Integer> result) {
|
||||||
|
isVisited[current] = true;
|
||||||
|
for (int dest : adjVertices.get(current)) {
|
||||||
|
if (!isVisited[dest])
|
||||||
|
topologicalSortRecursive(dest, isVisited, result);
|
||||||
|
}
|
||||||
|
result.push(current);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -2,6 +2,7 @@ package com.baeldung.tree;
|
||||||
|
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.Queue;
|
import java.util.Queue;
|
||||||
|
import java.util.Stack;
|
||||||
|
|
||||||
public class BinaryTree {
|
public class BinaryTree {
|
||||||
|
|
||||||
|
@ -147,6 +148,68 @@ public class BinaryTree {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public void traverseInOrderWithoutRecursion() {
|
||||||
|
Stack<Node> stack = new Stack<Node>();
|
||||||
|
Node current = root;
|
||||||
|
stack.push(root);
|
||||||
|
while(! stack.isEmpty()) {
|
||||||
|
while(current.left != null) {
|
||||||
|
current = current.left;
|
||||||
|
stack.push(current);
|
||||||
|
}
|
||||||
|
current = stack.pop();
|
||||||
|
System.out.print(" " + current.value);
|
||||||
|
if(current.right != null) {
|
||||||
|
current = current.right;
|
||||||
|
stack.push(current);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void traversePreOrderWithoutRecursion() {
|
||||||
|
Stack<Node> stack = new Stack<Node>();
|
||||||
|
Node current = root;
|
||||||
|
stack.push(root);
|
||||||
|
while(! stack.isEmpty()) {
|
||||||
|
current = stack.pop();
|
||||||
|
System.out.print(" " + current.value);
|
||||||
|
|
||||||
|
if(current.right != null)
|
||||||
|
stack.push(current.right);
|
||||||
|
|
||||||
|
if(current.left != null)
|
||||||
|
stack.push(current.left);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void traversePostOrderWithoutRecursion() {
|
||||||
|
Stack<Node> stack = new Stack<Node>();
|
||||||
|
Node prev = root;
|
||||||
|
Node current = root;
|
||||||
|
stack.push(root);
|
||||||
|
|
||||||
|
while (!stack.isEmpty()) {
|
||||||
|
current = stack.peek();
|
||||||
|
boolean hasChild = (current.left != null || current.right != null);
|
||||||
|
boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null));
|
||||||
|
|
||||||
|
if (!hasChild || isPrevLastChild) {
|
||||||
|
current = stack.pop();
|
||||||
|
System.out.print(" " + current.value);
|
||||||
|
prev = current;
|
||||||
|
} else {
|
||||||
|
if (current.right != null) {
|
||||||
|
stack.push(current.right);
|
||||||
|
}
|
||||||
|
if (current.left != null) {
|
||||||
|
stack.push(current.left);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class Node {
|
class Node {
|
||||||
int value;
|
int value;
|
||||||
Node left;
|
Node left;
|
||||||
|
|
|
@ -0,0 +1,37 @@
|
||||||
|
package com.baeldung.graph;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class GraphUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirectedGraph_whenDFS_thenPrintAllValues() {
|
||||||
|
Graph graph = createDirectedGraph();
|
||||||
|
graph.dfs(0);
|
||||||
|
System.out.println();
|
||||||
|
graph.dfsWithoutRecursion(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() {
|
||||||
|
Graph graph = createDirectedGraph();
|
||||||
|
graph.topologicalSort(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Graph createDirectedGraph() {
|
||||||
|
Graph graph = new Graph();
|
||||||
|
graph.addVertex(0);
|
||||||
|
graph.addVertex(1);
|
||||||
|
graph.addVertex(2);
|
||||||
|
graph.addVertex(3);
|
||||||
|
graph.addVertex(4);
|
||||||
|
graph.addVertex(5);
|
||||||
|
graph.addEdge(0, 1);
|
||||||
|
graph.addEdge(0, 2);
|
||||||
|
graph.addEdge(1, 3);
|
||||||
|
graph.addEdge(2, 3);
|
||||||
|
graph.addEdge(3, 4);
|
||||||
|
graph.addEdge(4, 5);
|
||||||
|
return graph;
|
||||||
|
}
|
||||||
|
}
|
|
@ -87,6 +87,8 @@ public class BinaryTreeUnitTest {
|
||||||
BinaryTree bt = createBinaryTree();
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
bt.traverseInOrder(bt.root);
|
bt.traverseInOrder(bt.root);
|
||||||
|
System.out.println();
|
||||||
|
bt.traverseInOrderWithoutRecursion();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -95,6 +97,8 @@ public class BinaryTreeUnitTest {
|
||||||
BinaryTree bt = createBinaryTree();
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
bt.traversePreOrder(bt.root);
|
bt.traversePreOrder(bt.root);
|
||||||
|
System.out.println();
|
||||||
|
bt.traversePreOrderWithoutRecursion();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -103,6 +107,8 @@ public class BinaryTreeUnitTest {
|
||||||
BinaryTree bt = createBinaryTree();
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
bt.traversePostOrder(bt.root);
|
bt.traversePostOrder(bt.root);
|
||||||
|
System.out.println();
|
||||||
|
bt.traversePostOrderWithoutRecursion();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -165,7 +165,7 @@ public class JacksonSerializationIgnoreUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenIgnoringNullFieldsOnClass_whenWritingObjectWithNullField_thenFieldIsIgnored() throws JsonProcessingException {
|
public final void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
|
||||||
final ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull();
|
final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull();
|
||||||
|
|
||||||
|
@ -178,7 +178,7 @@ public class JacksonSerializationIgnoreUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenIgnoringNullFieldsGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
|
public final void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
|
||||||
final ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
mapper.setSerializationInclusion(Include.NON_NULL);
|
mapper.setSerializationInclusion(Include.NON_NULL);
|
||||||
final MyDto dtoObject = new MyDto();
|
final MyDto dtoObject = new MyDto();
|
||||||
|
|
|
@ -0,0 +1,148 @@
|
||||||
|
package com.baeldung.binarynumbers;
|
||||||
|
|
||||||
|
public class BinaryNumbers {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method takes a decimal number and convert it into a binary number.
|
||||||
|
* example:- input:10, output:1010
|
||||||
|
*
|
||||||
|
* @param decimalNumber
|
||||||
|
* @return binary number
|
||||||
|
*/
|
||||||
|
public Integer convertDecimalToBinary(Integer decimalNumber) {
|
||||||
|
|
||||||
|
if (decimalNumber == 0) {
|
||||||
|
return decimalNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuilder binaryNumber = new StringBuilder();
|
||||||
|
|
||||||
|
while (decimalNumber > 0) {
|
||||||
|
|
||||||
|
int remainder = decimalNumber % 2;
|
||||||
|
int result = decimalNumber / 2;
|
||||||
|
|
||||||
|
binaryNumber.append(remainder);
|
||||||
|
decimalNumber = result;
|
||||||
|
}
|
||||||
|
|
||||||
|
binaryNumber = binaryNumber.reverse();
|
||||||
|
|
||||||
|
return Integer.valueOf(binaryNumber.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method takes a binary number and convert it into a decimal number.
|
||||||
|
* example:- input:101, output:5
|
||||||
|
*
|
||||||
|
* @param binary number
|
||||||
|
* @return decimal Number
|
||||||
|
*/
|
||||||
|
public Integer convertBinaryToDecimal(Integer binaryNumber) {
|
||||||
|
|
||||||
|
Integer result = 0;
|
||||||
|
Integer base = 1;
|
||||||
|
|
||||||
|
while (binaryNumber > 0) {
|
||||||
|
|
||||||
|
int lastDigit = binaryNumber % 10;
|
||||||
|
binaryNumber = binaryNumber / 10;
|
||||||
|
|
||||||
|
result += lastDigit * base;
|
||||||
|
|
||||||
|
base = base * 2;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method accepts two binary numbers and returns sum of input numbers.
|
||||||
|
* Example:- firstNum: 101, secondNum: 100, output: 1001
|
||||||
|
*
|
||||||
|
* @param firstNum
|
||||||
|
* @param secondNum
|
||||||
|
* @return addition of input numbers
|
||||||
|
*/
|
||||||
|
public Integer addBinaryNumber(Integer firstNum, Integer secondNum) {
|
||||||
|
|
||||||
|
StringBuilder output = new StringBuilder();
|
||||||
|
|
||||||
|
int carry = 0;
|
||||||
|
int temp;
|
||||||
|
|
||||||
|
while (firstNum != 0 || secondNum != 0) {
|
||||||
|
|
||||||
|
temp = (firstNum % 10 + secondNum % 10 + carry) % 2;
|
||||||
|
output.append(temp);
|
||||||
|
|
||||||
|
carry = (firstNum % 10 + secondNum % 10 + carry) / 2;
|
||||||
|
|
||||||
|
firstNum = firstNum / 10;
|
||||||
|
secondNum = secondNum / 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (carry != 0) {
|
||||||
|
output.append(carry);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Integer.valueOf(output.reverse()
|
||||||
|
.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method takes two binary number as input and subtract second number from the first number.
|
||||||
|
* example:- firstNum: 1000, secondNum: 11, output: 101
|
||||||
|
* @param firstNum
|
||||||
|
* @param secondNum
|
||||||
|
* @return Result of subtraction of secondNum from first
|
||||||
|
*/
|
||||||
|
public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) {
|
||||||
|
|
||||||
|
int onesComplement = Integer.valueOf(getOnesComplement(secondNum));
|
||||||
|
|
||||||
|
StringBuilder output = new StringBuilder();
|
||||||
|
|
||||||
|
int carry = 0;
|
||||||
|
int temp;
|
||||||
|
|
||||||
|
while (firstNum != 0 || onesComplement != 0) {
|
||||||
|
|
||||||
|
temp = (firstNum % 10 + onesComplement % 10 + carry) % 2;
|
||||||
|
output.append(temp);
|
||||||
|
|
||||||
|
carry = (firstNum % 10 + onesComplement % 10 + carry) / 2;
|
||||||
|
|
||||||
|
firstNum = firstNum / 10;
|
||||||
|
onesComplement = onesComplement / 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
String additionOfFirstNumAndOnesComplement = output.reverse()
|
||||||
|
.toString();
|
||||||
|
|
||||||
|
if (carry == 1) {
|
||||||
|
return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry);
|
||||||
|
} else {
|
||||||
|
return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getOnesComplement(Integer num) {
|
||||||
|
|
||||||
|
StringBuilder onesComplement = new StringBuilder();
|
||||||
|
|
||||||
|
while (num > 0) {
|
||||||
|
int lastDigit = num % 10;
|
||||||
|
if (lastDigit == 0) {
|
||||||
|
onesComplement.append(1);
|
||||||
|
} else {
|
||||||
|
onesComplement.append(0);
|
||||||
|
}
|
||||||
|
num = num / 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Integer.valueOf(onesComplement.reverse()
|
||||||
|
.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,73 @@
|
||||||
|
package com.baeldung.binarynumbers;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class BinaryNumbersUnitTest {
|
||||||
|
|
||||||
|
private BinaryNumbers binaryNumbers = new BinaryNumbers();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void given_decimalNumber_then_returnBinaryNumber() {
|
||||||
|
assertEquals(Integer.valueOf(1000), binaryNumbers.convertDecimalToBinary(8));
|
||||||
|
assertEquals(Integer.valueOf(10100), binaryNumbers.convertDecimalToBinary(20));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void given_decimalNumber_then_convertToBinaryNumber() {
|
||||||
|
assertEquals("1000", Integer.toBinaryString(8));
|
||||||
|
assertEquals("10100", Integer.toBinaryString(20));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void given_binaryNumber_then_ConvertToDecimalNumber() {
|
||||||
|
assertEquals(8, Integer.parseInt("1000", 2));
|
||||||
|
assertEquals(20, Integer.parseInt("10100", 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void given_binaryNumber_then_returnDecimalNumber() {
|
||||||
|
assertEquals(Integer.valueOf(8), binaryNumbers.convertBinaryToDecimal(1000));
|
||||||
|
assertEquals(Integer.valueOf(20), binaryNumbers.convertBinaryToDecimal(10100));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void given_twoBinaryNumber_then_returnAddition() {
|
||||||
|
// adding 4 and 10
|
||||||
|
assertEquals(Integer.valueOf(1110), binaryNumbers.addBinaryNumber(100, 1010));
|
||||||
|
|
||||||
|
// adding 26 and 14
|
||||||
|
assertEquals(Integer.valueOf(101000), binaryNumbers.addBinaryNumber(11010, 1110));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void given_twoBinaryNumber_then_returnSubtraction() {
|
||||||
|
// subtracting 16 from 25
|
||||||
|
assertEquals(Integer.valueOf(1001), binaryNumbers.substractBinaryNumber(11001, 10000));
|
||||||
|
|
||||||
|
// subtracting 29 from 16, the output here is negative
|
||||||
|
assertEquals(Integer.valueOf(1101), binaryNumbers.substractBinaryNumber(10000, 11101));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void given_binaryLiteral_thenReturnDecimalValue() {
|
||||||
|
|
||||||
|
byte five = 0b101;
|
||||||
|
assertEquals((byte) 5, five);
|
||||||
|
|
||||||
|
short three = 0b11;
|
||||||
|
assertEquals((short) 3, three);
|
||||||
|
|
||||||
|
int nine = 0B1001;
|
||||||
|
assertEquals(9, nine);
|
||||||
|
|
||||||
|
long twentyNine = 0B11101;
|
||||||
|
assertEquals(29, twentyNine);
|
||||||
|
|
||||||
|
int minusThirtySeven = -0B100101;
|
||||||
|
assertEquals(-37, minusThirtySeven);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.string.changecase;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class ToLowerCaseUnitTest {
|
||||||
|
|
||||||
|
private static final Locale TURKISH = new Locale("tr");
|
||||||
|
private String name = "John Doe";
|
||||||
|
private String foreignUppercase = "\u0049";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() {
|
||||||
|
assertEquals("john doe", name.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() {
|
||||||
|
assertEquals("\u0069", foreignUppercase.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() {
|
||||||
|
assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.string.changecase;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class ToUpperCaseUnitTest {
|
||||||
|
|
||||||
|
private static final Locale TURKISH = new Locale("tr");
|
||||||
|
private String name = "John Doe";
|
||||||
|
private String foreignLowercase = "\u0069";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() {
|
||||||
|
assertEquals("JOHN DOE", name.toUpperCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() {
|
||||||
|
assertEquals("\u0049", foreignLowercase.toUpperCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() {
|
||||||
|
assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH));
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.string;
|
package com.baeldung.string.multiline;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
|
@ -0,0 +1,56 @@
|
||||||
|
package com.baeldung.string.todouble;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.text.DecimalFormat;
|
||||||
|
import java.text.ParseException;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class StringToDoubleConversionUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidString_WhenParseDouble_ThenResultIsPrimitiveDouble() {
|
||||||
|
assertEquals(1.23, Double.parseDouble("1.23"), 0.000001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenNullString_WhenParseDouble_ThenNullPointerExceptionIsThrown() {
|
||||||
|
Double.parseDouble(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NumberFormatException.class)
|
||||||
|
public void givenInalidString_WhenParseDouble_ThenNumberFormatExceptionIsThrown() {
|
||||||
|
Double.parseDouble("&");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidString_WhenValueOf_ThenResultIsPrimitiveDouble() {
|
||||||
|
assertEquals(1.23, Double.valueOf("1.23"), 0.000001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenNullString_WhenValueOf_ThenNullPointerExceptionIsThrown() {
|
||||||
|
Double.valueOf(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NumberFormatException.class)
|
||||||
|
public void givenInalidString_WhenValueOf_ThenNumberFormatExceptionIsThrown() {
|
||||||
|
Double.valueOf("&");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidString_WhenDecimalFormat_ThenResultIsValidDouble() throws ParseException {
|
||||||
|
assertEquals(1.23, new DecimalFormat("#").parse("1.23").doubleValue(), 0.000001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenNullString_WhenDecimalFormat_ThenNullPointerExceptionIsThrown() throws ParseException {
|
||||||
|
new DecimalFormat("#").parse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = ParseException.class)
|
||||||
|
public void givenInvalidString_WhenDecimalFormat_ThenParseExceptionIsThrown() throws ParseException {
|
||||||
|
new DecimalFormat("#").parse("&");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package org.baeldung.javabeanconstraints.bigdecimal;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
import javax.validation.constraints.DecimalMin;
|
||||||
|
import javax.validation.constraints.Digits;
|
||||||
|
|
||||||
|
public class Invoice {
|
||||||
|
|
||||||
|
@DecimalMin(value = "0.0", inclusive = false)
|
||||||
|
@Digits(integer=3, fraction=2)
|
||||||
|
private BigDecimal price;
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
public Invoice(BigDecimal price, String description) {
|
||||||
|
this.price = price;
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,62 @@
|
||||||
|
package org.baeldung.javabeanconstraints.bigdecimal;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import javax.validation.ConstraintViolation;
|
||||||
|
import javax.validation.Validation;
|
||||||
|
import javax.validation.Validator;
|
||||||
|
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class InvoiceUnitTest {
|
||||||
|
|
||||||
|
private static Validator validator;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setupValidatorInstance() {
|
||||||
|
validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPriceIntegerDigitLessThanThreeWithDecimalValue_thenShouldGiveConstraintViolations() {
|
||||||
|
Invoice invoice = new Invoice(new BigDecimal(10.21), "Book purchased");
|
||||||
|
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||||
|
assertThat(violations.size()).isEqualTo(1);
|
||||||
|
violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPriceIntegerDigitLessThanThreeWithIntegerValue_thenShouldNotGiveConstraintViolations() {
|
||||||
|
Invoice invoice = new Invoice(new BigDecimal(10), "Book purchased");
|
||||||
|
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||||
|
assertThat(violations.size()).isEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPriceIntegerDigitGreaterThanThree_thenShouldGiveConstraintViolations() {
|
||||||
|
Invoice invoice = new Invoice(new BigDecimal(1021.21), "Book purchased");
|
||||||
|
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||||
|
assertThat(violations.size()).isEqualTo(1);
|
||||||
|
violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPriceIsZero_thenShouldGiveConstraintViolations() {
|
||||||
|
Invoice invoice = new Invoice(new BigDecimal(000.00), "Book purchased");
|
||||||
|
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||||
|
assertThat(violations.size()).isEqualTo(1);
|
||||||
|
violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("must be greater than 0.0"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPriceIsGreaterThanZero_thenShouldNotGiveConstraintViolations() {
|
||||||
|
Invoice invoice = new Invoice(new BigDecimal(100.50), "Book purchased");
|
||||||
|
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||||
|
assertThat(violations.size()).isEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,6 +0,0 @@
|
||||||
## Relevant articles:
|
|
||||||
|
|
||||||
- [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices)
|
|
||||||
- [Intro to JHipster](http://www.baeldung.com/jhipster)
|
|
||||||
- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service)
|
|
||||||
- [Creating New Roles and Authorities in JHipster](https://www.baeldung.com/jhipster-new-roles)
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
## Relevant Articles
|
||||||
|
|
||||||
|
- [JHipster with a Microservice Architecture](https://www.baeldung.com/jhipster-microservices)
|
|
@ -1,4 +1,6 @@
|
||||||
### Relevant articles
|
## Relevant Articles
|
||||||
|
|
||||||
|
- [Intro to JHipster](https://www.baeldung.com/jhipster)
|
||||||
|
|
||||||
|
|
||||||
# baeldung
|
# baeldung
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
## Relevant Articles
|
||||||
|
|
||||||
|
- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service)
|
|
@ -0,0 +1,5 @@
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Transferring a File Through SFTP in Java](https://www.baeldung.com/java-file-sftp)
|
||||||
|
|
|
@ -0,0 +1,40 @@
|
||||||
|
<?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>libraries-io</artifactId>
|
||||||
|
<name>libraries-io</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- sftp file transfer -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.jcraft</groupId>
|
||||||
|
<artifactId>jsch</artifactId>
|
||||||
|
<version>${jsch.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.hierynomus</groupId>
|
||||||
|
<artifactId>sshj</artifactId>
|
||||||
|
<version>${sshj.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-vfs2</artifactId>
|
||||||
|
<version>${vfs.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- sftp -->
|
||||||
|
<jsch.version>0.1.55</jsch.version>
|
||||||
|
<sshj.version>0.27.0</sshj.version>
|
||||||
|
<vfs.version>2.4</vfs.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
|
@ -0,0 +1 @@
|
||||||
|
This is a sample text content
|
|
@ -0,0 +1,106 @@
|
||||||
|
package org.baeldung.java.io.remote;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.apache.commons.vfs2.FileObject;
|
||||||
|
import org.apache.commons.vfs2.FileSystemManager;
|
||||||
|
import org.apache.commons.vfs2.Selectors;
|
||||||
|
import org.apache.commons.vfs2.VFS;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.jcraft.jsch.ChannelSftp;
|
||||||
|
import com.jcraft.jsch.JSch;
|
||||||
|
import com.jcraft.jsch.JSchException;
|
||||||
|
import com.jcraft.jsch.Session;
|
||||||
|
import com.jcraft.jsch.SftpException;
|
||||||
|
|
||||||
|
import net.schmizz.sshj.SSHClient;
|
||||||
|
import net.schmizz.sshj.sftp.SFTPClient;
|
||||||
|
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
|
||||||
|
|
||||||
|
public class SftpFileTransferLiveTest {
|
||||||
|
|
||||||
|
private String remoteHost = "HOST_NAME_HERE";
|
||||||
|
private String username = "USERNAME_HERE";
|
||||||
|
private String password = "PASSWORD_HERE";
|
||||||
|
private String localFile = "src/main/resources/input.txt";
|
||||||
|
private String remoteFile = "welcome.txt";
|
||||||
|
private String localDir = "src/main/resources/";
|
||||||
|
private String remoteDir = "remote_sftp_test/";
|
||||||
|
private String knownHostsFileLoc = "/Users/USERNAME/known_hosts_sample";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
|
||||||
|
ChannelSftp channelSftp = setupJsch();
|
||||||
|
channelSftp.connect();
|
||||||
|
channelSftp.put(localFile, remoteDir + "jschFile.txt");
|
||||||
|
channelSftp.exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDownloadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
|
||||||
|
ChannelSftp channelSftp = setupJsch();
|
||||||
|
channelSftp.connect();
|
||||||
|
channelSftp.get(remoteFile, localDir + "jschFile.txt");
|
||||||
|
channelSftp.exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUploadFileUsingSshj_thenSuccess() throws IOException {
|
||||||
|
SSHClient sshClient = setupSshj();
|
||||||
|
SFTPClient sftpClient = sshClient.newSFTPClient();
|
||||||
|
sftpClient.put(localFile, remoteDir + "sshjFile.txt");
|
||||||
|
sftpClient.close();
|
||||||
|
sshClient.disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDownloadFileUsingSshj_thenSuccess() throws IOException {
|
||||||
|
SSHClient sshClient = setupSshj();
|
||||||
|
SFTPClient sftpClient = sshClient.newSFTPClient();
|
||||||
|
sftpClient.get(remoteFile, localDir + "sshjFile.txt");
|
||||||
|
sftpClient.close();
|
||||||
|
sshClient.disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUploadFileUsingApacheVfs_thenSuccess() throws IOException {
|
||||||
|
FileSystemManager manager = VFS.getManager();
|
||||||
|
FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localFile);
|
||||||
|
FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt");
|
||||||
|
remote.copyFrom(local, Selectors.SELECT_SELF);
|
||||||
|
local.close();
|
||||||
|
remote.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDownloadFileUsingApacheVfs_thenSuccess() throws IOException {
|
||||||
|
FileSystemManager manager = VFS.getManager();
|
||||||
|
FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localDir + "vfsFile.txt");
|
||||||
|
FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteFile);
|
||||||
|
local.copyFrom(remote, Selectors.SELECT_SELF);
|
||||||
|
local.close();
|
||||||
|
remote.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ====== ssh-keyscan -H -t rsa remoteHost >> known_hosts_sample
|
||||||
|
|
||||||
|
private ChannelSftp setupJsch() throws JSchException {
|
||||||
|
JSch jsch = new JSch();
|
||||||
|
jsch.setKnownHosts(knownHostsFileLoc);
|
||||||
|
Session jschSession = jsch.getSession(username, remoteHost);
|
||||||
|
jschSession.setPassword(password);
|
||||||
|
//jschSession.setConfig("StrictHostKeyChecking", "no");
|
||||||
|
jschSession.connect();
|
||||||
|
return (ChannelSftp) jschSession.openChannel("sftp");
|
||||||
|
}
|
||||||
|
|
||||||
|
private SSHClient setupSshj() throws IOException {
|
||||||
|
SSHClient client = new SSHClient();
|
||||||
|
client.addHostKeyVerifier(new PromiscuousVerifier());
|
||||||
|
client.connect(remoteHost);
|
||||||
|
client.authPassword(username, password);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -42,7 +42,6 @@
|
||||||
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
|
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
|
||||||
- [Introduction to Smooks](http://www.baeldung.com/smooks)
|
- [Introduction to Smooks](http://www.baeldung.com/smooks)
|
||||||
- [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan)
|
- [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan)
|
||||||
- [Introduction to OpenCSV](http://www.baeldung.com/opencsv)
|
|
||||||
- [A Guide to Unirest](http://www.baeldung.com/unirest)
|
- [A Guide to Unirest](http://www.baeldung.com/unirest)
|
||||||
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
|
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
|
||||||
- [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy)
|
- [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy)
|
||||||
|
|
|
@ -13,9 +13,9 @@ public class GetterLazy {
|
||||||
private static final String DELIMETER = ",";
|
private static final String DELIMETER = ",";
|
||||||
|
|
||||||
@Getter(lazy = true)
|
@Getter(lazy = true)
|
||||||
private final Map<String, Long> transactions = readTxnsFromFile();
|
private final Map<String, Long> transactions = getTransactions();
|
||||||
|
|
||||||
private Map<String, Long> readTxnsFromFile() {
|
private Map<String, Long> getTransactions() {
|
||||||
|
|
||||||
final Map<String, Long> cache = new HashMap<>();
|
final Map<String, Long> cache = new HashMap<>();
|
||||||
List<String> txnRows = readTxnListFromFile();
|
List<String> txnRows = readTxnListFromFile();
|
||||||
|
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.lombok.intro;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import lombok.SneakyThrows;
|
||||||
|
import lombok.Synchronized;
|
||||||
|
|
||||||
|
public class Utility {
|
||||||
|
|
||||||
|
@SneakyThrows
|
||||||
|
public String resourceAsString() throws IOException {
|
||||||
|
try (InputStream is = this.getClass().getResourceAsStream("sure_in_my_jar.txt")) {
|
||||||
|
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
|
||||||
|
return br.lines().collect(Collectors.joining("\n"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
public void putValueInCache(String key, String value) {
|
||||||
|
System.out.println("Thread safe here with key : [" + key + "] and value[" + value + "]");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
Hello
|
|
@ -121,8 +121,8 @@ public class AuthorizationEndpoint {
|
||||||
String redirectUri = originalParams.getFirst("resolved_redirect_uri");
|
String redirectUri = originalParams.getFirst("resolved_redirect_uri");
|
||||||
StringBuilder sb = new StringBuilder(redirectUri);
|
StringBuilder sb = new StringBuilder(redirectUri);
|
||||||
|
|
||||||
String approbationStatus = params.getFirst("approbation_status");
|
String approvalStatus = params.getFirst("approval_status");
|
||||||
if ("NO".equals(approbationStatus)) {
|
if ("NO".equals(approvalStatus)) {
|
||||||
URI location = UriBuilder.fromUri(sb.toString())
|
URI location = UriBuilder.fromUri(sb.toString())
|
||||||
.queryParam("error", "User doesn't approved the request.")
|
.queryParam("error", "User doesn't approved the request.")
|
||||||
.queryParam("error_description", "User doesn't approved the request.")
|
.queryParam("error_description", "User doesn't approved the request.")
|
||||||
|
|
|
@ -15,15 +15,14 @@ import javax.ws.rs.core.HttpHeaders;
|
||||||
import javax.ws.rs.core.MediaType;
|
import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.MultivaluedMap;
|
import javax.ws.rs.core.MultivaluedMap;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.Arrays;
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
|
||||||
|
|
||||||
@Path("token")
|
@Path("token")
|
||||||
public class TokenEndpoint {
|
public class TokenEndpoint {
|
||||||
|
|
||||||
List<String> supportedGrantTypes = Collections.singletonList("authorization_code");
|
List<String> supportedGrantTypes = Arrays.asList("authorization_code", "refresh_token");
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
private AppDataRepository appDataRepository;
|
private AppDataRepository appDataRepository;
|
||||||
|
@ -39,36 +38,36 @@ public class TokenEndpoint {
|
||||||
|
|
||||||
//Check grant_type params
|
//Check grant_type params
|
||||||
String grantType = params.getFirst("grant_type");
|
String grantType = params.getFirst("grant_type");
|
||||||
Objects.requireNonNull(grantType, "grant_type params is required");
|
if (grantType == null || grantType.isEmpty())
|
||||||
if (!supportedGrantTypes.contains(grantType)) {
|
return responseError("Invalid_request", "grant_type is required", Response.Status.BAD_REQUEST);
|
||||||
JsonObject error = Json.createObjectBuilder()
|
|
||||||
.add("error", "unsupported_grant_type")
|
|
||||||
.add("error_description", "grant type should be one of :" + supportedGrantTypes)
|
|
||||||
.build();
|
|
||||||
return Response.status(Response.Status.BAD_REQUEST)
|
|
||||||
.entity(error).build();
|
|
||||||
|
|
||||||
|
if (!supportedGrantTypes.contains(grantType)) {
|
||||||
|
return responseError("unsupported_grant_type", "grant_type should be one of :" + supportedGrantTypes, Response.Status.BAD_REQUEST);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Client Authentication
|
//Client Authentication
|
||||||
String[] clientCredentials = extract(authHeader);
|
String[] clientCredentials = extract(authHeader);
|
||||||
|
if (clientCredentials.length != 2) {
|
||||||
|
return responseError("Invalid_request", "Bad Credentials client_id/client_secret", Response.Status.BAD_REQUEST);
|
||||||
|
}
|
||||||
String clientId = clientCredentials[0];
|
String clientId = clientCredentials[0];
|
||||||
String clientSecret = clientCredentials[1];
|
|
||||||
Client client = appDataRepository.getClient(clientId);
|
Client client = appDataRepository.getClient(clientId);
|
||||||
if (client == null || clientSecret == null || !clientSecret.equals(client.getClientSecret())) {
|
if (client == null) {
|
||||||
JsonObject error = Json.createObjectBuilder()
|
return responseError("Invalid_request", "Invalid client_id", Response.Status.BAD_REQUEST);
|
||||||
.add("error", "invalid_client")
|
}
|
||||||
.build();
|
String clientSecret = clientCredentials[1];
|
||||||
return Response.status(Response.Status.UNAUTHORIZED)
|
if (!clientSecret.equals(client.getClientSecret())) {
|
||||||
.entity(error).build();
|
return responseError("Invalid_request", "Invalid client_secret", Response.Status.UNAUTHORIZED);
|
||||||
}
|
}
|
||||||
|
|
||||||
AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get();
|
AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get();
|
||||||
JsonObject tokenResponse = null;
|
JsonObject tokenResponse = null;
|
||||||
try {
|
try {
|
||||||
tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params);
|
tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params);
|
||||||
|
} catch (WebApplicationException e) {
|
||||||
|
return e.getResponse();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
return responseError("Invalid_request", "Can't get token", Response.Status.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Response.ok(tokenResponse)
|
return Response.ok(tokenResponse)
|
||||||
|
@ -81,6 +80,15 @@ public class TokenEndpoint {
|
||||||
if (authHeader != null && authHeader.startsWith("Basic ")) {
|
if (authHeader != null && authHeader.startsWith("Basic ")) {
|
||||||
return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":");
|
return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":");
|
||||||
}
|
}
|
||||||
return null;
|
return new String[]{};
|
||||||
|
}
|
||||||
|
|
||||||
|
private Response responseError(String error, String errorDescription, Response.Status status) {
|
||||||
|
JsonObject errorResponse = Json.createObjectBuilder()
|
||||||
|
.add("error", error)
|
||||||
|
.add("error_description", errorDescription)
|
||||||
|
.build();
|
||||||
|
return Response.status(status)
|
||||||
|
.entity(errorResponse).build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,87 @@
|
||||||
|
package com.baeldung.oauth2.authorization.server.handler;
|
||||||
|
|
||||||
|
import com.baeldung.oauth2.authorization.server.PEMKeyUtils;
|
||||||
|
import com.nimbusds.jose.*;
|
||||||
|
import com.nimbusds.jose.crypto.RSASSASigner;
|
||||||
|
import com.nimbusds.jose.crypto.RSASSAVerifier;
|
||||||
|
import com.nimbusds.jose.jwk.JWK;
|
||||||
|
import com.nimbusds.jose.jwk.RSAKey;
|
||||||
|
import com.nimbusds.jwt.JWTClaimsSet;
|
||||||
|
import com.nimbusds.jwt.SignedJWT;
|
||||||
|
import org.eclipse.microprofile.config.Config;
|
||||||
|
|
||||||
|
import javax.inject.Inject;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public abstract class AbstractGrantTypeHandler implements AuthorizationGrantTypeHandler {
|
||||||
|
|
||||||
|
//Always RSA 256, but could be parametrized
|
||||||
|
protected JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
protected Config config;
|
||||||
|
|
||||||
|
//30 min
|
||||||
|
protected Long expiresInMin = 30L;
|
||||||
|
|
||||||
|
protected JWSVerifier getJWSVerifier() throws Exception {
|
||||||
|
String verificationkey = config.getValue("verificationkey", String.class);
|
||||||
|
String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey);
|
||||||
|
RSAKey rsaPublicKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey);
|
||||||
|
return new RSASSAVerifier(rsaPublicKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected JWSSigner getJwsSigner() throws Exception {
|
||||||
|
String signingkey = config.getValue("signingkey", String.class);
|
||||||
|
String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey);
|
||||||
|
RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey);
|
||||||
|
return new RSASSASigner(rsaKey.toRSAPrivateKey());
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String getAccessToken(String clientId, String subject, String approvedScope) throws Exception {
|
||||||
|
//4. Signing
|
||||||
|
JWSSigner jwsSigner = getJwsSigner();
|
||||||
|
|
||||||
|
Instant now = Instant.now();
|
||||||
|
//Long expiresInMin = 30L;
|
||||||
|
Date expirationTime = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES));
|
||||||
|
|
||||||
|
//3. JWT Payload or claims
|
||||||
|
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
|
||||||
|
.issuer("http://localhost:9080")
|
||||||
|
.subject(subject)
|
||||||
|
.claim("upn", subject)
|
||||||
|
.claim("client_id", clientId)
|
||||||
|
.audience("http://localhost:9280")
|
||||||
|
.claim("scope", approvedScope)
|
||||||
|
.claim("groups", Arrays.asList(approvedScope.split(" ")))
|
||||||
|
.expirationTime(expirationTime) // expires in 30 minutes
|
||||||
|
.notBeforeTime(Date.from(now))
|
||||||
|
.issueTime(Date.from(now))
|
||||||
|
.jwtID(UUID.randomUUID().toString())
|
||||||
|
.build();
|
||||||
|
SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims);
|
||||||
|
signedJWT.sign(jwsSigner);
|
||||||
|
return signedJWT.serialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String getRefreshToken(String clientId, String subject, String approvedScope) throws Exception {
|
||||||
|
JWSSigner jwsSigner = getJwsSigner();
|
||||||
|
Instant now = Instant.now();
|
||||||
|
//6.Build refresh token
|
||||||
|
JWTClaimsSet refreshTokenClaims = new JWTClaimsSet.Builder()
|
||||||
|
.subject(subject)
|
||||||
|
.claim("client_id", clientId)
|
||||||
|
.claim("scope", approvedScope)
|
||||||
|
//refresh token for 1 day.
|
||||||
|
.expirationTime(Date.from(now.plus(1, ChronoUnit.DAYS)))
|
||||||
|
.build();
|
||||||
|
SignedJWT signedRefreshToken = new SignedJWT(jwsHeader, refreshTokenClaims);
|
||||||
|
signedRefreshToken.sign(jwsSigner);
|
||||||
|
return signedRefreshToken.serialize();
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,18 +1,7 @@
|
||||||
package com.baeldung.oauth2.authorization.server.handler;
|
package com.baeldung.oauth2.authorization.server.handler;
|
||||||
|
|
||||||
import com.baeldung.oauth2.authorization.server.PEMKeyUtils;
|
|
||||||
import com.baeldung.oauth2.authorization.server.model.AuthorizationCode;
|
import com.baeldung.oauth2.authorization.server.model.AuthorizationCode;
|
||||||
import com.nimbusds.jose.JOSEObjectType;
|
|
||||||
import com.nimbusds.jose.JWSAlgorithm;
|
|
||||||
import com.nimbusds.jose.JWSHeader;
|
|
||||||
import com.nimbusds.jose.crypto.RSASSASigner;
|
|
||||||
import com.nimbusds.jose.jwk.JWK;
|
|
||||||
import com.nimbusds.jose.jwk.RSAKey;
|
|
||||||
import com.nimbusds.jwt.JWTClaimsSet;
|
|
||||||
import com.nimbusds.jwt.SignedJWT;
|
|
||||||
import org.eclipse.microprofile.config.Config;
|
|
||||||
|
|
||||||
import javax.inject.Inject;
|
|
||||||
import javax.inject.Named;
|
import javax.inject.Named;
|
||||||
import javax.json.Json;
|
import javax.json.Json;
|
||||||
import javax.json.JsonObject;
|
import javax.json.JsonObject;
|
||||||
|
@ -20,22 +9,14 @@ import javax.persistence.EntityManager;
|
||||||
import javax.persistence.PersistenceContext;
|
import javax.persistence.PersistenceContext;
|
||||||
import javax.ws.rs.WebApplicationException;
|
import javax.ws.rs.WebApplicationException;
|
||||||
import javax.ws.rs.core.MultivaluedMap;
|
import javax.ws.rs.core.MultivaluedMap;
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.temporal.ChronoUnit;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@Named("authorization_code")
|
@Named("authorization_code")
|
||||||
public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantTypeHandler {
|
public class AuthorizationCodeGrantTypeHandler extends AbstractGrantTypeHandler {
|
||||||
|
|
||||||
@PersistenceContext
|
@PersistenceContext
|
||||||
private EntityManager entityManager;
|
private EntityManager entityManager;
|
||||||
|
|
||||||
@Inject
|
|
||||||
private Config config;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
|
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
|
||||||
//1. code is required
|
//1. code is required
|
||||||
|
@ -58,42 +39,16 @@ public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantType
|
||||||
throw new WebApplicationException("invalid_grant");
|
throw new WebApplicationException("invalid_grant");
|
||||||
}
|
}
|
||||||
|
|
||||||
//JWT Header
|
|
||||||
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
|
|
||||||
|
|
||||||
Instant now = Instant.now();
|
|
||||||
Long expiresInMin = 30L;
|
|
||||||
Date expiresIn = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES));
|
|
||||||
|
|
||||||
//3. JWT Payload or claims
|
//3. JWT Payload or claims
|
||||||
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
|
String accessToken = getAccessToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
|
||||||
.issuer("http://localhost:9080")
|
String refreshToken = getRefreshToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
|
||||||
.subject(authorizationCode.getUserId())
|
|
||||||
.claim("upn", authorizationCode.getUserId())
|
|
||||||
.audience("http://localhost:9280")
|
|
||||||
.claim("scope", authorizationCode.getApprovedScopes())
|
|
||||||
.claim("groups", Arrays.asList(authorizationCode.getApprovedScopes().split(" ")))
|
|
||||||
.expirationTime(expiresIn) // expires in 30 minutes
|
|
||||||
.notBeforeTime(Date.from(now))
|
|
||||||
.issueTime(Date.from(now))
|
|
||||||
.jwtID(UUID.randomUUID().toString())
|
|
||||||
.build();
|
|
||||||
SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims);
|
|
||||||
|
|
||||||
//4. Signing
|
|
||||||
String signingkey = config.getValue("signingkey", String.class);
|
|
||||||
String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey);
|
|
||||||
RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey);
|
|
||||||
signedJWT.sign(new RSASSASigner(rsaKey.toRSAPrivateKey()));
|
|
||||||
|
|
||||||
//5. Finally the JWT access token
|
|
||||||
String accessToken = signedJWT.serialize();
|
|
||||||
|
|
||||||
return Json.createObjectBuilder()
|
return Json.createObjectBuilder()
|
||||||
.add("token_type", "Bearer")
|
.add("token_type", "Bearer")
|
||||||
.add("access_token", accessToken)
|
.add("access_token", accessToken)
|
||||||
.add("expires_in", expiresInMin * 60)
|
.add("expires_in", expiresInMin * 60)
|
||||||
.add("scope", authorizationCode.getApprovedScopes())
|
.add("scope", authorizationCode.getApprovedScopes())
|
||||||
|
.add("refresh_token", refreshToken)
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,72 @@
|
||||||
|
package com.baeldung.oauth2.authorization.server.handler;
|
||||||
|
|
||||||
|
import com.nimbusds.jose.JWSVerifier;
|
||||||
|
import com.nimbusds.jwt.SignedJWT;
|
||||||
|
|
||||||
|
import javax.inject.Named;
|
||||||
|
import javax.json.Json;
|
||||||
|
import javax.json.JsonObject;
|
||||||
|
import javax.ws.rs.WebApplicationException;
|
||||||
|
import javax.ws.rs.core.MultivaluedMap;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
@Named("refresh_token")
|
||||||
|
public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
|
||||||
|
String refreshToken = params.getFirst("refresh_token");
|
||||||
|
if (refreshToken == null || "".equals(refreshToken)) {
|
||||||
|
throw new WebApplicationException("invalid_grant");
|
||||||
|
}
|
||||||
|
|
||||||
|
//Decode refresh token
|
||||||
|
SignedJWT signedRefreshToken = SignedJWT.parse(refreshToken);
|
||||||
|
JWSVerifier verifier = getJWSVerifier();
|
||||||
|
|
||||||
|
if (!signedRefreshToken.verify(verifier)) {
|
||||||
|
throw new WebApplicationException("Invalid refresh token.");
|
||||||
|
}
|
||||||
|
if (!(new Date().before(signedRefreshToken.getJWTClaimsSet().getExpirationTime()))) {
|
||||||
|
throw new WebApplicationException("Refresh token expired.");
|
||||||
|
}
|
||||||
|
String refreshTokenClientId = signedRefreshToken.getJWTClaimsSet().getStringClaim("client_id");
|
||||||
|
if (!clientId.equals(refreshTokenClientId)) {
|
||||||
|
throw new WebApplicationException("Invalid client_id.");
|
||||||
|
}
|
||||||
|
|
||||||
|
//At this point, the refresh token is valid and not yet expired
|
||||||
|
//So create a new access token from it.
|
||||||
|
String subject = signedRefreshToken.getJWTClaimsSet().getSubject();
|
||||||
|
String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope");
|
||||||
|
|
||||||
|
String requestedScopes = params.getFirst("scope");
|
||||||
|
if (requestedScopes != null && !requestedScopes.isEmpty()) {
|
||||||
|
Set<String> rScopes = new HashSet(Arrays.asList(requestedScopes.split(" ")));
|
||||||
|
Set<String> aScopes = new HashSet(Arrays.asList(approvedScopes.split(" ")));
|
||||||
|
if (!aScopes.containsAll(rScopes)) {
|
||||||
|
JsonObject error = Json.createObjectBuilder()
|
||||||
|
.add("error", "Invalid_request")
|
||||||
|
.add("error_description", "Requested scopes should be a subset of the original scopes.")
|
||||||
|
.build();
|
||||||
|
Response response = Response.status(Response.Status.BAD_REQUEST).entity(error).build();
|
||||||
|
throw new WebApplicationException(response);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
requestedScopes = approvedScopes;
|
||||||
|
}
|
||||||
|
|
||||||
|
String accessToken = getAccessToken(clientId, subject, requestedScopes);
|
||||||
|
return Json.createObjectBuilder()
|
||||||
|
.add("token_type", "Bearer")
|
||||||
|
.add("access_token", accessToken)
|
||||||
|
.add("expires_in", expiresInMin * 60)
|
||||||
|
.add("scope", requestedScopes)
|
||||||
|
.add("refresh_token", refreshToken)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
|
@ -41,8 +41,8 @@
|
||||||
|
|
||||||
<tr>
|
<tr>
|
||||||
<td colspan="2">
|
<td colspan="2">
|
||||||
<input type="submit" name="approbation_status" value="YES"/>
|
<input type="submit" name="approval_status" value="YES"/>
|
||||||
<input type="submit" name="approbation_status" value="NO"/>
|
<input type="submit" name="approval_status" value="NO"/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
</table>
|
</table>
|
||||||
|
|
|
@ -0,0 +1,23 @@
|
||||||
|
package com.baeldung.oauth2.client;
|
||||||
|
|
||||||
|
import javax.servlet.RequestDispatcher;
|
||||||
|
import javax.servlet.ServletException;
|
||||||
|
import javax.servlet.http.HttpServlet;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
public abstract class AbstractServlet extends HttpServlet {
|
||||||
|
|
||||||
|
protected void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||||
|
RequestDispatcher requestDispatcher = request.getRequestDispatcher(location);
|
||||||
|
requestDispatcher.forward(request, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected String getAuthorizationHeaderValue(String clientId, String clientSecret) {
|
||||||
|
String token = clientId + ":" + clientSecret;
|
||||||
|
String encodedString = Base64.getEncoder().encodeToString(token.getBytes());
|
||||||
|
return "Basic " + encodedString;
|
||||||
|
}
|
||||||
|
}
|
|
@ -4,10 +4,8 @@ import org.eclipse.microprofile.config.Config;
|
||||||
|
|
||||||
import javax.inject.Inject;
|
import javax.inject.Inject;
|
||||||
import javax.json.JsonObject;
|
import javax.json.JsonObject;
|
||||||
import javax.servlet.RequestDispatcher;
|
|
||||||
import javax.servlet.ServletException;
|
import javax.servlet.ServletException;
|
||||||
import javax.servlet.annotation.WebServlet;
|
import javax.servlet.annotation.WebServlet;
|
||||||
import javax.servlet.http.HttpServlet;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import javax.ws.rs.client.Client;
|
import javax.ws.rs.client.Client;
|
||||||
|
@ -18,10 +16,9 @@ import javax.ws.rs.core.Form;
|
||||||
import javax.ws.rs.core.HttpHeaders;
|
import javax.ws.rs.core.HttpHeaders;
|
||||||
import javax.ws.rs.core.MediaType;
|
import javax.ws.rs.core.MediaType;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Base64;
|
|
||||||
|
|
||||||
@WebServlet(urlPatterns = "/callback")
|
@WebServlet(urlPatterns = "/callback")
|
||||||
public class CallbackServlet extends HttpServlet {
|
public class CallbackServlet extends AbstractServlet {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
private Config config;
|
private Config config;
|
||||||
|
@ -29,6 +26,9 @@ public class CallbackServlet extends HttpServlet {
|
||||||
@Override
|
@Override
|
||||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||||
|
|
||||||
|
String clientId = config.getValue("client.clientId", String.class);
|
||||||
|
String clientSecret = config.getValue("client.clientSecret", String.class);
|
||||||
|
|
||||||
//Error:
|
//Error:
|
||||||
String error = request.getParameter("error");
|
String error = request.getParameter("error");
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
|
@ -53,24 +53,15 @@ public class CallbackServlet extends HttpServlet {
|
||||||
form.param("code", code);
|
form.param("code", code);
|
||||||
form.param("redirect_uri", config.getValue("client.redirectUri", String.class));
|
form.param("redirect_uri", config.getValue("client.redirectUri", String.class));
|
||||||
|
|
||||||
|
try {
|
||||||
JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE)
|
JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE)
|
||||||
.header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue())
|
.header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret))
|
||||||
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class);
|
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class);
|
||||||
|
|
||||||
request.getSession().setAttribute("tokenResponse", tokenResponse);
|
request.getSession().setAttribute("tokenResponse", tokenResponse);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
System.out.println(ex.getMessage());
|
||||||
|
request.setAttribute("error", ex.getMessage());
|
||||||
|
}
|
||||||
dispatch("/", request, response);
|
dispatch("/", request, response);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
|
||||||
RequestDispatcher requestDispatcher = request.getRequestDispatcher(location);
|
|
||||||
requestDispatcher.forward(request, response);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getAuthorizationHeaderValue() {
|
|
||||||
String clientId = config.getValue("client.clientId", String.class);
|
|
||||||
String clientSecret = config.getValue("client.clientSecret", String.class);
|
|
||||||
String token = clientId + ":" + clientSecret;
|
|
||||||
String encodedString = Base64.getEncoder().encodeToString(token.getBytes());
|
|
||||||
return "Basic " + encodedString;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,57 @@
|
||||||
|
package com.baeldung.oauth2.client;
|
||||||
|
|
||||||
|
import org.eclipse.microprofile.config.Config;
|
||||||
|
|
||||||
|
import javax.inject.Inject;
|
||||||
|
import javax.json.JsonObject;
|
||||||
|
import javax.servlet.ServletException;
|
||||||
|
import javax.servlet.annotation.WebServlet;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import javax.ws.rs.client.Client;
|
||||||
|
import javax.ws.rs.client.ClientBuilder;
|
||||||
|
import javax.ws.rs.client.Entity;
|
||||||
|
import javax.ws.rs.client.WebTarget;
|
||||||
|
import javax.ws.rs.core.Form;
|
||||||
|
import javax.ws.rs.core.HttpHeaders;
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@WebServlet(urlPatterns = "/refreshtoken")
|
||||||
|
public class RefreshTokenServlet extends AbstractServlet {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
private Config config;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||||
|
|
||||||
|
String clientId = config.getValue("client.clientId", String.class);
|
||||||
|
String clientSecret = config.getValue("client.clientSecret", String.class);
|
||||||
|
|
||||||
|
JsonObject actualTokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse");
|
||||||
|
Client client = ClientBuilder.newClient();
|
||||||
|
WebTarget target = client.target(config.getValue("provider.tokenUri", String.class));
|
||||||
|
|
||||||
|
Form form = new Form();
|
||||||
|
form.param("grant_type", "refresh_token");
|
||||||
|
form.param("refresh_token", actualTokenResponse.getString("refresh_token"));
|
||||||
|
|
||||||
|
String scope = request.getParameter("scope");
|
||||||
|
if (scope != null && !scope.isEmpty()) {
|
||||||
|
form.param("scope", scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
Response jaxrsResponse = target.request(MediaType.APPLICATION_JSON_TYPE)
|
||||||
|
.header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret))
|
||||||
|
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class);
|
||||||
|
JsonObject tokenResponse = jaxrsResponse.readEntity(JsonObject.class);
|
||||||
|
if (jaxrsResponse.getStatus() == 200) {
|
||||||
|
request.getSession().setAttribute("tokenResponse", tokenResponse);
|
||||||
|
} else {
|
||||||
|
request.setAttribute("error", tokenResponse.getString("error_description", "error!"));
|
||||||
|
}
|
||||||
|
dispatch("/", request, response);
|
||||||
|
}
|
||||||
|
}
|
|
@ -10,6 +10,7 @@
|
||||||
body {
|
body {
|
||||||
margin: 0px;
|
margin: 0px;
|
||||||
}
|
}
|
||||||
|
|
||||||
input[type=text], input[type=password] {
|
input[type=text], input[type=password] {
|
||||||
width: 75%;
|
width: 75%;
|
||||||
padding: 4px 0px;
|
padding: 4px 0px;
|
||||||
|
@ -17,6 +18,7 @@
|
||||||
border: 1px solid #502bcc;
|
border: 1px solid #502bcc;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
.container-error {
|
.container-error {
|
||||||
padding: 16px;
|
padding: 16px;
|
||||||
border: 1px solid #cc102a;
|
border: 1px solid #cc102a;
|
||||||
|
@ -25,6 +27,7 @@
|
||||||
margin-left: 25px;
|
margin-left: 25px;
|
||||||
margin-bottom: 25px;
|
margin-bottom: 25px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.container {
|
.container {
|
||||||
padding: 16px;
|
padding: 16px;
|
||||||
border: 1px solid #130ecc;
|
border: 1px solid #130ecc;
|
||||||
|
@ -81,8 +84,20 @@
|
||||||
<li>access_token: ${tokenResponse.getString("access_token")}</li>
|
<li>access_token: ${tokenResponse.getString("access_token")}</li>
|
||||||
<li>scope: ${tokenResponse.getString("scope")}</li>
|
<li>scope: ${tokenResponse.getString("scope")}</li>
|
||||||
<li>Expires in (s): ${tokenResponse.getInt("expires_in")}</li>
|
<li>Expires in (s): ${tokenResponse.getInt("expires_in")}</li>
|
||||||
|
<li>refresh_token: ${tokenResponse.getString("refresh_token")}</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="container">
|
||||||
|
<span><h4>Refresh Token</h4></span>
|
||||||
|
<hr>
|
||||||
|
<ul>
|
||||||
|
<li><a href="refreshtoken">Refresh token (original scope)</a></li>
|
||||||
|
<li><a href="refreshtoken?scope=resource.read">Refresh token (scope: resource.read)</a></li>
|
||||||
|
<li><a href="refreshtoken?scope=resource.write">Refresh token (scope: resource.write)</a></li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<span><h4>OAuth2 Resource Server Call</h4></span>
|
<span><h4>OAuth2 Resource Server Call</h4></span>
|
||||||
<hr>
|
<hr>
|
||||||
|
@ -90,7 +105,6 @@
|
||||||
<li><a href="downstream?action=read">Read Protected Resource</a></li>
|
<li><a href="downstream?action=read">Read Protected Resource</a></li>
|
||||||
<li><a href="downstream?action=write">Write Protected Resource</a></li>
|
<li><a href="downstream?action=write">Write Protected Resource</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
|
|
|
@ -1 +0,0 @@
|
||||||
This is a parent module for projects that want to take advantage of the latest Spring Boot improvements/features.
|
|
|
@ -1,92 +0,0 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<artifactId>parent-boot-performance</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>parent-boot-performance</name>
|
|
||||||
<packaging>pom</packaging>
|
|
||||||
<description>Parent for all modules that want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2</description>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencyManagement>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-dependencies</artifactId>
|
|
||||||
<version>${spring-boot.version}</version>
|
|
||||||
<type>pom</type>
|
|
||||||
<scope>import</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
</dependencyManagement>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>io.rest-assured</groupId>
|
|
||||||
<artifactId>rest-assured</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<pluginManagement>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
<version>${spring-boot.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<mainClass>${start-class}</mainClass>
|
|
||||||
<!-- this is necessary as we're not using the Boot parent -->
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</pluginManagement>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<repositories>
|
|
||||||
<repository>
|
|
||||||
<id>spring-milestones</id>
|
|
||||||
<name>Spring Milestones</name>
|
|
||||||
<url>https://repo.spring.io/milestone</url>
|
|
||||||
</repository>
|
|
||||||
</repositories>
|
|
||||||
|
|
||||||
<profiles>
|
|
||||||
<profile>
|
|
||||||
<id>thin-jar</id>
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
<dependencies>
|
|
||||||
<!-- The following enables the "thin jar" deployment option. -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot.experimental</groupId>
|
|
||||||
<artifactId>spring-boot-thin-layout</artifactId>
|
|
||||||
<version>${thin.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
</profile>
|
|
||||||
</profiles>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<rest-assured.version>3.1.0</rest-assured.version>
|
|
||||||
<!-- plugins -->
|
|
||||||
<thin.version>1.0.21.RELEASE</thin.version>
|
|
||||||
<spring-boot.version>2.2.0.M3</spring-boot.version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue