Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2019-04-08 14:12:22 +02:00
commit cc8a7ca9fb
1431 changed files with 85203 additions and 5558 deletions

View File

@ -41,7 +41,6 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<akka.http.version>10.0.11</akka.http.version>
<akka.stream.version>2.5.11</akka.stream.version>
</properties>

View File

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

View File

@ -54,7 +54,6 @@
</build>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<io.jenetics.version>3.7.0</io.jenetics.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>

View File

@ -17,3 +17,4 @@
- [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)

View File

@ -39,6 +39,11 @@
<version>${org.assertj.core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.dpaukov</groupId>
<artifactId>combinatoricslib3</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
<build>
@ -74,11 +79,10 @@
</reporting>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
<guava.version>25.1-jre</guava.version>
<guava.version>27.0.1-jre</guava.version>
</properties>
</project>

View File

@ -0,0 +1,29 @@
package com.baeldung.algorithms.combination;
import java.util.Arrays;
import java.util.Iterator;
import org.apache.commons.math3.util.CombinatoricsUtils;
public class ApacheCommonsCombinationGenerator {
private static final int N = 6;
private static final int R = 3;
/**
* Print all combinations of r elements from a set
* @param n - number of elements in set
* @param r - number of elements in selection
*/
public static void generate(int n, int r) {
Iterator<int[]> iterator = CombinatoricsUtils.combinationsIterator(n, r);
while (iterator.hasNext()) {
final int[] combination = iterator.next();
System.out.println(Arrays.toString(combination));
}
}
public static void main(String[] args) {
generate(N, R);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.algorithms.combination;
import org.paukov.combinatorics3.Generator;
public class CombinatoricsLibCombinationGenerator {
public static void main(String[] args) {
Generator.combination(0, 1, 2, 3, 4, 5)
.simple(3)
.stream()
.forEach(System.out::println);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.combination;
import java.util.Arrays;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
public class GuavaCombinationsGenerator {
public static void main(String[] args) {
Set<Set<Integer>> combinations = Sets.combinations(ImmutableSet.of(0, 1, 2, 3, 4, 5), 3);
System.out.println(combinations.size());
System.out.println(Arrays.toString(combinations.toArray()));
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.algorithms.combination;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class IterativeCombinationGenerator {
private static final int N = 5;
private static final int R = 2;
/**
* Generate all combinations of r elements from a set
* @param n the number of elements in input set
* @param r the number of elements in a combination
* @return the list containing all combinations
*/
public List<int[]> generate(int n, int r) {
List<int[]> combinations = new ArrayList<>();
int[] combination = new int[r];
// initialize with lowest lexicographic combination
for (int i = 0; i < r; i++) {
combination[i] = i;
}
while (combination[r - 1] < n) {
combinations.add(combination.clone());
// generate next combination in lexicographic order
int t = r - 1;
while (t != 0 && combination[t] == n - r + t) {
t--;
}
combination[t]++;
for (int i = t + 1; i < r; i++) {
combination[i] = combination[i - 1] + 1;
}
}
return combinations;
}
public static void main(String[] args) {
IterativeCombinationGenerator generator = new IterativeCombinationGenerator();
List<int[]> combinations = generator.generate(N, R);
System.out.println(combinations.size());
for (int[] combination : combinations) {
System.out.println(Arrays.toString(combination));
}
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.algorithms.combination;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SelectionRecursiveCombinationGenerator {
private static final int N = 6;
private static final int R = 3;
/**
* Generate all combinations of r elements from a set
* @param n - number of elements in input set
* @param r - number of elements to be chosen
* @return the list containing all combinations
*/
public List<int[]> generate(int n, int r) {
List<int[]> combinations = new ArrayList<>();
helper(combinations, new int[r], 0, n - 1, 0);
return combinations;
}
/**
* Choose elements from set by recursing over elements selected
* @param combinations - List to store generated combinations
* @param data - current combination
* @param start - starting element of remaining set
* @param end - last element of remaining set
* @param index - number of elements chosen so far.
*/
private void helper(List<int[]> combinations, int data[], int start, int end, int index) {
if (index == data.length) {
int[] combination = data.clone();
combinations.add(combination);
} else {
int max = Math.min(end, end + 1 - data.length + index);
for (int i = start; i <= max; i++) {
data[index] = i;
helper(combinations, data, i + 1, end, index + 1);
}
}
}
public static void main(String[] args) {
SelectionRecursiveCombinationGenerator generator = new SelectionRecursiveCombinationGenerator();
List<int[]> combinations = generator.generate(N, R);
for (int[] combination : combinations) {
System.out.println(Arrays.toString(combination));
}
System.out.printf("generated %d combinations of %d items from %d ", combinations.size(), R, N);
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.algorithms.combination;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SetRecursiveCombinationGenerator {
private static final int N = 5;
private static final int R = 2;
/**
* Generate all combinations of r elements from a set
* @param n - number of elements in set
* @param r - number of elements in selection
* @return the list containing all combinations
*/
public List<int[]> generate(int n, int r) {
List<int[]> combinations = new ArrayList<>();
helper(combinations, new int[r], 0, n-1, 0);
return combinations;
}
/**
* @param combinations - List to contain the generated combinations
* @param data - List of elements in the selection
* @param start - index of the starting element in the remaining set
* @param end - index of the last element in the set
* @param index - number of elements selected so far
*/
private void helper(List<int[]> combinations, int data[], int start, int end, int index) {
if (index == data.length) {
int[] combination = data.clone();
combinations.add(combination);
} else if (start <= end) {
data[index] = start;
helper(combinations, data, start + 1, end, index + 1);
helper(combinations, data, start + 1, end, index);
}
}
public static void main(String[] args) {
SetRecursiveCombinationGenerator generator = new SetRecursiveCombinationGenerator();
List<int[]> combinations = generator.generate(N, R);
for (int[] combination : combinations) {
System.out.println(Arrays.toString(combination));
}
System.out.printf("generated %d combinations of %d items from %d ", combinations.size(), R, N);
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.algorithms.combination;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.Test;
public class CombinationUnitTest {
private static final int N = 5;
private static final int R = 3;
private static final int nCr = 10;
@Test
public void givenSetAndSelectionSize_whenCalculatedUsingSetRecursiveAlgorithm_thenExpectedCount() {
SetRecursiveCombinationGenerator generator = new SetRecursiveCombinationGenerator();
List<int[]> selection = generator.generate(N, R);
assertEquals(nCr, selection.size());
}
@Test
public void givenSetAndSelectionSize_whenCalculatedUsingSelectionRecursiveAlgorithm_thenExpectedCount() {
SelectionRecursiveCombinationGenerator generator = new SelectionRecursiveCombinationGenerator();
List<int[]> selection = generator.generate(N, R);
assertEquals(nCr, selection.size());
}
@Test
public void givenSetAndSelectionSize_whenCalculatedUsingIterativeAlgorithm_thenExpectedCount() {
IterativeCombinationGenerator generator = new IterativeCombinationGenerator();
List<int[]> selection = generator.generate(N, R);
assertEquals(nCr, selection.size());
}
}

View File

@ -84,7 +84,6 @@
</reporting>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<tradukisto.version>1.0.1</tradukisto.version>
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>

View File

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

View File

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

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

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

View File

@ -49,7 +49,6 @@
</build>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>

View File

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

View File

@ -82,7 +82,6 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler-plugin.version>3.5</compiler-plugin.version>
<avro.version>1.8.2</avro.version>
<java.version>1.8</java.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>

View File

@ -39,7 +39,7 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind.version}</version>
<version>${jackson.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
@ -59,7 +59,6 @@
<properties>
<curator.version>4.0.1</curator.version>
<zookeeper.version>3.4.11</zookeeper.version>
<jackson-databind.version>2.9.7</jackson-databind.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>

View File

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

View File

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

View File

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

View File

@ -32,8 +32,8 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
@ -41,7 +41,5 @@
<properties>
<geode.core>1.6.0</geode.core>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>

View File

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

View File

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

View File

@ -56,8 +56,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
@ -85,8 +85,6 @@
<org.apache.spark.spark-streaming-kafka.version>2.3.0</org.apache.spark.spark-streaming-kafka.version>
<com.datastax.spark.spark-cassandra-connector.version>2.3.0</com.datastax.spark.spark-cassandra-connector.version>
<com.datastax.spark.spark-cassandra-connector-java.version>1.5.2</com.datastax.spark.spark-cassandra-connector-java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven-compiler-plugin.version>3.2</maven-compiler-plugin.version>
</properties>

View File

@ -4,7 +4,6 @@
- [AWS S3 with Java](http://www.baeldung.com/aws-s3-java)
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
- [Managing EC2 Instances in Java](http://www.baeldung.com/ec2-java)
- [http://www.baeldung.com/aws-s3-multipart-upload](https://github.com/eugenp/tutorials/tree/master/aws)
- [Multipart Uploads in Amazon S3 with Java](http://www.baeldung.com/aws-s3-multipart-upload)
- [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests)
- [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3)

View File

@ -127,7 +127,6 @@
<docker.image.prefix>${azure.containerRegistry}.azurecr.io</docker.image.prefix>
<docker-maven-plugin.version>1.1.0</docker-maven-plugin.version>
<azure-webapp-maven-plugin.version>1.1.0</azure-webapp-maven-plugin.version>
<java.version>1.8</java.version>
</properties>
</project>

21
cas/pom.xml Normal file
View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>cas</artifactId>
<name>cas</name>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<modules>
<module>cas-secured-app</module>
<module>cas-server</module>
</modules>
</project>

View File

@ -66,7 +66,6 @@
<aspectjweaver.version>1.9.2</aspectjweaver.version>
<hamcrest-core.version>1.3</hamcrest-core.version>
<assertj-core.version>3.10.0</assertj-core.version>
<junit.version>4.12</junit.version>
<spring.version>5.1.2.RELEASE</spring.version>
</properties>
</project>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,3 @@
server.port=8082
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/uaa/oauth/token

View File

@ -4,3 +4,10 @@
- [JDBC with Groovy](http://www.baeldung.com/jdbc-groovy)
- [Working with JSON in Groovy](http://www.baeldung.com/groovy-json)
- [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read)
- [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)
- [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)

View File

@ -23,6 +23,12 @@
<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>
@ -103,9 +109,12 @@
<properties>
<junit.platform.version>1.0.0</junit.platform.version>
<groovy.version>2.4.13</groovy.version>
<groovy-all.version>2.4.13</groovy-all.version>
<groovy-sql.version>2.4.13</groovy-sql.version>
<!-- <groovy.version>2.4.13</groovy.version> -->
<!-- <groovy-all.version>2.4.13</groovy-all.version> -->
<!-- <groovy-sql.version>2.4.13</groovy-sql.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>

View File

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

View File

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

View File

@ -0,0 +1,6 @@
package com.baeldung.closures
class Employee {
String fullName
}

View File

@ -0,0 +1,8 @@
package com.baeldung.io
class Task implements Serializable {
String description
Date startDate
Date dueDate
int status
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

View File

@ -0,0 +1,4 @@
First line of text
Second line of text
Third line of text
Fourth line of text

View File

@ -0,0 +1,3 @@
Line one of output example
Line two of output example
Line three of output example

Binary file not shown.

View File

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

View File

@ -0,0 +1,57 @@
package com.baeldung.groovy.sql
import static org.junit.Assert.*
import java.util.Calendar.*
import java.time.LocalDate
import java.text.SimpleDateFormat
import org.junit.Test
class DateTest {
def dateStr = "2019-02-28"
def pattern = "yyyy-MM-dd"
@Test
void whenGetStringRepresentation_thenCorrectlyConvertIntoDate() {
def dateFormat = new SimpleDateFormat(pattern)
def date = dateFormat.parse(dateStr)
println(" String to Date with DateFormatter : " + date)
def cal = new GregorianCalendar();
cal.setTime(date);
assertEquals(cal.get(Calendar.YEAR),2019)
assertEquals(cal.get(Calendar.DAY_OF_MONTH),28)
assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY)
}
@Test
void whenGetStringRepresentation_thenCorrectlyConvertWithDateUtilsExtension() {
def date = Date.parse(pattern, dateStr)
println(" String to Date with Date.parse : " + date)
def cal = new GregorianCalendar();
cal.setTime(date);
assertEquals(cal.get(Calendar.YEAR),2019)
assertEquals(cal.get(Calendar.DAY_OF_MONTH),28)
assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY)
}
@Test
void whenGetStringRepresentation_thenCorrectlyConvertIntoDateWithLocalDate() {
def date = LocalDate.parse(dateStr, pattern)
println(" String to Date with LocalDate : " + date)
assertEquals(date.getYear(),2019)
assertEquals(date.getMonth(),java.time.Month.FEBRUARY)
assertEquals(date.getDayOfMonth(),28)
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.io
import static org.junit.Assert.*
import org.junit.Test
class DataAndObjectsUnitTest {
@Test
void whenUsingWithDataOutputStream_thenDataIsSerializedToAFile() {
String message = 'This is a serialized string'
int length = message.length()
boolean valid = true
new File('src/main/resources/ioData.txt').withDataOutputStream { out ->
out.writeUTF(message)
out.writeInt(length)
out.writeBoolean(valid)
}
String loadedMessage = ""
int loadedLength
boolean loadedValid
new File('src/main/resources/ioData.txt').withDataInputStream { is ->
loadedMessage = is.readUTF()
loadedLength = is.readInt()
loadedValid = is.readBoolean()
}
assertEquals(message, loadedMessage)
assertEquals(length, loadedLength)
assertEquals(valid, loadedValid)
}
@Test
void whenUsingWithObjectOutputStream_thenObjectIsSerializedToFile() {
Task task = new Task(description:'Take out the trash', startDate:new Date(), status:0)
new File('src/main/resources/ioSerializedObject.txt').withObjectOutputStream { out ->
out.writeObject(task)
}
Task taskRead
new File('src/main/resources/ioSerializedObject.txt').withObjectInputStream { is ->
taskRead = is.readObject()
}
assertEquals(task.description, taskRead.description)
assertEquals(task.startDate, taskRead.startDate)
assertEquals(task.status, taskRead.status)
}
}

View File

@ -0,0 +1,134 @@
package com.baeldung.io
import static org.junit.Assert.*
import org.junit.Test
class ReadExampleUnitTest {
@Test
void whenUsingEachLine_thenCorrectLinesReturned() {
def expectedList = [
'First line of text',
'Second line of text',
'Third line of text',
'Fourth line of text']
def lines = []
new File('src/main/resources/ioInput.txt').eachLine { line ->
lines.add(line)
}
assertEquals(expectedList, lines)
}
@Test
void whenUsingReadEachLineWithLineNumber_thenCorrectLinesReturned() {
def expectedList = [
'Second line of text',
'Third line of text',
'Fourth line of text']
def lineNoRange = 2..4
def lines = []
new File('src/main/resources/ioInput.txt').eachLine { line, lineNo ->
if (lineNoRange.contains(lineNo)) {
lines.add(line)
}
}
assertEquals(expectedList, lines)
}
@Test
void whenUsingReadEachLineWithLineNumberStartAtZero_thenCorrectLinesReturned() {
def expectedList = [
'Second line of text',
'Third line of text',
'Fourth line of text']
def lineNoRange = 1..3
def lines = []
new File('src/main/resources/ioInput.txt').eachLine(0, { line, lineNo ->
if (lineNoRange.contains(lineNo)) {
lines.add(line)
}
})
assertEquals(expectedList, lines)
}
@Test
void whenUsingWithReader_thenLineCountReturned() {
def expectedCount = 4
def actualCount = 0
new File('src/main/resources/ioInput.txt').withReader { reader ->
while(reader.readLine()) {
actualCount++
}
}
assertEquals(expectedCount, actualCount)
}
@Test
void whenUsingNewReader_thenOutputFileCreated() {
def outputPath = 'src/main/resources/ioOut.txt'
def reader = new File('src/main/resources/ioInput.txt').newReader()
new File(outputPath).append(reader)
reader.close()
def ioOut = new File(outputPath)
assertTrue(ioOut.exists())
ioOut.delete()
}
@Test
void whenUsingWithInputStream_thenCorrectBytesAreReturned() {
def expectedLength = 1139
byte[] data = []
new File("src/main/resources/binaryExample.jpg").withInputStream { stream ->
data = stream.getBytes()
}
assertEquals(expectedLength, data.length)
}
@Test
void whenUsingNewInputStream_thenOutputFileCreated() {
def outputPath = 'src/main/resources/binaryOut.jpg'
def is = new File('src/main/resources/binaryExample.jpg').newInputStream()
new File(outputPath).append(is)
is.close()
def ioOut = new File(outputPath)
assertTrue(ioOut.exists())
ioOut.delete()
}
@Test
void whenUsingCollect_thenCorrectListIsReturned() {
def expectedList = ['First line of text', 'Second line of text', 'Third line of text', 'Fourth line of text']
def actualList = new File('src/main/resources/ioInput.txt').collect {it}
assertEquals(expectedList, actualList)
}
@Test
void whenUsingAsStringArray_thenCorrectArrayIsReturned() {
String[] expectedArray = ['First line of text', 'Second line of text', 'Third line of text', 'Fourth line of text']
def actualArray = new File('src/main/resources/ioInput.txt') as String[]
assertArrayEquals(expectedArray, actualArray)
}
@Test
void whenUsingText_thenCorrectStringIsReturned() {
def ln = System.getProperty('line.separator')
def expectedString = "First line of text${ln}Second line of text${ln}Third line of text${ln}Fourth line of text"
def actualString = new File('src/main/resources/ioInput.txt').text
assertEquals(expectedString.toString(), actualString)
}
@Test
void whenUsingBytes_thenByteArrayIsReturned() {
def expectedLength = 1139
def contents = new File('src/main/resources/binaryExample.jpg').bytes
assertEquals(expectedLength, contents.length)
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.io
import org.junit.Test
import groovy.io.FileType
import groovy.io.FileVisitResult
class TraverseFileTreeUnitTest {
@Test
void whenUsingEachFile_filesAreListed() {
new File('src/main/resources').eachFile { file ->
println file.name
}
}
@Test(expected = IllegalArgumentException)
void whenUsingEachFileOnAFile_anErrorOccurs() {
new File('src/main/resources/ioInput.txt').eachFile { file ->
println file.name
}
}
@Test
void whenUsingEachFileMatch_filesAreListed() {
new File('src/main/resources').eachFileMatch(~/io.*\.txt/) { file ->
println file.name
}
}
@Test
void whenUsingEachFileRecurse_thenFilesInSubfoldersAreListed() {
new File('src/main').eachFileRecurse(FileType.FILES) { file ->
println "$file.parent $file.name"
}
}
@Test
void whenUsingEachFileRecurse_thenDirsInSubfoldersAreListed() {
new File('src/main').eachFileRecurse(FileType.DIRECTORIES) { file ->
println "$file.parent $file.name"
}
}
@Test
void whenUsingEachDirRecurse_thenDirsAndSubDirsAreListed() {
new File('src/main').eachDirRecurse { dir ->
println "$dir.parent $dir.name"
}
}
@Test
void whenUsingTraverse_thenDirectoryIsTraversed() {
new File('src/main').traverse { file ->
if (file.directory && file.name == 'groovy') {
FileVisitResult.SKIP_SUBTREE
} else {
println "$file.parent - $file.name"
}
}
}
}

View File

@ -0,0 +1,96 @@
package com.baeldung.io
import static org.junit.Assert.*
import org.junit.Before
import org.junit.Test
class WriteExampleUnitTest {
@Before
void clearOutputFile() {
new File('src/main/resources/ioOutput.txt').text = ''
new File('src/main/resources/ioBinaryOutput.bin').delete()
}
@Test
void whenUsingWithWriter_thenFileCreated() {
def outputLines = [
'Line one of output example',
'Line two of output example',
'Line three of output example'
]
def outputFileName = 'src/main/resources/ioOutput.txt'
new File(outputFileName).withWriter { writer ->
outputLines.each { line ->
writer.writeLine line
}
}
def writtenLines = new File(outputFileName).collect {it}
assertEquals(outputLines, writtenLines)
}
@Test
void whenUsingNewWriter_thenFileCreated() {
def outputLines = [
'Line one of output example',
'Line two of output example',
'Line three of output example'
]
def outputFileName = 'src/main/resources/ioOutput.txt'
def writer = new File(outputFileName).newWriter()
outputLines.forEach {line ->
writer.writeLine line
}
writer.flush()
writer.close()
def writtenLines = new File(outputFileName).collect {it}
assertEquals(outputLines, writtenLines)
}
@Test
void whenUsingDoubleLessThanOperator_thenFileCreated() {
def outputLines = [
'Line one of output example',
'Line two of output example',
'Line three of output example'
]
def ln = System.getProperty('line.separator')
def outputFileName = 'src/main/resources/ioOutput.txt'
new File(outputFileName) << "Line one of output example${ln}Line two of output example${ln}Line three of output example"
def writtenLines = new File(outputFileName).collect {it}
assertEquals(outputLines.size(), writtenLines.size())
}
@Test
void whenUsingBytes_thenBinaryFileCreated() {
def outputFileName = 'src/main/resources/ioBinaryOutput.bin'
def outputFile = new File(outputFileName)
byte[] outBytes = [44, 88, 22]
outputFile.bytes = outBytes
assertEquals(3, new File(outputFileName).size())
}
@Test
void whenUsingWithOutputStream_thenBinaryFileCreated() {
def outputFileName = 'src/main/resources/ioBinaryOutput.bin'
byte[] outBytes = [44, 88, 22]
new File(outputFileName).withOutputStream { stream ->
stream.write(outBytes)
}
assertEquals(3, new File(outputFileName).size())
}
@Test
void whenUsingNewOutputStream_thenBinaryFileCreated() {
def outputFileName = 'src/main/resources/ioBinaryOutput.bin'
byte[] outBytes = [44, 88, 22]
def os = new File(outputFileName).newOutputStream()
os.write(outBytes)
os.close()
assertEquals(3, new File(outputFileName).size())
}
}

View File

@ -0,0 +1,173 @@
package com.baeldung.groovy.lists
import static groovy.test.GroovyAssert.*
import org.junit.Test
class ListTest{
@Test
void testCreateList() {
def list = [1, 2, 3]
assertNotNull(list)
def listMix = ['A', "b", 1, true]
assertTrue(listMix == ['A', "b", 1, true])
def linkedList = [1, 2, 3] as LinkedList
assertTrue(linkedList instanceof LinkedList)
ArrayList arrList = [1, 2, 3]
assertTrue(arrList.class == ArrayList)
def copyList = new ArrayList(arrList)
assertTrue(copyList == arrList)
def cloneList = arrList.clone()
assertTrue(cloneList == arrList)
}
@Test
void testCreateEmptyList() {
def emptyList = []
assertTrue(emptyList.size() == 0)
}
@Test
void testCompareTwoLists() {
def list1 = [5, 6.0, 'p']
def list2 = [5, 6.0, 'p']
assertTrue(list1 == list2)
}
@Test
void testGetItemsFromList(){
def list = ["Hello", "World"]
assertTrue(list.get(1) == "World")
assertTrue(list[1] == "World")
assertTrue(list[-1] == "World")
assertTrue(list.getAt(1) == "World")
assertTrue(list.getAt(-2) == "Hello")
}
@Test
void testAddItemsToList() {
def list = []
list << 1
list.add("Apple")
assertTrue(list == [1, "Apple"])
list[2] = "Box"
list[4] = true
assertTrue(list == [1, "Apple", "Box", null, true])
list.add(1, 6.0)
assertTrue(list == [1, 6.0, "Apple", "Box", null, true])
def list2 = [1, 2]
list += list2
list += 12
assertTrue(list == [1, 6.0, "Apple", "Box", null, true, 1, 2, 12])
}
@Test
void testUpdateItemsInList() {
def list =[1, "Apple", 80, "App"]
list[1] = "Box"
list.set(2,90)
assertTrue(list == [1, "Box", 90, "App"])
}
@Test
void testRemoveItemsFromList(){
def list = [1, 2, 3, 4, 5, 5, 6, 6, 7]
list.remove(3)
assertTrue(list == [1, 2, 3, 5, 5, 6, 6, 7])
list.removeElement(5)
assertTrue(list == [1, 2, 3, 5, 6, 6, 7])
assertTrue(list - 6 == [1, 2, 3, 5, 7])
}
@Test
void testIteratingOnAList(){
def list = [1, "App", 3, 4]
list.each{ println it * 2}
list.eachWithIndex{ it, i -> println "$i : $it" }
}
@Test
void testCollectingToAnotherList(){
def list = ["Kay", "Henry", "Justin", "Tom"]
assertTrue(list.collect{"Hi " + it} == ["Hi Kay", "Hi Henry", "Hi Justin", "Hi Tom"])
}
@Test
void testJoinItemsInAList(){
assertTrue(["One", "Two", "Three"].join(",") == "One,Two,Three")
}
@Test
void testFilteringOnLists(){
def filterList = [2, 1, 3, 4, 5, 6, 76]
assertTrue(filterList.find{it > 3} == 4)
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})
}
@Test
void testGetUniqueItemsInAList(){
assertTrue([1, 3, 3, 4].toUnique() == [1, 3, 4])
def uniqueList = [1, 3, 3, 4]
uniqueList.unique()
assertTrue(uniqueList == [1, 3, 4])
assertTrue(["A", "B", "Ba", "Bat", "Cat"].toUnique{ it.size()} == ["A", "Ba", "Bat"])
}
@Test
void testSorting(){
assertTrue([1, 2, 1, 0].sort() == [0, 1, 1, 2])
Comparator mc = {a,b -> a == b? 0: a < b? 1 : -1}
def list = [1, 2, 1, 0]
list.sort(mc)
assertTrue(list == [2, 1, 1, 0])
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)
}
}

View File

@ -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())
}
}

View File

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

View File

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

View File

@ -4,3 +4,5 @@
- [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)

View File

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

View File

@ -0,0 +1,18 @@
package com.baeldung.epsilongc;
public class MemoryPolluter {
private static final int MEGABYTE_IN_BYTES = 1024 * 1024;
private static final int ITERATION_COUNT = 1024 * 10;
public static void main(String[] args) {
System.out.println("Starting pollution");
for (int i = 0; i < ITERATION_COUNT; i++) {
byte[] array = new byte[MEGABYTE_IN_BYTES];
}
System.out.println("Terminating");
}
}

View File

@ -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!");
}
}

View File

@ -0,0 +1,3 @@
module jlinkModule {
requires java.logging;
}

View File

@ -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());
}
}

49
core-java-12/pom.xml Normal file
View File

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

View File

@ -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 + '}';
}
}
}

View File

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

View File

@ -4,9 +4,9 @@
### Relevant Articles:
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
- [Guide to Java 8s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
- [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)
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
@ -38,3 +38,5 @@
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated)
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
- [Method References in Java](https://www.baeldung.com/java-method-references)
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)

View File

@ -180,7 +180,6 @@
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<commons-codec.version>1.10</commons-codec.version>
<lombok.version>1.16.12</lombok.version>
<vavr.version>0.9.0</vavr.version>
<protonpack.version>1.13</protonpack.version>
<joda.version>2.10</joda.version>

View File

@ -124,11 +124,44 @@ public class Java8SortUnitTest {
@Test
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void givenStreamComparatorOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final List<Human> sortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName)).collect(Collectors.toList());
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
final List<String> letters = Lists.newArrayList("B", "A", "C");
final List<String> reverseSortedLetters = letters.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
Assert.assertThat(reverseSortedLetters.get(0), equalTo("C"));
}
@Test
public final void givenStreamCustomOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final Comparator<Human> reverseNameComparator = (h1, h2) -> h2.getName().compareTo(h1.getName());
final List<Human> reverseSortedHumans = humans.stream().sorted(reverseNameComparator).collect(Collectors.toList());
Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
}
@Test
public final void givenStreamComparatorOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final List<Human> reverseSortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder())).collect(Collectors.toList());
Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
}
}

View File

@ -0,0 +1,110 @@
package com.baeldung.java8.optional;
import org.junit.Before;
import org.junit.Test;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static org.junit.Assert.*;
public class OptionalChainingUnitTest {
private boolean getEmptyEvaluated;
private boolean getHelloEvaluated;
private boolean getByeEvaluated;
@Before
public void setUp() {
getEmptyEvaluated = false;
getHelloEvaluated = false;
getByeEvaluated = false;
}
@Test
public void givenThreeOptionals_whenChaining_thenFirstNonEmptyIsReturned() {
Optional<String> found = Stream.of(getEmpty(), getHello(), getBye())
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
assertEquals(getHello(), found);
}
@Test
public void givenTwoEmptyOptionals_whenChaining_thenEmptyOptionalIsReturned() {
Optional<String> found = Stream.of(getEmpty(), getEmpty())
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
assertFalse(found.isPresent());
}
@Test
public void givenTwoEmptyOptionals_whenChaining_thenDefaultIsReturned() {
String found = Stream.<Supplier<Optional<String>>>of(
() -> createOptional("empty"),
() -> createOptional("empty")
)
.map(Supplier::get)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst()
.orElseGet(() -> "default");
assertEquals("default", found);
}
@Test
public void givenThreeOptionals_whenChaining_thenFirstNonEmptyIsReturnedAndRestNotEvaluated() {
Optional<String> found = Stream.<Supplier<Optional<String>>>of(this::getEmpty, this::getHello, this::getBye)
.map(Supplier::get)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
assertTrue(this.getEmptyEvaluated);
assertTrue(this.getHelloEvaluated);
assertFalse(this.getByeEvaluated);
assertEquals(getHello(), found);
}
@Test
public void givenTwoOptionalsReturnedByOneArgMethod_whenChaining_thenFirstNonEmptyIsReturned() {
Optional<String> found = Stream.<Supplier<Optional<String>>>of(
() -> createOptional("empty"),
() -> createOptional("hello")
)
.map(Supplier::get)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
assertEquals(createOptional("hello"), found);
}
private Optional<String> getEmpty() {
this.getEmptyEvaluated = true;
return Optional.empty();
}
private Optional<String> getHello() {
this.getHelloEvaluated = true;
return Optional.of("hello");
}
private Optional<String> getBye() {
this.getByeEvaluated = true;
return Optional.of("bye");
}
private Optional<String> createOptional(String input) {
if (input == null || input == "" || input == "empty") {
return Optional.empty();
}
return Optional.of(input);
}
}

View File

@ -9,14 +9,13 @@
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture)
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)
- [Exploring the New HTTP Client in Java 9 and 11](http://www.baeldung.com/java-9-http-client)
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
@ -25,5 +24,7 @@
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)
- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation)

