Merge branch 'master' into master

This commit is contained in:
Loredana Crusoveanu 2019-04-13 14:22:12 +03:00 committed by GitHub
commit 3990032d76
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1331 changed files with 72513 additions and 4984 deletions

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

@ -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>
@ -77,7 +82,7 @@
<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,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

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

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

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

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

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

View File

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

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

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

@ -10,3 +10,6 @@
- [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)

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,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,4 +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)

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

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

@ -0,0 +1,6 @@
=========
## Core Java 8 Cookbooks and Examples (part 2)
### Relevant Articles:
- [Anonymous Classes in Java](http://www.baeldung.com/)

43
core-java-8-2/pom.xml Normal file
View File

@ -0,0 +1,43 @@
<?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>
</properties>
<dependencies>
</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>

View File

@ -0,0 +1,15 @@
package com.baeldung.anonymous;
public class Book {
final String title;
public Book(String title) {
this.title = title;
}
public String description() {
return "Title: " + title;
}
}

View File

@ -0,0 +1,64 @@
package com.baeldung.anonymous;
import java.util.ArrayList;
import java.util.List;
/**
* Code snippet that illustrates the usage of anonymous classes.
*
* Note that use of Runnable instances in this example does not demonstrate their
* common use.
*
* @author A. Shcherbakov
*
*/
public class Main {
public static void main(String[] args) {
final List<Runnable> actions = new ArrayList<Runnable>(2);
Runnable action = new Runnable() {
@Override
public void run() {
System.out.println("Hello from runnable.");
}
};
actions.add(action);
Book book = new Book("Design Patterns") {
@Override
public String description() {
return "Famous GoF book.";
}
};
System.out.println(String.format("Title: %s, description: %s", book.title, book.description()));
actions.add(new Runnable() {
@Override
public void run() {
System.out.println("Hello from runnable #2.");
}
});
int count = 1;
Runnable action2 = new Runnable() {
static final int x = 0;
// static int y = 0;
@Override
public void run() {
System.out.println(String.format("Runnable with captured variables: count = %s, x = %s", count, x));
}
};
actions.add(action2);
for (Runnable a : actions) {
a.run();
}
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Unit test for simple App.
*/
public class UnitTest {
/**
* Stub test
*/
@Test
public void givenPreconditions_whenCondition_shouldResult() {
assertTrue(true);
}
}

View File

@ -3,10 +3,10 @@
## Core Java 8 Cookbooks and Examples
### 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)
- [Guide to Java 8s 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)
- [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)
@ -39,3 +39,4 @@
- [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

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

View File

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

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.java8.lambda.tips;
@FunctionalInterface

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.java8.lambda.tips;
@FunctionalInterface

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.java8.lambda.tips;
@FunctionalInterface

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.java8.lambda.tips;
@FunctionalInterface

View File

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

View File

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

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.java8.lambda.tips;
import java.util.function.Function;

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

@ -1,8 +1,8 @@
package com.baeldung.java8;
package com.baeldung.java8.lambda.tips;
import com.baeldung.Foo;
import com.baeldung.FooExtended;
import com.baeldung.UseFoo;
import com.baeldung.java8.lambda.tips.Foo;
import com.baeldung.java8.lambda.tips.FooExtended;
import com.baeldung.java8.lambda.tips.UseFoo;
import org.junit.Before;
import org.junit.Test;

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

@ -5,27 +5,21 @@
[Java 9 New Features](http://www.baeldung.com/new-java-9)
### Relevant Articles:
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
- [Java 9 New Features](https://www.baeldung.com/new-java-9)
- [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)
- [Java 9 Variable Handles Demystified](http://www.baeldung.com/java-variable-handles)
- [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)
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
- [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)
- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api)
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)

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

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

@ -0,0 +1,6 @@
=========
## Core Java Collections 2
### Relevant Articles:
- Java - Copying a HashMap

View File

@ -0,0 +1,78 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-map</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-map</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse.collections.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>${commons-exec.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<junit.platform.version>1.2.0</junit.platform.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.11.1</assertj.version>
<eclipse.collections.version>7.1.0</eclipse.collections.version>
<commons-exec.version>1.3</commons-exec.version>
</properties>
</project>

View File

@ -0,0 +1,55 @@
package com.baeldung.copyinghashmap;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.SerializationUtils;
public class CopyHashMap {
public static <String, Employee> HashMap<String, Employee> copyUsingConstructor(HashMap<String, Employee> originalMap) {
return new HashMap<String, Employee>(originalMap);
}
public static <String, Employee> HashMap<String, Employee> copyUsingClone(HashMap<String, Employee> originalMap) {
return (HashMap<String, Employee>) originalMap.clone();
}
public static <String, Employee> HashMap<String, Employee> copyUsingPut(HashMap<String, Employee> originalMap) {
HashMap<String, Employee> shallowCopy = new HashMap<String, Employee>();
Set<Entry<String, Employee>> entries = originalMap.entrySet();
for(Map.Entry<String, Employee> mapEntry: entries) {
shallowCopy.put(mapEntry.getKey(), mapEntry.getValue());
}
return shallowCopy;
}
public static <String, Employee> HashMap<String, Employee> copyUsingPutAll(HashMap<String, Employee> originalMap) {
HashMap<String, Employee> shallowCopy = new HashMap<String, Employee>();
shallowCopy.putAll(originalMap);
return shallowCopy;
}
public static <String, Employee> HashMap<String, Employee> copyUsingJava8Stream(HashMap<String, Employee> originalMap) {
Set<Entry<String, Employee>> entries = originalMap.entrySet();
HashMap<String, Employee> shallowCopy = (HashMap<String, Employee>) entries
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return shallowCopy;
}
public static <String, Employee> HashMap<String, Employee> shallowCopy(HashMap<String, Employee> originalMap) {
return (HashMap<String, Employee>) originalMap.clone();
}
public static <String, Employee> HashMap<String, Employee> deepCopy(HashMap<String, Employee> originalMap) {
return SerializationUtils.clone(originalMap);
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.copyinghashmap;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
public class CopyHashMapUnitTest {
@Test
public void givenHashMap_whenShallowCopy_thenCopyisNotSameAsOriginal() {
HashMap<String, Employee> map = new HashMap<>();
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Norman");
map.put("emp1",emp1);
map.put("emp2",emp2);
HashMap<String, Employee> shallowCopy = CopyHashMap.shallowCopy(map);
assertThat(shallowCopy).isNotSameAs(map);
}
@Test
public void givenHashMap_whenShallowCopyModifyingOriginalObject_thenCopyShouldChange() {
HashMap<String, Employee> map = new HashMap<>();
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Norman");
map.put("emp1",emp1);
map.put("emp2",emp2);
HashMap<String, Employee> shallowCopy = CopyHashMap.shallowCopy(map);
emp1.setName("Johny");
assertThat(shallowCopy.get("emp1")).isEqualTo(map.get("emp1"));
}
@Test
public void givenHashMap_whenDeepCopyModifyingOriginalObject_thenCopyShouldNotChange() {
HashMap<String, Employee> map = new HashMap<>();
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Norman");
map.put("emp1",emp1);
map.put("emp2",emp2);
HashMap<String, Employee> deepCopy = CopyHashMap.deepCopy(map);
emp1.setName("Johny");
assertThat(deepCopy.get("emp1")).isNotEqualTo(map.get("emp1"));
}
@Test
public void givenImmutableMap_whenCopyUsingGuava_thenCopyShouldNotChange() {
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Norman");
Map<String, Employee> map = ImmutableMap.<String, Employee> builder()
.put("emp1",emp1)
.put("emp2",emp2)
.build();
Map<String, Employee> shallowCopy = ImmutableMap.copyOf(map);
assertThat(shallowCopy).isSameAs(map);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.copyinghashmap;
import java.io.Serializable;
public class Employee implements Serializable{
private String name;
public Employee(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}

View File

@ -3,7 +3,7 @@
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [Java Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
@ -33,3 +33,4 @@
- [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

@ -1,17 +1,21 @@
package com.baeldung.performance;
import org.openjdk.jmh.annotations.*;
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;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.SingleShotTime)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Measurement(batchSize = 100000, iterations = 10)
@Warmup(batchSize = 100000, iterations = 10)
@ -19,8 +23,8 @@ public class ArraySortBenchmark {
@State(Scope.Thread)
public static class Initialize {
Integer[] numbers = {5, 22, 10, 0};
int[] primitives = {5, 22, 10, 0};
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

View File

@ -12,7 +12,7 @@
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
- [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables)
- [CyclicBarrier in Java](http://www.baeldung.com/java-cyclic-barrier)
- [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile)
- [Guide to the Volatile Keyword in Java](http://www.baeldung.com/java-volatile)
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
- [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule)
@ -20,5 +20,6 @@
- [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads)
- [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)
- [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)
- [Passing Parameters to Java Threads](https://www.baeldung.com/java-thread-parameters)

View File

@ -7,12 +7,13 @@
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future)
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
- [Guide to the Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
- [Implementing a Runnable vs Extending a Thread](http://www.baeldung.com/java-runnable-vs-extending-thread)
- [How to Kill a Java Thread](http://www.baeldung.com/java-thread-stop)
- [ExecutorService - Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads)
- [ExecutorService Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads)
- [wait and notify() Methods in Java](http://www.baeldung.com/java-wait-notify)
- [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)
- [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,18 +3,18 @@
## 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)
- [Java Convert File to InputStream](http://www.baeldung.com/convert-file-to-input-stream)
- [Java Scanner](http://www.baeldung.com/java-scanner)
- [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)
- [How to Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Java Append Data to a File](http://www.baeldung.com/java-append-to-file)
- [FileNotFoundException in Java](http://www.baeldung.com/java-filenotfound-exception)
- [How to Read a File in Java](http://www.baeldung.com/reading-file-in-java)
@ -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)

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](https://www.baeldung.com/jvm-method-inlining)

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

19
core-java-lambdas/pom.xml Normal file
View File

@ -0,0 +1,19 @@
<?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-java-lambdas</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
</project>

View File

@ -0,0 +1,88 @@
package com.baeldung.lambdas;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
import java.util.stream.IntStream;
/**
* Class with examples about working with capturing lambdas.
*/
public class LambdaVariables {
private volatile boolean run = true;
private int start = 0;
private ExecutorService executor = Executors.newFixedThreadPool(3);
public static void main(String[] args) {
new LambdaVariables().localVariableMultithreading();
}
Supplier<Integer> incrementer(int start) {
return () -> start; // can't modify start parameter inside the lambda
}
Supplier<Integer> incrementer() {
return () -> start++;
}
public void localVariableMultithreading() {
boolean run = true;
executor.execute(() -> {
while (run) {
// do operation
}
});
// commented because it doesn't compile, it's just an example of non-final local variables in lambdas
// run = false;
}
public void instanceVariableMultithreading() {
executor.execute(() -> {
while (run) {
// do operation
}
});
run = false;
}
/**
* WARNING: always avoid this workaround!!
*/
public void workaroundSingleThread() {
int[] holder = new int[] { 2 };
IntStream sums = IntStream
.of(1, 2, 3)
.map(val -> val + holder[0]);
holder[0] = 0;
System.out.println(sums.sum());
}
/**
* WARNING: always avoid this workaround!!
*/
public void workaroundMultithreading() {
int[] holder = new int[] { 2 };
Runnable runnable = () -> System.out.println(IntStream
.of(1, 2, 3)
.map(val -> val + holder[0])
.sum());
new Thread(runnable).start();
// simulating some processing
try {
Thread.sleep(new Random().nextInt(3) * 1000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
holder[0] = 0;
}
}

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>

View File

@ -0,0 +1,16 @@
package com.baeldung.supertypecompilerexception;
public class MyClass {
private int myField1 = 10;
private int myField2;
public MyClass() {
//uncomment this to see the supertype compiler error:
//this(myField1);
}
public MyClass(int i) {
myField2 = i;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.supertypecompilerexception;
public class MyClassSolution1 {
private int myField1 = 10;
private int myField2;
public MyClassSolution1() {
myField2 = myField1;
}
public MyClassSolution1(int i) {
myField2 = i;
}
}

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