Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2019-04-25 17:34:31 +02:00
commit febda47e65
582 changed files with 12804 additions and 962 deletions

4
.gitignore vendored
View File

@ -19,6 +19,7 @@
.idea/ .idea/
*.iml *.iml
*.iws *.iws
out/
# Mac # Mac
.DS_Store .DS_Store
@ -27,6 +28,9 @@
log/ log/
target/ target/
# Gradle
.gradle/
spring-openid/src/main/resources/application.properties spring-openid/src/main/resources/application.properties
.recommenders/ .recommenders/
/spring-hibernate4/nbproject/ /spring-hibernate4/nbproject/

View File

@ -1,4 +1,4 @@
### Relevant Articles: ### 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: ### 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`

View File

@ -0,0 +1,3 @@
### Revelant Articles
- [A Quick Guide To Using Cloud Foundry UAA](https://www.baeldung.com/cloud-foundry-uaa)

7
core-groovy-2/README.md Normal file
View File

@ -0,0 +1,7 @@
# Groovy
## Relevant articles:
- [String Matching in Groovy](http://www.baeldung.com/)
- [Groovy def Keyword]

131
core-groovy-2/pom.xml Normal file
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-2</artifactId>
<version>1.0-SNAPSHOT</version>
<name>core-groovy-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy-all.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-dateutil</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-sql</artifactId>
<version>${groovy-sql.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>${spock-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>${gmavenplus-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>compile</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>junit5</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*Test5.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<configuration>
<useFile>false</useFile>
<includes>
<include>**/*Test.java</include>
<include>**/*Spec.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>central</id>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
<properties>
<junit.platform.version>1.0.0</junit.platform.version>
<groovy.version>2.5.6</groovy.version>
<groovy-all.version>2.5.6</groovy-all.version>
<groovy-sql.version>2.5.6</groovy-sql.version>
<hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version>
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,79 @@
package com.baeldung.defkeyword
import org.codehaus.groovy.runtime.NullObject
import org.codehaus.groovy.runtime.typehandling.GroovyCastException
import groovy.transform.TypeChecked
import groovy.transform.TypeCheckingMode
@TypeChecked
class DefUnitTest extends GroovyTestCase {
def id
def firstName = "Samwell"
def listOfCountries = ['USA', 'UK', 'FRANCE', 'INDIA']
@TypeChecked(TypeCheckingMode.SKIP)
def multiply(x, y) {
return x*y
}
@TypeChecked(TypeCheckingMode.SKIP)
void testDefVariableDeclaration() {
def list
assert list.getClass() == org.codehaus.groovy.runtime.NullObject
assert list.is(null)
list = [1,2,4]
assert list instanceof ArrayList
}
@TypeChecked(TypeCheckingMode.SKIP)
void testTypeVariables() {
int rate = 200
try {
rate = [12] //GroovyCastException
rate = "nill" //GroovyCastException
} catch(GroovyCastException) {
println "Cannot assign anything other than integer"
}
}
@TypeChecked(TypeCheckingMode.SKIP)
void testDefVariableMultipleAssignment() {
def rate
assert rate == null
assert rate.getClass() == org.codehaus.groovy.runtime.NullObject
rate = 12
assert rate instanceof Integer
rate = "Not Available"
assert rate instanceof String
rate = [1, 4]
assert rate instanceof List
assert divide(12, 3) instanceof BigDecimal
assert divide(1, 0) instanceof String
}
def divide(int x, int y) {
if(y==0) {
return "Should not divide by 0"
} else {
return x/y
}
}
def greetMsg() {
println "Hello! I am Groovy"
}
void testDefVsType() {
def int count
assert count instanceof Integer
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.strings
import spock.lang.Specification
import java.util.regex.Pattern
class StringMatchingSpec extends Specification {
def "pattern operator example"() {
given: "a pattern"
def p = ~'foo'
expect:
p instanceof Pattern
and: "you can use slash strings to avoid escaping of blackslash"
def digitPattern = ~/\d*/
digitPattern.matcher('4711').matches()
}
def "match operator example"() {
expect:
'foobar' ==~ /.*oba.*/
and: "matching is strict"
!('foobar' ==~ /foo/)
}
def "find operator example"() {
when: "using the find operator"
def matcher = 'foo and bar, baz and buz' =~ /(\w+) and (\w+)/
then: "will find groups"
matcher.size() == 2
and: "can access groups using array"
matcher[0][0] == 'foo and bar'
matcher[1][2] == 'buz'
and: "you can use it as a predicate"
'foobarbaz' =~ /bar/
}
}

View File

@ -8,6 +8,8 @@
- [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings) - [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings)
- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating) - [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating)
- [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits) - [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) - [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) - [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) - [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)

View File

@ -0,0 +1,44 @@
package com.baeldung.strings
import spock.lang.Specification
import java.util.regex.Pattern
class StringMatchingSpec extends Specification {
def "pattern operator example"() {
given: "a pattern"
def p = ~'foo'
expect:
p instanceof Pattern
and: "you can use slash strings to avoid escaping of blackslash"
def digitPattern = ~/\d*/
digitPattern.matcher('4711').matches()
}
def "match operator example"() {
expect:
'foobar' ==~ /.*oba.*/
and: "matching is strict"
!('foobar' ==~ /foo/)
}
def "find operator example"() {
when: "using the find operator"
def matcher = 'foo and bar, baz and buz' =~ /(\w+) and (\w+)/
then: "will find groups"
matcher.size() == 2
and: "can access groups using array"
matcher[0][0] == 'foo and bar'
matcher[1][2] == 'buz'
and: "you can use it as a predicate"
'foobarbaz' =~ /bar/
}
}

View File

@ -6,3 +6,4 @@
- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control) - [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) - [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) - [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)

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

@ -3,7 +3,7 @@
## Core Java 8 Cookbooks and Examples ## Core Java 8 Cookbooks and Examples
### Relevant Articles: ### Relevant Articles:
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) - [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) - [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 Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features) - [New Features in Java 8](http://www.baeldung.com/java-8-new-features)

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
package com.baeldung; package com.baeldung.java8.lambda.tips;
@FunctionalInterface @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; import java.util.function.Function;

View File

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

View File

@ -29,4 +29,11 @@ public class CalculatorUnitTest {
int result = calculator.calculate(new AddCommand(3, 7)); int result = calculator.calculate(new AddCommand(3, 7));
assertEquals(10, result); assertEquals(10, result);
} }
@Test
public void whenCalculateUsingFactory_thenReturnCorrectResult() {
Calculator calculator = new Calculator();
int result = calculator.calculateUsingFactory(3, 4, "add");
assertEquals(7, result);
}
} }

View File

@ -5,26 +5,21 @@
[Java 9 New Features](http://www.baeldung.com/new-java-9) [Java 9 New Features](http://www.baeldung.com/new-java-9)
### Relevant Articles: ### 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) - [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)
- [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) - [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 Variable Handles Demystified](http://www.baeldung.com/java-variable-handles)
- [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 and 11](http://www.baeldung.com/java-9-http-client) - [Exploring the New HTTP Client in Java 9 and 11](http://www.baeldung.com/java-9-http-client)
- [Method Handles in Java](http://www.baeldung.com/java-method-handles) - [Method Handles in Java](http://www.baeldung.com/java-method-handles)
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) - [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) - [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) - [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) - [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)
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) - [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar) - [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) - [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

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

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

View File

@ -3,7 +3,7 @@
## Core Java Collections Cookbooks and Examples ## Core Java Collections Cookbooks and Examples
### Relevant Articles: ### 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) - [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) - [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) - [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)

View File

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

View File

@ -7,13 +7,13 @@
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) - [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) - [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) - [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) - [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) - [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) - [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) - [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) - [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) - [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) - [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread)

View File

@ -6,7 +6,7 @@
- [How to Read a Large File Efficiently with Java](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 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 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 Scanner](http://www.baeldung.com/java-scanner)
- [Java Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer) - [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) - [Java Directory Size](http://www.baeldung.com/java-folder-size)
@ -14,7 +14,7 @@
- [File Size 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) - [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer) - [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) - [Java Append Data to a File](http://www.baeldung.com/java-append-to-file)
- [FileNotFoundException in Java](http://www.baeldung.com/java-filenotfound-exception) - [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) - [How to Read a File in Java](http://www.baeldung.com/reading-file-in-java)

View File

@ -0,0 +1,165 @@
package com.baeldung.filechannel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
public class FileChannelUnitTest {
@Test
public void givenFile_whenReadWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException {
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
FileChannel channel = reader.getChannel();
ByteArrayOutputStream out = new ByteArrayOutputStream();) {
int bufferSize = 1024;
if (bufferSize > channel.size()) {
bufferSize = (int) channel.size();
}
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
while (channel.read(buff) > 0) {
out.write(buff.array(), 0, buff.position());
buff.clear();
}
String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8);
assertEquals("Hello world", fileContent);
}
}
@Test
public void givenFile_whenReadWithFileChannelUsingFileInputStream_thenCorrect() throws IOException {
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
FileInputStream fin = new FileInputStream("src/test/resources/test_read.in");
FileChannel channel = fin.getChannel();) {
int bufferSize = 1024;
if (bufferSize > channel.size()) {
bufferSize = (int) channel.size();
}
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
while (channel.read(buff) > 0) {
out.write(buff.array(), 0, buff.position());
buff.clear();
}
String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8);
assertEquals("Hello world", fileContent);
}
}
@Test
public void givenFile_whenReadAFileSectionIntoMemoryWithFileChannel_thenCorrect() throws IOException {
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
FileChannel channel = reader.getChannel();
ByteArrayOutputStream out = new ByteArrayOutputStream();) {
MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_ONLY, 6, 5);
if (buff.hasRemaining()) {
byte[] data = new byte[buff.remaining()];
buff.get(data);
assertEquals("world", new String(data, StandardCharsets.UTF_8));
}
}
}
@Test
public void whenWriteWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException {
String file = "src/test/resources/test_write_using_filechannel.txt";
try (RandomAccessFile writer = new RandomAccessFile(file, "rw");
FileChannel channel = writer.getChannel();) {
ByteBuffer buff = ByteBuffer.wrap("Hello world".getBytes(StandardCharsets.UTF_8));
channel.write(buff);
// now we verify whether the file was written correctly
RandomAccessFile reader = new RandomAccessFile(file, "r");
assertEquals("Hello world", reader.readLine());
reader.close();
}
}
@Test
public void givenFile_whenWriteAFileUsingLockAFileSectionWithFileChannel_thenCorrect() throws IOException {
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "rw");
FileChannel channel = reader.getChannel();
FileLock fileLock = channel.tryLock(6, 5, Boolean.FALSE);) {
assertNotNull(fileLock);
}
}
@Test
public void givenFile_whenReadWithFileChannelGetPosition_thenCorrect() throws IOException {
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
FileChannel channel = reader.getChannel();) {
int bufferSize = 1024;
if (bufferSize > channel.size()) {
bufferSize = (int) channel.size();
}
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
while (channel.read(buff) > 0) {
out.write(buff.array(), 0, buff.position());
buff.clear();
}
// the original file is 11 bytes long, so that's where the position pointer should be
assertEquals(11, channel.position());
channel.position(4);
assertEquals(4, channel.position());
}
}
@Test
public void whenGetFileSize_thenCorrect() throws IOException {
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
FileChannel channel = reader.getChannel();) {
// the original file is 11 bytes long, so that's where the position pointer should be
assertEquals(11, channel.size());
}
}
@Test
public void whenTruncateFile_thenCorrect() throws IOException {
String input = "this is a test input";
FileOutputStream fout = new FileOutputStream("src/test/resources/test_truncate.txt");
FileChannel channel = fout.getChannel();
ByteBuffer buff = ByteBuffer.wrap(input.getBytes());
channel.write(buff);
buff.flip();
channel = channel.truncate(5);
assertEquals(5, channel.size());
fout.close();
channel.close();
}
}

