commit
15cbaa9bdb
|
@ -19,6 +19,7 @@
|
|||
.idea/
|
||||
*.iml
|
||||
*.iws
|
||||
out/
|
||||
|
||||
# Mac
|
||||
.DS_Store
|
||||
|
@ -27,6 +28,9 @@
|
|||
log/
|
||||
target/
|
||||
|
||||
# Gradle
|
||||
.gradle/
|
||||
|
||||
spring-openid/src/main/resources/application.properties
|
||||
.recommenders/
|
||||
/spring-hibernate4/nbproject/
|
||||
|
|
|
@ -14,18 +14,19 @@
|
|||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-stream_2.11</artifactId>
|
||||
<artifactId>akka-stream_${scala.version}</artifactId>
|
||||
<version>${akkastreams.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-stream-testkit_2.11</artifactId>
|
||||
<artifactId>akka-stream-testkit_${scala.version}</artifactId>
|
||||
<version>${akkastreams.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<akkastreams.version>2.5.2</akkastreams.version>
|
||||
<scala.version>2.11</scala.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -14,6 +14,5 @@
|
|||
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
|
||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||
- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm)
|
||||
|
|
|
@ -8,9 +8,6 @@
|
|||
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
|
||||
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
|
||||
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
|
||||
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
|
||||
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
||||
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
|
||||
|
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.algorithms.relativelyprime;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
class RelativelyPrime {
|
||||
|
||||
static boolean iterativeRelativelyPrime(int a, int b) {
|
||||
return iterativeGCD(a, b) == 1;
|
||||
}
|
||||
|
||||
static boolean recursiveRelativelyPrime(int a, int b) {
|
||||
return recursiveGCD(a, b) == 1;
|
||||
}
|
||||
|
||||
static boolean bigIntegerRelativelyPrime(int a, int b) {
|
||||
return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).equals(BigInteger.ONE);
|
||||
}
|
||||
|
||||
private static int iterativeGCD(int a, int b) {
|
||||
int tmp;
|
||||
while (b != 0) {
|
||||
if (a < b) {
|
||||
tmp = a;
|
||||
a = b;
|
||||
b = tmp;
|
||||
}
|
||||
tmp = b;
|
||||
b = a % b;
|
||||
a = tmp;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
private static int recursiveGCD(int a, int b) {
|
||||
if (b == 0) {
|
||||
return a;
|
||||
}
|
||||
if (a < b) {
|
||||
return recursiveGCD(b, a);
|
||||
}
|
||||
return recursiveGCD(b, a % b);
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.algorithms.reversingtree;
|
||||
|
||||
public class TreeNode {
|
||||
|
||||
private int value;
|
||||
private TreeNode rightChild;
|
||||
private TreeNode leftChild;
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public TreeNode getRightChild() {
|
||||
return rightChild;
|
||||
}
|
||||
|
||||
public void setRightChild(TreeNode rightChild) {
|
||||
this.rightChild = rightChild;
|
||||
}
|
||||
|
||||
public TreeNode getLeftChild() {
|
||||
return leftChild;
|
||||
}
|
||||
|
||||
public void setLeftChild(TreeNode leftChild) {
|
||||
this.leftChild = leftChild;
|
||||
}
|
||||
|
||||
public TreeNode(int value, TreeNode leftChild, TreeNode rightChild) {
|
||||
this.value = value;
|
||||
this.rightChild = rightChild;
|
||||
this.leftChild = leftChild;
|
||||
}
|
||||
|
||||
public TreeNode(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.algorithms.reversingtree;
|
||||
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class TreeReverser {
|
||||
|
||||
public void reverseRecursive(TreeNode treeNode) {
|
||||
if (treeNode == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
TreeNode temp = treeNode.getLeftChild();
|
||||
treeNode.setLeftChild(treeNode.getRightChild());
|
||||
treeNode.setRightChild(temp);
|
||||
|
||||
reverseRecursive(treeNode.getLeftChild());
|
||||
reverseRecursive(treeNode.getRightChild());
|
||||
}
|
||||
|
||||
public void reverseIterative(TreeNode treeNode) {
|
||||
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
|
||||
|
||||
if (treeNode != null) {
|
||||
queue.add(treeNode);
|
||||
}
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
|
||||
TreeNode node = queue.poll();
|
||||
if (node.getLeftChild() != null)
|
||||
queue.add(node.getLeftChild());
|
||||
if (node.getRightChild() != null)
|
||||
queue.add(node.getRightChild());
|
||||
|
||||
TreeNode temp = node.getLeftChild();
|
||||
node.setLeftChild(node.getRightChild());
|
||||
node.setRightChild(temp);
|
||||
}
|
||||
}
|
||||
|
||||
public String toString(TreeNode root) {
|
||||
if (root == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
StringBuffer buffer = new StringBuffer(String.valueOf(root.getValue())).append(" ");
|
||||
|
||||
buffer.append(toString(root.getLeftChild()));
|
||||
buffer.append(toString(root.getRightChild()));
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.algorithms.relativelyprime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.baeldung.algorithms.relativelyprime.RelativelyPrime.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class RelativelyPrimeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNonRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnFalse() {
|
||||
|
||||
boolean result = iterativeRelativelyPrime(45, 35);
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnTrue() {
|
||||
|
||||
boolean result = iterativeRelativelyPrime(500, 501);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnFalse() {
|
||||
|
||||
boolean result = recursiveRelativelyPrime(45, 35);
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnTrue() {
|
||||
|
||||
boolean result = recursiveRelativelyPrime(500, 501);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonRelativelyPrimeNumbers_whenCheckingUsingBigIntegers_shouldReturnFalse() {
|
||||
|
||||
boolean result = bigIntegerRelativelyPrime(45, 35);
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRelativelyPrimeNumbers_whenCheckingBigIntegers_shouldReturnTrue() {
|
||||
|
||||
boolean result = bigIntegerRelativelyPrime(500, 501);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.algorithms.reversingtree;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TreeReverserUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTreeWhenReversingRecursivelyThenReversed() {
|
||||
TreeReverser reverser = new TreeReverser();
|
||||
|
||||
TreeNode treeNode = createBinaryTree();
|
||||
|
||||
reverser.reverseRecursive(treeNode);
|
||||
|
||||
assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
|
||||
.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeWhenReversingIterativelyThenReversed() {
|
||||
TreeReverser reverser = new TreeReverser();
|
||||
|
||||
TreeNode treeNode = createBinaryTree();
|
||||
|
||||
reverser.reverseIterative(treeNode);
|
||||
|
||||
assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
|
||||
.trim());
|
||||
}
|
||||
|
||||
private TreeNode createBinaryTree() {
|
||||
|
||||
TreeNode leaf1 = new TreeNode(1);
|
||||
TreeNode leaf2 = new TreeNode(3);
|
||||
TreeNode leaf3 = new TreeNode(6);
|
||||
TreeNode leaf4 = new TreeNode(9);
|
||||
|
||||
TreeNode nodeRight = new TreeNode(7, leaf3, leaf4);
|
||||
TreeNode nodeLeft = new TreeNode(2, leaf1, leaf2);
|
||||
|
||||
TreeNode root = new TreeNode(4, nodeLeft, nodeRight);
|
||||
|
||||
return root;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
/target/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
|
@ -0,0 +1,7 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
||||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
|
|
@ -0,0 +1,39 @@
|
|||
<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>algorithms-miscellaneous-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-miscellaneous-3</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -10,6 +10,14 @@
|
|||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.antlr</groupId>
|
||||
<artifactId>antlr4-runtime</artifactId>
|
||||
<version>${antlr.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -44,13 +52,7 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.antlr</groupId>
|
||||
<artifactId>antlr4-runtime</artifactId>
|
||||
<version>${antlr.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<antlr.version>4.7.1</antlr.version>
|
||||
<mojo.version>3.0.0</mojo.version>
|
||||
|
|
|
@ -12,9 +12,18 @@
|
|||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<cxf-version>3.2.0</cxf-version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-client</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-sse</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
|
@ -45,17 +54,8 @@
|
|||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-client</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-sse</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<cxf-version>3.2.0</cxf-version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -13,11 +13,28 @@
|
|||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
<openliberty-version>18.0.0.2</openliberty-version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
<version>2.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.json.bind</groupId>
|
||||
<artifactId>javax.json.bind-api</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
|
@ -59,27 +76,10 @@
|
|||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
<version>2.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.json.bind</groupId>
|
||||
<artifactId>javax.json.bind-api</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<properties>
|
||||
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
<openliberty-version>18.0.0.2</openliberty-version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -3,7 +3,3 @@
|
|||
## Core Java Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
|
||||
- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file)
|
||||
- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
|
||||
|
||||
|
|
|
@ -6,6 +6,12 @@
|
|||
<version>0.0.1</version>
|
||||
<name>apache-meecrowave</name>
|
||||
<description>A sample REST API application with Meecrowave</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-core -->
|
||||
|
|
|
@ -17,7 +17,7 @@ import okhttp3.Request;
|
|||
import okhttp3.Response;
|
||||
|
||||
@RunWith(MonoMeecrowave.Runner.class)
|
||||
public class ArticleEndpointsTest {
|
||||
public class ArticleEndpointsUnitTest {
|
||||
|
||||
@ConfigurationInject
|
||||
private Meecrowave.Builder config;
|
|
@ -1,8 +1,9 @@
|
|||
package com.baeldung.autofactory.provided;
|
||||
|
||||
import com.baeldung.autofactory.model.Camera;
|
||||
import com.google.auto.factory.AutoFactory;
|
||||
import com.google.auto.factory.Provided;
|
||||
import javafx.scene.Camera;
|
||||
|
||||
|
||||
import javax.inject.Provider;
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Deploy Spring Boot App to Azure](http://www.baeldung.com/spring-boot-azure)
|
||||
- [Deploy a Spring Boot App to Azure](http://www.baeldung.com/spring-boot-azure)
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Blade - A Complete GuideBook](http://www.baeldung.com/blade)
|
||||
- [Blade – A Complete Guidebook](http://www.baeldung.com/blade)
|
||||
|
||||
Run Integration Tests with `mvn integration-test`
|
||||
Run Integration Tests with `mvn integration-test`
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
### Revelant Articles
|
||||
|
||||
- [A Quick Guide To Using Cloud Foundry UAA](https://www.baeldung.com/cloud-foundry-uaa)
|
|
@ -0,0 +1,68 @@
|
|||
issuer:
|
||||
uri: http://localhost:8080/uaa
|
||||
|
||||
spring_profiles: default,hsqldb
|
||||
|
||||
encryption:
|
||||
active_key_label: CHANGE-THIS-KEY
|
||||
encryption_keys:
|
||||
- label: CHANGE-THIS-KEY
|
||||
passphrase: CHANGEME
|
||||
|
||||
login:
|
||||
serviceProviderKey: |
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIICXQIBAAKBgQDHtC5gUXxBKpEqZTLkNvFwNGnNIkggNOwOQVNbpO0WVHIivig5
|
||||
L39WqS9u0hnA+O7MCA/KlrAR4bXaeVVhwfUPYBKIpaaTWFQR5cTR1UFZJL/OF9vA
|
||||
fpOwznoD66DDCnQVpbCjtDYWX+x6imxn8HCYxhMol6ZnTbSsFW6VZjFMjQIDAQAB
|
||||
AoGAVOj2Yvuigi6wJD99AO2fgF64sYCm/BKkX3dFEw0vxTPIh58kiRP554Xt5ges
|
||||
7ZCqL9QpqrChUikO4kJ+nB8Uq2AvaZHbpCEUmbip06IlgdA440o0r0CPo1mgNxGu
|
||||
lhiWRN43Lruzfh9qKPhleg2dvyFGQxy5Gk6KW/t8IS4x4r0CQQD/dceBA+Ndj3Xp
|
||||
ubHfxqNz4GTOxndc/AXAowPGpge2zpgIc7f50t8OHhG6XhsfJ0wyQEEvodDhZPYX
|
||||
kKBnXNHzAkEAyCA76vAwuxqAd3MObhiebniAU3SnPf2u4fdL1EOm92dyFs1JxyyL
|
||||
gu/DsjPjx6tRtn4YAalxCzmAMXFSb1qHfwJBAM3qx3z0gGKbUEWtPHcP7BNsrnWK
|
||||
vw6By7VC8bk/ffpaP2yYspS66Le9fzbFwoDzMVVUO/dELVZyBnhqSRHoXQcCQQCe
|
||||
A2WL8S5o7Vn19rC0GVgu3ZJlUrwiZEVLQdlrticFPXaFrn3Md82ICww3jmURaKHS
|
||||
N+l4lnMda79eSp3OMmq9AkA0p79BvYsLshUJJnvbk76pCjR28PK4dV1gSDUEqQMB
|
||||
qy45ptdwJLqLJCeNoR0JUcDNIRhOCuOPND7pcMtX6hI/
|
||||
-----END RSA PRIVATE KEY-----
|
||||
serviceProviderKeyPassword: password
|
||||
serviceProviderCertificate: |
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDSTCCArKgAwIBAgIBADANBgkqhkiG9w0BAQQFADB8MQswCQYDVQQGEwJhdzEO
|
||||
MAwGA1UECBMFYXJ1YmExDjAMBgNVBAoTBWFydWJhMQ4wDAYDVQQHEwVhcnViYTEO
|
||||
MAwGA1UECxMFYXJ1YmExDjAMBgNVBAMTBWFydWJhMR0wGwYJKoZIhvcNAQkBFg5h
|
||||
cnViYUBhcnViYS5hcjAeFw0xNTExMjAyMjI2MjdaFw0xNjExMTkyMjI2MjdaMHwx
|
||||
CzAJBgNVBAYTAmF3MQ4wDAYDVQQIEwVhcnViYTEOMAwGA1UEChMFYXJ1YmExDjAM
|
||||
BgNVBAcTBWFydWJhMQ4wDAYDVQQLEwVhcnViYTEOMAwGA1UEAxMFYXJ1YmExHTAb
|
||||
BgkqhkiG9w0BCQEWDmFydWJhQGFydWJhLmFyMIGfMA0GCSqGSIb3DQEBAQUAA4GN
|
||||
ADCBiQKBgQDHtC5gUXxBKpEqZTLkNvFwNGnNIkggNOwOQVNbpO0WVHIivig5L39W
|
||||
qS9u0hnA+O7MCA/KlrAR4bXaeVVhwfUPYBKIpaaTWFQR5cTR1UFZJL/OF9vAfpOw
|
||||
znoD66DDCnQVpbCjtDYWX+x6imxn8HCYxhMol6ZnTbSsFW6VZjFMjQIDAQABo4Ha
|
||||
MIHXMB0GA1UdDgQWBBTx0lDzjH/iOBnOSQaSEWQLx1syGDCBpwYDVR0jBIGfMIGc
|
||||
gBTx0lDzjH/iOBnOSQaSEWQLx1syGKGBgKR+MHwxCzAJBgNVBAYTAmF3MQ4wDAYD
|
||||
VQQIEwVhcnViYTEOMAwGA1UEChMFYXJ1YmExDjAMBgNVBAcTBWFydWJhMQ4wDAYD
|
||||
VQQLEwVhcnViYTEOMAwGA1UEAxMFYXJ1YmExHTAbBgkqhkiG9w0BCQEWDmFydWJh
|
||||
QGFydWJhLmFyggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAYvBJ
|
||||
0HOZbbHClXmGUjGs+GS+xC1FO/am2suCSYqNB9dyMXfOWiJ1+TLJk+o/YZt8vuxC
|
||||
KdcZYgl4l/L6PxJ982SRhc83ZW2dkAZI4M0/Ud3oePe84k8jm3A7EvH5wi5hvCkK
|
||||
RpuRBwn3Ei+jCRouxTbzKPsuCVB+1sNyxMTXzf0=
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
#The secret that an external login server will use to authenticate to the uaa using the id `login`
|
||||
LOGIN_SECRET: loginsecret
|
||||
|
||||
jwt:
|
||||
token:
|
||||
signing-key: |
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpAIBAAKCAQEAqUeygEfDGxI6c1VDQ6xIyUSLrP6iz1y97iHFbtXSxXaArL4a
|
||||
...
|
||||
v6Mtt5LcRAAVP7pemunTdju4h8Q/noKYlVDVL30uLYUfKBL4UKfOBw==
|
||||
-----END RSA PRIVATE KEY-----
|
||||
verification-key: |
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqUeygEfDGxI6c1VDQ6xI
|
||||
...
|
||||
AwIDAQAB
|
||||
-----END PUBLIC KEY-----
|
|
@ -0,0 +1,41 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>cf-uaa-oauth2-client</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>uaa-client-webapp</name>
|
||||
<description>Demo project for Spring Boot</description>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-client</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.cfuaa.oauth2.client;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class CFUAAOAuth2ClientApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CFUAAOAuth2ClientApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package com.baeldung.cfuaa.oauth2.client;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
|
||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
|
||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@RestController
|
||||
public class CFUAAOAuth2ClientController {
|
||||
|
||||
@Value("${resource.server.url}")
|
||||
private String remoteResourceServer;
|
||||
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
private OAuth2AuthorizedClientService authorizedClientService;
|
||||
|
||||
public CFUAAOAuth2ClientController(OAuth2AuthorizedClientService authorizedClientService) {
|
||||
this.authorizedClientService = authorizedClientService;
|
||||
this.restTemplate = new RestTemplate();
|
||||
}
|
||||
|
||||
@RequestMapping("/")
|
||||
public String index(OAuth2AuthenticationToken authenticationToken) {
|
||||
OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
|
||||
OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();
|
||||
|
||||
String response = "Hello, " + authenticationToken.getPrincipal().getName();
|
||||
response += "</br></br>";
|
||||
response += "Here is your accees token :</br>" + oAuth2AccessToken.getTokenValue();
|
||||
response += "</br>";
|
||||
response += "</br>You can use it to call these Resource Server APIs:";
|
||||
response += "</br></br>";
|
||||
response += "<a href='/read'>Call Resource Server Read API</a>";
|
||||
response += "</br>";
|
||||
response += "<a href='/write'>Call Resource Server Write API</a>";
|
||||
return response;
|
||||
}
|
||||
|
||||
@RequestMapping("/read")
|
||||
public String read(OAuth2AuthenticationToken authenticationToken) {
|
||||
String url = remoteResourceServer + "/read";
|
||||
return callResourceServer(authenticationToken, url);
|
||||
}
|
||||
|
||||
@RequestMapping("/write")
|
||||
public String write(OAuth2AuthenticationToken authenticationToken) {
|
||||
String url = remoteResourceServer + "/write";
|
||||
return callResourceServer(authenticationToken, url);
|
||||
}
|
||||
|
||||
private String callResourceServer(OAuth2AuthenticationToken authenticationToken, String url) {
|
||||
OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
|
||||
OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("Authorization", "Bearer " + oAuth2AccessToken.getTokenValue());
|
||||
|
||||
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
|
||||
ResponseEntity<String> responseEntity = null;
|
||||
|
||||
String response = null;
|
||||
try {
|
||||
responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
|
||||
response = responseEntity.getBody();
|
||||
} catch (HttpClientErrorException e) {
|
||||
response = e.getMessage();
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
server.port=8081
|
||||
|
||||
resource.server.url=http://localhost:8082
|
||||
|
||||
spring.security.oauth2.client.registration.uaa.client-name=Web App Client
|
||||
spring.security.oauth2.client.registration.uaa.client-id=webappclient
|
||||
spring.security.oauth2.client.registration.uaa.client-secret=webappclientsecret
|
||||
spring.security.oauth2.client.registration.uaa.scope=resource.read,resource.write,openid,profile
|
||||
|
||||
spring.security.oauth2.client.provider.uaa.issuer-uri=http://localhost:8080/uaa/oauth/token
|
||||
|
|
@ -0,0 +1 @@
|
|||
tintin
|
|
@ -0,0 +1,42 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.cfuaa</groupId>
|
||||
<artifactId>cf-uaa-oauth2-resource-server</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>cf-uaa-oauth2-resource-server</name>
|
||||
<description>Demo project for Spring Boot</description>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.cfuaa.oauth2.resourceserver;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class CFUAAOAuth2ResourceServerApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CFUAAOAuth2ResourceServerApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.cfuaa.oauth2.resourceserver;
|
||||
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
@RestController
|
||||
public class CFUAAOAuth2ResourceServerRestController {
|
||||
|
||||
@GetMapping("/")
|
||||
public String index(@AuthenticationPrincipal Jwt jwt) {
|
||||
return String.format("Hello, %s!", jwt.getSubject());
|
||||
}
|
||||
|
||||
@GetMapping("/read")
|
||||
public String read(JwtAuthenticationToken jwtAuthenticationToken) {
|
||||
return "Hello write: " + jwtAuthenticationToken.getTokenAttributes();
|
||||
}
|
||||
|
||||
@GetMapping("/write")
|
||||
public String write(Principal principal) {
|
||||
return "Hello write: " + principal.getName();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.cfuaa.oauth2.resourceserver;
|
||||
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@EnableWebSecurity
|
||||
public class CFUAAOAuth2ResourceServerSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.antMatchers("/read/**").hasAuthority("SCOPE_resource.read")
|
||||
.antMatchers("/write/**").hasAuthority("SCOPE_resource.write")
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.oauth2ResourceServer()
|
||||
.jwt();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
server.port=8082
|
||||
|
||||
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/uaa/oauth/token
|
|
@ -0,0 +1,7 @@
|
|||
# Groovy
|
||||
|
||||
## Relevant articles:
|
||||
|
||||
- [String Matching in Groovy](http://www.baeldung.com/)
|
||||
- [Groovy def Keyword]
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-groovy-2</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>${groovy-all.version}</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-dateutil</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-sql</artifactId>
|
||||
<version>${groovy-sql.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>${hsqldb.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.spockframework</groupId>
|
||||
<artifactId>spock-core</artifactId>
|
||||
<version>${spock-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmavenplus</groupId>
|
||||
<artifactId>gmavenplus-plugin</artifactId>
|
||||
<version>${gmavenplus-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>addSources</goal>
|
||||
<goal>addTestSources</goal>
|
||||
<goal>compile</goal>
|
||||
<goal>compileTests</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>${maven-failsafe-plugin.version}</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>junit5</id>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*Test5.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.20.1</version>
|
||||
<configuration>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
<include>**/*Spec.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
<url>http://jcenter.bintray.com</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<groovy.version>2.5.6</groovy.version>
|
||||
<groovy-all.version>2.5.6</groovy-all.version>
|
||||
<groovy-sql.version>2.5.6</groovy-sql.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
package com.baeldung.defkeyword
|
||||
|
||||
import org.codehaus.groovy.runtime.NullObject
|
||||
import org.codehaus.groovy.runtime.typehandling.GroovyCastException
|
||||
|
||||
import groovy.transform.TypeChecked
|
||||
import groovy.transform.TypeCheckingMode
|
||||
|
||||
@TypeChecked
|
||||
class DefUnitTest extends GroovyTestCase {
|
||||
|
||||
def id
|
||||
def firstName = "Samwell"
|
||||
def listOfCountries = ['USA', 'UK', 'FRANCE', 'INDIA']
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
def multiply(x, y) {
|
||||
return x*y
|
||||
}
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
void testDefVariableDeclaration() {
|
||||
|
||||
def list
|
||||
assert list.getClass() == org.codehaus.groovy.runtime.NullObject
|
||||
assert list.is(null)
|
||||
|
||||
list = [1,2,4]
|
||||
assert list instanceof ArrayList
|
||||
}
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
void testTypeVariables() {
|
||||
int rate = 200
|
||||
try {
|
||||
rate = [12] //GroovyCastException
|
||||
rate = "nill" //GroovyCastException
|
||||
} catch(GroovyCastException) {
|
||||
println "Cannot assign anything other than integer"
|
||||
}
|
||||
}
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
void testDefVariableMultipleAssignment() {
|
||||
def rate
|
||||
assert rate == null
|
||||
assert rate.getClass() == org.codehaus.groovy.runtime.NullObject
|
||||
|
||||
rate = 12
|
||||
assert rate instanceof Integer
|
||||
|
||||
rate = "Not Available"
|
||||
assert rate instanceof String
|
||||
|
||||
rate = [1, 4]
|
||||
assert rate instanceof List
|
||||
|
||||
assert divide(12, 3) instanceof BigDecimal
|
||||
assert divide(1, 0) instanceof String
|
||||
|
||||
}
|
||||
|
||||
def divide(int x, int y) {
|
||||
if(y==0) {
|
||||
return "Should not divide by 0"
|
||||
} else {
|
||||
return x/y
|
||||
}
|
||||
}
|
||||
|
||||
def greetMsg() {
|
||||
println "Hello! I am Groovy"
|
||||
}
|
||||
|
||||
void testDefVsType() {
|
||||
def int count
|
||||
assert count instanceof Integer
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.strings
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
import java.util.regex.Pattern
|
||||
|
||||
class StringMatchingSpec extends Specification {
|
||||
|
||||
def "pattern operator example"() {
|
||||
given: "a pattern"
|
||||
def p = ~'foo'
|
||||
|
||||
expect:
|
||||
p instanceof Pattern
|
||||
|
||||
and: "you can use slash strings to avoid escaping of blackslash"
|
||||
def digitPattern = ~/\d*/
|
||||
digitPattern.matcher('4711').matches()
|
||||
}
|
||||
|
||||
def "match operator example"() {
|
||||
expect:
|
||||
'foobar' ==~ /.*oba.*/
|
||||
|
||||
and: "matching is strict"
|
||||
!('foobar' ==~ /foo/)
|
||||
}
|
||||
|
||||
def "find operator example"() {
|
||||
when: "using the find operator"
|
||||
def matcher = 'foo and bar, baz and buz' =~ /(\w+) and (\w+)/
|
||||
|
||||
then: "will find groups"
|
||||
matcher.size() == 2
|
||||
|
||||
and: "can access groups using array"
|
||||
matcher[0][0] == 'foo and bar'
|
||||
matcher[1][2] == 'buz'
|
||||
|
||||
and: "you can use it as a predicate"
|
||||
'foobarbaz' =~ /bar/
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
# Groovy
|
||||
|
||||
## Relevant articles:
|
||||
|
||||
- [Maps in Groovy](http://www.baeldung.com/)
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-groovy-collections</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy-collections</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>${groovy-all.version}</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-dateutil</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-sql</artifactId>
|
||||
<version>${groovy-sql.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>${hsqldb.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.spockframework</groupId>
|
||||
<artifactId>spock-core</artifactId>
|
||||
<version>${spock-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmavenplus</groupId>
|
||||
<artifactId>gmavenplus-plugin</artifactId>
|
||||
<version>${gmavenplus-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>addSources</goal>
|
||||
<goal>addTestSources</goal>
|
||||
<goal>compile</goal>
|
||||
<goal>compileTests</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>${maven-failsafe-plugin.version}</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>junit5</id>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*Test5.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.20.1</version>
|
||||
<configuration>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
<include>**/*Spec.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
<url>http://jcenter.bintray.com</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<groovy.version>2.5.6</groovy.version>
|
||||
<groovy-all.version>2.5.6</groovy-all.version>
|
||||
<groovy-sql.version>2.5.6</groovy-sql.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
package com.baeldung.map;
|
||||
|
||||
import static groovy.test.GroovyAssert.*
|
||||
import org.junit.Test
|
||||
|
||||
class MapTest{
|
||||
|
||||
@Test
|
||||
void createMap() {
|
||||
|
||||
def emptyMap = [:]
|
||||
assertNotNull(emptyMap)
|
||||
|
||||
assertTrue(emptyMap instanceof java.util.LinkedHashMap)
|
||||
|
||||
def map = [name:"Jerry", age: 42, city: "New York"]
|
||||
assertTrue(map.size() == 3)
|
||||
}
|
||||
|
||||
@Test
|
||||
void addItemsToMap() {
|
||||
|
||||
def map = [name:"Jerry"]
|
||||
|
||||
map["age"] = 42
|
||||
|
||||
map.city = "New York"
|
||||
|
||||
def hobbyLiteral = "hobby"
|
||||
def hobbyMap = [(hobbyLiteral): "Singing"]
|
||||
map.putAll(hobbyMap)
|
||||
|
||||
assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"])
|
||||
assertTrue(hobbyMap.hobby == "Singing")
|
||||
assertTrue(hobbyMap[hobbyLiteral] == "Singing")
|
||||
|
||||
map.plus([1:20]) // returns new map
|
||||
|
||||
map << [2:30]
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void getItemsFromMap() {
|
||||
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
assertTrue(map["name"] == "Jerry")
|
||||
|
||||
assertTrue(map.name == "Jerry")
|
||||
|
||||
def propertyAge = "age"
|
||||
assertTrue(map[propertyAge] == 42)
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeItemsFromMap() {
|
||||
|
||||
def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49]
|
||||
|
||||
def minusMap = map.minus([2:42, 4:34]);
|
||||
assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49])
|
||||
|
||||
minusMap.removeAll{it -> it.key instanceof String}
|
||||
assertTrue( minusMap == [ 1:20, 6:39, 7:49])
|
||||
|
||||
minusMap.retainAll{it -> it.value %2 == 0}
|
||||
assertTrue( minusMap == [1:20])
|
||||
}
|
||||
|
||||
@Test
|
||||
void iteratingOnMaps(){
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
map.each{ entry -> println "$entry.key: $entry.value" }
|
||||
|
||||
map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" }
|
||||
|
||||
map.eachWithIndex{ key, value, i -> println "$i $key: $value" }
|
||||
}
|
||||
|
||||
@Test
|
||||
void filteringAndSearchingMaps(){
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
assertTrue(map.find{ it.value == "New York"}.key == "city")
|
||||
|
||||
assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"])
|
||||
|
||||
map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")}
|
||||
|
||||
assertTrue(map.every{it -> it.value instanceof String} == false)
|
||||
|
||||
assertTrue(map.any{it -> it.value instanceof String} == true)
|
||||
}
|
||||
|
||||
@Test
|
||||
void collect(){
|
||||
|
||||
def map = [1: [name:"Jerry", age: 42, city: "New York"],
|
||||
2: [name:"Long", age: 25, city: "New York"],
|
||||
3: [name:"Dustin", age: 29, city: "New York"],
|
||||
4: [name:"Dustin", age: 34, city: "New York"]]
|
||||
|
||||
def names = map.collect{entry -> entry.value.name} // returns only list
|
||||
assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"])
|
||||
|
||||
def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name}
|
||||
assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set)
|
||||
|
||||
def idNames = map.collectEntries{key, value -> [key, value.name]}
|
||||
assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"])
|
||||
|
||||
def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name}
|
||||
assertTrue(below30Names == ["Long", "Dustin"])
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void group(){
|
||||
def map = [1:20, 2: 40, 3: 11, 4: 93]
|
||||
|
||||
def subMap = map.groupBy{it.value % 2}
|
||||
println subMap
|
||||
assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]])
|
||||
|
||||
def keySubMap = map.subMap([1, 2])
|
||||
assertTrue(keySubMap == [1:20, 2:40])
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void sorting(){
|
||||
def map = [ab:20, a: 40, cb: 11, ba: 93]
|
||||
|
||||
def naturallyOrderedMap = map.sort()
|
||||
assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap)
|
||||
|
||||
def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator)
|
||||
assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap)
|
||||
|
||||
def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value })
|
||||
assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap)
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -8,3 +8,8 @@
|
|||
- [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings)
|
||||
- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating)
|
||||
- [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits)
|
||||
- [Closures in Groovy](https://www.baeldung.com/groovy-closures)
|
||||
- [Finding Elements in Collections in Groovy](https://www.baeldung.com/groovy-collections-find-elements)
|
||||
- [Lists in Groovy](https://www.baeldung.com/groovy-lists)
|
||||
- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date)
|
||||
- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung
|
||||
|
||||
class Person {
|
||||
private String firstname
|
||||
private String lastname
|
||||
private Integer age
|
||||
|
||||
Person(String firstname, String lastname, Integer age) {
|
||||
this.firstname = firstname
|
||||
this.lastname = lastname
|
||||
this.age = age
|
||||
}
|
||||
|
||||
String getFirstname() {
|
||||
return firstname
|
||||
}
|
||||
|
||||
void setFirstname(String firstname) {
|
||||
this.firstname = firstname
|
||||
}
|
||||
|
||||
String getLastname() {
|
||||
return lastname
|
||||
}
|
||||
|
||||
void setLastname(String lastname) {
|
||||
this.lastname = lastname
|
||||
}
|
||||
|
||||
Integer getAge() {
|
||||
return age
|
||||
}
|
||||
|
||||
void setAge(Integer age) {
|
||||
this.age = age
|
||||
}
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package com.baeldung.closures
|
||||
|
||||
class Closures {
|
||||
|
||||
def printWelcome = {
|
||||
println "Welcome to Closures!"
|
||||
}
|
||||
|
||||
def print = { name ->
|
||||
println name
|
||||
}
|
||||
|
||||
def formatToLowerCase(name) {
|
||||
return name.toLowerCase()
|
||||
}
|
||||
def formatToLowerCaseClosure = { name ->
|
||||
return name.toLowerCase()
|
||||
}
|
||||
|
||||
def count=0
|
||||
|
||||
def increaseCount = {
|
||||
count++
|
||||
}
|
||||
|
||||
def greet = {
|
||||
return "Hello! ${it}"
|
||||
}
|
||||
|
||||
def multiply = { x, y ->
|
||||
return x*y
|
||||
}
|
||||
|
||||
def calculate = {int x, int y, String operation ->
|
||||
|
||||
//log closure
|
||||
def log = {
|
||||
println "Performing $it"
|
||||
}
|
||||
|
||||
def result = 0
|
||||
switch(operation) {
|
||||
case "ADD":
|
||||
log("Addition")
|
||||
result = x+y
|
||||
break
|
||||
case "SUB":
|
||||
log("Subtraction")
|
||||
result = x-y
|
||||
break
|
||||
case "MUL":
|
||||
log("Multiplication")
|
||||
result = x*y
|
||||
break
|
||||
case "DIV":
|
||||
log("Division")
|
||||
result = x/y
|
||||
break
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
def addAll = { int... args ->
|
||||
return args.sum()
|
||||
}
|
||||
|
||||
def volume(Closure areaCalculator, int... dimensions) {
|
||||
if(dimensions.size() == 3) {
|
||||
|
||||
//consider dimension[0] = length, dimension[1] = breadth, dimension[2] = height
|
||||
//for cube and cuboid
|
||||
return areaCalculator(dimensions[0], dimensions[1]) * dimensions[2]
|
||||
} else if(dimensions.size() == 2) {
|
||||
|
||||
//consider dimension[0] = radius, dimension[1] = height
|
||||
//for cylinder and cone
|
||||
return areaCalculator(dimensions[0]) * dimensions[1]
|
||||
} else if(dimensions.size() == 1) {
|
||||
|
||||
//consider dimension[0] = radius
|
||||
//for sphere
|
||||
return areaCalculator(dimensions[0]) * dimensions[0]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package com.baeldung.closures
|
||||
|
||||
class Employee {
|
||||
|
||||
String fullName
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package com.baeldung.closures
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
class ClosuresUnitTest extends GroovyTestCase {
|
||||
|
||||
Closures closures = new Closures()
|
||||
|
||||
void testDeclaration() {
|
||||
|
||||
closures.print("Hello! Closure")
|
||||
closures.formatToLowerCaseClosure("Hello! Closure")
|
||||
|
||||
closures.print.call("Hello! Closure")
|
||||
closures.formatToLowerCaseClosure.call("Hello! Closure")
|
||||
|
||||
}
|
||||
|
||||
void testClosureVsMethods() {
|
||||
assert closures.formatToLowerCase("TONY STARK") == closures.formatToLowerCaseClosure("Tony STark")
|
||||
}
|
||||
|
||||
void testParameters() {
|
||||
//implicit parameter
|
||||
assert closures.greet("Alex") == "Hello! Alex"
|
||||
|
||||
//multiple parameters
|
||||
assert closures.multiply(2, 4) == 8
|
||||
|
||||
assert closures.calculate(12, 4, "ADD") == 16
|
||||
assert closures.calculate(12, 4, "SUB") == 8
|
||||
assert closures.calculate(43, 8, "DIV") == 5.375
|
||||
|
||||
//varags
|
||||
assert closures.addAll(12, 10, 14) == 36
|
||||
|
||||
}
|
||||
|
||||
void testClosureAsAnArgument() {
|
||||
assert closures.volume({ l, b -> return l*b }, 12, 6, 10) == 720
|
||||
|
||||
assert closures.volume({ radius -> return Math.PI*radius*radius/3 }, 5, 10) == Math.PI * 250/3
|
||||
}
|
||||
|
||||
void testGStringsLazyEvaluation() {
|
||||
def name = "Samwell"
|
||||
def welcomeMsg = "Welcome! $name"
|
||||
|
||||
assert welcomeMsg == "Welcome! Samwell"
|
||||
|
||||
// changing the name does not affect original interpolated value
|
||||
name = "Tarly"
|
||||
assert welcomeMsg != "Welcome! Tarly"
|
||||
|
||||
def fullName = "Tarly Samson"
|
||||
def greetStr = "Hello! ${-> fullName}"
|
||||
|
||||
assert greetStr == "Hello! Tarly Samson"
|
||||
|
||||
// this time changing the variable affects the interpolated String's value
|
||||
fullName = "Jon Smith"
|
||||
assert greetStr == "Hello! Jon Smith"
|
||||
}
|
||||
|
||||
void testClosureInLists() {
|
||||
def list = [10, 11, 12, 13, 14, true, false, "BUNTHER"]
|
||||
list.each {
|
||||
println it
|
||||
}
|
||||
|
||||
assert [13, 14] == list.findAll{ it instanceof Integer && it >= 13}
|
||||
}
|
||||
|
||||
void testClosureInMaps() {
|
||||
def map = [1:10, 2:30, 4:5]
|
||||
|
||||
assert [10, 60, 20] == map.collect{it.key * it.value}
|
||||
}
|
||||
|
||||
}
|
|
@ -129,13 +129,13 @@ class ListTest{
|
|||
assertTrue(filterList.findAll{it > 3} == [4, 5, 6, 76])
|
||||
|
||||
assertTrue(filterList.findAll{ it instanceof Number} == [2, 1, 3, 4, 5, 6, 76])
|
||||
|
||||
|
||||
assertTrue(filterList.grep( Number )== [2, 1, 3, 4, 5, 6, 76])
|
||||
|
||||
|
||||
assertTrue(filterList.grep{ it> 6 }== [76])
|
||||
|
||||
def conditionList = [2, 1, 3, 4, 5, 6, 76]
|
||||
|
||||
|
||||
assertFalse(conditionList.every{ it < 6})
|
||||
|
||||
assertTrue(conditionList.any{ it%2 == 0})
|
||||
|
@ -165,7 +165,7 @@ class ListTest{
|
|||
|
||||
def strList = ["na", "ppp", "as"]
|
||||
assertTrue(strList.max() == "ppp")
|
||||
|
||||
|
||||
Comparator minc = {a,b -> a == b? 0: a < b? -1 : 1}
|
||||
def numberList = [3, 2, 0, 7]
|
||||
assertTrue(numberList.min(minc) == 0)
|
||||
|
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.lists
|
||||
|
||||
import com.baeldung.Person
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.*
|
||||
|
||||
class ListUnitTest {
|
||||
|
||||
private final personList = [
|
||||
new Person("Regina", "Fitzpatrick", 25),
|
||||
new Person("Abagail", "Ballard", 26),
|
||||
new Person("Lucian", "Walter", 30),
|
||||
]
|
||||
|
||||
@Test
|
||||
void whenListContainsElement_thenCheckReturnsTrue() {
|
||||
def list = ['a', 'b', 'c']
|
||||
|
||||
assertTrue(list.indexOf('a') > -1)
|
||||
assertTrue(list.contains('a'))
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenListContainsElement_thenCheckWithMembershipOperatorReturnsTrue() {
|
||||
def list = ['a', 'b', 'c']
|
||||
|
||||
assertTrue('a' in list)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingStreamMatching_thenShouldEvaluateList() {
|
||||
assertTrue(personList.stream().anyMatch {it.age > 20})
|
||||
assertFalse(personList.stream().allMatch {it.age < 30})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingCollectionMatching_thenShouldEvaluateList() {
|
||||
assertTrue(personList.any {it.age > 20})
|
||||
assertFalse(personList.every {it.age < 30})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingStreamFind_thenShouldReturnMatchingElements() {
|
||||
assertTrue(personList.stream().filter {it.age > 20}.findAny().isPresent())
|
||||
assertFalse(personList.stream().filter {it.age > 30}.findAny().isPresent())
|
||||
assertTrue(personList.stream().filter {it.age > 20}.findAll().size() == 3)
|
||||
assertTrue(personList.stream().filter {it.age > 30}.findAll().isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingCollectionFind_thenShouldReturnMatchingElements() {
|
||||
assertNotNull(personList.find {it.age > 20})
|
||||
assertNull(personList.find {it.age > 30})
|
||||
assertTrue(personList.findAll {it.age > 20}.size() == 3)
|
||||
assertTrue(personList.findAll {it.age > 30}.isEmpty())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,148 @@
|
|||
package com.baeldung.groovy.map;
|
||||
|
||||
import static groovy.test.GroovyAssert.*
|
||||
import org.junit.Test
|
||||
|
||||
class MapTest{
|
||||
|
||||
@Test
|
||||
void createMap() {
|
||||
|
||||
def emptyMap = [:]
|
||||
assertNotNull(emptyMap)
|
||||
|
||||
assertTrue(emptyMap instanceof java.util.LinkedHashMap)
|
||||
|
||||
def map = [name:"Jerry", age: 42, city: "New York"]
|
||||
assertTrue(map.size() == 3)
|
||||
}
|
||||
|
||||
@Test
|
||||
void addItemsToMap() {
|
||||
|
||||
def map = [name:"Jerry"]
|
||||
|
||||
map["age"] = 42
|
||||
|
||||
map.city = "New York"
|
||||
|
||||
def hobbyLiteral = "hobby"
|
||||
def hobbyMap = [(hobbyLiteral): "Singing"]
|
||||
map.putAll(hobbyMap)
|
||||
|
||||
assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"])
|
||||
assertTrue(hobbyMap.hobby == "Singing")
|
||||
assertTrue(hobbyMap[hobbyLiteral] == "Singing")
|
||||
|
||||
map.plus([1:20]) // returns new map
|
||||
|
||||
map << [2:30]
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void getItemsFromMap() {
|
||||
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
assertTrue(map["name"] == "Jerry")
|
||||
|
||||
assertTrue(map.name == "Jerry")
|
||||
|
||||
def propertyAge = "age"
|
||||
assertTrue(map[propertyAge] == 42)
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeItemsFromMap() {
|
||||
|
||||
def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49]
|
||||
|
||||
def minusMap = map.minus([2:42, 4:34]);
|
||||
assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49])
|
||||
|
||||
minusMap.removeAll{it -> it.key instanceof String}
|
||||
assertTrue( minusMap == [ 1:20, 6:39, 7:49])
|
||||
|
||||
minusMap.retainAll{it -> it.value %2 == 0}
|
||||
assertTrue( minusMap == [1:20])
|
||||
}
|
||||
|
||||
@Test
|
||||
void iteratingOnMaps(){
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
map.each{ entry -> println "$entry.key: $entry.value" }
|
||||
|
||||
map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" }
|
||||
|
||||
map.eachWithIndex{ key, value, i -> println "$i $key: $value" }
|
||||
}
|
||||
|
||||
@Test
|
||||
void filteringAndSearchingMaps(){
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
assertTrue(map.find{ it.value == "New York"}.key == "city")
|
||||
|
||||
assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"])
|
||||
|
||||
map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")}
|
||||
|
||||
assertTrue(map.every{it -> it.value instanceof String} == false)
|
||||
|
||||
assertTrue(map.any{it -> it.value instanceof String} == true)
|
||||
}
|
||||
|
||||
@Test
|
||||
void collect(){
|
||||
|
||||
def map = [1: [name:"Jerry", age: 42, city: "New York"],
|
||||
2: [name:"Long", age: 25, city: "New York"],
|
||||
3: [name:"Dustin", age: 29, city: "New York"],
|
||||
4: [name:"Dustin", age: 34, city: "New York"]]
|
||||
|
||||
def names = map.collect{entry -> entry.value.name} // returns only list
|
||||
assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"])
|
||||
|
||||
def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name}
|
||||
assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set)
|
||||
|
||||
def idNames = map.collectEntries{key, value -> [key, value.name]}
|
||||
assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"])
|
||||
|
||||
def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name}
|
||||
assertTrue(below30Names == ["Long", "Dustin"])
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void group(){
|
||||
def map = [1:20, 2: 40, 3: 11, 4: 93]
|
||||
|
||||
def subMap = map.groupBy{it.value % 2}
|
||||
println subMap
|
||||
assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]])
|
||||
|
||||
def keySubMap = map.subMap([1, 2])
|
||||
assertTrue(keySubMap == [1:20, 2:40])
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void sorting(){
|
||||
def map = [ab:20, a: 40, cb: 11, ba: 93]
|
||||
|
||||
def naturallyOrderedMap = map.sort()
|
||||
assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap)
|
||||
|
||||
def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator)
|
||||
assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap)
|
||||
|
||||
def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value })
|
||||
assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap)
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -1,10 +1,18 @@
|
|||
package com.baeldung.map
|
||||
|
||||
import static org.junit.Assert.*
|
||||
import com.baeldung.Person
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.*
|
||||
|
||||
class MapUnitTest {
|
||||
|
||||
private final personMap = [
|
||||
Regina : new Person("Regina", "Fitzpatrick", 25),
|
||||
Abagail: new Person("Abagail", "Ballard", 26),
|
||||
Lucian : new Person("Lucian", "Walter", 30)
|
||||
]
|
||||
|
||||
@Test
|
||||
void whenUsingEach_thenMapIsIterated() {
|
||||
def map = [
|
||||
|
@ -63,7 +71,7 @@ class MapUnitTest {
|
|||
'FF6347' : 'Tomato',
|
||||
'FF4500' : 'Orange Red'
|
||||
]
|
||||
|
||||
|
||||
map.eachWithIndex { key, val, index ->
|
||||
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
|
||||
println "$indent Hex Code: $key = Color Name: $val"
|
||||
|
@ -82,4 +90,65 @@ class MapUnitTest {
|
|||
println "Hex Code: $entry.key = Color Name: $entry.value"
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMapContainsKeyElement_thenCheckReturnsTrue() {
|
||||
def map = [a: 'd', b: 'e', c: 'f']
|
||||
|
||||
assertTrue(map.containsKey('a'))
|
||||
assertFalse(map.containsKey('e'))
|
||||
assertTrue(map.containsValue('e'))
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMapContainsKeyElement_thenCheckByMembershipReturnsTrue() {
|
||||
def map = [a: 'd', b: 'e', c: 'f']
|
||||
|
||||
assertTrue('a' in map)
|
||||
assertFalse('f' in map)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMapContainsFalseBooleanValues_thenCheckReturnsFalse() {
|
||||
def map = [a: true, b: false, c: null]
|
||||
|
||||
assertTrue(map.containsKey('b'))
|
||||
assertTrue('a' in map)
|
||||
assertFalse('b' in map)
|
||||
assertFalse('c' in map)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingStreamMatching_thenShouldEvaluateMap() {
|
||||
assertTrue(personMap.keySet().stream().anyMatch {it == "Regina"})
|
||||
assertFalse(personMap.keySet().stream().allMatch {it == "Albert"})
|
||||
assertFalse(personMap.values().stream().allMatch {it.age < 30})
|
||||
assertTrue(personMap.entrySet().stream().anyMatch {it.key == "Abagail" && it.value.lastname == "Ballard"})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingCollectionMatching_thenShouldEvaluateMap() {
|
||||
assertTrue(personMap.keySet().any {it == "Regina"})
|
||||
assertFalse(personMap.keySet().every {it == "Albert"})
|
||||
assertFalse(personMap.values().every {it.age < 30})
|
||||
assertTrue(personMap.any {firstname, person -> firstname == "Abagail" && person.lastname == "Ballard"})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingCollectionFind_thenShouldReturnElements() {
|
||||
assertNotNull(personMap.find {it.key == "Abagail" && it.value.lastname == "Ballard"})
|
||||
assertTrue(personMap.findAll {it.value.age > 20}.size() == 3)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingStreamFind_thenShouldReturnElements() {
|
||||
assertTrue(
|
||||
personMap.entrySet().stream()
|
||||
.filter {it.key == "Abagail" && it.value.lastname == "Ballard"}
|
||||
.findAny().isPresent())
|
||||
assertTrue(
|
||||
personMap.entrySet().stream()
|
||||
.filter {it.value.age > 20}
|
||||
.findAll().size() == 3)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.set
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.assertTrue
|
||||
|
||||
class SetUnitTest {
|
||||
|
||||
@Test
|
||||
void whenSetContainsElement_thenCheckReturnsTrue() {
|
||||
def set = ['a', 'b', 'c'] as Set
|
||||
|
||||
assertTrue(set.contains('a'))
|
||||
assertTrue('a' in set)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.strings
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
import java.util.regex.Pattern
|
||||
|
||||
class StringMatchingSpec extends Specification {
|
||||
|
||||
def "pattern operator example"() {
|
||||
given: "a pattern"
|
||||
def p = ~'foo'
|
||||
|
||||
expect:
|
||||
p instanceof Pattern
|
||||
|
||||
and: "you can use slash strings to avoid escaping of blackslash"
|
||||
def digitPattern = ~/\d*/
|
||||
digitPattern.matcher('4711').matches()
|
||||
}
|
||||
|
||||
def "match operator example"() {
|
||||
expect:
|
||||
'foobar' ==~ /.*oba.*/
|
||||
|
||||
and: "matching is strict"
|
||||
!('foobar' ==~ /foo/)
|
||||
}
|
||||
|
||||
def "find operator example"() {
|
||||
when: "using the find operator"
|
||||
def matcher = 'foo and bar, baz and buz' =~ /(\w+) and (\w+)/
|
||||
|
||||
then: "will find groups"
|
||||
matcher.size() == 2
|
||||
|
||||
and: "can access groups using array"
|
||||
matcher[0][0] == 'foo and bar'
|
||||
matcher[1][2] == 'buz'
|
||||
|
||||
and: "you can use it as a predicate"
|
||||
'foobarbaz' =~ /bar/
|
||||
}
|
||||
|
||||
}
|
|
@ -4,3 +4,6 @@
|
|||
- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params)
|
||||
- [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api)
|
||||
- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control)
|
||||
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
|
||||
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
|
||||
- [Guide to jlink](https://www.baeldung.com/jlink)
|
||||
|
|
|
@ -14,6 +14,14 @@
|
|||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -31,6 +39,7 @@
|
|||
<properties>
|
||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<guava.version>27.1-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.jlink;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class HelloWorld {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(HelloWorld.class.getName());
|
||||
|
||||
public static void main(String[] args) {
|
||||
LOG.info("Hello World!");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
module jlinkModule {
|
||||
requires java.logging;
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class EmptyStringToEmptyOptionalUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEmptyString_whenFilteringOnOptional_thenEmptyOptionalIsReturned() {
|
||||
String str = "";
|
||||
Optional<String> opt = Optional.ofNullable(str).filter(s -> !s.isEmpty());
|
||||
Assert.assertFalse(opt.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyString_whenFilteringOnOptionalInJava11_thenEmptyOptionalIsReturned() {
|
||||
String str = "";
|
||||
Optional<String> opt = Optional.ofNullable(str).filter(Predicate.not(String::isEmpty));
|
||||
Assert.assertFalse(opt.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyString_whenPassingResultOfEmptyToNullToOfNullable_thenEmptyOptionalIsReturned() {
|
||||
String str = "";
|
||||
Optional<String> opt = Optional.ofNullable(Strings.emptyToNull(str));
|
||||
Assert.assertFalse(opt.isPresent());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-12</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-12</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>12</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>12</maven.compiler.target.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,71 @@
|
|||
package com.baeldung.collectors;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static java.util.stream.Collectors.maxBy;
|
||||
import static java.util.stream.Collectors.minBy;
|
||||
import static java.util.stream.Collectors.teeing;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Unit tests for collectors additions in Java 12.
|
||||
*/
|
||||
public class CollectorsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenTeeing_ItShouldCombineTheResultsAsExpected() {
|
||||
List<Integer> numbers = Arrays.asList(42, 4, 2, 24);
|
||||
Range range = numbers.stream()
|
||||
.collect(teeing(minBy(Integer::compareTo), maxBy(Integer::compareTo), (min, max) -> new Range(min.orElse(null), max.orElse(null))));
|
||||
|
||||
assertThat(range).isEqualTo(new Range(2, 42));
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a closed range of numbers between {@link #min} and
|
||||
* {@link #max}, both inclusive.
|
||||
*/
|
||||
private static class Range {
|
||||
|
||||
private final Integer min;
|
||||
|
||||
private final Integer max;
|
||||
|
||||
Range(Integer min, Integer max) {
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
Integer getMin() {
|
||||
return min;
|
||||
}
|
||||
|
||||
Integer getMax() {
|
||||
return max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Range range = (Range) o;
|
||||
return Objects.equals(getMin(), range.getMin()) && Objects.equals(getMax(), range.getMax());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getMin(), getMax());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Range{" + "min=" + min + ", max=" + max + '}';
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.switchExpression;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SwitchUnitTest {
|
||||
|
||||
@Test
|
||||
public void switchJava12(){
|
||||
|
||||
var month = Month.AUG;
|
||||
|
||||
var value = switch(month){
|
||||
case JAN,JUN, JUL -> 3;
|
||||
case FEB,SEP, OCT, NOV, DEC -> 1;
|
||||
case MAR,MAY, APR, AUG -> 2;
|
||||
};
|
||||
|
||||
Assert.assertEquals(value, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void switchLocalVariable(){
|
||||
var month = Month.AUG;
|
||||
int i = switch (month){
|
||||
case JAN,JUN, JUL -> 3;
|
||||
case FEB,SEP, OCT, NOV, DEC -> 1;
|
||||
case MAR,MAY, APR, AUG -> {
|
||||
int j = month.toString().length() * 4;
|
||||
break j;
|
||||
}
|
||||
};
|
||||
Assert.assertEquals(12, i);
|
||||
}
|
||||
|
||||
enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}
|
||||
}
|
|
@ -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,6 @@
|
|||
=========
|
||||
|
||||
## Core Java 8 Cookbooks and Examples (part 2)
|
||||
|
||||
### Relevant Articles:
|
||||
- [Anonymous Classes in Java](http://www.baeldung.com/)
|
|
@ -0,0 +1,50 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-8-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-8-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>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<icu.version>64.2</icu.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.ibm.icu</groupId>
|
||||
<artifactId>icu4j</artifactId>
|
||||
<version>${icu.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.jarArguments;
|
||||
|
||||
public class JarExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Hello Baeldung Reader in JarExample!");
|
||||
|
||||
if(args == null) {
|
||||
System.out.println("You have not provided any arguments!");
|
||||
}else {
|
||||
System.out.println("There are "+args.length+" argument(s)!");
|
||||
for(int i=0; i<args.length; i++) {
|
||||
System.out.println("Argument("+(i+1)+"):" + args[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.localization;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
public class App {
|
||||
|
||||
/**
|
||||
* Runs all available formatter
|
||||
* @throws ParseException
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
List<Locale> locales = Arrays.asList(new Locale[] { Locale.UK, Locale.ITALY, Locale.FRANCE, Locale.forLanguageTag("pl-PL") });
|
||||
Localization.run(locales);
|
||||
JavaSEFormat.run(locales);
|
||||
ICUFormat.run(locales);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.localization;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
import com.ibm.icu.text.MessageFormat;
|
||||
|
||||
public class ICUFormat {
|
||||
|
||||
public static String getLabel(Locale locale, Object[] data) {
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
|
||||
String format = bundle.getString("label-icu");
|
||||
MessageFormat formatter = new MessageFormat(format, locale);
|
||||
return formatter.format(data);
|
||||
}
|
||||
|
||||
public static void run(List<Locale> locales) {
|
||||
System.out.println("ICU formatter");
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 0 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 1 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 2 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 3 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 0 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 1 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 2 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 3 })));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.localization;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
public class JavaSEFormat {
|
||||
|
||||
public static String getLabel(Locale locale, Object[] data) {
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
|
||||
final String pattern = bundle.getString("label");
|
||||
final MessageFormat formatter = new MessageFormat(pattern, locale);
|
||||
return formatter.format(data);
|
||||
}
|
||||
|
||||
public static void run(List<Locale> locales) {
|
||||
System.out.println("Java formatter");
|
||||
final Date date = new Date(System.currentTimeMillis());
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 0 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 2 })));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.localization;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
public class Localization {
|
||||
|
||||
public static String getLabel(Locale locale) {
|
||||
final ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
|
||||
return bundle.getString("label");
|
||||
}
|
||||
|
||||
public static void run(List<Locale> locales) {
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale)));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
Main-Class: com.baeldung.jarArguments.JarExample
|
|
@ -0,0 +1,2 @@
|
|||
label=On {0, date, short} {1} has sent you {2, choice, 0#no messages|1#a message|2#two messages|2<{2,number,integer} messages}.
|
||||
label-icu={0} has sent you {2, plural, =0 {no messages} =1 {a message} other {{2, number, integer} messages}}.
|
|
@ -0,0 +1,2 @@
|
|||
label={0, date, short}, {1}{2, choice, 0# ne|0<} vous a envoyé {2, choice, 0#aucun message|1#un message|2#deux messages|2<{2,number,integer} messages}.
|
||||
label-icu={0} {2, plural, =0 {ne } other {}}vous a envoyé {2, plural, =0 {aucun message} =1 {un message} other {{2, number, integer} messages}}.
|
|
@ -0,0 +1,2 @@
|
|||
label={0, date, short} {1} ti ha inviato {2, choice, 0#nessun messagio|1#un messaggio|2#due messaggi|2<{2, number, integer} messaggi}.
|
||||
label-icu={0} {2, plural, =0 {non } other {}}ti ha inviato {2, plural, =0 {nessun messaggio} =1 {un messaggio} other {{2, number, integer} messaggi}}.
|
|
@ -0,0 +1,2 @@
|
|||
label=W {0, date, short} {1}{2, choice, 0# nie|0<} wys\u0142a\u0142a ci {2, choice, 0#\u017Cadnych wiadomo\u015Bci|1#wiadomo\u015B\u0107|2#dwie wiadomo\u015Bci|2<{2, number, integer} wiadomo\u015Bci}.
|
||||
label-icu={0} {2, plural, =0 {nie } other {}}{1, select, male {wys\u0142a\u0142} female {wys\u0142a\u0142a} other {wys\u0142a\u0142o}} ci {2, plural, =0 {\u017Cadnej wiadomo\u015Bci} =1 {wiadomo\u015B\u0107} other {{2, number, integer} wiadomo\u015Bci}}.
|
|
@ -0,0 +1 @@
|
|||
label=Alice has sent you a message.
|
|
@ -0,0 +1 @@
|
|||
label=Alice vous a envoyé un message.
|
|
@ -0,0 +1 @@
|
|||
label=Alice ti ha inviato un messaggio.
|
|
@ -0,0 +1 @@
|
|||
label=Alice wys\u0142a\u0142a ci wiadomo\u015B\u0107.
|
|
@ -0,0 +1,74 @@
|
|||
package com.baeldung.localization;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.localization.ICUFormat;
|
||||
|
||||
public class ICUFormatUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenInUK_whenAliceSendsNothing_thenCorrectMessage() {
|
||||
assertEquals("Alice has sent you no messages.", ICUFormat.getLabel(Locale.UK, new Object[] { "Alice", "female", 0 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInUK_whenAliceSendsOneMessage_thenCorrectMessage() {
|
||||
assertEquals("Alice has sent you a message.", ICUFormat.getLabel(Locale.UK, new Object[] { "Alice", "female", 1 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInUK_whenBobSendsSixMessages_thenCorrectMessage() {
|
||||
assertEquals("Bob has sent you 6 messages.", ICUFormat.getLabel(Locale.UK, new Object[] { "Bob", "male", 6 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInItaly_whenAliceSendsNothing_thenCorrectMessage() {
|
||||
assertEquals("Alice non ti ha inviato nessun messaggio.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Alice", "female", 0 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInItaly_whenAliceSendsOneMessage_thenCorrectMessage() {
|
||||
assertEquals("Alice ti ha inviato un messaggio.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Alice", "female", 1 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInItaly_whenBobSendsSixMessages_thenCorrectMessage() {
|
||||
assertEquals("Bob ti ha inviato 6 messaggi.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Bob", "male", 6 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInFrance_whenAliceSendsNothing_thenCorrectMessage() {
|
||||
assertEquals("Alice ne vous a envoyé aucun message.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Alice", "female", 0 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInFrance_whenAliceSendsOneMessage_thenCorrectMessage() {
|
||||
assertEquals("Alice vous a envoyé un message.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Alice", "female", 1 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInFrance_whenBobSendsSixMessages_thenCorrectMessage() {
|
||||
assertEquals("Bob vous a envoyé 6 messages.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Bob", "male", 6 }));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenInPoland_whenAliceSendsNothing_thenCorrectMessage() {
|
||||
assertEquals("Alice nie wysłała ci żadnej wiadomości.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Alice", "female", 0 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInPoland_whenAliceSendsOneMessage_thenCorrectMessage() {
|
||||
assertEquals("Alice wysłała ci wiadomość.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Alice", "female", 1 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInPoland_whenBobSendsSixMessages_thenCorrectMessage() {
|
||||
assertEquals("Bob wysłał ci 6 wiadomości.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Bob", "male", 6 }));
|
||||
}
|
||||
|
||||
}
|
|
@ -3,7 +3,7 @@
|
|||
## Core Java 8 Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
|
||||
- [Guide to Java 8’s Collectors](http://www.baeldung.com/java-8-collectors)
|
||||
- [Functional Interfaces in Java 8](http://www.baeldung.com/java-8-functional-interfaces)
|
||||
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
||||
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
|
||||
|
|
|
@ -1,12 +0,0 @@
|
|||
package com.baeldung;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public interface Adder {
|
||||
|
||||
String addWithFunction(Function<String, String> f);
|
||||
|
||||
void addWithConsumer(Consumer<Integer> f);
|
||||
|
||||
}
|
|
@ -1,18 +0,0 @@
|
|||
package com.baeldung;
|
||||
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class AdderImpl implements Adder {
|
||||
|
||||
@Override
|
||||
public String addWithFunction(final Function<String, String> f) {
|
||||
return f.apply("Something ");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addWithConsumer(final Consumer<Integer> f) {
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public interface Processor {
|
||||
|
||||
String processWithCallable(Callable<String> c) throws Exception;
|
||||
|
||||
String processWithSupplier(Supplier<String> s);
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class ProcessorImpl implements Processor {
|
||||
|
||||
@Override
|
||||
public String processWithCallable(Callable<String> c) throws Exception {
|
||||
return c.call();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String processWithSupplier(Supplier<String> s) {
|
||||
return s.get();
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue