Merge branch 'master' into master

This commit is contained in:
iaforek
2017-07-07 09:58:30 +01:00
committed by GitHub
774 changed files with 24476 additions and 5184 deletions
+2 -1
View File
@@ -17,9 +17,10 @@
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea
.idea/
*.iml
+19 -2
View File
@@ -102,7 +102,7 @@
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
- [Guide to UUID in JAVA] (http://www.baeldung.com/guide-to-uuid-in-java)
- [Guide to UUID in JAVA](http://www.baeldung.com/guide-to-uuid-in-java)
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
@@ -113,4 +113,21 @@
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string)
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
- [Split a String in Java](http://www.baeldung.com/java-split-string)
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
+374 -353
View File
@@ -1,399 +1,420 @@
<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</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
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</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java</name>
<name>core-java</name>
<dependencies>
<dependencies>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version>
</dependency>
<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>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.decimal4j</groupId>
<artifactId>decimal4j</artifactId>
<version>${decimal4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>org.decimal4j</groupId>
<artifactId>decimal4j</artifactId>
<version>${decimal4j.version}</version>
</dependency>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<!-- marshalling -->
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- marshalling -->
<!-- logging -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- logging -->
<!-- test scoped -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.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.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.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>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.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>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.1.0.1</version>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.1.0.1</version>
</dependency>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<dependency>
<groupId>com.sun.messaging.mq</groupId>
<artifactId>fscontext</artifactId>
<version>${fscontext.version}</version>
</dependency>
</dependencies>
<plugins>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</build>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath/>
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
</plugins>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<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>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</build>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<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>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<!-- util -->
<guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<commons-io.version>2.5</commons-io.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<lombok.version>1.16.12</lombok.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<!-- util -->
<guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<commons-io.version>2.5</commons-io.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<lombok.version>1.16.12</lombok.version>
<fscontext.version>4.6-b01</fscontext.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
</properties>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project>
@@ -6,7 +6,7 @@ public class NumbersConsumer implements Runnable {
private final BlockingQueue<Integer> queue;
private final int poisonPill;
public NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
this.queue = queue;
this.poisonPill = poisonPill;
}
@@ -9,7 +9,7 @@ public class NumbersProducer implements Runnable {
private final int poisonPill;
private final int poisonPillPerProducer;
public NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
this.numbersQueue = numbersQueue;
this.poisonPill = poisonPill;
this.poisonPillPerProducer = poisonPillPerProducer;
@@ -7,7 +7,7 @@ public class BrokenWorker implements Runnable {
private final List<String> outputScraper;
private final CountDownLatch countDownLatch;
public BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
this.outputScraper = outputScraper;
this.countDownLatch = countDownLatch;
}
@@ -10,7 +10,7 @@ public class WaitingWorker implements Runnable {
private final CountDownLatch callingThreadBlocker;
private final CountDownLatch completedThreadCounter;
public WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
this.outputScraper = outputScraper;
this.readyThreadCounter = readyThreadCounter;
@@ -7,7 +7,7 @@ public class Worker implements Runnable {
private final List<String> outputScraper;
private final CountDownLatch countDownLatch;
public Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
this.outputScraper = outputScraper;
this.countDownLatch = countDownLatch;
}
@@ -0,0 +1,81 @@
package com.baeldung.concurrent.cyclicbarrier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
private CyclicBarrier cyclicBarrier;
private List<List<Integer>> partialResults = Collections.synchronizedList(new ArrayList<>());
private Random random = new Random();
private int NUM_PARTIAL_RESULTS;
private int NUM_WORKERS;
private void runSimulation(int numWorkers, int numberOfPartialResults) {
NUM_PARTIAL_RESULTS = numberOfPartialResults;
NUM_WORKERS = numWorkers;
cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute "
+ NUM_PARTIAL_RESULTS + " partial results each");
for (int i = 0; i < NUM_WORKERS; i++) {
Thread worker = new Thread(new NumberCruncherThread());
worker.setName("Thread " + i);
worker.start();
}
}
class NumberCruncherThread implements Runnable {
@Override
public void run() {
String thisThreadName = Thread.currentThread().getName();
List<Integer> partialResult = new ArrayList<>();
for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
Integer num = random.nextInt(10);
System.out.println(thisThreadName
+ ": Crunching some numbers! Final result - " + num);
partialResult.add(num);
}
partialResults.add(partialResult);
try {
System.out.println(thisThreadName + " waiting for others to reach barrier.");
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
class AggregatorThread implements Runnable {
@Override
public void run() {
String thisThreadName = Thread.currentThread().getName();
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS
+ " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
int sum = 0;
for (List<Integer> threadResult : partialResults) {
System.out.print("Adding ");
for (Integer partialResult : threadResult) {
System.out.print(partialResult+" ");
sum += partialResult;
}
System.out.println();
}
System.out.println(Thread.currentThread().getName() + ": Final result = " + sum);
}
}
public static void main(String[] args) {
CyclicBarrierDemo play = new CyclicBarrierDemo();
play.runSimulation(5, 3);
}
}
@@ -9,7 +9,7 @@ public class DelayObject implements Delayed {
private String data;
private long startTime;
public DelayObject(String data, long delayInMilliseconds) {
DelayObject(String data, long delayInMilliseconds) {
this.data = data;
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
}
@@ -7,9 +7,9 @@ import java.util.concurrent.atomic.AtomicInteger;
public class DelayQueueConsumer implements Runnable {
private BlockingQueue<DelayObject> queue;
private final Integer numberOfElementsToTake;
public final AtomicInteger numberOfConsumedElements = new AtomicInteger();
final AtomicInteger numberOfConsumedElements = new AtomicInteger();
public DelayQueueConsumer(BlockingQueue<DelayObject> queue, Integer numberOfElementsToTake) {
DelayQueueConsumer(BlockingQueue<DelayObject> queue, Integer numberOfElementsToTake) {
this.queue = queue;
this.numberOfElementsToTake = numberOfElementsToTake;
}
@@ -9,9 +9,9 @@ public class DelayQueueProducer implements Runnable {
private final Integer numberOfElementsToProduce;
private final Integer delayOfEachProducedMessageMilliseconds;
public DelayQueueProducer(BlockingQueue<DelayObject> queue,
Integer numberOfElementsToProduce,
Integer delayOfEachProducedMessageMilliseconds) {
DelayQueueProducer(BlockingQueue<DelayObject> queue,
Integer numberOfElementsToProduce,
Integer delayOfEachProducedMessageMilliseconds) {
this.queue = queue;
this.numberOfElementsToProduce = numberOfElementsToProduce;
this.delayOfEachProducedMessageMilliseconds = delayOfEachProducedMessageMilliseconds;
@@ -5,7 +5,7 @@ public class Philosopher implements Runnable {
private final Object leftFork;
private final Object rightFork;
public Philosopher(Object left, Object right) {
Philosopher(Object left, Object right) {
this.leftFork = left;
this.rightFork = right;
}
@@ -30,7 +30,6 @@ public class Philosopher implements Runnable {
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
@@ -7,7 +7,7 @@ public class FactorialSquareCalculator extends RecursiveTask<Integer> {
final private Integer n;
public FactorialSquareCalculator(Integer n) {
FactorialSquareCalculator(Integer n) {
this.n = n;
}
@@ -3,15 +3,15 @@ package com.baeldung.concurrent.future;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class SquareCalculator {
class SquareCalculator {
private final ExecutorService executor;
public SquareCalculator(ExecutorService executor) {
SquareCalculator(ExecutorService executor) {
this.executor = executor;
}
public Future<Integer> calculate(Integer input) {
Future<Integer> calculate(Integer input) {
return executor.submit(() -> {
Thread.sleep(1000);
return input * input;
@@ -13,71 +13,71 @@ import static java.lang.Thread.sleep;
public class ReentrantLockWithCondition {
static Logger logger = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
private static Logger LOG = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
Stack<String> stack = new Stack<>();
int CAPACITY = 5;
private Stack<String> stack = new Stack<>();
private static final int CAPACITY = 5;
ReentrantLock lock = new ReentrantLock();
Condition stackEmptyCondition = lock.newCondition();
Condition stackFullCondition = lock.newCondition();
private ReentrantLock lock = new ReentrantLock();
private Condition stackEmptyCondition = lock.newCondition();
private Condition stackFullCondition = lock.newCondition();
public void pushToStack(String item) throws InterruptedException {
try {
lock.lock();
if (stack.size() == CAPACITY) {
logger.info(Thread.currentThread().getName() + " wait on stack full");
stackFullCondition.await();
}
logger.info("Pushing the item " + item);
stack.push(item);
stackEmptyCondition.signalAll();
} finally {
lock.unlock();
}
private void pushToStack(String item) throws InterruptedException {
try {
lock.lock();
if (stack.size() == CAPACITY) {
LOG.info(Thread.currentThread().getName() + " wait on stack full");
stackFullCondition.await();
}
LOG.info("Pushing the item " + item);
stack.push(item);
stackEmptyCondition.signalAll();
} finally {
lock.unlock();
}
}
}
public String popFromStack() throws InterruptedException {
try {
lock.lock();
if (stack.size() == 0) {
logger.info(Thread.currentThread().getName() + " wait on stack empty");
stackEmptyCondition.await();
}
return stack.pop();
} finally {
stackFullCondition.signalAll();
lock.unlock();
}
}
private String popFromStack() throws InterruptedException {
try {
lock.lock();
if (stack.size() == 0) {
LOG.info(Thread.currentThread().getName() + " wait on stack empty");
stackEmptyCondition.await();
}
return stack.pop();
} finally {
stackFullCondition.signalAll();
lock.unlock();
}
}
public static void main(String[] args) {
final int threadCount = 2;
ReentrantLockWithCondition object = new ReentrantLockWithCondition();
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
service.execute(() -> {
for (int i = 0; i < 10; i++) {
try {
object.pushToStack("Item " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
final int threadCount = 2;
ReentrantLockWithCondition object = new ReentrantLockWithCondition();
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
service.execute(() -> {
for (int i = 0; i < 10; i++) {
try {
object.pushToStack("Item " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
});
service.execute(() -> {
for (int i = 0; i < 10; i++) {
try {
logger.info("Item popped " + object.popFromStack());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
service.execute(() -> {
for (int i = 0; i < 10; i++) {
try {
LOG.info("Item popped " + object.popFromStack());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
});
service.shutdown();
}
service.shutdown();
}
}
@@ -12,81 +12,77 @@ import static java.lang.Thread.sleep;
public class SharedObjectWithLock {
Logger logger = LoggerFactory.getLogger(SharedObjectWithLock.class);
private static final Logger LOG = LoggerFactory.getLogger(SharedObjectWithLock.class);
ReentrantLock lock = new ReentrantLock(true);
private ReentrantLock lock = new ReentrantLock(true);
int counter = 0;
private int counter = 0;
public void perform() {
void perform() {
lock.lock();
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
try {
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
counter++;
} catch (Exception exception) {
logger.error(" Interrupted Exception ", exception);
} finally {
lock.unlock();
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
}
}
lock.lock();
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
try {
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
counter++;
} catch (Exception exception) {
LOG.error(" Interrupted Exception ", exception);
} finally {
lock.unlock();
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
}
}
public void performTryLock() {
private void performTryLock() {
logger.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
try {
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
if (isLockAcquired) {
try {
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
LOG.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
try {
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
if (isLockAcquired) {
try {
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
sleep(1000);
} finally {
lock.unlock();
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
sleep(1000);
} finally {
lock.unlock();
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
}
}
} catch (InterruptedException exception) {
logger.error(" Interrupted Exception ", exception);
}
logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
}
}
}
} catch (InterruptedException exception) {
LOG.error(" Interrupted Exception ", exception);
}
LOG.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
}
public ReentrantLock getLock() {
return lock;
}
public ReentrantLock getLock() {
return lock;
}
boolean isLocked() {
return lock.isLocked();
}
boolean isLocked() {
return lock.isLocked();
}
boolean hasQueuedThreads() {
return lock.hasQueuedThreads();
}
boolean hasQueuedThreads() {
return lock.hasQueuedThreads();
}
int getCounter() {
return counter;
}
int getCounter() {
return counter;
}
public static void main(String[] args) {
public static void main(String[] args) {
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
service.execute(() -> {
object.perform();
});
service.execute(() -> {
object.performTryLock();
});
service.execute(object::perform);
service.execute(object::performTryLock);
service.shutdown();
service.shutdown();
}
}
}
@@ -12,93 +12,93 @@ import java.util.concurrent.locks.StampedLock;
import static java.lang.Thread.sleep;
public class StampedLockDemo {
Map<String, String> map = new HashMap<>();
Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
private Map<String, String> map = new HashMap<>();
private Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
private final StampedLock lock = new StampedLock();
private final StampedLock lock = new StampedLock();
public void put(String key, String value) throws InterruptedException {
long stamp = lock.writeLock();
public void put(String key, String value) throws InterruptedException {
long stamp = lock.writeLock();
try {
logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
map.put(key, value);
} finally {
lock.unlockWrite(stamp);
logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
}
}
try {
logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
map.put(key, value);
} finally {
lock.unlockWrite(stamp);
logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
}
}
public String get(String key) throws InterruptedException {
long stamp = lock.readLock();
logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
try {
sleep(5000);
return map.get(key);
public String get(String key) throws InterruptedException {
long stamp = lock.readLock();
logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
try {
sleep(5000);
return map.get(key);
} finally {
lock.unlockRead(stamp);
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
} finally {
lock.unlockRead(stamp);
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
}
}
}
}
public String readWithOptimisticLock(String key) throws InterruptedException {
long stamp = lock.tryOptimisticRead();
String value = map.get(key);
private String readWithOptimisticLock(String key) throws InterruptedException {
long stamp = lock.tryOptimisticRead();
String value = map.get(key);
if (!lock.validate(stamp)) {
stamp = lock.readLock();
try {
sleep(5000);
return map.get(key);
if (!lock.validate(stamp)) {
stamp = lock.readLock();
try {
sleep(5000);
return map.get(key);
} finally {
lock.unlock(stamp);
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
} finally {
lock.unlock(stamp);
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
}
}
return value;
}
}
}
return value;
}
public static void main(String[] args) {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
StampedLockDemo object = new StampedLockDemo();
public static void main(String[] args) {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
StampedLockDemo object = new StampedLockDemo();
Runnable writeTask = () -> {
Runnable writeTask = () -> {
try {
object.put("key1", "value1");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Runnable readTask = () -> {
try {
object.put("key1", "value1");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Runnable readTask = () -> {
try {
object.get("key1");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Runnable readOptimisticTask = () -> {
try {
object.get("key1");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Runnable readOptimisticTask = () -> {
try {
object.readWithOptimisticLock("key1");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
service.submit(writeTask);
service.submit(writeTask);
service.submit(readTask);
service.submit(readOptimisticTask);
try {
object.readWithOptimisticLock("key1");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
service.submit(writeTask);
service.submit(writeTask);
service.submit(readTask);
service.submit(readOptimisticTask);
service.shutdown();
service.shutdown();
}
}
}
@@ -15,106 +15,106 @@ import static java.lang.Thread.sleep;
public class SynchronizedHashMapWithRWLock {
static Map<String, String> syncHashMap = new HashMap<>();
Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
private static Map<String, String> syncHashMap = new HashMap<>();
private Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Lock readLock = lock.readLock();
private final Lock writeLock = lock.writeLock();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Lock readLock = lock.readLock();
private final Lock writeLock = lock.writeLock();
public void put(String key, String value) throws InterruptedException {
public void put(String key, String value) throws InterruptedException {
try {
writeLock.lock();
logger.info(Thread.currentThread().getName() + " writing");
syncHashMap.put(key, value);
sleep(1000);
} finally {
writeLock.unlock();
}
try {
writeLock.lock();
logger.info(Thread.currentThread().getName() + " writing");
syncHashMap.put(key, value);
sleep(1000);
} finally {
writeLock.unlock();
}
}
}
public String get(String key) {
try {
readLock.lock();
logger.info(Thread.currentThread().getName() + " reading");
return syncHashMap.get(key);
} finally {
readLock.unlock();
}
}
public String get(String key) {
try {
readLock.lock();
logger.info(Thread.currentThread().getName() + " reading");
return syncHashMap.get(key);
} finally {
readLock.unlock();
}
}
public String remove(String key) {
try {
writeLock.lock();
return syncHashMap.remove(key);
} finally {
writeLock.unlock();
}
}
public String remove(String key) {
try {
writeLock.lock();
return syncHashMap.remove(key);
} finally {
writeLock.unlock();
}
}
public boolean containsKey(String key) {
try {
readLock.lock();
return syncHashMap.containsKey(key);
} finally {
readLock.unlock();
}
}
public boolean containsKey(String key) {
try {
readLock.lock();
return syncHashMap.containsKey(key);
} finally {
readLock.unlock();
}
}
boolean isReadLockAvailable() {
return readLock.tryLock();
}
boolean isReadLockAvailable() {
return readLock.tryLock();
}
public static void main(String[] args) throws InterruptedException {
public static void main(String[] args) throws InterruptedException {
final int threadCount = 3;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 3;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
service.execute(new Thread(new Writer(object), "Writer"));
service.execute(new Thread(new Reader(object), "Reader1"));
service.execute(new Thread(new Reader(object), "Reader2"));
service.execute(new Thread(new Writer(object), "Writer"));
service.execute(new Thread(new Reader(object), "Reader1"));
service.execute(new Thread(new Reader(object), "Reader2"));
service.shutdown();
}
service.shutdown();
}
private static class Reader implements Runnable {
private static class Reader implements Runnable {
SynchronizedHashMapWithRWLock object;
SynchronizedHashMapWithRWLock object;
public Reader(SynchronizedHashMapWithRWLock object) {
this.object = object;
}
Reader(SynchronizedHashMapWithRWLock object) {
this.object = object;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
object.get("key" + i);
}
}
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
object.get("key" + i);
}
}
}
private static class Writer implements Runnable {
private static class Writer implements Runnable {
SynchronizedHashMapWithRWLock object;
SynchronizedHashMapWithRWLock object;
public Writer(SynchronizedHashMapWithRWLock object) {
this.object = object;
}
public Writer(SynchronizedHashMapWithRWLock object) {
this.object = object;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
object.put("key" + i, "value" + i);
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
object.put("key" + i, "value" + i);
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
@@ -0,0 +1,31 @@
package com.baeldung.concurrent.semaphores;
import java.util.concurrent.Semaphore;
class CounterUsingMutex {
private final Semaphore mutex;
private int count;
CounterUsingMutex() {
mutex = new Semaphore(1);
count = 0;
}
void increase() throws InterruptedException {
mutex.acquire();
this.count = this.count + 1;
Thread.sleep(1000);
mutex.release();
}
int getCount() {
return this.count;
}
boolean hasQueuedThreads() {
return mutex.hasQueuedThreads();
}
}
@@ -0,0 +1,23 @@
package com.baeldung.concurrent.semaphores;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.concurrent.TimedSemaphore;
class DelayQueueUsingTimedSemaphore {
private final TimedSemaphore semaphore;
DelayQueueUsingTimedSemaphore(long period, int slotLimit) {
semaphore = new TimedSemaphore(period, TimeUnit.SECONDS, slotLimit);
}
boolean tryAdd() {
return semaphore.tryAcquire();
}
int availableSlots() {
return semaphore.getAvailablePermits();
}
}
@@ -0,0 +1,25 @@
package com.baeldung.concurrent.semaphores;
import java.util.concurrent.Semaphore;
class LoginQueueUsingSemaphore {
private final Semaphore semaphore;
LoginQueueUsingSemaphore(int slotLimit) {
semaphore = new Semaphore(slotLimit);
}
boolean tryLogin() {
return semaphore.tryAcquire();
}
void logout() {
semaphore.release();
}
int availableSlots() {
return semaphore.availablePermits();
}
}
@@ -2,20 +2,20 @@ package com.baeldung.concurrent.skiplist;
import java.time.ZonedDateTime;
public class Event {
class Event {
private final ZonedDateTime eventTime;
private final String content;
public Event(ZonedDateTime eventTime, String content) {
Event(ZonedDateTime eventTime, String content) {
this.eventTime = eventTime;
this.content = content;
}
public ZonedDateTime getEventTime() {
ZonedDateTime getEventTime() {
return eventTime;
}
public String getContent() {
String getContent() {
return content;
}
}
@@ -5,24 +5,24 @@ import java.util.Comparator;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class EventWindowSort {
class EventWindowSort {
private final ConcurrentSkipListMap<ZonedDateTime, String> events
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
public void acceptEvent(Event event) {
void acceptEvent(Event event) {
events.put(event.getEventTime(), event.getContent());
}
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
return events.tailMap(ZonedDateTime
.now()
.minusMinutes(1));
.now()
.minusMinutes(1));
}
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
return events.headMap(ZonedDateTime
.now()
.minusMinutes(1));
.now()
.minusMinutes(1));
}
}
@@ -13,10 +13,10 @@ public class WaitSleepExample {
private static final Object LOCK = new Object();
public static void main(String... args) throws InterruptedException {
sleepWaitInSyncronizedBlocks();
sleepWaitInSynchronizedBlocks();
}
private static void sleepWaitInSyncronizedBlocks() throws InterruptedException {
private static void sleepWaitInSynchronizedBlocks() throws InterruptedException {
Thread.sleep(1000); // called on the thread
LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
@@ -25,5 +25,5 @@ public class WaitSleepExample {
LOG.debug("Object '" + LOCK + "' is woken after waiting for 1 second");
}
}
}
@@ -5,13 +5,13 @@ public class BaeldungSynchronizedBlocks {
private int count = 0;
private static int staticCount = 0;
public void performSynchronisedTask() {
void performSynchronisedTask() {
synchronized (this) {
setCount(getCount() + 1);
}
}
public static void performStaticSyncTask() {
static void performStaticSyncTask() {
synchronized (BaeldungSynchronizedBlocks.class) {
setStaticCount(getStaticCount() + 1);
}
@@ -25,11 +25,11 @@ public class BaeldungSynchronizedBlocks {
this.count = count;
}
public static int getStaticCount() {
static int getStaticCount() {
return staticCount;
}
public static void setStaticCount(int staticCount) {
private static void setStaticCount(int staticCount) {
BaeldungSynchronizedBlocks.staticCount = staticCount;
}
}
@@ -5,17 +5,17 @@ public class BaeldungSynchronizedMethods {
private int sum = 0;
private int syncSum = 0;
public static int staticSum = 0;
static int staticSum = 0;
public void calculate() {
void calculate() {
setSum(getSum() + 1);
}
public synchronized void synchronisedCalculate() {
synchronized void synchronisedCalculate() {
setSyncSum(getSyncSum() + 1);
}
public static synchronized void syncStaticCalculate() {
static synchronized void syncStaticCalculate() {
staticSum = staticSum + 1;
}
@@ -27,11 +27,11 @@ public class BaeldungSynchronizedMethods {
this.sum = sum;
}
public int getSyncSum() {
int getSyncSum() {
return syncSum;
}
public void setSyncSum(int syncSum) {
private void setSyncSum(int syncSum) {
this.syncSum = syncSum;
}
}
@@ -6,40 +6,40 @@ import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
public class UseLocalDate {
class UseLocalDate {
public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
return LocalDate.of(year, month, dayOfMonth);
}
public LocalDate getLocalDateUsingParseMethod(String representation) {
LocalDate getLocalDateUsingParseMethod(String representation) {
return LocalDate.parse(representation);
}
public LocalDate getLocalDateFromClock() {
LocalDate getLocalDateFromClock() {
LocalDate localDate = LocalDate.now();
return localDate;
}
public LocalDate getNextDay(LocalDate localDate) {
LocalDate getNextDay(LocalDate localDate) {
return localDate.plusDays(1);
}
public LocalDate getPreviousDay(LocalDate localDate) {
LocalDate getPreviousDay(LocalDate localDate) {
return localDate.minus(1, ChronoUnit.DAYS);
}
public DayOfWeek getDayOfWeek(LocalDate localDate) {
DayOfWeek getDayOfWeek(LocalDate localDate) {
DayOfWeek day = localDate.getDayOfWeek();
return day;
}
public LocalDate getFirstDayOfMonth() {
LocalDate getFirstDayOfMonth() {
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
return firstDayOfMonth;
}
public LocalDateTime getStartOfDay(LocalDate localDate) {
LocalDateTime getStartOfDay(LocalDate localDate) {
LocalDateTime startofDay = localDate.atStartOfDay();
return startofDay;
}
@@ -5,31 +5,27 @@ import java.time.temporal.ChronoUnit;
public class UseLocalTime {
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
LocalTime localTime = LocalTime.of(hour, min, seconds);
return localTime;
LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
return LocalTime.of(hour, min, seconds);
}
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
LocalTime localTime = LocalTime.parse(timeRepresentation);
return localTime;
LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
return LocalTime.parse(timeRepresentation);
}
public LocalTime getLocalTimeFromClock() {
LocalTime localTime = LocalTime.now();
return localTime;
private LocalTime getLocalTimeFromClock() {
return LocalTime.now();
}
public LocalTime addAnHour(LocalTime localTime) {
LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS);
return newTime;
LocalTime addAnHour(LocalTime localTime) {
return localTime.plus(1, ChronoUnit.HOURS);
}
public int getHourFromLocalTime(LocalTime localTime) {
int getHourFromLocalTime(LocalTime localTime) {
return localTime.getHour();
}
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
return localTime.withMinute(minute);
}
}
@@ -3,13 +3,13 @@ package com.baeldung.datetime;
import java.time.LocalDate;
import java.time.Period;
public class UsePeriod {
class UsePeriod {
public LocalDate modifyDates(LocalDate localDate, Period period) {
LocalDate modifyDates(LocalDate localDate, Period period) {
return localDate.plus(period);
}
public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
return Period.between(localDate1, localDate2);
}
}
@@ -8,12 +8,10 @@ import java.util.Date;
public class UseToInstant {
public LocalDateTime convertDateToLocalDate(Date date) {
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
return localDateTime;
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
return localDateTime;
return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
}
}
@@ -4,10 +4,9 @@ import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class UseZonedDateTime {
class UseZonedDateTime {
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
return zonedDateTime;
ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
return ZonedDateTime.of(localDateTime, zoneId);
}
}
@@ -0,0 +1,26 @@
package com.baeldung.deserialization;
import java.io.Serializable;
public class AppleProduct implements Serializable {
private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated)
// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated)
public String headphonePort;
public String thunderboltPort;
public String lighteningPort;
public String getHeadphonePort() {
return headphonePort;
}
public String getThunderboltPort() {
return thunderboltPort;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.deserialization;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Base64;
public class DeserializationUtility {
public static void main(String[] args) throws ClassNotFoundException, IOException {
String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
System.out.println("Deserializing AppleProduct...");
AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj);
System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort());
System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort());
}
public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException {
byte[] data = Base64.getDecoder().decode(s);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
Object o = ois.readObject();
ois.close();
return o;
}
}
@@ -0,0 +1,30 @@
package com.baeldung.deserialization;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Base64;
public class SerializationUtility {
public static void main(String[] args) throws ClassNotFoundException, IOException {
AppleProduct macBook = new AppleProduct();
macBook.headphonePort = "headphonePort2020";
macBook.thunderboltPort = "thunderboltPort2020";
String serializedObj = serializeObjectToString(macBook);
System.out.println("Serialized AppleProduct object to string:");
System.out.println(serializedObj);
}
public static String serializeObjectToString(Serializable o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
}
@@ -13,8 +13,7 @@ public class DirectoryMonitoringExample {
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
public static final int POLL_INTERVAL = 500;
private static final int POLL_INTERVAL = 500;
public static void main(String[] args) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
@@ -6,12 +6,12 @@ public class Computer {
private String color;
private Integer healty;
public Computer(final int age, final String color) {
Computer(final int age, final String color) {
this.age = age;
this.color = color;
}
public Computer(final Integer age, final String color, final Integer healty) {
Computer(final Integer age, final String color, final Integer healty) {
this.age = age;
this.color = color;
this.healty = healty;
@@ -28,7 +28,7 @@ public class Computer {
this.age = age;
}
public String getColor() {
String getColor() {
return color;
}
@@ -36,11 +36,11 @@ public class Computer {
this.color = color;
}
public Integer getHealty() {
Integer getHealty() {
return healty;
}
public void setHealty(final Integer healty) {
void setHealty(final Integer healty) {
this.healty = healty;
}
@@ -72,10 +72,7 @@ public class Computer {
final Computer computer = (Computer) o;
if (age != null ? !age.equals(computer.age) : computer.age != null) {
return false;
}
return color != null ? color.equals(computer.color) : computer.color == null;
return (age != null ? age.equals(computer.age) : computer.age == null) && (color != null ? color.equals(computer.color) : computer.color == null);
}
@@ -7,8 +7,8 @@ import java.util.List;
public class ComputerUtils {
public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
@@ -18,7 +18,7 @@ public class ComputerUtils {
return result;
}
public static void repair(final Computer computer) {
static void repair(final Computer computer) {
if (computer.getHealty() < 50) {
computer.setHealty(100);
}
@@ -13,7 +13,7 @@ public class MacbookPro extends Computer {
super(age, color);
}
public MacbookPro(Integer age, String color, Integer healty) {
MacbookPro(Integer age, String color, Integer healty) {
super(age, color, healty);
}
@@ -15,7 +15,7 @@ public class TimingDynamicInvocationHandler implements InvocationHandler {
private Object target;
public TimingDynamicInvocationHandler(Object target) {
TimingDynamicInvocationHandler(Object target) {
this.target = target;
for(Method method: target.getClass().getDeclaredMethods()) {
@@ -1,10 +1,10 @@
package com.baeldung.equalshashcode.entities;
import java.awt.Color;
import java.awt.*;
public class Square extends Rectangle {
Color color;
private Color color;
public Square(double width, Color color) {
super(width, width);
@@ -0,0 +1,43 @@
package com.baeldung.filesystem.jndi;
import java.io.File;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class LookupFSJNDI {
private InitialContext ctx = null;
public LookupFSJNDI() throws NamingException {
super();
init();
}
private void init() throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put (Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
// URI to namespace (actual directory)
env.put(Context.PROVIDER_URL, "file:./src/test/resources");
ctx = new InitialContext(env);
}
public InitialContext getCtx() {
return ctx;
}
public File getFile(String fileName) {
File file;
try {
file = (File)getCtx().lookup(fileName);
} catch (NamingException e) {
file = null;
}
return file;
}
}
@@ -0,0 +1,23 @@
package com.baeldung.java.reflection;
import java.lang.annotation.Annotation;
public class DynamicGreeter implements Greeter {
private String greet;
public DynamicGreeter(String greet) {
this.greet = greet;
}
@Override
public Class<? extends Annotation> annotationType() {
return DynamicGreeter.class;
}
@Override
public String greet() {
return greet;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.java.reflection;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Greeter {
public String greet() default "";
}
@@ -0,0 +1,58 @@
package com.baeldung.java.reflection;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
public class GreetingAnnotation {
private static final String ANNOTATION_METHOD = "annotationData";
private static final String ANNOTATION_FIELDS = "declaredAnnotations";
private static final String ANNOTATIONS = "annotations";
public static void main(String ...args) {
Greeter greetings = Greetings.class.getAnnotation(Greeter.class);
System.err.println("Hello there, " + greetings.greet() + " !!");
Greeter targetValue = new DynamicGreeter("Good evening");
//alterAnnotationValueJDK8(Greetings.class, Greeter.class, targetValue);
alterAnnotationValueJDK7(Greetings.class, Greeter.class, targetValue);
greetings = Greetings.class.getAnnotation(Greeter.class);
System.err.println("Hello there, " + greetings.greet() + " !!");
}
@SuppressWarnings("unchecked")
public static void alterAnnotationValueJDK8(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
try {
Method method = Class.class.getDeclaredMethod(ANNOTATION_METHOD, null);
method.setAccessible(true);
Object annotationData = method.invoke(targetClass);
Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS);
annotations.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData);
map.put(targetAnnotation, targetValue);
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static void alterAnnotationValueJDK7(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
try {
Field annotations = Class.class.getDeclaredField(ANNOTATIONS);
annotations.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(targetClass);
System.out.println(map);
map.put(targetAnnotation, targetValue);
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,6 @@
package com.baeldung.java.reflection;
@Greeter(greet="Good morning")
public class Greetings {
}
@@ -0,0 +1,69 @@
package com.baeldung.javanetworking.url;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class URLDemo {
private final Logger log = LoggerFactory.getLogger(URLDemo.class);
String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
// parsed locator
String URLPROTOCOL = "https";
// final static String URLAUTHORITY = "wordpress.org:443";
String URLHOST = "wordpress.org";
String URLPATH = "/support/topic/page-jumps-within-wordpress/";
// final static String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
// final static int URLPORT = 443;
int URLDEFAULTPORT = 443;
String URLQUERY = "replies=3";
String URLREFERENCE = "post-2278484";
String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
URL url;
URLConnection urlConnection = null;
HttpURLConnection connection = null;
BufferedReader in = null;
String urlContent = "";
public String testURL(String urlString) throws IOException, IllegalArgumentException {
String urlStringCont = "";
// comment the if clause if experiment with URL
/*if (!URLSTRING.equals(urlString)) {
throw new IllegalArgumentException("URL String argument is not proper: " + urlString);
}*/
// creating URL object
url = new URL(urlString);
// get URL connection
urlConnection = url.openConnection();
connection = null;
// we can check, if connection is proper type
if (urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
} else {
log.info("Please enter an HTTP URL");
throw new IOException("HTTP URL is not correct");
}
// we can check response code (200 OK is expected)
log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String current;
while ((current = in.readLine()) != null) {
urlStringCont += current;
}
return urlStringCont;
}
public static void main(String[] args) throws Exception {
URLDemo demo = new URLDemo();
String content = demo.testURL(demo.URLCOMPOUND);
demo.log.info(content);
}
}
@@ -0,0 +1,71 @@
package com.baeldung.map.iteration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MapIteration {
public static void main(String[] args) {
MapIteration mapIteration = new MapIteration();
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Three", 3);
map.put("Two", 2);
System.out.println("Iterating Keys of Map Using KeySet");
mapIteration.iterateKeys(map);
System.out.println("Iterating Map Using Entry Set");
mapIteration.iterateUsingEntrySet(map);
System.out.println("Iterating Using Iterator and Map Entry");
mapIteration.iterateUsingIteratorAndEntry(map);
System.out.println("Iterating Using KeySet and For Each");
mapIteration.iterateUsingKeySetAndForeach(map);
System.out.println("Iterating Map Using Lambda Expression");
mapIteration.iterateUsingLambda(map);
System.out.println("Iterating Using Stream API");
mapIteration.iterateUsingStreamAPI(map);
}
public void iterateUsingEntrySet(Map<String, Integer> map) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
public void iterateUsingLambda(Map<String, Integer> map) {
map.forEach((k, v) -> System.out.println((k + ":" + v)));
}
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> pair = iterator.next();
System.out.println(pair.getKey() + ":" + pair.getValue());
}
}
public void iterateUsingKeySetAndForeach(Map<String, Integer> map) {
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
}
public void iterateUsingStreamAPI(Map<String, Integer> map) {
map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}
public void iterateKeys(Map<String, Integer> map) {
for (String key : map.keySet()) {
System.out.println(key);
}
}
}
@@ -0,0 +1,18 @@
package com.baeldung.maths;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalImpl {
public static void main(String[] args) {
BigDecimal serviceTax = new BigDecimal("56.0084578639");
serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
BigDecimal entertainmentTax = new BigDecimal("23.00689");
entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
BigDecimal totalTax = serviceTax.add(entertainmentTax);
}
}
@@ -0,0 +1,16 @@
package com.baeldung.maths;
import java.math.BigInteger;
public class BigIntegerImpl {
public static void main(String[] args) {
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
}
}
@@ -11,4 +11,4 @@ public class NoClassDefFoundErrorExample {
test = new ClassWithInitErrors();
return test;
}
}
}
@@ -0,0 +1,19 @@
package com.baeldung.outofmemoryerror;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class OutOfMemoryGCLimitExceed {
public static void addRandomDataToMap() {
Map<Integer, String> dataMap = new HashMap<>();
Random r = new Random();
while (true) {
dataMap.put(r.nextInt(), String.valueOf(r.nextInt()));
}
}
public static void main(String[] args) {
OutOfMemoryGCLimitExceed.addRandomDataToMap();
}
}
@@ -0,0 +1,39 @@
package com.baeldung.reflection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
class BaeldungReflectionUtils {
private static final Logger LOG = LoggerFactory.getLogger(BaeldungReflectionUtils.class);
static List<String> getNullPropertiesList(Customer customer) throws Exception {
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
return Arrays.stream(propDescArr)
.filter(nulls(customer))
.map(PropertyDescriptor::getName)
.collect(Collectors.toList());
}
private static Predicate<PropertyDescriptor> nulls(Customer customer) {
return pd -> {
boolean result = false;
try {
Method getterMethod = pd.getReadMethod();
result = (getterMethod != null && getterMethod.invoke(customer) == null);
} catch (Exception e) {
LOG.error("error invoking getter method");
}
return result;
};
}
}
@@ -0,0 +1,56 @@
package com.baeldung.reflection;
public class Customer {
private Integer id;
private String name;
private String emailId;
private Long phoneNumber;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", emailId=" + emailId + ", phoneNumber=" +
phoneNumber + "]";
}
Customer(Integer id, String name, String emailId, Long phoneNumber) {
super();
this.id = id;
this.name = name;
this.emailId = emailId;
this.phoneNumber = phoneNumber;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
@@ -1,4 +1,4 @@
package com.baeuldung.serialization;
package com.baeldung.serialization;
public class Address {
@@ -1,4 +1,4 @@
package com.baeuldung.serialization;
package com.baeldung.serialization;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -1,4 +1,4 @@
package com.baeuldung.serialization;
package com.baeldung.serialization;
import java.io.Serializable;
public class Person implements Serializable {
@@ -5,17 +5,17 @@ import java.util.stream.Stream;
public class StreamApi {
public String getLastElementUsingReduce(List<String> valueList) {
public static String getLastElementUsingReduce(List<String> valueList) {
Stream<String> stream = valueList.stream();
return stream.reduce((first, second) -> second).orElse(null);
}
public Integer getInfiniteStreamLastElementUsingReduce() {
public static Integer getInfiniteStreamLastElementUsingReduce() {
Stream<Integer> stream = Stream.iterate(0, i -> i + 1);
return stream.limit(20).reduce((first, second) -> second).orElse(null);
}
public String getLastElementUsingSkip(List<String> valueList) {
public static String getLastElementUsingSkip(List<String> valueList) {
long count = valueList.stream().count();
Stream<String> stream = valueList.stream();
return stream.skip(count - 1).findFirst().orElse(null);
@@ -0,0 +1,16 @@
package com.baeldung.typeerasure;
public class ArrayContentPrintUtil {
public static <E> void printArray(E[] array) {
for (E element : array) {
System.out.printf("%s ", element);
}
}
public static <E extends Comparable<E>> void printArray(E[] array) {
for (E element : array) {
System.out.printf("%s ", element);
}
}
}
@@ -0,0 +1,37 @@
package com.baeldung.typeerasure;
import java.util.Arrays;
public class BoundStack<E extends Comparable<E>> {
private E[] stackContent;
private int total;
public BoundStack(int capacity) {
this.stackContent = (E[]) new Object[capacity];
}
public void push(E data) {
if (total == stackContent.length) {
resize(2 * stackContent.length);
}
stackContent[total++] = data;
}
public E pop() {
if (!isEmpty()) {
E datum = stackContent[total];
stackContent[total--] = null;
return datum;
}
return null;
}
private void resize(int capacity) {
Arrays.copyOf(stackContent, capacity);
}
public boolean isEmpty() {
return total == 0;
}
}
@@ -0,0 +1,13 @@
package com.baeldung.typeerasure;
public class IntegerStack extends Stack<Integer> {
public IntegerStack(int capacity) {
super(capacity);
}
public void push(Integer value) {
System.out.println("Pushing into my integerStack");
super.push(value);
}
}
@@ -0,0 +1,39 @@
package com.baeldung.typeerasure;
import java.util.Arrays;
public class Stack<E> {
private E[] stackContent;
private int total;
public Stack(int capacity) {
this.stackContent = (E[]) new Object[capacity];
}
public void push(E data) {
System.out.println("In base stack push#");
if (total == stackContent.length) {
resize(2 * stackContent.length);
}
stackContent[total++] = data;
}
public E pop() {
if (!isEmpty()) {
E datum = stackContent[total];
stackContent[total--] = null;
return datum;
}
return null;
}
private void resize(int capacity) {
Arrays.copyOf(stackContent, capacity);
}
public boolean isEmpty() {
return total == 0;
}
}
+9
View File
@@ -0,0 +1,9 @@
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
@@ -9,6 +9,8 @@ import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertTrue;
public class ArrayCopyUtilUnitTest {
private static Employee[] employees;
private static final int MAX = 2;
@@ -46,10 +48,10 @@ public class ArrayCopyUtilUnitTest {
System.arraycopy(array, 2, copiedArray, 0, 3);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[2]);
Assert.assertTrue(copiedArray[1] == array[3]);
Assert.assertTrue(copiedArray[2] == array[4]);
assertTrue(3 == copiedArray.length);
assertTrue(copiedArray[0] == array[2]);
assertTrue(copiedArray[1] == array[3]);
assertTrue(copiedArray[2] == array[4]);
}
@Test
@@ -58,10 +60,10 @@ public class ArrayCopyUtilUnitTest {
int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[1]);
Assert.assertTrue(copiedArray[1] == array[2]);
Assert.assertTrue(copiedArray[2] == array[3]);
assertTrue(3 == copiedArray.length);
assertTrue(copiedArray[0] == array[1]);
assertTrue(copiedArray[1] == array[2]);
assertTrue(copiedArray[2] == array[3]);
}
@Test
@@ -73,9 +75,9 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
assertTrue(copiedArray[1] != array[1]);
}
@Test
@@ -85,7 +87,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element caused change in the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
@@ -96,9 +98,9 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
assertTrue(copiedArray[1] != array[1]);
}
@Test
@@ -108,7 +110,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);;
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element changed the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
@@ -138,7 +140,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
@@ -8,4 +8,4 @@ public class ClassNotFoundExceptionTest {
public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}
}
@@ -11,9 +11,9 @@ import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CompletableFutureUnitTest {
public class CompletableFutureLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureUnitTest.class);
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class);
@Test
@@ -24,7 +24,7 @@ public class CompletableFutureUnitTest {
assertEquals("Hello", result);
}
public Future<String> calculateAsync() throws InterruptedException {
private Future<String> calculateAsync() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
@@ -44,7 +44,7 @@ public class CompletableFutureUnitTest {
assertEquals("Hello", result);
}
public Future<String> calculateAsyncWithCancellation() throws InterruptedException {
private Future<String> calculateAsyncWithCancellation() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
@@ -24,8 +24,8 @@ public class LongAccumulatorUnitTest {
//when
Runnable accumulateAction = () -> IntStream
.rangeClosed(0, numberOfIncrements)
.forEach(accumulator::accumulate);
.rangeClosed(0, numberOfIncrements)
.forEach(accumulator::accumulate);
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(accumulateAction);
@@ -17,7 +17,7 @@ public class CopyOnWriteArrayListUnitTest {
public void givenCopyOnWriteList_whenIterateAndAddElementToUnderneathList_thenShouldNotChangeIterator() {
//given
final CopyOnWriteArrayList<Integer> numbers =
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
//when
Iterator<Integer> iterator = numbers.iterator();
@@ -42,7 +42,7 @@ public class CopyOnWriteArrayListUnitTest {
public void givenCopyOnWriteList_whenIterateOverItAndTryToRemoveElement_thenShouldThrowException() {
//given
final CopyOnWriteArrayList<Integer> numbers =
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
//when
Iterator<Integer> iterator = numbers.iterator();
@@ -4,7 +4,11 @@ import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.concurrent.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static junit.framework.TestCase.assertEquals;
@@ -19,7 +23,7 @@ public class DelayQueueIntegrationTest {
int delayOfEachProducedMessageMilliseconds = 500;
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
DelayQueueProducer producer
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
//when
executor.submit(producer);
@@ -41,7 +45,7 @@ public class DelayQueueIntegrationTest {
int delayOfEachProducedMessageMilliseconds = 10_000;
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
DelayQueueProducer producer
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
//when
executor.submit(producer);
@@ -63,7 +67,7 @@ public class DelayQueueIntegrationTest {
int delayOfEachProducedMessageMilliseconds = -10_000;
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
DelayQueueProducer producer
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
//when
executor.submit(producer);
@@ -1,10 +1,10 @@
package com.baeldung.concurrent.future;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.util.concurrent.ForkJoinPool;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class FactorialSquareCalculatorUnitTest {
@@ -8,7 +8,12 @@ import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -9,65 +9,65 @@ import static junit.framework.TestCase.assertEquals;
public class SharedObjectWithLockManualTest {
@Test
public void whenLockAcquired_ThenLockedIsTrue() {
final SharedObjectWithLock object = new SharedObjectWithLock();
@Test
public void whenLockAcquired_ThenLockedIsTrue() {
final SharedObjectWithLock object = new SharedObjectWithLock();
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeThreads(object, threadCount, service);
executeThreads(object, threadCount, service);
assertEquals(true, object.isLocked());
assertEquals(true, object.isLocked());
service.shutdown();
}
service.shutdown();
}
@Test
public void whenLocked_ThenQueuedThread() {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
@Test
public void whenLocked_ThenQueuedThread() {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
executeThreads(object, threadCount, service);
executeThreads(object, threadCount, service);
assertEquals(object.hasQueuedThreads(), true);
assertEquals(object.hasQueuedThreads(), true);
service.shutdown();
service.shutdown();
}
}
public void whenTryLock_ThenQueuedThread() {
final SharedObjectWithLock object = new SharedObjectWithLock();
public void whenTryLock_ThenQueuedThread() {
final SharedObjectWithLock object = new SharedObjectWithLock();
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeThreads(object, threadCount, service);
executeThreads(object, threadCount, service);
assertEquals(true, object.isLocked());
assertEquals(true, object.isLocked());
service.shutdown();
}
service.shutdown();
}
@Test
public void whenGetCount_ThenCorrectCount() throws InterruptedException {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
@Test
public void whenGetCount_ThenCorrectCount() throws InterruptedException {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
executeThreads(object, threadCount, service);
Thread.sleep(1000);
assertEquals(object.getCounter(), 4);
executeThreads(object, threadCount, service);
Thread.sleep(1000);
assertEquals(object.getCounter(), 4);
service.shutdown();
service.shutdown();
}
}
private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(object::perform);
}
}
private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(object::perform);
}
}
}
@@ -1,6 +1,5 @@
package com.baeldung.concurrent.locks;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
@@ -10,49 +9,49 @@ import static junit.framework.TestCase.assertEquals;
public class SynchronizedHashMapWithRWLockManualTest {
@Test
public void whenWriting_ThenNoReading() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 3;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
@Test
public void whenWriting_ThenNoReading() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 3;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeWriterThreads(object, threadCount, service);
executeWriterThreads(object, threadCount, service);
assertEquals(object.isReadLockAvailable(), false);
assertEquals(object.isReadLockAvailable(), false);
service.shutdown();
}
service.shutdown();
}
@Test
public void whenReading_ThenMultipleReadingAllowed() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 5;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
@Test
public void whenReading_ThenMultipleReadingAllowed() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 5;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeReaderThreads(object, threadCount, service);
executeReaderThreads(object, threadCount, service);
assertEquals(object.isReadLockAvailable(), true);
assertEquals(object.isReadLockAvailable(), true);
service.shutdown();
}
service.shutdown();
}
private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(() -> {
try {
object.put("key" + threadCount, "value" + threadCount);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(() -> {
try {
object.put("key" + threadCount, "value" + threadCount);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++)
service.execute(() -> {
object.get("key" + threadCount);
});
}
private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++)
service.execute(() -> {
object.get("key" + threadCount);
});
}
}
@@ -42,7 +42,7 @@ public class PriorityBlockingQueueIntegrationTest {
try {
Integer poll = queue.take();
LOG.debug("Polled: " + poll);
} catch (InterruptedException e) {
} catch (InterruptedException ignored) {
}
}
});
@@ -0,0 +1,114 @@
package com.baeldung.concurrent.semaphores;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SemaphoresManualTest {
// ========= login queue ======
@Test
public void givenLoginQueue_whenReachLimit_thenBlocked() {
final int slots = 10;
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(loginQueue::tryLogin));
executorService.shutdown();
assertEquals(0, loginQueue.availableSlots());
assertFalse(loginQueue.tryLogin());
}
@Test
public void givenLoginQueue_whenLogout_thenSlotsAvailable() {
final int slots = 10;
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(loginQueue::tryLogin));
executorService.shutdown();
assertEquals(0, loginQueue.availableSlots());
loginQueue.logout();
assertTrue(loginQueue.availableSlots() > 0);
assertTrue(loginQueue.tryLogin());
}
// ========= delay queue =======
@Test
public void givenDelayQueue_whenReachLimit_thenBlocked() {
final int slots = 50;
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
final DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(delayQueue::tryAdd));
executorService.shutdown();
assertEquals(0, delayQueue.availableSlots());
assertFalse(delayQueue.tryAdd());
}
@Test
public void givenDelayQueue_whenTimePass_thenSlotsAvailable() throws InterruptedException {
final int slots = 50;
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
final DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(delayQueue::tryAdd));
executorService.shutdown();
assertEquals(0, delayQueue.availableSlots());
Thread.sleep(1000);
assertTrue(delayQueue.availableSlots() > 0);
assertTrue(delayQueue.tryAdd());
}
// ========== mutex ========
@Test
public void whenMutexAndMultipleThreads_thenBlocked() throws InterruptedException {
final int count = 5;
final ExecutorService executorService = Executors.newFixedThreadPool(count);
final CounterUsingMutex counter = new CounterUsingMutex();
IntStream.range(0, count)
.forEach(user -> executorService.execute(() -> {
try {
counter.increase();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}));
executorService.shutdown();
assertTrue(counter.hasQueuedThreads());
}
@Test
public void givenMutexAndMultipleThreads_ThenDelay_thenCorrectCount() throws InterruptedException {
final int count = 5;
final ExecutorService executorService = Executors.newFixedThreadPool(count);
final CounterUsingMutex counter = new CounterUsingMutex();
IntStream.range(0, count)
.forEach(user -> executorService.execute(() -> {
try {
counter.increase();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}));
executorService.shutdown();
assertTrue(counter.hasQueuedThreads());
Thread.sleep(5000);
assertFalse(counter.hasQueuedThreads());
assertEquals(count, counter.getCount());
}
}
@@ -1,13 +1,13 @@
package com.baeldung.concurrent.synchronize;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BaeldungSychronizedBlockTest {
@@ -17,7 +17,7 @@ public class BaeldungSychronizedBlockTest {
BaeldungSynchronizedBlocks synchronizedBlocks = new BaeldungSynchronizedBlocks();
IntStream.range(0, 1000)
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, synchronizedBlocks.getCount());
@@ -28,7 +28,7 @@ public class BaeldungSychronizedBlockTest {
ExecutorService service = Executors.newCachedThreadPool();
IntStream.range(0, 1000)
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
@@ -1,14 +1,14 @@
package com.baeldung.concurrent.synchronize;
import static org.junit.Assert.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BaeldungSynchronizeMethodsTest {
@@ -19,7 +19,7 @@ public class BaeldungSynchronizeMethodsTest {
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
IntStream.range(0, 1000)
.forEach(count -> service.submit(method::calculate));
.forEach(count -> service.submit(method::calculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, method.getSum());
@@ -31,7 +31,7 @@ public class BaeldungSynchronizeMethodsTest {
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
IntStream.range(0, 1000)
.forEach(count -> service.submit(method::synchronisedCalculate));
.forEach(count -> service.submit(method::synchronisedCalculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, method.getSyncSum());
@@ -42,7 +42,7 @@ public class BaeldungSynchronizeMethodsTest {
ExecutorService service = Executors.newCachedThreadPool();
IntStream.range(0, 1000)
.forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
.forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, BaeldungSynchronizedMethods.staticSum);
@@ -7,13 +7,15 @@ import java.time.Month;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class UseLocalDateTimeUnitTest {
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
@Test
public void givenString_whenUsingParse_thenLocalDateTime() {
Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
Assert.assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
}
}
@@ -7,48 +7,50 @@ import java.time.LocalDateTime;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class UseLocalDateUnitTest {
UseLocalDate useLocalDate = new UseLocalDate();
@Test
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
}
@Test
public void givenString_whenUsingParse_thenLocalDate() {
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
}
@Test
public void whenUsingClock_thenLocalDate() {
Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
}
@Test
public void givenDate_whenUsingPlus_thenNextDay() {
Assert.assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
}
@Test
public void givenDate_whenUsingMinus_thenPreviousDay() {
Assert.assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
}
@Test
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() {
Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
}
@Test
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
}
@Test
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() {
Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
}
}
@@ -0,0 +1,67 @@
package com.baeldung.deserialization;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InvalidClassException;
import org.junit.Ignore;
import org.junit.Test;
public class DeserializationUnitTest {
private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
private static long userDefinedSerialVersionUID = 1234567L;
/**
* Tests the deserialization of the original "AppleProduct" (no exceptions are thrown)
* @throws ClassNotFoundException
* @throws IOException
*/
@Test
public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException {
assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
AppleProduct macBook = new AppleProduct();
macBook.headphonePort = "headphonePort2020";
macBook.thunderboltPort = "thunderboltPort2020";
// serializes the "AppleProduct" object
String serializedProduct = SerializationUtility.serializeObjectToString(macBook);
// deserializes the "AppleProduct" object
AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct);
assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort));
assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort));
}
/**
* Tests the deserialization of the modified (non-compatible) "AppleProduct".
* The test should result in an InvalidClassException being thrown.
*
* Note: to run this test:
* 1. Modify the value of the serialVersionUID identifier in AppleProduct.java
* 2. Remove the @Ignore annotation
* 3. Run the test individually (do not run the entire set of tests)
* 4. Revert the changes made in 1 & 2 (so that you're able to re-run the tests successfully)
*
* @throws ClassNotFoundException
* @throws IOException
*/
@Ignore
@Test(expected = InvalidClassException.class)
public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException {
assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
// attempts to deserialize the "AppleProduct" object
DeserializationUtility.deSerializeObjectFromString(serializedObj);
}
}
@@ -83,7 +83,7 @@ public class ComputerUtilsUnitTest {
final TriFunction<Integer, String, Integer, MacbookPro> integerStringIntegerObjectTriFunction = MacbookPro::new;
final MacbookPro macbookPro = integerStringIntegerObjectTriFunction.apply(2010, "black", 100);
Double initialValue = new Double(999.99);
Double initialValue = 999.99;
final Double actualValue = macbookPro.calculateValue(initialValue);
Assert.assertEquals(766.659, actualValue, 0.0);
}
@@ -6,7 +6,12 @@ import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
@@ -14,6 +19,10 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class FileOperationsManualTest {
@Test
@@ -25,7 +34,7 @@ public class FileOperationsManualTest {
InputStream inputStream = new FileInputStream(file);
String data = readFromInputStream(inputStream);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@@ -36,7 +45,7 @@ public class FileOperationsManualTest {
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
String data = readFromInputStream(inputStream);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@@ -47,7 +56,7 @@ public class FileOperationsManualTest {
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
String data = readFromInputStream(inputStream);
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
}
@Test
@@ -61,7 +70,7 @@ public class FileOperationsManualTest {
InputStream inputStream = urlConnection.getInputStream();
String data = readFromInputStream(inputStream);
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
}
@Test
@@ -72,7 +81,7 @@ public class FileOperationsManualTest {
File file = new File(classLoader.getResource("fileTest.txt").getFile());
String data = FileUtils.readFileToString(file);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@@ -84,7 +93,7 @@ public class FileOperationsManualTest {
byte[] fileBytes = Files.readAllBytes(path);
String data = new String(fileBytes);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@@ -98,7 +107,7 @@ public class FileOperationsManualTest {
lines.forEach(line -> data.append(line).append("\n"));
lines.close();
Assert.assertEquals(expectedData, data.toString().trim());
assertEquals(expectedData, data.toString().trim());
}
private String readFromInputStream(InputStream inputStream) throws IOException {
@@ -0,0 +1,41 @@
package com.baeldung.filesystem.jndi.test;
import com.baeldung.filesystem.jndi.LookupFSJNDI;
import org.junit.Test;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.File;
import static org.junit.Assert.assertNotNull;
public class LookupFSJNDIIntegrationTest {
LookupFSJNDI fsjndi;
InitialContext ctx = null;
final String FILENAME = "test.find";
public LookupFSJNDIIntegrationTest() {
try {
fsjndi = new LookupFSJNDI();
} catch (NamingException e) {
fsjndi = null;
}
}
@Test
public void whenInitializationLookupFSJNDIIsNotNull_thenSuccess() {
assertNotNull("Class LookupFSJNDI has instance", fsjndi);
}
@Test
public void givenLookupFSJNDI_whengetInitialContextIsNotNull_thenSuccess() {
ctx = fsjndi.getCtx();
assertNotNull("Context exists", ctx);
}
@Test
public void givenInitialContext_whenLokupFileExists_thenSuccess() {
File file = fsjndi.getFile(FILENAME);
assertNotNull("File exists", file);
}
}
@@ -25,7 +25,7 @@ public class FunctionalInterfaceUnitTest {
@Test
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map<String, Integer> nameMap = new HashMap<>();
Integer value = nameMap.computeIfAbsent("John", s -> s.length());
Integer value = nameMap.computeIfAbsent("John", String::length);
assertEquals(new Integer(4), nameMap.get("John"));
assertEquals(new Integer(4), value);
@@ -2,7 +2,7 @@ package com.baeldung.hashing;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
public class SHA256HashingUnitTest {
@@ -2,7 +2,6 @@ package com.baeldung.http;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
@@ -17,6 +16,9 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class HttpRequestLiveTest {
@Test
@@ -39,7 +41,7 @@ public class HttpRequestLiveTest {
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
@@ -67,7 +69,7 @@ public class HttpRequestLiveTest {
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
@@ -0,0 +1,43 @@
package com.baeldung.java.currentmethod;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* The class presents various ways of finding the name of currently executed method.
*/
public class CurrentlyExecutedMethodFinderTest {
@Test
public void givenCurrentThread_whenGetStackTrace_thenFindMethod() {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
assertEquals("givenCurrentThread_whenGetStackTrace_thenFindMethod", stackTrace[1].getMethodName());
}
@Test
public void givenException_whenGetStackTrace_thenFindMethod() {
String methodName = new Exception().getStackTrace()[0].getMethodName();
assertEquals("givenException_whenGetStackTrace_thenFindMethod", methodName);
}
@Test
public void givenThrowable_whenGetStacktrace_thenFindMethod() {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
assertEquals("givenThrowable_whenGetStacktrace_thenFindMethod", stackTrace[0].getMethodName());
}
@Test
public void givenObject_whenGetEnclosingMethod_thenFindMethod() {
String methodName = new Object() {}.getClass().getEnclosingMethod().getName();
assertEquals("givenObject_whenGetEnclosingMethod_thenFindMethod", methodName);
}
@Test
public void givenLocal_whenGetEnclosingMethod_thenFindMethod() {
class Local {};
String methodName = Local.class.getEnclosingMethod().getName();
assertEquals("givenLocal_whenGetEnclosingMethod_thenFindMethod", methodName);
}
}
@@ -0,0 +1,52 @@
package com.baeldung.java8;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class Java8MapAndFlatMap {
@Test
public void givenStream_whenCalledMap_thenProduceList() {
List<String> myList = Stream.of("a", "b")
.map(String::toUpperCase)
.collect(Collectors.toList());
assertEquals(asList("A", "B"), myList);
}
@Test
public void givenStream_whenCalledFlatMap_thenProduceFlattenedList() throws Exception {
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
System.out.println(list);
System.out.println(list
.stream().flatMap(Collection::stream)
.collect(Collectors.toList()));
}
@Test
public void givenOptional_whenCalledMap_thenProduceOptional() {
Optional<String> s = Optional.of("test");
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
}
@Test
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
assertEquals(Optional.of(Optional.of("STRING")), Optional
.of("string")
.map(s -> Optional.of("STRING")));
assertEquals(Optional.of("STRING"), Optional
.of("string")
.flatMap(s -> Optional.of("STRING")));
}
}
@@ -0,0 +1,106 @@
package com.baeldung.javanetworking.url.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.javanetworking.url.URLDemo;
@FixMethodOrder
public class URLDemoTest {
private final Logger log = LoggerFactory.getLogger(URLDemo.class);
static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
// parsed locator
static String URLPROTOCOL = "https";
String URLAUTHORITY = "wordpress.org:443";
static String URLHOST = "wordpress.org";
static String URLPATH = "/support/topic/page-jumps-within-wordpress/";
String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
int URLPORT = 443;
static int URLDEFAULTPORT = 443;
static String URLQUERY = "replies=3";
static String URLREFERENCE = "post-2278484";
static String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
static URL url;
URLConnection urlConnection = null;
HttpURLConnection connection = null;
BufferedReader in = null;
String urlContent = "";
@BeforeClass
public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws MalformedURLException {
url = new URL(URLCOMPOUND);
}
// check parsed URL
@Test
public void givenURL_whenURLIsParsed_thenSuccess() {
assertNotNull("URL is null", url);
assertEquals("URL string is not equal", url.toString(), URLSTRING);
assertEquals("Protocol is not equal", url.getProtocol(), URLPROTOCOL);
assertEquals("Authority is not equal", url.getAuthority(), URLAUTHORITY);
assertEquals("Host string is not equal", url.getHost(), URLHOST);
assertEquals("Path string is not equal", url.getPath(), URLPATH);
assertEquals("File string is not equal", url.getFile(), URLFILENAME);
assertEquals("Port number is not equal", url.getPort(), URLPORT);
assertEquals("Default port number is not equal", url.getDefaultPort(), URLDEFAULTPORT);
assertEquals("Query string is not equal", url.getQuery(), URLQUERY);
assertEquals("Reference string is not equal", url.getRef(), URLREFERENCE);
}
// Obtain the content from location
@Test
public void givenURL_whenOpenConnectionAndContentIsNotEmpty_thenSuccess() throws IOException {
try {
urlConnection = url.openConnection();
} catch (IOException ex) {
urlConnection = null;
ex.printStackTrace();
}
assertNotNull("URL Connection is null", urlConnection);
connection = null;
assertTrue("URLConnection is not HttpURLConnection", urlConnection instanceof HttpURLConnection);
if (urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
}
assertNotNull("Connection is null", connection);
log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
try {
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException ex) {
in = null;
ex.printStackTrace();
}
assertNotNull("Input stream failed", in);
String current;
try {
while ((current = in.readLine()) != null) {
urlContent += current;
}
} catch (IOException ex) {
urlContent = null;
ex.printStackTrace();
}
assertNotNull("Content is null", urlContent);
assertTrue("Content is empty", urlContent.length() > 0);
}
}
@@ -14,7 +14,7 @@ import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Test;
public class FlattenNestedListUnitTest {
List<List<String>> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
private List<List<String>> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
@Test
public void givenNestedList_thenFlattenImperatively() {
@@ -36,13 +36,13 @@ public class FlattenNestedListUnitTest {
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
}
public <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
private <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
List<T> ls = new ArrayList<>();
list.forEach(ls::addAll);
return ls;
}
public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
private <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream().flatMap(Collection::stream).collect(Collectors.toList());
}
}
@@ -1,18 +1,19 @@
package com.baeldung.list.listoflist;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class ListOfListsUnitTest {
private List<ArrayList<? extends Stationery>> listOfLists = new ArrayList<ArrayList<? extends Stationery>>();
private ArrayList<Pen> penList = new ArrayList<>();
private ArrayList<Pencil> pencilList = new ArrayList<>();
private ArrayList<Rubber> rubberList = new ArrayList<>();
private List<List<? extends Stationery>> listOfLists = new ArrayList<>();
private List<Pen> penList = new ArrayList<>();
private List<Pencil> pencilList = new ArrayList<>();
private List<Rubber> rubberList = new ArrayList<>();
@SuppressWarnings("unchecked")
@Before
@@ -29,11 +30,11 @@ public class ListOfListsUnitTest {
@Test
public void givenListOfLists_thenCheckNames() {
assertEquals("Pen 1", ((Pen) listOfLists.get(0)
.get(0)).getName());
.get(0)).getName());
assertEquals("Pencil 1", ((Pencil) listOfLists.get(1)
.get(0)).getName());
.get(0)).getName());
assertEquals("Rubber 1", ((Rubber) listOfLists.get(2)
.get(0)).getName());
.get(0)).getName());
}
@SuppressWarnings("unchecked")
@@ -43,10 +44,10 @@ public class ListOfListsUnitTest {
((ArrayList<Pencil>) listOfLists.get(1)).remove(0);
listOfLists.remove(1);
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1)
.get(0)).getName());
.get(0)).getName());
listOfLists.remove(0);
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0)
.get(0)).getName());
.get(0)).getName());
}
@Test
@@ -60,17 +61,17 @@ public class ListOfListsUnitTest {
ArrayList<Rubber> rubbers = new ArrayList<>();
rubbers.add(new Rubber("Rubber 1"));
rubbers.add(new Rubber("Rubber 2"));
List<ArrayList<? extends Stationery>> list = new ArrayList<ArrayList<? extends Stationery>>();
list.add(pens);
list.add(pencils);
list.add(rubbers);
assertEquals("Pen 1", ((Pen) list.get(0)
.get(0)).getName());
.get(0)).getName());
assertEquals("Pencil 1", ((Pencil) list.get(1)
.get(0)).getName());
.get(0)).getName());
assertEquals("Rubber 1", ((Rubber) list.get(2)
.get(0)).getName());
.get(0)).getName());
}
}
@@ -47,7 +47,7 @@ public class MappedByteBufferUnitTest {
//when
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite,
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
if (mappedByteBuffer != null) {
@@ -61,7 +61,7 @@ public class MappedByteBufferUnitTest {
}
public Path getFileURIFromResources(String fileName) throws Exception {
private Path getFileURIFromResources(String fileName) throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
return Paths.get(classLoader.getResource(fileName).getPath());
}
@@ -0,0 +1,25 @@
package com.baeldung.maths;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalImplTest {
@Test
public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
BigDecimal serviceTax = new BigDecimal("56.0084578639");
serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
BigDecimal entertainmentTax = new BigDecimal("23.00689");
entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
BigDecimal totalTax = serviceTax.add(entertainmentTax);
BigDecimal result = BigDecimal.valueOf(79.01);
Assert.assertEquals(result, totalTax);
}
}
@@ -0,0 +1,21 @@
package com.baeldung.maths;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigInteger;
public class BigIntegerImplTest {
@Test
public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() {
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
BigInteger result = new BigInteger("14110718640342675608722521633212952");
Assert.assertEquals(result, totalStars);
}
}
@@ -5,6 +5,9 @@ import org.decimal4j.util.DoubleRounder;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class RoundTest {
private double value = 2.03456d;
private int places = 2;
@@ -3,13 +3,13 @@ package com.baeldung.money;
import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.format.CurrencyStyle;
import org.junit.Ignore;
import org.junit.Test;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.UnknownCurrencyException;
import javax.money.convert.ConversionQueryBuilder;
import javax.money.convert.CurrencyConversion;
import javax.money.convert.MonetaryConversions;
import javax.money.format.AmountFormatQueryBuilder;
@@ -19,7 +19,11 @@ import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class JavaMoneyUnitTest {
@@ -36,17 +40,16 @@ public class JavaMoneyUnitTest {
@Test(expected = UnknownCurrencyException.class)
public void givenCurrencyCode_whenNoExist_thanThrowsError() {
Monetary.getCurrency("AAA");
fail(); // if no exception
}
@Test
public void givenAmounts_whenStringified_thanEquals() {
CurrencyUnit usd = Monetary.getCurrency("USD");
MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200)
.create();
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200)
.create();
Money moneyof = Money.of(12, usd);
FastMoney fastmoneyof = FastMoney.of(2, usd);
@@ -59,10 +62,10 @@ public class JavaMoneyUnitTest {
@Test
public void givenCurrencies_whenCompared_thanNotequal() {
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
Money oneEuro = Money.of(1, "EUR");
assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
@@ -72,10 +75,10 @@ public class JavaMoneyUnitTest {
@Test(expected = ArithmeticException.class)
public void givenAmount_whenDivided_thanThrowsException() {
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
oneDolar.divide(3);
fail(); // if no exception
}
@@ -85,8 +88,8 @@ public class JavaMoneyUnitTest {
List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
Money sumAmtCHF = (Money) monetaryAmounts
.stream()
.reduce(Money.of(0, "CHF"), MonetaryAmount::add);
.stream()
.reduce(Money.of(0, "CHF"), MonetaryAmount::add);
assertEquals("CHF 111.35", sumAmtCHF.toString());
}
@@ -97,18 +100,18 @@ public class JavaMoneyUnitTest {
Money moneyof = Money.of(12, usd);
MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200.50)
.create();
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200.50)
.create();
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
Money subtractedAmount = Money
.of(1, "USD")
.subtract(fstAmtUSD);
.of(1, "USD")
.subtract(fstAmtUSD);
MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
MonetaryAmount divideAmount = oneDolar.divide(0.25);
@@ -124,22 +127,23 @@ public class JavaMoneyUnitTest {
@Test
public void givenAmount_whenRounded_thanEquals() {
MonetaryAmount fstAmtEUR = Monetary
.getDefaultAmountFactory()
.setCurrency("EUR")
.setNumber(1.30473908)
.create();
.getDefaultAmountFactory()
.setCurrency("EUR")
.setNumber(1.30473908)
.create();
MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
assertEquals("EUR 1.30473908", fstAmtEUR.toString());
assertEquals("EUR 1.3", roundEUR.toString());
}
@Test
@Ignore("Currency providers are not always available")
public void givenAmount_whenConversion_thenNotNull() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
@@ -152,10 +156,10 @@ public class JavaMoneyUnitTest {
@Test
public void givenLocale_whenFormatted_thanEquals() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
String usFormatted = formatUSD.format(oneDollar);
@@ -167,16 +171,16 @@ public class JavaMoneyUnitTest {
@Test
public void givenAmount_whenCustomFormat_thanEquals() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
.of(Locale.US)
.set(CurrencyStyle.NAME)
.set("pattern", "00000.00 ¤")
.build());
.of(Locale.US)
.set(CurrencyStyle.NAME)
.set("pattern", "00000.00 ¤")
.build());
String customFormatted = customFormat.format(oneDollar);
assertNotNull(customFormat);
@@ -9,4 +9,4 @@ public class NoClassDefFoundErrorTest {
NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample();
sample.getClassWithInitErrors();
}
}
}
@@ -0,0 +1,24 @@
package com.baeldung.reflection;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertTrue;
public class BaeldungReflectionUtilsTest {
@Test
public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception {
Customer customer = new Customer(1, "Himanshu", null, null);
List<String> result = BaeldungReflectionUtils.getNullPropertiesList(customer);
List<String> expectedFieldNames = Arrays.asList("emailId", "phoneNumber");
assertTrue(result.size() == expectedFieldNames.size());
assertTrue(result.containsAll(expectedFieldNames));
}
}
@@ -1,71 +1,73 @@
package com.baeldung.regexp;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
public class EscapingCharsTest {
@Test
public void givenRegexWithDot_whenMatchingStr_thenMatches() {
String strInput = "foof";
String strRegex = "foo.";
assertEquals(true, strInput.matches(strRegex));
}
@Test
public void givenRegexWithDotEsc_whenMatchingStr_thenNotMatching() {
String strInput = "foof";
String strRegex = "foo\\.";
assertEquals(false, strInput.matches(strRegex));
}
@Test
public void givenRegexWithPipeEscaped_whenSplitStr_thenSplits() {
String strInput = "foo|bar|hello|world";
String strRegex = "\\Q|\\E";
assertEquals(4, strInput.split(strRegex).length);
}
@Test
public void givenRegexWithPipeEscQuoteMeth_whenSplitStr_thenSplits() {
String strInput = "foo|bar|hello|world";
String strRegex = "|";
assertEquals(4,strInput.split(Pattern.quote(strRegex)).length);
assertEquals(4, strInput.split(Pattern.quote(strRegex)).length);
}
@Test
public void givenRegexWithDollar_whenReplacing_thenNotReplace() {
String strInput = "I gave $50 to my brother."
+ "He bought candy for $35. Now he has $15 left.";
+ "He bought candy for $35. Now he has $15 left.";
String strRegex = "$";
String strReplacement = "£";
String output = "I gave £50 to my brother."
+ "He bought candy for £35. Now he has £15 left.";
+ "He bought candy for £35. Now he has £15 left.";
Pattern p = Pattern.compile(strRegex);
Matcher m = p.matcher(strInput);
assertThat(output, not(equalTo(m.replaceAll(strReplacement))));
}
@Test
public void givenRegexWithDollarEsc_whenReplacing_thenReplace() {
String strInput = "I gave $50 to my brother."
+ "He bought candy for $35. Now he has $15 left.";
+ "He bought candy for $35. Now he has $15 left.";
String strRegex = "\\$";
String strReplacement = "£";
String output = "I gave £50 to my brother."
+ "He bought candy for £35. Now he has £15 left.";
+ "He bought candy for £35. Now he has £15 left.";
Pattern p = Pattern.compile(strRegex);
Matcher m = p.matcher(strInput);
assertEquals(output,m.replaceAll(strReplacement));
assertEquals(output, m.replaceAll(strReplacement));
}
}
@@ -4,7 +4,11 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import javax.script.*;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

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