Merge branch 'master' into BAEL-13599

This commit is contained in:
Loredana Crusoveanu 2019-04-27 22:56:34 +03:00 committed by GitHub
commit 89058e9747
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
133 changed files with 2676 additions and 183 deletions

View File

@ -1,8 +1,9 @@
package com.baeldung.autofactory.provided;
import com.baeldung.autofactory.model.Camera;
import com.google.auto.factory.AutoFactory;
import com.google.auto.factory.Provided;
import javafx.scene.Camera;
import javax.inject.Provider;

View File

@ -0,0 +1,6 @@
# Groovy
## Relevant articles:
- [Maps in Groovy](http://www.baeldung.com/)

View File

@ -0,0 +1,131 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-groovy-collections</artifactId>
<version>1.0-SNAPSHOT</version>
<name>core-groovy-collections</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy-all.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-dateutil</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-sql</artifactId>
<version>${groovy-sql.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>${spock-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>${gmavenplus-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>compile</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>junit5</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*Test5.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<configuration>
<useFile>false</useFile>
<includes>
<include>**/*Test.java</include>
<include>**/*Spec.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>central</id>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
<properties>
<junit.platform.version>1.0.0</junit.platform.version>
<groovy.version>2.5.6</groovy.version>
<groovy-all.version>2.5.6</groovy-all.version>
<groovy-sql.version>2.5.6</groovy-sql.version>
<hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version>
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,148 @@
package com.baeldung.map;
import static groovy.test.GroovyAssert.*
import org.junit.Test
class MapTest{
@Test
void createMap() {
def emptyMap = [:]
assertNotNull(emptyMap)
assertTrue(emptyMap instanceof java.util.LinkedHashMap)
def map = [name:"Jerry", age: 42, city: "New York"]
assertTrue(map.size() == 3)
}
@Test
void addItemsToMap() {
def map = [name:"Jerry"]
map["age"] = 42
map.city = "New York"
def hobbyLiteral = "hobby"
def hobbyMap = [(hobbyLiteral): "Singing"]
map.putAll(hobbyMap)
assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"])
assertTrue(hobbyMap.hobby == "Singing")
assertTrue(hobbyMap[hobbyLiteral] == "Singing")
map.plus([1:20]) // returns new map
map << [2:30]
}
@Test
void getItemsFromMap() {
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
assertTrue(map["name"] == "Jerry")
assertTrue(map.name == "Jerry")
def propertyAge = "age"
assertTrue(map[propertyAge] == 42)
}
@Test
void removeItemsFromMap() {
def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49]
def minusMap = map.minus([2:42, 4:34]);
assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49])
minusMap.removeAll{it -> it.key instanceof String}
assertTrue( minusMap == [ 1:20, 6:39, 7:49])
minusMap.retainAll{it -> it.value %2 == 0}
assertTrue( minusMap == [1:20])
}
@Test
void iteratingOnMaps(){
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
map.each{ entry -> println "$entry.key: $entry.value" }
map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" }
map.eachWithIndex{ key, value, i -> println "$i $key: $value" }
}
@Test
void filteringAndSearchingMaps(){
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
assertTrue(map.find{ it.value == "New York"}.key == "city")
assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"])
map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")}
assertTrue(map.every{it -> it.value instanceof String} == false)
assertTrue(map.any{it -> it.value instanceof String} == true)
}
@Test
void collect(){
def map = [1: [name:"Jerry", age: 42, city: "New York"],
2: [name:"Long", age: 25, city: "New York"],
3: [name:"Dustin", age: 29, city: "New York"],
4: [name:"Dustin", age: 34, city: "New York"]]
def names = map.collect{entry -> entry.value.name} // returns only list
assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"])
def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name}
assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set)
def idNames = map.collectEntries{key, value -> [key, value.name]}
assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"])
def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name}
assertTrue(below30Names == ["Long", "Dustin"])
}
@Test
void group(){
def map = [1:20, 2: 40, 3: 11, 4: 93]
def subMap = map.groupBy{it.value % 2}
println subMap
assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]])
def keySubMap = map.subMap([1, 2])
assertTrue(keySubMap == [1:20, 2:40])
}
@Test
void sorting(){
def map = [ab:20, a: 40, cb: 11, ba: 93]
def naturallyOrderedMap = map.sort()
assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap)
def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator)
assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap)
def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value })
assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap)
}
}

View File

@ -0,0 +1,148 @@
package com.baeldung.groovy.map;
import static groovy.test.GroovyAssert.*
import org.junit.Test
class MapTest{
@Test
void createMap() {
def emptyMap = [:]
assertNotNull(emptyMap)
assertTrue(emptyMap instanceof java.util.LinkedHashMap)
def map = [name:"Jerry", age: 42, city: "New York"]
assertTrue(map.size() == 3)
}
@Test
void addItemsToMap() {
def map = [name:"Jerry"]
map["age"] = 42
map.city = "New York"
def hobbyLiteral = "hobby"
def hobbyMap = [(hobbyLiteral): "Singing"]
map.putAll(hobbyMap)
assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"])
assertTrue(hobbyMap.hobby == "Singing")
assertTrue(hobbyMap[hobbyLiteral] == "Singing")
map.plus([1:20]) // returns new map
map << [2:30]
}
@Test
void getItemsFromMap() {
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
assertTrue(map["name"] == "Jerry")
assertTrue(map.name == "Jerry")
def propertyAge = "age"
assertTrue(map[propertyAge] == 42)
}
@Test
void removeItemsFromMap() {
def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49]
def minusMap = map.minus([2:42, 4:34]);
assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49])
minusMap.removeAll{it -> it.key instanceof String}
assertTrue( minusMap == [ 1:20, 6:39, 7:49])
minusMap.retainAll{it -> it.value %2 == 0}
assertTrue( minusMap == [1:20])
}
@Test
void iteratingOnMaps(){
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
map.each{ entry -> println "$entry.key: $entry.value" }
map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" }
map.eachWithIndex{ key, value, i -> println "$i $key: $value" }
}
@Test
void filteringAndSearchingMaps(){
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
assertTrue(map.find{ it.value == "New York"}.key == "city")
assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"])
map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")}
assertTrue(map.every{it -> it.value instanceof String} == false)
assertTrue(map.any{it -> it.value instanceof String} == true)
}
@Test
void collect(){
def map = [1: [name:"Jerry", age: 42, city: "New York"],
2: [name:"Long", age: 25, city: "New York"],
3: [name:"Dustin", age: 29, city: "New York"],
4: [name:"Dustin", age: 34, city: "New York"]]
def names = map.collect{entry -> entry.value.name} // returns only list
assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"])
def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name}
assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set)
def idNames = map.collectEntries{key, value -> [key, value.name]}
assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"])
def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name}
assertTrue(below30Names == ["Long", "Dustin"])
}
@Test
void group(){
def map = [1:20, 2: 40, 3: 11, 4: 93]
def subMap = map.groupBy{it.value % 2}
println subMap
assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]])
def keySubMap = map.subMap([1, 2])
assertTrue(keySubMap == [1:20, 2:40])
}
@Test
void sorting(){
def map = [ab:20, a: 40, cb: 11, ba: 93]
def naturallyOrderedMap = map.sort()
assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap)
def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator)
assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap)
def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value })
assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap)
}
}

View File

@ -27,34 +27,35 @@ public class OptionalUnitTest {
@Test
public void givenNonNull_whenCreatesNonNullable_thenCorrect() {
String name = "baeldung";
Optional.of(name);
Optional<String> opt = Optional.of(name);
assertTrue(opt.isPresent());
}
@Test(expected = NullPointerException.class)
public void givenNull_whenThrowsErrorOnCreate_thenCorrect() {
String name = null;
Optional<String> opt = Optional.of(name);
Optional.of(name);
}
@Test
public void givenNonNull_whenCreatesOptional_thenCorrect() {
String name = "baeldung";
Optional<String> opt = Optional.of(name);
assertEquals("Optional[baeldung]", opt.toString());
assertTrue(opt.isPresent());
}
@Test
public void givenNonNull_whenCreatesNullable_thenCorrect() {
String name = "baeldung";
Optional<String> opt = Optional.ofNullable(name);
assertEquals("Optional[baeldung]", opt.toString());
assertTrue(opt.isPresent());
}
@Test
public void givenNull_whenCreatesNullable_thenCorrect() {
String name = null;
Optional<String> opt = Optional.ofNullable(name);
assertEquals("Optional.empty", opt.toString());
assertFalse(opt.isPresent());
}
// Checking Value With isPresent()

View File

@ -0,0 +1,34 @@
package com.baeldung.array;
import java.util.ArrayList;
import java.util.Arrays;
public class AddElementToEndOfArray {
public Integer[] addElementUsingArraysCopyOf(Integer[] srcArray, int elementToAdd) {
Integer[] destArray = Arrays.copyOf(srcArray, srcArray.length + 1);
destArray[destArray.length - 1] = elementToAdd;
return destArray;
}
public Integer[] addElementUsingArrayList(Integer[] srcArray, int elementToAdd) {
Integer[] destArray = new Integer[srcArray.length + 1];
ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(srcArray));
arrayList.add(elementToAdd);
return arrayList.toArray(destArray);
}
public Integer[] addElementUsingSystemArrayCopy(Integer[] srcArray, int elementToAdd) {
Integer[] destArray = new Integer[srcArray.length + 1];
System.arraycopy(srcArray, 0, destArray, 0, srcArray.length);
destArray[destArray.length - 1] = elementToAdd;
return destArray;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.array;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class AddElementToEndOfArrayUnitTest {
AddElementToEndOfArray addElementToEndOfArray;
@Before
public void init() {
addElementToEndOfArray = new AddElementToEndOfArray();
}
@Test
public void givenSourceArrayAndElement_whenAddElementUsingArraysCopyIsInvoked_thenNewElementMustBeAdded() {
Integer[] sourceArray = {1, 2, 3, 4};
int elementToAdd = 5;
Integer[] destArray = addElementToEndOfArray.addElementUsingArraysCopyOf(sourceArray, elementToAdd);
Integer[] expectedArray = {1, 2, 3, 4, 5};
assertArrayEquals(expectedArray, destArray);
}
@Test
public void givenSourceArrayAndElement_whenAddElementUsingArrayListIsInvoked_thenNewElementMustBeAdded() {
Integer[] sourceArray = {1, 2, 3, 4};
int elementToAdd = 5;
Integer[] destArray = addElementToEndOfArray.addElementUsingArrayList(sourceArray, elementToAdd);
Integer[] expectedArray = {1, 2, 3, 4, 5};
assertArrayEquals(expectedArray, destArray);
}
@Test
public void givenSourceArrayAndElement_whenAddElementUsingSystemArrayCopyIsInvoked_thenNewElementMustBeAdded() {
Integer[] sourceArray = {1, 2, 3, 4};
int elementToAdd = 5;
Integer[] destArray = addElementToEndOfArray.addElementUsingSystemArrayCopy(sourceArray, elementToAdd);
Integer[] expectedArray = {1, 2, 3, 4, 5};
assertArrayEquals(expectedArray, destArray);
}
}

View File

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

View File

@ -1,78 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>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,6 @@
=========
## Core Java Sets Cookbooks and Examples
### Relevant Articles:
- [Set Operations in Java](http://www.baeldung.com/set-operations-in-java)

View File

@ -0,0 +1,33 @@
<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-set</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-set</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>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.3</commons-collections4.version>
<guava.version>27.1-jre</guava.version>
</properties>
</project>

View File

@ -0,0 +1,93 @@
package com.baeldung.set;
import static org.junit.Assert.*;
import org.apache.commons.collections4.SetUtils;
import org.junit.Test;
import com.google.common.collect.Sets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SetOperationsUnitTest {
private Set<Integer> setA = setOf(1,2,3,4);
private Set<Integer> setB = setOf(2,4,6,8);
private static Set<Integer> setOf(Integer... values) {
return new HashSet<Integer>(Arrays.asList(values));
}
@Test
public void givenTwoSets_WhenWeRetainAll_ThenWeIntersectThem() {
Set<Integer> intersectSet = new HashSet<>(setA);
intersectSet.retainAll(setB);
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoSets_WhenWeAddAll_ThenWeUnionThem() {
Set<Integer> unionSet = new HashSet<>(setA);
unionSet.addAll(setB);
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
@Test
public void givenTwoSets_WhenRemoveAll_ThenWeGetTheDifference() {
Set<Integer> differenceSet = new HashSet<>(setA);
differenceSet.removeAll(setB);
assertEquals(setOf(1,3), differenceSet);
}
@Test
public void givenTwoStreams_WhenWeFilterThem_ThenWeCanGetTheIntersect() {
Set<Integer> intersectSet = setA.stream()
.filter(setB::contains)
.collect(Collectors.toSet());
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoStreams_WhenWeConcatThem_ThenWeGetTheUnion() {
Set<Integer> unionSet = Stream.concat(setA.stream(), setB.stream())
.collect(Collectors.toSet());
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
@Test
public void givenTwoStreams_WhenWeFilterThem_ThenWeCanGetTheDifference() {
Set<Integer> differenceSet = setA.stream()
.filter(val -> !setB.contains(val))
.collect(Collectors.toSet());
assertEquals(setOf(1,3), differenceSet);
}
@Test
public void givenTwoSets_WhenWeUseApacheCommonsIntersect_ThenWeGetTheIntersect() {
Set<Integer> intersectSet = SetUtils.intersection(setA, setB);
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoSets_WhenWeUseApacheCommonsUnion_ThenWeGetTheUnion() {
Set<Integer> unionSet = SetUtils.union(setA, setB);
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
@Test
public void givenTwoSets_WhenWeUseGuavaIntersect_ThenWeGetTheIntersect() {
Set<Integer> intersectSet = Sets.intersection(setA, setB);
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoSets_WhenWeUseGuavaUnion_ThenWeGetTheUnion() {
Set<Integer> unionSet = Sets.union(setA, setB);
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
}

19
core-java-modules/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-modules</artifactId>
<name>core-java-modules</name>
<packaging>pom</packaging>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>pre-jpms</module>
</modules>
</project>

View File

@ -0,0 +1,74 @@
<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>pre-jpms</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>pre-jpms</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
<build>
<finalName>pre-jpms</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.1</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
${project.build.directory}/dependency-jars/
</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.baeldung.prejpms.App</mainClass>
<addClasspath>true</addClasspath>
<classpathPrefix>dependency-jars/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,77 @@
package com.baeldung.prejpms;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.crypto.provider.SunJCE;
import sun.misc.BASE64Encoder;
import sun.reflect.Reflection;
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
public static void main(String[] args) throws Exception {
getCrytpographyProviderName();
getCallStackClassNames();
getXmlFromObject(new Book(100, "Java Modules Architecture"));
getBase64EncodedString("Java");
}
private static void getCrytpographyProviderName() {
try {
LOGGER.info("1. JCE Provider Name: {}\n", new SunJCE().getName());
} catch (Throwable e) {
LOGGER.error(e.toString());
}
}
private static void getCallStackClassNames() {
try {
StringBuffer sbStack = new StringBuffer();
int i = 0;
Class<?> caller = Reflection.getCallerClass(i++);
do {
sbStack.append(i + ".")
.append(caller.getName())
.append("\n");
caller = Reflection.getCallerClass(i++);
} while (caller != null);
LOGGER.info("2. Call Stack:\n{}", sbStack);
} catch (Throwable e) {
LOGGER.error(e.toString());
}
}
private static void getXmlFromObject(Book book) {
try {
Marshaller marshallerObj = JAXBContext.newInstance(Book.class)
.createMarshaller();
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
marshallerObj.marshal(book, sw);
LOGGER.info("3. Xml for Book object:\n{}", sw);
} catch (Throwable e) {
LOGGER.error(e.toString());
}
}
private static void getBase64EncodedString(String inputString) {
try {
String encodedString = new BASE64Encoder().encode(inputString.getBytes());
LOGGER.info("4. Base Encoded String: {}", encodedString);
} catch (Throwable e) {
LOGGER.error(e.toString());
}
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.prejpms;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "book")
public class Book {
private long id;
private String name;
public Book() {
}
public Book(long id, String name) {
this.id = id;
this.name = name;
}
@XmlAttribute
public void setId(Long id) {
this.id = id;
}
@XmlElement(name = "title")
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
}

View File

@ -0,0 +1,10 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -20,9 +20,21 @@
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>${byte-buddy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -37,6 +49,12 @@
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test-junit5</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -69,10 +87,11 @@
</build>
<properties>
<kotlin.version>1.2.71</kotlin.version>
<junit.platform.version>1.1.1</junit.platform.version>
<junit.vintage.version>5.2.0</junit.vintage.version>
<kotlin.version>1.3.30</kotlin.version>
<junit.jupiter.version>5.4.2</junit.jupiter.version>
<mockito.version>2.27.0</mockito.version>
<byte-buddy.version>1.9.12</byte-buddy.version>
<assertj.version>3.10.0</assertj.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,31 @@
package com.baeldung.jvmannotations
import java.util.*
interface Document {
@JvmDefault
fun getType() = "document"
}
class TextDocument : Document {
override fun getType() = "text"
fun transformList(list : List<Number>) : List<Number> {
return list.filter { n -> n.toInt() > 1 }
}
fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> {
return list.filter { n -> n.toInt() > 1 }
}
var list : List<@JvmWildcard Any> = ArrayList()
}
class XmlDocument(d : Document) : Document by d
fun main() {
val myDocument = TextDocument()
val myTextDocument = XmlDocument(myDocument)
println("${myDocument.getType()} ${myTextDocument.getType()}")
}

View File

@ -0,0 +1,9 @@
package com.baeldung.jvmannotations;
public class HtmlDocument implements Document {
@Override
public String getType() {
return "HTML";
}
}

View File

@ -0,0 +1,66 @@
@file:JvmName("MessageHelper")
@file:JvmMultifileClass //used
package com.baeldung.jvmannotations
import java.util.*
@JvmName("getMyUsername")
fun getMyName() : String {
return "myUserId"
}
object MessageBroker {
@JvmStatic
var totalMessagesSent = 0
const val maxMessageLength = 0
@JvmStatic
fun clearAllMessages() {
}
@JvmStatic
@JvmOverloads
@Throws(Exception::class)
fun findMessages(sender : String, type : String = "text", maxResults : Int = 10) : List<Message> {
if(sender.isEmpty()) {
throw Exception()
}
return ArrayList()
}
}
class Message {
// this would cause a compilation error since sender is immutable
// @set:JvmName("setSender")
val sender = "myself"
// this works as name is overridden
@JvmName("getSenderName")
fun getSender() : String = "from:$sender"
@get:JvmName("getReceiverName")
@set:JvmName("setReceiverName")
var receiver : String = ""
@get:JvmName("getContent")
@set:JvmName("setContent")
var text = ""
// generates a warning
@get:JvmName("getId")
private val id = 0
@get:JvmName("hasAttachment")
var hasAttachment = true
var isEncrypted = true
fun setReceivers(receiverNames : List<String>) {
}
@JvmName("setReceiverIds")
fun setReceivers(receiverNames : List<Int>) {
}
}

View File

@ -0,0 +1,6 @@
@file:JvmMultifileClass
@file:JvmName("MessageHelper") //applies to all top level functions / variables / constants
package com.baeldung.jvmannotations
fun convert(message: Message) {
}

44
fastUtil/pom.xml Normal file
View File

@ -0,0 +1,44 @@
<?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>fastUtil</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/it.unimi.dsi/fastutil -->
<dependency>
<groupId>it.unimi.dsi</groupId>
<artifactId>fastutil</artifactId>
<version>8.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,23 @@
package com.baeldung;
import it.unimi.dsi.fastutil.ints.IntBigArrays;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class BigArraysUnitTest {
@Test
public void givenValidAray_whenWrapped_checkAccessFromIntBigArraysMethodsCorrect() {
int[] oneDArray = new int[] { 2, 1, 5, 2, 1, 7 };
int[][] twoDArray = IntBigArrays.wrap(oneDArray.clone());
int firstIndex = IntBigArrays.get(twoDArray, 0);
int lastIndex = IntBigArrays.get(twoDArray, IntBigArrays.length(twoDArray)-1);
assertEquals(2, firstIndex);
assertEquals(7, lastIndex);
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
public class FastUtilTypeSpecificBenchmarkUnitTest {
@Param({"100", "1000", "10000", "100000"})
public int setSize;
@Benchmark
public IntSet givenFastUtilsIntSetWithInitialSizeSet_whenPopulated_checkTimeTaken() {
IntSet intSet = new IntOpenHashSet(setSize);
for(int i = 0; i < setSize; i++){
intSet.add(i);
}
return intSet;
}
@Benchmark
public Set<Integer> givenCollectionsHashSetWithInitialSizeSet_whenPopulated_checkTimeTaken() {
Set<Integer> intSet = new HashSet<Integer>(setSize);
for(int i = 0; i < setSize; i++){
intSet.add(i);
}
return intSet;
}
public static void main(String... args) throws RunnerException {
Options opts = new OptionsBuilder()
.include(".*")
.warmupIterations(1)
.measurementIterations(2)
.jvmArgs("-Xms2g", "-Xmx2g")
.shouldDoGC(true)
.forks(1)
.build();
new Runner(opts).run();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung;
import it.unimi.dsi.fastutil.doubles.Double2DoubleMap;
import it.unimi.dsi.fastutil.doubles.Double2DoubleOpenHashMap;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class FastUtilTypeSpecificUnitTest {
@Test
public void givenValidDouble2DoubleMap_whenContentsQueried_checkCorrect(){
Double2DoubleMap d2dMap = new Double2DoubleOpenHashMap();
d2dMap.put(2.0, 5.5);
d2dMap.put(3.0, 6.6);
assertEquals(5.5, d2dMap.get(2.0));
}
}

View File

@ -9,4 +9,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [HttpClient 4 Get the Status Code](http://www.baeldung.com/httpclient-status-code)
- [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl)
- [Custom HTTP Header with the HttpClient](http://www.baeldung.com/httpclient-custom-http-header)
- [Custom HTTP Header with the HttpClient](http://www.baeldung.com/httpclient-custom-http-header)
- [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication)
- [Posting with HttpClient](https://www.baeldung.com/httpclient-post-http-request)

View File

@ -23,19 +23,18 @@ import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
/*
* NOTE : Need module spring-security-rest-basic-auth to be running
* NOTE : Need module httpclient-simple to be running
*/
public class HttpClientAuthLiveTest {
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://localhost:8081/spring-security-rest-basic-auth/api/foos/1";
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://localhost:8082/httpclient-simple/api/foos/1";
private static final String DEFAULT_USER = "user1";
private static final String DEFAULT_PASS = "user1Pass";
@ -111,7 +110,7 @@ public class HttpClientAuthLiveTest {
}
private HttpContext context() {
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
final HttpHost targetHost = new HttpHost("localhost", 8082, "http");
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));

View File

@ -12,7 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [HttpClient 4 Cookbook](http://www.baeldung.com/httpclient4)
- [Unshorten URLs with HttpClient](http://www.baeldung.com/unshorten-url-httpclient)
- [HttpClient 4 Follow Redirects for POST](http://www.baeldung.com/httpclient-redirect-on-http-post)
- [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication)
- [Multipart Upload with HttpClient 4](http://www.baeldung.com/httpclient-multipart-upload)
- [HttpAsyncClient Tutorial](http://www.baeldung.com/httpasyncclient-tutorial)
- [HttpClient 4 Tutorial](http://www.baeldung.com/httpclient-guide)

View File

@ -33,9 +33,6 @@ public class FooUnitTest {
srcCollection.add(sam);
srcCollection.add(alice);
srcCollection.add(buffy);
// make sure the collection isn't sorted accidentally
assertFalse("Oops: source collection is already sorted!", isSorted(srcCollection));
}
/**

View File

@ -36,6 +36,17 @@
<artifactId>colt</artifactId>
<version>${colt.version}</version>
</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>
@ -43,6 +54,8 @@
<trove4j.version>3.0.2</trove4j.version>
<fastutil.version>8.1.0</fastutil.version>
<colt.version>1.2.0</colt.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<assertj.version>3.11.1</assertj.version>
</properties>
</project>

View File

@ -1,4 +1,4 @@
package com.baeldung.copyinghashmap;
package com.baeldung.map;
import java.util.HashMap;
import java.util.Map;

View File

@ -1,4 +1,4 @@
package com.baeldung.copyinghashmap;
package com.baeldung.map;
import static org.assertj.core.api.Assertions.assertThat;

View File

@ -1,4 +1,4 @@
package com.baeldung.copyinghashmap;
package com.baeldung.map;
import java.io.Serializable;

View File

@ -30,6 +30,16 @@
</repositories>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<dependency>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
<version>${classgraph.version}</version>
</dependency>
<dependency>
<groupId>org.jbpm</groupId>
<artifactId>jbpm-test</artifactId>
@ -38,6 +48,8 @@
</dependencies>
<properties>
<assertj.version>3.6.2</assertj.version>
<classgraph.version>4.8.22</classgraph.version>
<jbpm.version>6.0.0.Final</jbpm.version>
</properties>
</project>

View File

@ -0,0 +1,74 @@
package com.baeldung.classgraph;
import io.github.classgraph.*;
import org.junit.Test;
import java.io.IOException;
import java.util.function.Consumer;
import static org.assertj.core.api.Assertions.assertThat;
public class ClassGraphUnitTest {
@Test
public void whenClassAnnotationFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithAnnotation(TestAnnotation.class.getName());
assertThat(classInfos).extracting(ClassInfo::getName).contains(ClassWithAnnotation.class.getName());
});
}
@Test
public void whenMethodAnnotationFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithMethodAnnotation(TestAnnotation.class.getName());
assertThat(classInfos).extracting(ClassInfo::getName).contains(MethodWithAnnotation.class.getName());
});
}
@Test
public void whenMethodAnnotationValueFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithMethodAnnotation(TestAnnotation.class.getName());
ClassInfoList filteredClassInfos = classInfos.filter(classInfo -> {
return classInfo.getMethodInfo().stream().anyMatch(methodInfo -> {
AnnotationInfo annotationInfo = methodInfo.getAnnotationInfo(TestAnnotation.class.getName());
if (annotationInfo == null) {
return false;
}
return "web".equals(annotationInfo.getParameterValues().getValue("value"));
});
});
assertThat(filteredClassInfos)
.extracting(ClassInfo::getName)
.contains(MethodWithAnnotationParameterWeb.class.getName());
});
}
@Test
public void whenFieldAnnotationFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithFieldAnnotation(TestAnnotation.class.getName());
assertThat(classInfos).extracting(ClassInfo::getName).contains(FieldWithAnnotation.class.getName());
});
}
@Test
public void whenResourceIsUsed_thenItCanBeFoundAndLoaded() throws IOException {
try (ScanResult result = new ClassGraph().whitelistPaths("classgraph").scan()) {
ResourceList resources = result.getResourcesWithExtension("config");
assertThat(resources).extracting(Resource::getPath).containsOnly("classgraph/my.config");
assertThat(resources.get(0).getContentAsString()).isEqualTo("my data");
}
}
private void doTest(Consumer<ScanResult> checker) {
try (ScanResult result = new ClassGraph().enableAllInfo()
.whitelistPackages(getClass().getPackage().getName())
.scan())
{
checker.accept(result);
}
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.classgraph;
@TestAnnotation
public class ClassWithAnnotation {
}

View File

@ -0,0 +1,7 @@
package com.baeldung.classgraph;
public class FieldWithAnnotation {
@TestAnnotation
private String s;
}

View File

@ -0,0 +1,8 @@
package com.baeldung.classgraph;
public class MethodWithAnnotation {
@TestAnnotation
public void service() {
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.classgraph;
public class MethodWithAnnotationParameterDao {
@TestAnnotation("dao")
public void service() {
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.classgraph;
public class MethodWithAnnotationParameterWeb {
@TestAnnotation("web")
public void service() {
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.classgraph;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
@Target({TYPE, METHOD, FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
String value() default "";
}

View File

@ -0,0 +1 @@
my data

View File

@ -44,6 +44,8 @@ public class CourseServiceUnitTest {
CourseEntity courseEntity = new CourseEntity();
CourseService.copyProperties(course, courseEntity);
Assert.assertNotNull(course.getName());
Assert.assertNotNull(courseEntity.getName());
Assert.assertEquals(course.getName(), courseEntity.getName());
Assert.assertEquals(course.getCodes(), courseEntity.getCodes());
Assert.assertNull(courseEntity.getStudent("ST-1"));

View File

@ -2,3 +2,4 @@
- [Guide to ScribeJava](https://www.baeldung.com/scribejava)
- [Guide to Passay](https://www.baeldung.com/java-passay)
- [Guide to Google Tink](https://www.baeldung.com/google-tink)

View File

@ -0,0 +1,14 @@
<?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>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>daomodule</name>
</project>

View File

@ -0,0 +1,12 @@
package com.baeldung.dao;
import java.util.List;
import java.util.Optional;
public interface Dao<T> {
Optional<T> findById(int id);
List<T> findAll();
}

View File

@ -0,0 +1,3 @@
module com.baeldung.dao {
exports com.baeldung.dao;
}

View File

@ -0,0 +1,18 @@
<?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>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>entitymodule</name>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,19 @@
package com.baeldung.entity;
public class User {
private final String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" + "name=" + name + '}';
}
}

View File

@ -0,0 +1,3 @@
module com.baeldung.entity {
exports com.baeldung.entity;
}

View File

@ -0,0 +1,32 @@
<?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>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.mainappmodule</groupId>
<artifactId>mainappmodule</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>mainappmodule</name>
<dependencies>
<dependency>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.baeldung.userdaomodule</groupId>
<artifactId>userdaomodule</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,19 @@
package com.baeldung.mainapp;
import com.baeldung.dao.Dao;
import com.baeldung.entity.User;
import com.baeldung.userdao.UserDao;
import java.util.HashMap;
import java.util.Map;
public class Application {
public static void main(String[] args) {
Map<Integer, User> users = new HashMap<>();
users.put(1, new User("Julie"));
users.put(2, new User("David"));
Dao userDao = new UserDao(users);
userDao.findAll().forEach(System.out::println);
}
}

View File

@ -0,0 +1,6 @@
module com.baeldung.mainapp {
requires com.baeldung.entity;
requires com.baeldung.userdao;
requires com.baeldung.dao;
uses com.baeldung.dao.Dao;
}

View File

@ -0,0 +1,58 @@
<?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.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<name>multimodule-maven-project</name>
<parent>
<groupId>com.baeldung.maven-java-11</groupId>
<artifactId>maven-java-11</artifactId>
<version>1.0</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.12.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>entitymodule</module>
<module>daomodule</module>
<module>userdaomodule</module>
<module>mainappmodule</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,31 @@
<?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>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.userdaomodule</groupId>
<artifactId>userdaomodule</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>userdaomodule</name>
<dependencies>
<dependency>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.userdao;
import com.baeldung.dao.Dao;
import com.baeldung.entity.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class UserDao implements Dao<User> {
private final Map<Integer, User> users;
public UserDao() {
users = new HashMap<>();
}
public UserDao(Map<Integer, User> users) {
this.users = users;
}
@Override
public List<User> findAll() {
return new ArrayList<>(users.values());
}
@Override
public Optional<User> findById(int id) {
return Optional.ofNullable(users.get(id));
}
}

View File

@ -0,0 +1,6 @@
module com.baeldung.userdao {
requires com.baeldung.entity;
requires com.baeldung.dao;
provides com.baeldung.dao.Dao with com.baeldung.userdao.UserDao;
exports com.baeldung.userdao;
}

View File

@ -0,0 +1,36 @@
package com.baeldung.userdao.test;
import com.baeldung.dao.Dao;
import com.baeldung.entity.User;
import com.baeldung.userdao.UserDao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Before;
import org.junit.Test;
public class UserDaoUnitTest {
private Dao userDao;
@Before
public void setUpUserDaoInstance() {
Map<Integer, User> users = new HashMap<>();
users.put(1, new User("Julie"));
users.put(2, new User("David"));
userDao = new UserDao(users);
}
@Test
public void givenUserDaoIntance_whenCalledFindById_thenCorrect() {
assertThat(userDao.findById(1), isA(Optional.class));
}
@Test
public void givenUserDaoIntance_whenCalledFindAll_thenCorrect() {
assertThat(userDao.findAll(), isA(List.class));
}
}

22
maven-java-11/pom.xml Normal file
View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.maven-java-11</groupId>
<artifactId>maven-java-11</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<name>maven-java-11</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>multimodule-maven-project</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>

View File

@ -35,8 +35,8 @@
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<mongo.version>3.4.1</mongo.version>
<mongo.version>3.10.1</mongo.version>
<flapdoodle.version>1.11</flapdoodle.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,79 @@
package com.baeldung;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MongoBsonExample
{
public static void main(String[] args)
{
//
// 4.1 Connect to cluster (default is localhost:27017)
//
MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("myDB");
MongoCollection<Document> collection = database.getCollection("employees");
//
// 4.2 Insert new document
//
Document employee = new Document()
.append("first_name", "Joe")
.append("last_name", "Smith")
.append("title", "Java Developer")
.append("years_of_service", 3)
.append("skills", Arrays.asList("java", "spring", "mongodb"))
.append("manager", new Document()
.append("first_name", "Sally")
.append("last_name", "Johanson"));
collection.insertOne(employee);
//
// 4.3 Find documents
//
Document query = new Document("last_name", "Smith");
List results = new ArrayList<>();
collection.find(query).into(results);
query =
new Document("$or", Arrays.asList(
new Document("last_name", "Smith"),
new Document("first_name", "Joe")));
results = new ArrayList<>();
collection.find(query).into(results);
//
// 4.4 Update document
//
query = new Document(
"skills",
new Document(
"$elemMatch",
new Document("$eq", "spring")));
Document update = new Document(
"$push",
new Document("skills", "security"));
collection.updateMany(query, update);
//
// 4.5 Delete documents
//
query = new Document(
"years_of_service",
new Document("$lt", 0));
collection.deleteMany(query);
}
}

View File

@ -35,7 +35,7 @@
<module>querydsl</module>
<module>redis</module>
<module>solr</module>
<module>spring-boot-h2/spring-boot-h2-database</module>
<module>spring-boot-persistence-h2</module>
<module>spring-boot-persistence</module>
<module>spring-boot-persistence-mongodb</module>
<module>spring-data-cassandra</module>

View File

@ -1,2 +1,3 @@
### Relevant Articles:
- [Access the Same In-Memory H2 Database in Multiple Spring Boot Applications](https://www.baeldung.com/spring-boot-access-h2-database-multiple-apps)
- [Spring Boot With H2 Database](https://www.baeldung.com/spring-boot-h2-database)

View File

@ -14,7 +14,7 @@
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>

View File

@ -26,6 +26,12 @@
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>net.ttddyy</groupId>
<artifactId>datasource-proxy</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
@ -35,7 +41,5 @@
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,53 @@
package com.baeldung.batchinserts;
import java.lang.reflect.Method;
import javax.sql.DataSource;
import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
@Component
@Profile("batchinserts")
public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
if (bean instanceof DataSource) {
ProxyFactory factory = new ProxyFactory(bean);
factory.setProxyTargetClass(true);
factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean));
return factory.getProxy();
}
return bean;
}
private static class ProxyDataSourceInterceptor implements MethodInterceptor {
private final DataSource dataSource;
public ProxyDataSourceInterceptor(final DataSource dataSource) {
this.dataSource = ProxyDataSourceBuilder.create(dataSource).name("Batch-Insert-Logger").asJson().countQuery().logQueryToSysOut().build();
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
Method proxyMethod = ReflectionUtils.findMethod(dataSource.getClass(), invocation.getMethod().getName());
if (proxyMethod != null) {
return proxyMethod.invoke(dataSource, invocation.getArguments());
}
return invocation.proceed();
}
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.batchinserts.model;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class School {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
@OneToMany(mappedBy = "school")
private List<Student> students;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.batchinserts.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
@ManyToOne
private School school;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
}

View File

@ -0,0 +1,6 @@
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.jdbc.batch_size=5
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.batch_versioned_data=true

View File

@ -0,0 +1,94 @@
package com.baeldung.batchinserts;
import static com.baeldung.batchinserts.TestObjectHelper.createSchool;
import static com.baeldung.batchinserts.TestObjectHelper.createStudent;
import com.baeldung.batchinserts.model.School;
import com.baeldung.batchinserts.model.Student;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@ActiveProfiles("batchinserts")
public class JpaBatchInsertsIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
private static final int BATCH_SIZE = 5;
@Transactional
@Test
public void whenInsertingSingleTypeOfEntity_thenCreatesSingleBatch() {
for (int i = 0; i < 10; i++) {
School school = createSchool(i);
entityManager.persist(school);
}
}
@Transactional
@Test
public void whenFlushingAfterBatch_ThenClearsMemory() {
for (int i = 0; i < 10; i++) {
if (i > 0 && i % BATCH_SIZE == 0) {
entityManager.flush();
entityManager.clear();
}
School school = createSchool(i);
entityManager.persist(school);
}
}
@Transactional
@Test
public void whenThereAreMultipleEntities_ThenCreatesNewBatch() {
for (int i = 0; i < 10; i++) {
if (i > 0 && i % BATCH_SIZE == 0) {
entityManager.flush();
entityManager.clear();
}
School school = createSchool(i);
entityManager.persist(school);
Student firstStudent = createStudent(school);
Student secondStudent = createStudent(school);
entityManager.persist(firstStudent);
entityManager.persist(secondStudent);
}
}
@Transactional
@Test
public void whenUpdatingEntities_thenCreatesBatch() {
for (int i = 0; i < 10; i++) {
School school = createSchool(i);
entityManager.persist(school);
}
entityManager.flush();
TypedQuery<School> schoolQuery = entityManager.createQuery("SELECT s from School s", School.class);
List<School> allSchools = schoolQuery.getResultList();
for (School school : allSchools) {
school.setName("Updated_" + school.getName());
}
}
@After
public void tearDown() {
entityManager.flush();
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.batchinserts;
import static com.baeldung.batchinserts.TestObjectHelper.createSchool;
import com.baeldung.batchinserts.model.School;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@ActiveProfiles("batchinserts")
@TestPropertySource(properties = "spring.jpa.properties.hibernate.jdbc.batch_size=-1")
public class JpaNoBatchInsertsIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Test
public void whenNotConfigured_ThenSendsInsertsSeparately() {
for (int i = 0; i < 10; i++) {
School school = createSchool(i);
entityManager.persist(school);
}
}
@After
public void tearDown() {
entityManager.flush();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.batchinserts;
import com.baeldung.batchinserts.model.School;
import com.baeldung.batchinserts.model.Student;
public class TestObjectHelper {
public static School createSchool(int nameIdentifier) {
School school = new School();
school.setName("School" + (nameIdentifier + 1));
return school;
}
public static Student createStudent(School school) {
Student student = new Student();
student.setName("Student-" + school.getName());
student.setSchool(school);
return student;
}
}

28
picocli/pom.xml Normal file
View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<artifactId>picocli</artifactId>
<dependencies>
<dependency>
<groupId>info.picocli</groupId>
<artifactId>picocli</artifactId>
<version>3.9.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,41 @@
package com.baeldung.picocli.git;
import com.baeldung.picocli.git.commands.programmative.GitCommand;
import com.baeldung.picocli.git.commands.subcommands.GitAddCommand;
import com.baeldung.picocli.git.commands.subcommands.GitCommitCommand;
import com.baeldung.picocli.git.commands.subcommands.GitConfigCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import picocli.CommandLine;
@SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
private GitCommand gitCommand;
private GitAddCommand addCommand;
private GitCommitCommand commitCommand;
private GitConfigCommand configCommand;
@Autowired
public Application(GitCommand gitCommand, GitAddCommand addCommand, GitCommitCommand commitCommand, GitConfigCommand configCommand) {
this.gitCommand = gitCommand;
this.addCommand = addCommand;
this.commitCommand = commitCommand;
this.configCommand = configCommand;
}
@Override
public void run(String... args) {
CommandLine commandLine = new CommandLine(gitCommand);
commandLine.addSubcommand("add", addCommand);
commandLine.addSubcommand("commit", commitCommand);
commandLine.addSubcommand("config", configCommand);
commandLine.parseWithHandler(new CommandLine.RunLast(), args);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.picocli.git.commands.declarative;
import com.baeldung.picocli.git.model.ConfigElement;
import com.baeldung.picocli.git.commands.subcommands.GitAddCommand;
import com.baeldung.picocli.git.commands.subcommands.GitCommitCommand;
import com.baeldung.picocli.git.commands.subcommands.GitConfigCommand;
import picocli.CommandLine;
import static picocli.CommandLine.*;
import static picocli.CommandLine.Command;
@Command(
name = "git",
subcommands = {
GitAddCommand.class,
GitCommitCommand.class,
GitConfigCommand.class
}
)
public class GitCommand implements Runnable {
public static void main(String[] args) {
CommandLine commandLine = new CommandLine(new GitCommand());
commandLine.registerConverter(ConfigElement.class, ConfigElement::from);
commandLine.parseWithHandler(new RunLast(), args);
}
@Override
public void run() {
System.out.println("The popular git command");
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.picocli.git.commands.methods;
import picocli.CommandLine;
import static picocli.CommandLine.Command;
@Command(name = "git")
public class GitCommand implements Runnable {
public static void main(String[] args) {
CommandLine.run(new GitCommand(), args);
}
@Override
public void run() {
System.out.println("The popular git command");
}
@Command(name = "add")
public void addCommand() {
System.out.println("Adding some files to the staging area");
}
@Command(name = "commit")
public void commitCommand() {
System.out.println("Committing files in the staging area, how wonderful?");
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.picocli.git.commands.programmative;
import com.baeldung.picocli.git.commands.subcommands.GitAddCommand;
import com.baeldung.picocli.git.commands.subcommands.GitCommitCommand;
import org.springframework.stereotype.Component;
import picocli.CommandLine;
import static picocli.CommandLine.Command;
import static picocli.CommandLine.RunLast;
@Command(name = "git")
@Component
public class GitCommand implements Runnable {
public static void main(String[] args) {
CommandLine commandLine = new CommandLine(new GitCommand());
commandLine.addSubcommand("add", new GitAddCommand());
commandLine.addSubcommand("commit", new GitCommitCommand());
commandLine.parseWithHandler(new RunLast(), args);
}
@Override
public void run() {
System.out.println("The popular git command");
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.picocli.git.commands.subcommands;
import org.springframework.stereotype.Component;
import java.nio.file.Path;
import java.util.List;
import static picocli.CommandLine.*;
@Command(
name = "add"
)
@Component
public class GitAddCommand implements Runnable {
@Option(names = "-A")
private boolean allFiles;
@Parameters(index = "0..*")
private List<Path> files;
@Override
public void run() {
if (allFiles) {
System.out.println("Adding all files to the staging area");
}
if (files != null) {
files.forEach(path -> System.out.println("Adding " + path + " to the staging area"));
}
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.picocli.git.commands.subcommands;
import org.springframework.stereotype.Component;
import static picocli.CommandLine.Command;
import static picocli.CommandLine.Option;
@Command(
name = "commit"
)
@Component
public class GitCommitCommand implements Runnable {
@Option(names = {"-m", "--message"}, required = true)
private String[] messages;
@Override
public void run() {
System.out.println("Committing files in the staging area, how wonderful?");
if (messages != null) {
System.out.println("The commit message is");
for (String message : messages) {
System.out.println(message);
}
}
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.picocli.git.commands.subcommands;
import com.baeldung.picocli.git.model.ConfigElement;
import org.springframework.stereotype.Component;
import static picocli.CommandLine.Command;
import static picocli.CommandLine.Parameters;
@Command(
name = "config"
)
@Component
public class GitConfigCommand implements Runnable {
@Parameters(index = "0")
private ConfigElement element;
@Parameters(index = "1")
private String value;
@Override
public void run() {
System.out.println("Setting " + element.value() + " to " + value);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.picocli.git.model;
import java.util.Arrays;
public enum ConfigElement {
USERNAME("user.name"),
EMAIL("user.email");
private final String value;
ConfigElement(String value) {
this.value = value;
}
public String value() {
return value;
}
public static ConfigElement from(String value) {
return Arrays.stream(values())
.filter(element -> element.value.equals(value))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("The argument " + value + " doesn't match any ConfigElement"));
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.picocli.helloworld;
import picocli.CommandLine;
import static picocli.CommandLine.Command;
@Command(
name = "hello",
description = "Says hello"
)
public class HelloWorldCommand implements Runnable {
public static void main(String[] args) {
CommandLine.run(new HelloWorldCommand(), args);
}
@Override
public void run() {
System.out.println("Hello World!");
}
}

28
pom.xml
View File

@ -12,6 +12,7 @@
<modules>
<module>lombok-custom</module>
<module>picocli</module>
</modules>
<dependencies>
@ -377,6 +378,7 @@
<module>checker-plugin</module>
<module>core-groovy</module>
<module>core-groovy-2</module>
<module>core-groovy-collections</module>
<!-- <module>core-java-10</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
<!-- <module>core-java-11</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
<!-- <module>core-java-12</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
@ -387,8 +389,8 @@
<!--<module>core-java-os</module> --> <!-- We haven't upgraded to java 9.-->
<module>core-java-arrays</module>
<module>core-java-collections</module>
<module>core-java-collections-map</module>
<module>core-java-collections-list</module>
<module>core-java-collections-set</module>
<module>core-java-concurrency-basic</module>
<module>core-java-concurrency-collections</module>
<module>core-java-io</module>
@ -397,6 +399,7 @@
<module>core-java-lang</module>
<module>core-java-lang-oop</module>
<module>core-java-lang-oop-2</module>
<module>core-java-modules</module>
<module>core-java-networking</module>
<module>core-java-perf</module>
<module>core-java-sun</module>
@ -619,18 +622,20 @@
<module>spring-boot-camel</module>
<!-- <module>spring-boot-cli</module> --> <!-- Not a maven project -->
<module>spring-boot-client</module>
<module>spring-boot-configuration</module>
<module>spring-boot-crud</module>
<module>spring-boot-ctx-fluent</module>
<module>spring-boot-custom-starter</module>
<module>spring-boot-disable-console-logging</module>
<!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project -->
<module>spring-boot-exceptions</module>
<module>spring-boot-jasypt</module>
<module>spring-boot-keycloak</module>
<module>spring-boot-logging-log4j2</module>
<module>spring-boot-mvc</module>
<module>spring-boot-mvc-birt</module>
<module>spring-boot-ops</module>
<module>spring-boot-ops-2</module>
<module>spring-boot-rest</module>
<module>spring-boot-data</module>
<module>spring-boot-property-exp</module>
@ -820,9 +825,9 @@
<module>spring-boot-bootstrap</module>
<module>spring-boot-camel</module>
<module>spring-boot-client</module>
<module>spring-boot-configuration</module>
<module>spring-boot-custom-starter</module>
<module>greeter-spring-boot-autoconfigure</module>
<module>spring-boot-exceptions</module>
<module>greeter-spring-boot-autoconfigure</module>
<module>greeter-spring-boot-sample-app</module>
<module>persistence-modules/spring-boot-h2/spring-boot-h2-database</module>
<module>spring-boot-jasypt</module>
@ -1049,6 +1054,7 @@
<module>checker-plugin</module>
<module>core-groovy</module>
<module>core-groovy-2</module>
<module>core-groovy-collections</module>
<!-- <module>core-java-10</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
<!-- <module>core-java-11</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
<module>core-java-8</module>
@ -1057,8 +1063,8 @@
<!--<module>core-java-os</module> --> <!-- We haven't upgraded to java 9.-->
<module>core-java-arrays</module>
<module>core-java-collections</module>
<module>core-java-collections-map</module>
<module>core-java-collections-list</module>
<module>core-java-collections-set</module>
<module>core-java-concurrency-basic</module>
<module>core-java-concurrency-collections</module>
<module>core-java-io</module>
@ -1067,6 +1073,7 @@
<module>core-java-lang</module>
<module>core-java-lang-oop</module>
<module>core-java-lang-oop-2</module>
<module>core-java-modules</module>
<module>core-java-networking</module>
<module>core-java-perf</module>
<module>core-java-sun</module>
@ -1168,6 +1175,7 @@
<module>mapstruct</module>
<module>maven</module>
<!-- <module>maven-java-11</module> --> <!-- we haven't upgraded to Java 11 -->
<module>maven-archetype</module>
<!-- <module>maven-polyglot/maven-polyglot-json-app</module> --> <!-- Not a maven project -->
<module>maven-polyglot/maven-polyglot-json-extension</module>
@ -1275,11 +1283,11 @@
<module>spring-boot-camel</module>
<!-- <module>spring-boot-cli</module> --> <!-- Not a maven project -->
<module>spring-boot-client</module>
<module>spring-boot-configuration</module>
<module>spring-boot-crud</module>
<module>spring-boot-ctx-fluent</module>
<module>spring-boot-custom-starter</module>
<module>spring-boot-disable-console-logging</module>
<module>spring-boot-exceptions</module>
<!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project -->
<module>spring-boot-jasypt</module>
<module>spring-boot-keycloak</module>
@ -1287,6 +1295,7 @@
<module>spring-boot-mvc</module>
<module>spring-boot-mvc-birt</module>
<module>spring-boot-ops</module>
<module>spring-boot-ops-2</module>
<module>spring-boot-rest</module>
<module>spring-boot-data</module>
<module>spring-boot-property-exp</module>
@ -1495,8 +1504,9 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<gib.referenceBranch>refs/remotes/origin/master</gib.referenceBranch>
<gib.skipTestsForNotImpactedModules>true</gib.skipTestsForNotImpactedModules>
<gib.referenceBranch>refs/remotes/origin/master</gib.referenceBranch>
<gib.skipTestsForUpstreamModules>true</gib.skipTestsForUpstreamModules>
<gib.buildUpstream>false</gib.buildUpstream>
<gib.failOnMissingGitDir>false</gib.failOnMissingGitDir>
<gib.failOnError>false</gib.failOnError>
<gib.enabled>false</gib.enabled>
@ -1537,7 +1547,7 @@
<directory-maven-plugin.version>0.3.1</directory-maven-plugin.version>
<maven-install-plugin.version>2.5.1</maven-install-plugin.version>
<custom-pmd.version>0.0.1</custom-pmd.version>
<gitflow-incremental-builder.version>3.4</gitflow-incremental-builder.version>
<gitflow-incremental-builder.version>3.8</gitflow-incremental-builder.version>
<maven-jxr-plugin.version>2.3</maven-jxr-plugin.version>
<!-- <maven-pmd-plugin.version>3.9.0</maven-pmd-plugin.version> -->
<maven-pmd-plugin.version>3.8</maven-pmd-plugin.version>

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