View File

@ -0,0 +1 @@
this

View File

@ -0,0 +1 @@
Hello world

View File

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

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

View File

@ -3,3 +3,4 @@
## Core Java Lang OOP 2 Cookbooks and Examples ## Core Java Lang OOP 2 Cookbooks and Examples
### Relevant Articles: ### Relevant Articles:
- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors)

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

@ -10,7 +10,7 @@
- [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy) - [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy)
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance) - [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting) - [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
- [The "final" Keyword in Java](http://www.baeldung.com/java-final) - [The “final” Keyword in Java](http://www.baeldung.com/java-final)
- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure) - [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference) - [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding) - [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding)

View File

@ -12,7 +12,7 @@
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) - [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization) - [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator) - [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable) - [Comparator and Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break) - [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
- [Nested Classes in Java](http://www.baeldung.com/java-nested-classes) - [Nested Classes in Java](http://www.baeldung.com/java-nested-classes)
- [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces) - [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces)

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

@ -14,4 +14,5 @@
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
- [Guide to Java URL Encoding/Decoding](http://www.baeldung.com/java-url-encoding-decoding) - [Guide to Java URL Encoding/Decoding](http://www.baeldung.com/java-url-encoding-decoding)
- [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) - [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri) - [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
- [Read an InputStream using the Java Server Socket](https://www.baeldung.com/java-inputstream-server-socket)

View File

@ -17,8 +17,8 @@ public class ProxyAcceptCookiePolicy implements CookiePolicy {
host = uri.getHost(); host = uri.getHost();
} }
if (!HttpCookie.domainMatches(acceptedProxy, host)) { if (HttpCookie.domainMatches(acceptedProxy, host)) {
return false; return true;
} }
return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie); return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie);

View File

@ -29,7 +29,7 @@
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid) - [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) - [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
- [Class Loaders in Java](http://www.baeldung.com/java-classloaders) - [Class Loaders in Java](http://www.baeldung.com/java-classloaders)
- [Guide to Java Clock Class](http://www.baeldung.com/java-clock) - [Guide to the Java Clock Class](http://www.baeldung.com/java-clock)
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class) - [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) - [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object) - [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)

View File

@ -2,5 +2,8 @@
- [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type) - [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type)
- [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges) - [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges)
- [Creating a Kotlin Range Iterator on a Custom Object](https://www.baeldung.com/kotlin-custom-range-iterator)
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations)
- [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) - [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts)
- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison) - [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison)

View File

@ -5,7 +5,7 @@ version '1.0-SNAPSHOT'
buildscript { buildscript {
ext.kotlin_version = '1.2.41' ext.kotlin_version = '1.3.30'
repositories { repositories {
mavenCentral() mavenCentral()
@ -26,8 +26,6 @@ sourceCompatibility = 1.8
compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileKotlin { kotlinOptions.jvmTarget = "1.8" }
compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" }
kotlin { experimental { coroutines "enable" } }
repositories { repositories {
mavenCentral() mavenCentral()
jcenter() jcenter()
@ -39,10 +37,22 @@ sourceSets {
srcDirs 'com/baeldung/ktor' srcDirs 'com/baeldung/ktor'
} }
} }
}
test {
useJUnitPlatform()
testLogging {
events "passed", "skipped", "failed"
}
} }
dependencies { dependencies {
compile "ch.qos.logback:logback-classic:1.2.1" implementation "ch.qos.logback:logback-classic:1.2.1"
testCompile group: 'junit', name: 'junit', version: '4.12' implementation "org.jetbrains.kotlin:kotlin-stdlib:${kotlin_version}"
} testImplementation 'org.junit.jupiter:junit-jupiter:5.4.2'
testImplementation 'junit:junit:4.12'
testImplementation 'org.assertj:assertj-core:3.12.2'
testImplementation 'org.mockito:mockito-core:2.27.0'
testImplementation "org.jetbrains.kotlin:kotlin-test:${kotlin_version}"
testImplementation "org.jetbrains.kotlin:kotlin-test-junit5:${kotlin_version}"
}

Binary file not shown.

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip

18
core-kotlin-2/gradlew vendored
View File

@ -1,5 +1,21 @@
#!/usr/bin/env sh #!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
############################################################################## ##############################################################################
## ##
## Gradle start up script for UN*X ## Gradle start up script for UN*X
@ -28,7 +44,7 @@ APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"` APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS="" DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD="maximum"

View File

@ -1,3 +1,19 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem http://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off @if "%DEBUG%" == "" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@ -14,7 +30,7 @@ set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS= set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe @rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome if defined JAVA_HOME goto findJavaFromJavaHome

View File

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

11
core-kotlin-io/.gitignore vendored Normal file
View File

@ -0,0 +1,11 @@
/bin/
#ignore gradle
.gradle/
#ignore build and generated files
build/
node/
target/
out/

3
core-kotlin-io/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant articles:
- [InputStream to String in Kotlin](https://www.baeldung.com/kotlin-inputstream-to-string)

97
core-kotlin-io/pom.xml Normal file
View File

@ -0,0 +1,97 @@
<?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-kotlin-io</artifactId>
<name>core-kotlin-io</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-kotlin</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../parent-kotlin</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<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>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test</artifactId>
<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>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmTarget>1.8</jvmTarget>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<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>

View File

@ -0,0 +1,18 @@
package com.baeldung.inputstream
import java.io.InputStream
fun InputStream.readUpToChar(stopChar: Char): String {
val stringBuilder = StringBuilder()
var currentChar = this.read().toChar()
while (currentChar != stopChar) {
stringBuilder.append(currentChar)
currentChar = this.read().toChar()
if (this.available() <= 0) {
stringBuilder.append(currentChar)
break
}
}
return stringBuilder.toString()
}

View File

@ -0,0 +1,79 @@
package com.baeldung.console
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.Console
import java.io.InputStreamReader
import java.io.PrintStream
import java.util.*
class ConsoleIOUnitTest {
@Test
fun givenText_whenPrint_thenPrintText() {
val expectedTest = "Hello from Kotlin"
val out = ByteArrayOutputStream()
System.setOut(PrintStream(out))
print(expectedTest)
out.flush()
val printedText = String(out.toByteArray())
assertThat(printedText).isEqualTo(expectedTest)
}
@Test
fun givenInput_whenRead_thenReadText() {
val expectedTest = "Hello from Kotlin"
val input = ByteArrayInputStream(expectedTest.toByteArray())
System.setIn(input)
val readText = readLine()
assertThat(readText).isEqualTo(expectedTest)
}
@Test
fun givenInput_whenReadWithScanner_thenReadText() {
val expectedTest = "Hello from Kotlin"
val scanner = Scanner(ByteArrayInputStream(expectedTest.toByteArray()))
val readText = scanner.nextLine()
assertThat(readText).isEqualTo(expectedTest)
}
@Test
fun givenInput_whenReadWithBufferedReader_thenReadText() {
val expectedTest = "Hello from Kotlin"
val reader = BufferedReader(InputStreamReader(ByteArrayInputStream(expectedTest.toByteArray())))
val readText = reader.readLine()
assertThat(readText).isEqualTo(expectedTest)
}
@Test
fun givenInput_whenReadWithConsole_thenReadText() {
val expectedTest = "Hello from Kotlin"
val console = mock(Console::class.java)
`when`(console.readLine()).thenReturn(expectedTest)
val readText = console.readLine()
assertThat(readText).isEqualTo(expectedTest)
}
@AfterEach
fun resetIO() {
System.setOut(System.out)
System.setIn(System.`in`)
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.inputstream
import kotlinx.io.core.use
import org.junit.Test
import java.io.BufferedReader
import java.io.File
import kotlin.test.assertEquals
class InputStreamToStringTest {
private val fileName = "src/test/resources/inputstream2string.txt"
private val endOfLine = System.lineSeparator()
private val fileFullContent = "Computer programming can be a hassle$endOfLine" +
"It's like trying to take a defended castle"
@Test
fun whenReadFileWithBufferedReader_thenFullFileContentIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val content = inputStream.bufferedReader().use(BufferedReader::readText)
assertEquals(fileFullContent, content)
}
@Test
fun whenReadFileWithBufferedReaderReadText_thenFullFileContentIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val reader = BufferedReader(inputStream.reader())
var content: String
try {
content = reader.readText()
} finally {
reader.close()
}
assertEquals(fileFullContent, content)
}
@Test
fun whenReadFileWithBufferedReaderManually_thenFullFileContentIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val reader = BufferedReader(inputStream.reader())
val content = StringBuilder()
try {
var line = reader.readLine()
while (line != null) {
content.append(line)
line = reader.readLine()
}
} finally {
reader.close()
}
assertEquals(fileFullContent.replace(endOfLine, ""), content.toString())
}
@Test
fun whenReadFileUpToStopChar_thenPartBeforeStopCharIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val content = inputStream.use { it.readUpToChar(' ') }
assertEquals("Computer", content)
}
@Test
fun whenReadFileWithoutContainingStopChar_thenFullFileContentIsReadAsString() {
val file = File(fileName)
val inputStream = file.inputStream()
val content = inputStream.use { it.readUpToChar('-') }
assertEquals(fileFullContent, content)
}
}

View File

@ -0,0 +1,2 @@
Computer programming can be a hassle
It's like trying to take a defended castle

View File

@ -0,0 +1 @@
mock-maker-inline

View File

@ -1,7 +1,7 @@
## Relevant articles: ## Relevant articles:
- [Introduction to the Kotlin Language](http://www.baeldung.com/kotlin) - [Introduction to the Kotlin Language](http://www.baeldung.com/kotlin)
- [A guide to the “when{}” block in Kotlin](http://www.baeldung.com/kotlin-when) - [Guide to the “when{}” Block in Kotlin](http://www.baeldung.com/kotlin-when)
- [Comprehensive Guide to Null Safety in Kotlin](http://www.baeldung.com/kotlin-null-safety) - [Comprehensive Guide to Null Safety in Kotlin](http://www.baeldung.com/kotlin-null-safety)
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability) - [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
- [Difference Between “==” and “===” operators in Kotlin](http://www.baeldung.com/kotlin-equality-operators) - [Difference Between “==” and “===” operators in Kotlin](http://www.baeldung.com/kotlin-equality-operators)

View File

@ -7,7 +7,7 @@ import org.junit.Test;
import static com.baeldung.kotlin.Strings.*; import static com.baeldung.kotlin.Strings.*;
public class StringUtilTest { public class StringUtilUnitTest {
@Test @Test
public void shouldEscapeXmlTagsInString() { public void shouldEscapeXmlTagsInString() {

View File

@ -3,7 +3,7 @@
### Relevant Articles: ### Relevant Articles:
- [Introduction to Couchbase SDK for Java](http://www.baeldung.com/java-couchbase-sdk) - [Introduction to Couchbase SDK for Java](http://www.baeldung.com/java-couchbase-sdk)
- [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring) - [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring)
- [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase) - [Asynchronous Batch Operations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase)
- [Querying Couchbase with MapReduce Views](http://www.baeldung.com/couchbase-query-mapreduce-view) - [Querying Couchbase with MapReduce Views](http://www.baeldung.com/couchbase-query-mapreduce-view)
- [Querying Couchbase with N1QL](http://www.baeldung.com/n1ql-couchbase) - [Querying Couchbase with N1QL](http://www.baeldung.com/n1ql-couchbase)

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

@ -11,6 +11,6 @@
- [Convert JSON to a Map Using Gson](https://www.baeldung.com/gson-json-to-map) - [Convert JSON to a Map Using Gson](https://www.baeldung.com/gson-json-to-map)
- [Working with Primitive Values in Gson](https://www.baeldung.com/java-gson-primitives) - [Working with Primitive Values in Gson](https://www.baeldung.com/java-gson-primitives)
- [Convert String to JsonObject with Gson](https://www.baeldung.com/gson-string-to-jsonobject) - [Convert String to JsonObject with Gson](https://www.baeldung.com/gson-string-to-jsonobject)
- [Mapping Multiple JSON Fields to One Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field) - [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field)
- [Serializing and Deserializing a List with Gson](https://www.baeldung.com/gson-list) - [Serializing and Deserializing a List with Gson](https://www.baeldung.com/gson-list)

13
guava-collections-set/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,37 @@
<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>guava-collections-set</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>guava-collections-set</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>guava-collections-set</finalName>
</build>
<properties>
<!-- util -->
<guava.version>27.1-jre</guava.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,92 @@
package org.baeldung.guava;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class GuavaMultiSetUnitTest {
@Test
public void givenMultiSet_whenAddingValues_shouldReturnCorrectCount() {
Multiset<String> bookStore = HashMultiset.create();
bookStore.add("Potter");
bookStore.add("Potter");
bookStore.add("Potter");
assertThat(bookStore.contains("Potter")).isTrue();
assertThat(bookStore.count("Potter")).isEqualTo(3);
}
@Test
public void givenMultiSet_whenRemovingValues_shouldReturnCorrectCount() {
Multiset<String> bookStore = HashMultiset.create();
bookStore.add("Potter");
bookStore.add("Potter");
bookStore.remove("Potter");
assertThat(bookStore.contains("Potter")).isTrue();
assertThat(bookStore.count("Potter")).isEqualTo(1);
}
@Test
public void givenMultiSet_whenSetCount_shouldReturnCorrectCount() {
Multiset<String> bookStore = HashMultiset.create();
bookStore.setCount("Potter", 50);
assertThat(bookStore.count("Potter")).isEqualTo(50);
}
@Test
public void givenMultiSet_whenSettingNegativeCount_shouldThrowException() {
Multiset<String> bookStore = HashMultiset.create();
assertThatThrownBy(() -> bookStore.setCount("Potter", -1))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void givenMultiSet_whenSettingCountWithEmptySet_shouldBeSuccessful() {
Multiset<String> bookStore = HashMultiset.create();
assertThat(bookStore.setCount("Potter", 0, 2)).isTrue();
}
@Test
public void givenMultiSet_whenSettingCountWithCorrectValue_shouldBeSuccessful() {
Multiset<String> bookStore = HashMultiset.create();
bookStore.add("Potter");
bookStore.add("Potter");
assertThat(bookStore.setCount("Potter", 2, 52)).isTrue();
}
@Test
public void givenMultiSet_whenSettingCountWithIncorrectValue_shouldFail() {
Multiset<String> bookStore = HashMultiset.create();
bookStore.add("Potter");
bookStore.add("Potter");
assertThat(bookStore.setCount("Potter", 5, 52)).isFalse();
}
@Test
public void givenMap_compareMultiSetOperations() {
Map<String, Integer> bookStore = new HashMap<>();
bookStore.put("Potter", 3);
assertThat(bookStore.containsKey("Potter")).isTrue();
assertThat(bookStore.get("Potter")).isEqualTo(3);
bookStore.put("Potter", 2);
assertThat(bookStore.get("Potter")).isEqualTo(2);
bookStore.put("Potter", null);
assertThat(bookStore.containsKey("Potter")).isTrue();
bookStore.put("Potter", -1);
assertThat(bookStore.containsKey("Potter")).isTrue();
}
}

View File

@ -1,4 +1,4 @@
### Relevant articles: ### Relevant articles:
- [New Stream, Comparator and Collector Functionality in Guava 21](http://www.baeldung.com/guava-21-new) - [New Stream, Comparator and Collector in Guava 21](http://www.baeldung.com/guava-21-new)
- [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent) - [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent)
- [Zipping Collections in Java](http://www.baeldung.com/java-collections-zip) - [Zipping Collections in Java](http://www.baeldung.com/java-collections-zip)

13
httpclient-simple/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,12 @@
=========
## HttpClient 4.x Cookbooks and Examples
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [HttpClient 4 Get the Status Code](http://www.baeldung.com/httpclient-status-code)
- [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl)
- [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication)

315
httpclient-simple/pom.xml Normal file
View File

@ -0,0 +1,315 @@
<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>httpclient-simple</artifactId>
<version>0.1-SNAPSHOT</version>
<name>httpclient-simple</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring-5</relativePath>
</parent>
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcore.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>${httpclient.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>${httpasyncclient.version}</version> <!-- 4.0.2 --> <!-- 4.1-beta1 -->
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
<scope>runtime</scope>
</dependency>
<!-- util -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>httpclient-simple</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
<systemPropertyVariables>
<webTarget>cargo</webTarget>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- various -->
<jstl.version>1.2</jstl.version>
<javax.servlet.version>3.1.0</javax.servlet.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-codec.version>1.10</commons-codec.version>
<httpasyncclient.version>4.1.4</httpasyncclient.version>
<!-- testing -->
<wiremock.version>2.5.1</wiremock.version>
<httpcore.version>4.4.11</httpcore.version>
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
<!-- maven plugins -->
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,30 @@
package org.baeldung.basic;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
final PrintWriter writer = response.getWriter();
writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("Baeldung");
super.afterPropertiesSet();
}
}

View File

@ -0,0 +1,39 @@
package org.baeldung.client;
import java.net.URI;
import org.apache.http.HttpHost;
import org.apache.http.client.AuthCache;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory {
HttpHost host;
public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) {
super();
this.host = host;
}
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
return createHttpContext();
}
private HttpContext createHttpContext() {
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(host, basicAuth);
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
return localcontext;
}
}

View File

@ -0,0 +1,44 @@
package org.baeldung.client;
import org.apache.http.HttpHost;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class RestTemplateFactory implements FactoryBean<RestTemplate>, InitializingBean {
private RestTemplate restTemplate;
public RestTemplateFactory() {
super();
}
// API
@Override
public RestTemplate getObject() {
return restTemplate;
}
@Override
public Class<RestTemplate> getObjectType() {
return RestTemplate.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() {
HttpHost host = new HttpHost("localhost", 8082, "http");
final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host);
restTemplate = new RestTemplate(requestFactory);
restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass"));
}
}

View File

@ -0,0 +1,16 @@
package org.baeldung.client.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("org.baeldung.client")
public class ClientConfig {
public ClientConfig() {
super();
}
// beans
}

View File

@ -0,0 +1,18 @@
package org.baeldung.filter;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
public class CustomFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,49 @@
package org.baeldung.filter;
import org.baeldung.security.RestAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user1")
.password(passwordEncoder().encode("user1Pass"))
.authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/securityNone")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,48 @@
package org.baeldung.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException {
final SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null) {
super.onAuthenticationSuccess(request, response, authentication);
return;
}
final String targetUrlParameter = getTargetUrlParameter();
if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
requestCache.removeRequest(request, response);
super.onAuthenticationSuccess(request, response, authentication);
return;
}
clearAuthenticationAttributes(request);
// Use the DefaultSavedRequest URL
// final String targetUrl = savedRequest.getRedirectUrl();
// logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
// getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
public void setRequestCache(final RequestCache requestCache) {
this.requestCache = requestCache;
}
}

View File

@ -0,0 +1,23 @@
package org.baeldung.security;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
/**
* The Entry Point will not redirect to any sort of Login - it will return the 401
*/
@Component
public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}

View File

@ -0,0 +1,16 @@
package org.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource({ "classpath:webSecurityConfig.xml" })
@ComponentScan("org.baeldung.security")
public class SecSecurityConfig {
public SecSecurityConfig() {
super();
}
}

View File

@ -0,0 +1,30 @@
package org.baeldung.spring;
import java.util.List;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
@ComponentScan("org.baeldung.web")
public class WebConfig implements WebMvcConfigurer {
public WebConfig() {
super();
}
// beans
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
}
//
}

View File

@ -0,0 +1,31 @@
package org.baeldung.web.controller;
import org.baeldung.web.dto.Bar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/bars")
public class BarController {
@Autowired
private ApplicationEventPublisher eventPublisher;
public BarController() {
super();
}
// API
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Bar findOne(@PathVariable("id") final Long id) {
return new Bar();
}
}

View File

@ -0,0 +1,33 @@
package org.baeldung.web.controller;
import org.baeldung.web.dto.Foo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/foos")
public class FooController {
@Autowired
private ApplicationEventPublisher eventPublisher;
public FooController() {
super();
}
// API
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasRole('ROLE_USER')")
public Foo findOne(@PathVariable("id") final Long id) {
return new Foo();
}
}

View File

@ -0,0 +1,14 @@
package org.baeldung.web.dto;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Bar implements Serializable {
public Bar() {
super();
}
}

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