View File

@ -390,7 +390,6 @@
<!-- util -->
<commons-lang3.version>3.8.1</commons-lang3.version>
<lombok.version>1.16.12</lombok.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>

View File

@ -5,7 +5,7 @@
### Relevant Articles:
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Random List Element](http://www.baeldung.com/java-random-list-element)
- [Java Get Random Item/Element From a List](http://www.baeldung.com/java-random-list-element)
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
@ -28,3 +28,6 @@
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)
- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int)
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list)

View File

@ -70,7 +70,6 @@
<commons-lang3.version>3.8.1</commons-lang3.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.11.1</assertj.version>
<lombok.version>1.16.12</lombok.version>
<trove4j.version>3.0.2</trove4j.version>
<fastutil.version>8.1.0</fastutil.version>
<colt.version>1.2.0</colt.version>

View File

@ -0,0 +1,44 @@
package com.baeldung.collection.filtering;
/**
* Java 8 Collection Filtering by List of Values base class.
*
* @author Rodolfo Felipe
*/
public class Employee {
private Integer employeeNumber;
private String name;
private Integer departmentId;
public Employee(Integer employeeNumber, String name, Integer departmentId) {
this.employeeNumber = employeeNumber;
this.name = name;
this.departmentId = departmentId;
}
public Integer getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(Integer employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.collection.filtering;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
/**
* Various filtering examples.
*
* @author Rodolfo Felipe
*/
public class CollectionFilteringUnitTest {
private List<Employee> buildEmployeeList() {
return Arrays.asList(new Employee(1, "Mike", 1), new Employee(2, "John", 1), new Employee(3, "Mary", 1), new Employee(4, "Joe", 2), new Employee(5, "Nicole", 2), new Employee(6, "Alice", 2), new Employee(7, "Bob", 3), new Employee(8, "Scarlett", 3));
}
private List<String> employeeNameFilter() {
return Arrays.asList("Alice", "Mike", "Bob");
}
@Test
public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingForEachLoop() {
List<Employee> filteredList = new ArrayList<>();
List<Employee> originalList = buildEmployeeList();
List<String> nameFilter = employeeNameFilter();
for (Employee employee : originalList) {
for (String name : nameFilter) {
if (employee.getName()
.equalsIgnoreCase(name)) {
filteredList.add(employee);
}
}
}
Assert.assertThat(filteredList.size(), Matchers.is(nameFilter.size()));
}
@Test
public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambda() {
List<Employee> filteredList;
List<Employee> originalList = buildEmployeeList();
List<String> nameFilter = employeeNameFilter();
filteredList = originalList.stream()
.filter(employee -> nameFilter.contains(employee.getName()))
.collect(Collectors.toList());
Assert.assertThat(filteredList.size(), Matchers.is(nameFilter.size()));
}
@Test
public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambdaAndHashSet() {
List<Employee> filteredList;
List<Employee> originalList = buildEmployeeList();
Set<String> nameFilterSet = employeeNameFilter().stream()
.collect(Collectors.toSet());
filteredList = originalList.stream()
.filter(employee -> nameFilterSet.contains(employee.getName()))
.collect(Collectors.toList());
Assert.assertThat(filteredList.size(), Matchers.is(nameFilterSet.size()));
}
}

View File

@ -32,3 +32,5 @@
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences)
- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector)
- [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack)
- [Time Comparison of Arrays.sort(Object[]) and Arrays.sort(int[])](https://www.baeldung.com/arrays-sortobject-vs-sortint)

View File

@ -73,7 +73,6 @@
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.11.1</assertj.version>
<eclipse.collections.version>7.1.0</eclipse.collections.version>
<lombok.version>1.16.12</lombok.version>
<commons-exec.version>1.3</commons-exec.version>
</properties>
</project>

View File

@ -0,0 +1,39 @@
package com.baeldung.java.sort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CollectionsSortCompare {
public static void main(String[] args) {
sortPrimitives();
sortReferenceType();
sortCollection();
}
private static void sortReferenceType() {
Integer[] numbers = {5, 22, 10, 0};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
private static void sortCollection() {
List<Integer> numbersList = new ArrayList<>();
numbersList.add(5);
numbersList.add(22);
numbersList.add(10);
numbersList.add(0);
Collections.sort(numbersList);
numbersList.forEach(System.out::print);
}
private static void sortPrimitives() {
int[] numbers = {5, 22, 10, 0};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.performance;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Measurement(batchSize = 100000, iterations = 10)
@Warmup(batchSize = 100000, iterations = 10)
public class ArraySortBenchmark {
@State(Scope.Thread)
public static class Initialize {
Integer[] numbers = { -769214442, -1283881723, 1504158300, -1260321086, -1800976432, 1278262737, 1863224321, 1895424914, 2062768552, -1051922993, 751605209, -1500919212, 2094856518, -1014488489, -931226326, -1677121986, -2080561705, 562424208, -1233745158, 41308167 };
int[] primitives = { -769214442, -1283881723, 1504158300, -1260321086, -1800976432, 1278262737, 1863224321, 1895424914, 2062768552, -1051922993, 751605209, -1500919212, 2094856518, -1014488489, -931226326, -1677121986, -2080561705, 562424208, -1233745158, 41308167 };
}
@Benchmark
public Integer[] benchmarkArraysIntegerSort(ArraySortBenchmark.Initialize state) {
Arrays.sort(state.numbers);
return state.numbers;
}
@Benchmark
public int[] benchmarkArraysIntSort(ArraySortBenchmark.Initialize state) {
Arrays.sort(state.primitives);
return state.primitives;
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(ArraySortBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -21,4 +21,5 @@
- [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch)
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)
- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)
- [Passing Parameters to Java Threads](https://www.baeldung.com/java-thread-parameters)

View File

@ -16,3 +16,4 @@
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
- [What is Thread-Safety and How to Achieve it](https://www.baeldung.com/java-thread-safety)
- [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread)

View File

@ -3,7 +3,7 @@
## Core Java IO Cookbooks and Examples
### Relevant Articles:
- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file)
- [How to Read a Large File Efficiently with Java](http://www.baeldung.com/java-read-lines-large-file)
- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
- [Java Write to File](http://www.baeldung.com/java-write-to-file)
- [Java - Convert File to InputStream](http://www.baeldung.com/convert-file-to-input-stream)
@ -11,7 +11,7 @@
- [Java Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer)
- [Java Directory Size](http://www.baeldung.com/java-folder-size)
- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library)
- [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size)
- [File Size in Java](http://www.baeldung.com/java-file-size)
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
@ -30,7 +30,6 @@
- [Download a File From an URL in Java](http://www.baeldung.com/java-download-file)
- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink)
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
- [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream)
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
@ -40,3 +39,4 @@
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
- [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files)
- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes)

View File

@ -246,8 +246,6 @@
</profiles>
<properties>
<!-- marshalling -->
<jackson.version>2.9.7</jackson.version>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
@ -259,7 +257,6 @@
<collections-generic.version>4.01</collections-generic.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<lombok.version>1.16.12</lombok.version>
<fscontext.version>4.6-b01</fscontext.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>

6
core-java-jvm/README.md Normal file
View File

@ -0,0 +1,6 @@
=========
## Core Java JVM Cookbooks and Examples
### Relevant Articles:
- [Method Inlining in the JVM](http://www.baeldung.com/method-inlining-in-the-jvm/)

40
core-java-jvm/pom.xml Normal file
View File

@ -0,0 +1,40 @@
<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-jvm</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-jvm</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<commons-lang3.version>3.5</commons-lang3.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,19 @@
package com.baeldung.inlining;
public class ConsecutiveNumbersSum {
private long totalSum;
private int totalNumbers;
public ConsecutiveNumbersSum(int totalNumbers) {
this.totalNumbers = totalNumbers;
}
public long getTotalSum() {
totalSum = 0;
for (int i = 1; i <= totalNumbers; i++) {
totalSum += i;
}
return totalSum;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.inlining;
public class InliningExample {
public static final int NUMBERS_OF_ITERATIONS = 15000;
public static void main(String[] args) {
for (int i = 1; i < NUMBERS_OF_ITERATIONS; i++) {
calculateSum(i);
}
}
private static long calculateSum(int n) {
return new ConsecutiveNumbersSum(n).getTotalSum();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.inlining;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ConsecutiveNumbersSumUnitTest {
private static final int TOTAL_NUMBERS = 10;
@Test
public void givenTotalIntegersNumber_whenSumCalculated_thenEquals() {
ConsecutiveNumbersSum consecutiveNumbersSum = new ConsecutiveNumbersSum(TOTAL_NUMBERS);
long expectedSum = calculateExpectedSum(TOTAL_NUMBERS);
assertEquals(expectedSum, consecutiveNumbersSum.getTotalSum());
}
private long calculateExpectedSum(int totalNumbers) {
return totalNumbers * (totalNumbers + 1) / 2;
}
}

4
core-java-lang-oop-2/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
target/
.idea/
bin/
*.iml

View File

@ -0,0 +1,5 @@
=========
## Core Java Lang OOP 2 Cookbooks and Examples
### Relevant Articles:

View File

@ -0,0 +1,27 @@
<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-lang-oop-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-oop-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>
<build>
<finalName>core-java-lang-oop-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

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