geroza
2018-11-09 16:18:03 -02:00
parent 8e6fff4fc8
commit 792d6f6cc4
84 changed files with 583 additions and 289 deletions

25
core-java-lang/.gitignore vendored Normal file
View File

@@ -0,0 +1,25 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

547
core-java-lang/pom.xml Normal file
View File

@@ -0,0 +1,547 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-lang</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-lang</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<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.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</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>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>${javamoney.moneta.version}</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>${esapi.version}</version>
</dependency>
<dependency>
<groupId>com.sun.messaging.mq</groupId>
<artifactId>fscontext</artifactId>
<version>${fscontext.version}</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.spring-web.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${javax.mail.version}</version>
</dependency>
<!-- Mime Type Resolution Libraries -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>${tika.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jmimemagic</groupId>
<artifactId>jmimemagic</artifactId>
<version>${jmime-magic.version}</version>
</dependency>
<!-- instrumentation -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javaassist.version}</version>
</dependency>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.8.0</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
</dependencies>
<build>
<finalName>core-java-lang</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.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-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-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<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-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-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<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>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<version>${onejar-maven-plugin.version}</version>
<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.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<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>
<include>**/*IntTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- java instrumentation profiles to build jars -->
<profile>
<id>buildAgentLoader</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>agentLoader</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/application/AgentLoader.class</include>
<include>com/baeldung/instrumentation/application/Launcher.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>buildApplication</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>application</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/application/MyAtm.class</include>
<include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
<include>com/baeldung/instrumentation/application/Launcher.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>buildAgent</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>agent</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<gson.version>2.8.2</gson.version>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-io.version>2.5</commons-io.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<lombok.version>1.16.12</lombok.version>
<fscontext.version>4.6-b01</fscontext.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
<!-- maven plugins -->
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<h2database.version>1.4.197</h2database.version>
<esapi.version>2.1.0.1</esapi.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<javax.mail.version>1.5.0-b01</javax.mail.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
<icu4j.version>61.1</icu4j.version>
<!-- Mime Type Libraries -->
<tika.version>1.18</tika.version>
<jmime-magic.version>0.1.5</jmime-magic.version>
<!-- instrumentation -->
<javaassist.version>3.21.0-GA</javaassist.version>
</properties>
</project>

View File

@@ -0,0 +1,139 @@
package com.baeldung.breakcontinue;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author Santosh
*
*/
public class BreakContinue {
public static int unlabeledBreak() {
String searchName = "Wilson";
int counter = 0;
List<String> names = Arrays.asList("John", "Peter", "Robert", "Wilson", "Anthony", "Donald", "Richard");
for (String name : names) {
counter++;
if (name.equalsIgnoreCase(searchName)) {
break;
}
}
return counter;
}
public static int unlabeledBreakNestedLoops() {
String searchName = "Wilson";
int counter = 0;
Map<String, List<String>> nameMap = new HashMap<>();
nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson"));
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold"));
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan"));
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
.iterator();
Entry<String, List<String>> entry = null;
List<String> names = null;
while (iterator.hasNext()) {
entry = iterator.next();
names = entry.getValue();
for (String name : names) {
if (name.equalsIgnoreCase(searchName)) {
counter++;
break;
}
}
}
return counter;
}
public static int labeledBreak() {
String searchName = "Wilson";
int counter = 0;
Map<String, List<String>> nameMap = new HashMap<>();
nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson"));
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold"));
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan"));
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
.iterator();
Entry<String, List<String>> entry = null;
List<String> names = null;
compare:
while (iterator.hasNext()) {
entry = iterator.next();
names = entry.getValue();
for (String name : names) {
if (name.equalsIgnoreCase(searchName)) {
counter++;
break compare;
}
}
}
return counter;
}
public static int unlabeledContinue() {
String searchName = "Wilson";
int counter = 0;
Map<String, List<String>> nameMap = new HashMap<>();
nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson"));
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold"));
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan"));
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
.iterator();
Entry<String, List<String>> entry = null;
List<String> names = null;
while (iterator.hasNext()) {
entry = iterator.next();
names = entry.getValue();
for (String name : names) {
if (!name.equalsIgnoreCase(searchName)) {
continue;
}
counter++;
}
}
return counter;
}
public static int labeledContinue() {
String searchName = "Wilson";
int counter = 0;
Map<String, List<String>> nameMap = new HashMap<>();
nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson"));
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold"));
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan"));
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
.iterator();
Entry<String, List<String>> entry = null;
List<String> names = null;
compare:
while (iterator.hasNext()) {
entry = iterator.next();
names = entry.getValue();
for (String name : names) {
if (name.equalsIgnoreCase(searchName)) {
counter++;
continue compare;
}
}
}
return counter;
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.chainedexception;
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
public class LogWithChain {
public static void main(String[] args) throws Exception {
getLeave();
}
private static void getLeave() throws NoLeaveGrantedException {
try {
howIsTeamLead();
} catch (TeamLeadUpsetException e) {
throw new NoLeaveGrantedException("Leave not sanctioned.", e);
}
}
private static void howIsTeamLead() throws TeamLeadUpsetException {
try {
howIsManager();
} catch (ManagerUpsetException e) {
throw new TeamLeadUpsetException("Team lead is not in good mood", e);
}
}
private static void howIsManager() throws ManagerUpsetException {
try {
howIsGirlFriendOfManager();
} catch (GirlFriendOfManagerUpsetException e) {
throw new ManagerUpsetException("Manager is in bad mood", e);
}
}
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.chainedexception;
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
public class LogWithoutChain {
public static void main(String[] args) throws Exception {
getLeave();
}
private static void getLeave() throws NoLeaveGrantedException {
try {
howIsTeamLead();
} catch (TeamLeadUpsetException e) {
e.printStackTrace();
throw new NoLeaveGrantedException("Leave not sanctioned.");
}
}
private static void howIsTeamLead() throws TeamLeadUpsetException {
try {
howIsManager();
} catch (ManagerUpsetException e) {
e.printStackTrace();
throw new TeamLeadUpsetException("Team lead is not in good mood");
}
}
private static void howIsManager() throws ManagerUpsetException {
try {
howIsGirlFriendOfManager();
} catch (GirlFriendOfManagerUpsetException e) {
e.printStackTrace();
throw new ManagerUpsetException("Manager is in bad mood");
}
}
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.chainedexception.exceptions;
public class GirlFriendOfManagerUpsetException extends Exception {
public GirlFriendOfManagerUpsetException(String message, Throwable cause) {
super(message, cause);
}
public GirlFriendOfManagerUpsetException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.chainedexception.exceptions;
public class ManagerUpsetException extends Exception {
public ManagerUpsetException(String message, Throwable cause) {
super(message, cause);
}
public ManagerUpsetException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.chainedexception.exceptions;
public class NoLeaveGrantedException extends Exception {
public NoLeaveGrantedException(String message, Throwable cause) {
super(message, cause);
}
public NoLeaveGrantedException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.chainedexception.exceptions;
public class TeamLeadUpsetException extends Exception {
public TeamLeadUpsetException(String message, Throwable cause) {
super(message, cause);
}
public TeamLeadUpsetException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.comparable;
public class Player implements Comparable<Player> {
private int ranking;
private String name;
private int age;
public Player(int ranking, String name, int age) {
this.ranking = ranking;
this.name = name;
this.age = age;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.name;
}
@Override
public int compareTo(Player otherPlayer) {
return (this.getRanking() - otherPlayer.getRanking());
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.comparable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam);
System.out.println("After Sorting : " + footballTeam);
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.comparator;
public class Player {
private int ranking;
private String name;
private int age;
public Player(int ranking, String name, int age) {
this.ranking = ranking;
this.name = name;
this.age = age;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.name;
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.comparator;
import java.util.Comparator;
public class PlayerAgeComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getAge() - secondPlayer.getAge());
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerAgeSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
//Instance of PlayerAgeComparator
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
Collections.sort(footballTeam, playerComparator);
System.out.println("After Sorting by age : " + footballTeam);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.comparator;
import java.util.Comparator;
public class PlayerRankingComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getRanking() - secondPlayer.getRanking());
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerRankingSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 40);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
//Instance of PlayerRankingComparator
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
Collections.sort(footballTeam, playerComparator);
System.out.println("After Sorting by ranking : " + footballTeam);
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.dynamicproxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicInvocationHandler implements InvocationHandler {
private static Logger LOGGER = LoggerFactory.getLogger(DynamicInvocationHandler.class);
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
LOGGER.info("Invoked method: {}", method.getName());
return 42;
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.dynamicproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TimingDynamicInvocationHandler implements InvocationHandler {
private static Logger LOGGER = LoggerFactory.getLogger(TimingDynamicInvocationHandler.class);
private final Map<String, Method> methods = new HashMap<>();
private Object target;
TimingDynamicInvocationHandler(Object target) {
this.target = target;
for(Method method: target.getClass().getDeclaredMethods()) {
this.methods.put(method.getName(), method);
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long start = System.nanoTime();
Object result = methods.get(method.getName()).invoke(target, args);
long elapsed = System.nanoTime() - start;
LOGGER.info("Executing {} finished in {} ns", method.getName(), elapsed);
return result;
}
}

View File

@@ -0,0 +1,63 @@
package com.baeldung.equalshashcode.entities;
import java.util.List;
import java.util.Set;
public class ComplexClass {
private List<?> genericList;
private Set<Integer> integerSet;
public ComplexClass(List<?> genericArrayList, Set<Integer> integerHashSet) {
super();
this.genericList = genericArrayList;
this.integerSet = integerHashSet;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((genericList == null) ? 0 : genericList.hashCode());
result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ComplexClass))
return false;
ComplexClass other = (ComplexClass) obj;
if (genericList == null) {
if (other.genericList != null)
return false;
} else if (!genericList.equals(other.genericList))
return false;
if (integerSet == null) {
if (other.integerSet != null)
return false;
} else if (!integerSet.equals(other.integerSet))
return false;
return true;
}
protected List<?> getGenericList() {
return genericList;
}
protected void setGenericArrayList(List<?> genericList) {
this.genericList = genericList;
}
protected Set<Integer> getIntegerSet() {
return integerSet;
}
protected void setIntegerSet(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
}

View File

@@ -0,0 +1,54 @@
package com.baeldung.equalshashcode.entities;
public class PrimitiveClass {
private boolean primitiveBoolean;
private int primitiveInt;
public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) {
super();
this.primitiveBoolean = primitiveBoolean;
this.primitiveInt = primitiveInt;
}
protected boolean isPrimitiveBoolean() {
return primitiveBoolean;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (primitiveBoolean ? 1231 : 1237);
result = prime * result + primitiveInt;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrimitiveClass other = (PrimitiveClass) obj;
if (primitiveBoolean != other.primitiveBoolean)
return false;
if (primitiveInt != other.primitiveInt)
return false;
return true;
}
protected void setPrimitiveBoolean(boolean primitiveBoolean) {
this.primitiveBoolean = primitiveBoolean;
}
protected int getPrimitiveInt() {
return primitiveInt;
}
protected void setPrimitiveInt(int primitiveInt) {
this.primitiveInt = primitiveInt;
}
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.equalshashcode.entities;
public class Rectangle extends Shape {
private double width;
private double length;
public Rectangle(double width, double length) {
this.width = width;
this.length = length;
}
@Override
public double area() {
return width * length;
}
@Override
public double perimeter() {
return 2 * (width + length);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(length);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(width);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Rectangle other = (Rectangle) obj;
if (Double.doubleToLongBits(length) != Double.doubleToLongBits(other.length))
return false;
if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width))
return false;
return true;
}
protected double getWidth() {
return width;
}
protected double getLength() {
return length;
}
}

View File

@@ -0,0 +1,7 @@
package com.baeldung.equalshashcode.entities;
public abstract class Shape {
public abstract double area();
public abstract double perimeter();
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.equalshashcode.entities;
import java.awt.*;
public class Square extends Rectangle {
private Color color;
public Square(double width, Color color) {
super(width, width);
this.color = color;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((color == null) ? 0 : color.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof Square)) {
return false;
}
Square other = (Square) obj;
if (color == null) {
if (other.color != null) {
return false;
}
} else if (!color.equals(other.color)) {
return false;
}
return true;
}
protected Color getColor() {
return color;
}
protected void setColor(Color color) {
this.color = color;
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.generics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Building {
private static final Logger LOGGER = LoggerFactory.getLogger(Building.class);
public void paint() {
LOGGER.info("Painting Building");
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.generics;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Generics {
// definition of a generic method
public static <T> List<T> fromArrayToList(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
// definition of a generic method
public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) {
return Arrays.stream(a).map(mapperFunction).collect(Collectors.toList());
}
// example of a generic method that has Number as an upper bound for T
public static <T extends Number> List<T> fromArrayToListWithUpperBound(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
// example of a generic method with a wild card, this method can be used
// with a list of any subtype of Building
public static void paintAllBuildings(List<? extends Building> buildings) {
buildings.forEach(Building::paint);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.generics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class House extends Building {
private static final Logger LOGGER = LoggerFactory.getLogger(House.class);
public void paint() {
LOGGER.info("Painting House");
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.hashcode.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class User {
private final Logger logger = LoggerFactory.getLogger(User.class);
private long id;
private String name;
private String email;
public User(long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null)
return false;
if (this.getClass() != o.getClass())
return false;
User user = (User) o;
return id == user.id && (name.equals(user.name) && email.equals(user.email));
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (int) id;
hash = 31 * hash + (name == null ? 0 : name.hashCode());
hash = 31 * hash + (email == null ? 0 : email.hashCode());
logger.info("hashCode() method called - Computed hash: " + hash);
return hash;
}
// getters and setters here
}

View File

@@ -0,0 +1,53 @@
package com.baeldung.initializationguide;
import java.io.Serializable;
public class User implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
static String forum;
private String name;
private int id;
{
id = 0;
System.out.println("Instance Initializer");
}
static {
forum = "Java";
System.out.println("Static Initializer");
}
public User(String name, int id) {
super();
this.name = name;
this.id = id;
}
public User() {
System.out.println("Constructor");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return this;
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.java.reflection;
public abstract class Animal implements Eating {
public static final String CATEGORY = "domestic";
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
protected abstract String getSound();
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.java.reflection;
public class Bird extends Animal {
private boolean walks;
public Bird() {
super("bird");
}
public Bird(String name, boolean walks) {
super(name);
setWalks(walks);
}
public Bird(String name) {
super(name);
}
@Override
public String eats() {
return "grains";
}
@Override
protected String getSound() {
return "chaps";
}
public boolean walks() {
return walks;
}
public void setWalks(boolean walks) {
this.walks = walks;
}
}

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

View File

@@ -0,0 +1,5 @@
package com.baeldung.java.reflection;
public interface Eating {
String eats();
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.java.reflection;
public class Goat extends Animal implements Locomotion {
public Goat(String name) {
super(name);
}
@Override
protected String getSound() {
return "bleat";
}
@Override
public String getLocomotion() {
return "walks";
}
@Override
public String eats() {
return "grass";
}
}

View File

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

View File

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

View File

@@ -0,0 +1,6 @@
package com.baeldung.java.reflection;
@Greeter(greet="Good morning")
public class Greetings {
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.java.reflection;
public interface Locomotion {
String getLocomotion();
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.java.reflection;
public class Operations {
public double publicSum(int a, double b) {
return a + b;
}
public static double publicStaticMultiply(float a, long b) {
return a * b;
}
private boolean privateAnd(boolean a, boolean b) {
return a && b;
}
protected int protectedMax(int a, int b) {
return a > b ? a : b;
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.java.reflection;
public class Person {
private String name;
private int age;
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.loops;
public class InfiniteLoops {
public void infiniteLoopUsingWhile() {
while (true) {
System.out.println("Infinite loop using while");
}
}
public void infiniteLoopUsingFor() {
for (;;) {
System.out.println("Infinite loop using for");
}
}
public void infiniteLoopUsingDoWhile() {
do {
System.out.println("Infinite loop using do-while");
} while (true);
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.loops;
public class LoopsInJava {
public int[] simple_for_loop() {
int[] arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = i;
System.out.println("Simple for loop: i - " + i);
}
return arr;
}
public int[] enhanced_for_each_loop() {
int[] intArr = { 0, 1, 2, 3, 4 };
int[] arr = new int[5];
for (int num : intArr) {
arr[num] = num;
System.out.println("Enhanced for-each loop: i - " + num);
}
return arr;
}
public int[] while_loop() {
int i = 0;
int[] arr = new int[5];
while (i < 5) {
arr[i] = i;
System.out.println("While loop: i - " + i++);
}
return arr;
}
public int[] do_while_loop() {
int i = 0;
int[] arr = new int[5];
do {
arr[i] = i;
System.out.println("Do-While loop: i - " + i++);
} while (i < 5);
return arr;
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.staticdemo;
/**
* This class demonstrates the use of static fields and static methods
* the instance variables engine and displacement are distinct for
* each and every object whereas static/class variable numberOfCars
* is unique and is shared across all objects of this class.
*
* @author baeldung
*
*/
public class Car {
private String name;
private String engine;
public static int numberOfCars;
public Car(String name, String engine) {
this.name = name;
this.engine = engine;
numberOfCars++;
}
//getters and setters
public static int getNumberOfCars() {
return numberOfCars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEngine() {
return engine;
}
public void setEngine(String engine) {
this.engine = engine;
}
public static void setNumberOfCars(int numberOfCars) {
Car.numberOfCars = numberOfCars;
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.staticdemo;
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.staticdemo;
import java.util.LinkedList;
import java.util.List;
public class StaticBlock {
private static List<String> ranks = new LinkedList<>();
static {
ranks.add("Lieutenant");
ranks.add("Captain");
ranks.add("Major");
}
static {
ranks.add("Colonel");
ranks.add("General");
}
//getters and setters
public static List<String> getRanks() {
return ranks;
}
public static void setRanks(List<String> ranks) {
StaticBlock.ranks = ranks;
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.breakcontinue;
import static com.baeldung.breakcontinue.BreakContinue.labeledBreak;
import static com.baeldung.breakcontinue.BreakContinue.labeledContinue;
import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreak;
import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreakNestedLoops;
import static com.baeldung.breakcontinue.BreakContinue.unlabeledContinue;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class BreakContinueUnitTest {
@Test
public void whenUnlabeledBreak_ThenEqual() {
assertEquals(4, unlabeledBreak());
}
@Test
public void whenUnlabeledBreakNestedLoops_ThenEqual() {
assertEquals(2, unlabeledBreakNestedLoops());
}
@Test
public void whenLabeledBreak_ThenEqual() {
assertEquals(1, labeledBreak());
}
@Test
public void whenUnlabeledContinue_ThenEqual() {
assertEquals(5, unlabeledContinue());
}
@Test
public void whenLabeledContinue_ThenEqual() {
assertEquals(3, labeledContinue());
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.comparable;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
public class ComparableUnitTest {
@Test
public void whenUsingComparable_thenSortedList() {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
Collections.sort(footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
}

View File

@@ -0,0 +1,47 @@
package com.baeldung.comparator;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class ComparatorUnitTest {
List<Player> footballTeam;
@Before
public void setUp() {
footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
}
@Test
public void whenUsingRankingComparator_thenSortedList() {
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
Collections.sort(footballTeam, playerComparator);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
@Test
public void whenUsingAgeComparator_thenSortedList() {
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
Collections.sort(footballTeam, playerComparator);
assertEquals(footballTeam.get(0)
.getName(), "John");
assertEquals(footballTeam.get(2)
.getRanking(), 45);
}
}

View File

@@ -0,0 +1,68 @@
package com.baeldung.comparator;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class Java8ComparatorUnitTest {
List<Player> footballTeam;
@Before
public void setUp() {
footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
}
@Test
public void whenComparing_UsingLambda_thenSorted() {
System.out.println("************** Java 8 Comaparator **************");
Comparator<Player> byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking();
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
@Test
public void whenComparing_UsingComparatorComparing_thenSorted() {
System.out.println("********* Comaparator.comparing method *********");
System.out.println("********* byRanking *********");
Comparator<Player> byRanking = Comparator.comparing(Player::getRanking);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
System.out.println("********* byAge *********");
Comparator<Player> byAge = Comparator.comparing(Player::getAge);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byAge);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Roger");
assertEquals(footballTeam.get(2)
.getRanking(), 45);
}
}

View File

@@ -0,0 +1,57 @@
package com.baeldung.dynamicproxy;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class DynamicProxyIntegrationTest {
@Test
public void givenDynamicProxy_thenPutWorks() {
Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyIntegrationTest.class.getClassLoader(), new Class[] { Map.class }, new DynamicInvocationHandler());
proxyInstance.put("hello", "world");
}
@Test
public void givenInlineDynamicProxy_thenGetWorksOtherMethodsDoNot() {
Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyIntegrationTest.class.getClassLoader(), new Class[] { Map.class }, (proxy, method, methodArgs) -> {
if (method.getName().equals("get")) {
return 42;
} else {
throw new UnsupportedOperationException("Unsupported method: " + method.getName());
}
});
int result = (int) proxyInstance.get("hello");
assertEquals(42, result);
try {
proxyInstance.put("hello", "world");
fail();
} catch(UnsupportedOperationException e) {
// expected
}
}
@Test
public void givenTimingDynamicProxy_thenMethodInvokationsProduceTiming() {
Map mapProxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyIntegrationTest.class.getClassLoader(), new Class[] { Map.class }, new TimingDynamicInvocationHandler(new HashMap<>()));
mapProxyInstance.put("hello", "world");
assertEquals("world", mapProxyInstance.get("hello"));
CharSequence csProxyInstance = (CharSequence) Proxy.newProxyInstance(DynamicProxyIntegrationTest.class.getClassLoader(), new Class[] { CharSequence.class }, new TimingDynamicInvocationHandler("Hello World"));
assertEquals('l', csProxyInstance.charAt(2));
assertEquals(11, csProxyInstance.length());
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.equalshashcode.entities;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.equalshashcode.entities.ComplexClass;
public class ComplexClassUnitTest {
@Test
public void testEqualsAndHashcodes() {
List<String> strArrayList = new ArrayList<String>();
strArrayList.add("abc");
strArrayList.add("def");
ComplexClass aObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
ComplexClass bObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
List<String> strArrayListD = new ArrayList<String>();
strArrayListD.add("lmn");
strArrayListD.add("pqr");
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67));
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.equalshashcode.entities;
import org.junit.Assert;
import org.junit.Test;
public class PrimitiveClassUnitTest {
@Test
public void testTwoEqualsObjects() {
PrimitiveClass aObject = new PrimitiveClass(false, 2);
PrimitiveClass bObject = new PrimitiveClass(false, 2);
PrimitiveClass dObject = new PrimitiveClass(true, 2);
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.equalshashcode.entities;
import java.awt.Color;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.equalshashcode.entities.Square;
public class SquareClassUnitTest {
@Test
public void testEqualsAndHashcodes() {
Square aObject = new Square(10, Color.BLUE);
Square bObject = new Square(10, Color.BLUE);
Square dObject = new Square(20, Color.BLUE);
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}
}

View File

@@ -0,0 +1,69 @@
package com.baeldung.generics;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
public class GenericsUnitTest {
// testing the generic method with Integer
@Test
public void givenArrayOfIntegers_thanListOfIntegersReturnedOK() {
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<Integer> list = Generics.fromArrayToList(intArray);
assertThat(list, hasItems(intArray));
}
// testing the generic method with Integer and String type
@Test
public void givenArrayOfIntegers_thanListOfStringReturnedOK() {
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<String> stringList = Generics.fromArrayToList(intArray, Object::toString);
assertThat(stringList, hasItems("1", "2", "3", "4", "5"));
}
// testing the generic method with String
@Test
public void givenArrayOfStrings_thanListOfStringsReturnedOK() {
String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" };
List<String> list = Generics.fromArrayToList(stringArray);
assertThat(list, hasItems(stringArray));
}
// testing the generic method with Number as upper bound with Integer
// if we test fromArrayToListWithUpperBound with any type that doesn't
// extend Number it will fail to compile
@Test
public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() {
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<Integer> list = Generics.fromArrayToListWithUpperBound(intArray);
assertThat(list, hasItems(intArray));
}
// testing paintAllBuildings method with a subtype of Building, the method
// will work with all subtypes of Building
@Test
public void givenSubTypeOfWildCardBoundedGenericType_thanPaintingOK() {
try {
List<Building> subBuildingsList = new ArrayList<>();
subBuildingsList.add(new Building());
subBuildingsList.add(new House());
// prints
// Painting Building
// Painting House
Generics.paintAllBuildings(subBuildingsList);
} catch (Exception e) {
fail();
}
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.hashcode.application;
import com.baeldung.hashcode.entities.User;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertTrue;
public class ApplicationUnitTest {
@Test
public void main_NoInputState_TextPrintedToConsole() throws Exception {
Map<User, User> users = new HashMap<>();
User user1 = new User(1L, "John", "john@domain.com");
User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
User user3 = new User(3L, "Mary", "mary@domain.com");
users.put(user1, user1);
users.put(user2, user2);
users.put(user3, user3);
assertTrue(users.containsKey(user1));
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.hashcode.entities;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class UserUnitTest {
private User user;
private User comparisonUser;
@Before
public void setUpUserInstances() {
this.user = new User(1L, "test", "test@domain.com");
this.comparisonUser = this.user;
}
@After
public void tearDownUserInstances() {
user = null;
comparisonUser = null;
}
@Test
public void equals_EqualUserInstance_TrueAssertion() {
Assert.assertTrue(user.equals(comparisonUser));
}
@Test
public void hashCode_UserHash_TrueAssertion() {
Assert.assertEquals(1792276941, user.hashCode());
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.initializationguide;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import java.lang.reflect.InvocationTargetException;
public class UserUnitTest {
@Test
public void givenUserInstance_whenIntializedWithNew_thenInstanceIsNotNull() {
User user = new User("Alice", 1);
assertThat(user).isNotNull();
}
@Test
public void givenUserInstance_whenInitializedWithReflection_thenInstanceIsNotNull() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
User user = User.class.getConstructor(String.class, int.class)
.newInstance("Alice", 2);
assertThat(user).isNotNull();
}
@Test
public void givenUserInstance_whenCopiedWithClone_thenExactMatchIsCreated() throws CloneNotSupportedException {
User user = new User("Alice", 3);
User clonedUser = (User) user.clone();
assertThat(clonedUser).isEqualTo(user);
}
@Test
public void givenUserInstance_whenValuesAreNotInitialized_thenUserNameAndIdReturnDefault() {
User user = new User();
assertThat(user.getName()).isNull();
assertThat(user.getId() == 0);
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.java.diamond;
public class Car<T extends Engine> implements Vehicle<T> {
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.java.diamond;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class DiamondOperatorUnitTest {
@Test
public void whenCreateCarUsingDiamondOperator_thenSuccess() {
Car<Diesel> myCar = new Car<>();
assertNotNull(myCar);
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.java.diamond;
public class Diesel implements Engine {
@Override
public void start() {
System.out.println("Started Diesel...");
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.java.diamond;
public interface Engine {
void start();
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.java.diamond;
public interface Vehicle<T extends Engine> {
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.java.doublebrace;
import org.junit.Test;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.assertTrue;
public class DoubleBraceUnitTest {
@Test
public void whenInitializeSetWithoutDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<>();
countries.add("India");
countries.add("USSR");
countries.add("USA");
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeSetWithDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<String>() {
{
add("India");
add("USSR");
add("USA");
}
};
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeUnmodifiableSetWithDoubleBrace_containsElements() {
Set<String> countries = Stream.of("India", "USSR", "USA")
.collect(collectingAndThen(toSet(), Collections::unmodifiableSet));
assertTrue(countries.contains("India"));
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.java.enumiteration;
import java.util.stream.Stream;
public enum DaysOfWeekEnum {
SUNDAY("off"),
MONDAY("working"),
TUESDAY("working"),
WEDNESDAY("working"),
THURSDAY("working"),
FRIDAY("working"),
SATURDAY("off");
private String typeOfDay;
DaysOfWeekEnum(String typeOfDay) {
this.typeOfDay = typeOfDay;
}
public String getTypeOfDay() {
return typeOfDay;
}
public void setTypeOfDay(String typeOfDay) {
this.typeOfDay = typeOfDay;
}
public static Stream<DaysOfWeekEnum> stream() {
return Stream.of(DaysOfWeekEnum.values());
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.java.enumiteration;
import java.util.EnumSet;
public class EnumIterationExamples {
public static void main(String[] args) {
System.out.println("Enum iteration using forEach:");
EnumSet.allOf(DaysOfWeekEnum.class).forEach(day -> System.out.println(day));
System.out.println("Enum iteration using Stream:");
DaysOfWeekEnum.stream().filter(d -> d.getTypeOfDay().equals("off")).forEach(System.out::println);
System.out.println("Enum iteration using for loop:");
for (DaysOfWeekEnum day : DaysOfWeekEnum.values()) {
System.out.println(day);
}
}
}

View File

@@ -0,0 +1,57 @@
package com.baeldung.java.reflection;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
public class OperationsUnitTest {
public OperationsUnitTest() {
}
@Test(expected = IllegalAccessException.class)
public void givenObject_whenInvokePrivateMethod_thenFail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method andPrivateMethod = Operations.class.getDeclaredMethod("privateAnd", boolean.class, boolean.class);
Operations operationsInstance = new Operations();
Boolean result = (Boolean) andPrivateMethod.invoke(operationsInstance, true, false);
assertFalse(result);
}
@Test
public void givenObject_whenInvokePrivateMethod_thenCorrect() throws Exception {
Method andPrivatedMethod = Operations.class.getDeclaredMethod("privateAnd", boolean.class, boolean.class);
andPrivatedMethod.setAccessible(true);
Operations operationsInstance = new Operations();
Boolean result = (Boolean) andPrivatedMethod.invoke(operationsInstance, true, false);
assertFalse(result);
}
@Test
public void givenObject_whenInvokePublicMethod_thenCorrect() throws Exception {
Method sumInstanceMethod = Operations.class.getMethod("publicSum", int.class, double.class);
Operations operationsInstance = new Operations();
Double result = (Double) sumInstanceMethod.invoke(operationsInstance, 1, 3);
assertThat(result, equalTo(4.0));
}
@Test
public void givenObject_whenInvokeStaticMethod_thenCorrect() throws Exception {
Method multiplyStaticMethod = Operations.class.getDeclaredMethod("publicStaticMultiply", float.class, long.class);
Double result = (Double) multiplyStaticMethod.invoke(null, 3.5f, 2);
assertThat(result, equalTo(7.0));
}
}

View File

@@ -0,0 +1,302 @@
package com.baeldung.java.reflection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class ReflectionUnitTest {
@Test
public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
final Object person = new Person();
final Field[] fields = person.getClass().getDeclaredFields();
final List<String> actualFieldNames = getFieldNames(fields);
assertTrue(Arrays.asList("name", "age").containsAll(actualFieldNames));
}
@Test
public void givenObject_whenGetsClassName_thenCorrect() {
final Object goat = new Goat("goat");
final Class<?> clazz = goat.getClass();
assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
}
@Test
public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException {
final Class<?> clazz = Class.forName("com.baeldung.java.reflection.Goat");
assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
}
@Test
public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final int goatMods = goatClass.getModifiers();
final int animalMods = animalClass.getModifiers();
assertTrue(Modifier.isPublic(goatMods));
assertTrue(Modifier.isAbstract(animalMods));
assertTrue(Modifier.isPublic(animalMods));
}
@Test
public void givenClass_whenGetsPackageInfo_thenCorrect() {
final Goat goat = new Goat("goat");
final Class<?> goatClass = goat.getClass();
final Package pkg = goatClass.getPackage();
assertEquals("com.baeldung.java.reflection", pkg.getName());
}
@Test
public void givenClass_whenGetsSuperClass_thenCorrect() {
final Goat goat = new Goat("goat");
final String str = "any string";
final Class<?> goatClass = goat.getClass();
final Class<?> goatSuperClass = goatClass.getSuperclass();
assertEquals("Animal", goatSuperClass.getSimpleName());
assertEquals("Object", str.getClass().getSuperclass().getSimpleName());
}
@Test
public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Class<?>[] goatInterfaces = goatClass.getInterfaces();
final Class<?>[] animalInterfaces = animalClass.getInterfaces();
assertEquals(1, goatInterfaces.length);
assertEquals(1, animalInterfaces.length);
assertEquals("Locomotion", goatInterfaces[0].getSimpleName());
assertEquals("Eating", animalInterfaces[0].getSimpleName());
}
@Test
public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Constructor<?>[] constructors = goatClass.getConstructors();
assertEquals(1, constructors.length);
assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName());
}
@Test
public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException {
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Field[] fields = animalClass.getDeclaredFields();
final List<String> actualFields = getFieldNames(fields);
assertEquals(2, actualFields.size());
assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY")));
}
@Test
public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Method[] methods = animalClass.getDeclaredMethods();
final List<String> actualMethods = getMethodNames(methods);
assertEquals(3, actualMethods.size());
assertTrue(actualMethods.containsAll(Arrays.asList("getName", "setName", "getSound")));
}
@Test
public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Constructor<?>[] constructors = birdClass.getConstructors();
assertEquals(3, constructors.length);
}
@Test
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
birdClass.getConstructor();
birdClass.getConstructor(String.class);
birdClass.getConstructor(String.class, boolean.class);
}
@Test
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Constructor<?> cons1 = birdClass.getConstructor();
final Constructor<?> cons2 = birdClass.getConstructor(String.class);
final Constructor<?> cons3 = birdClass.getConstructor(String.class, boolean.class);
final Bird bird1 = (Bird) cons1.newInstance();
final Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
final Bird bird3 = (Bird) cons3.newInstance("dove", true);
assertEquals("bird", bird1.getName());
assertEquals("Weaver bird", bird2.getName());
assertEquals("dove", bird3.getName());
assertFalse(bird1.walks());
assertTrue(bird3.walks());
}
@Test
public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field[] fields = birdClass.getFields();
assertEquals(1, fields.length);
assertEquals("CATEGORY", fields[0].getName());
}
@Test
public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field field = birdClass.getField("CATEGORY");
assertEquals("CATEGORY", field.getName());
}
@Test
public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field[] fields = birdClass.getDeclaredFields();
assertEquals(1, fields.length);
assertEquals("walks", fields[0].getName());
}
@Test
public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field field = birdClass.getDeclaredField("walks");
assertEquals("walks", field.getName());
}
@Test
public void givenClassField_whenGetsType_thenCorrect() throws Exception {
final Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks");
final Class<?> fieldClass = field.getType();
assertEquals("boolean", fieldClass.getSimpleName());
}
@Test
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Bird bird = (Bird) birdClass.newInstance();
final Field field = birdClass.getDeclaredField("walks");
field.setAccessible(true);
assertFalse(field.getBoolean(bird));
assertFalse(bird.walks());
field.set(bird, true);
assertTrue(field.getBoolean(bird));
assertTrue(bird.walks());
}
@Test
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field field = birdClass.getField("CATEGORY");
field.setAccessible(true);
assertEquals("domestic", field.get(null));
}
@Test
public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Method[] methods = birdClass.getMethods();
final List<String> methodNames = getMethodNames(methods);
assertTrue(methodNames.containsAll(Arrays.asList("equals", "notifyAll", "hashCode", "walks", "eats", "toString")));
}
@Test
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
final List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
assertEquals(expectedMethodNames.size(), actualMethodNames.size());
assertTrue(expectedMethodNames.containsAll(actualMethodNames));
assertTrue(actualMethodNames.containsAll(expectedMethodNames));
}
@Test
public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Method walksMethod = birdClass.getDeclaredMethod("walks");
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
assertFalse(walksMethod.isAccessible());
assertFalse(setWalksMethod.isAccessible());
walksMethod.setAccessible(true);
setWalksMethod.setAccessible(true);
assertTrue(walksMethod.isAccessible());
assertTrue(setWalksMethod.isAccessible());
}
@Test
public void givenMethod_whenInvokes_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Bird bird = (Bird) birdClass.newInstance();
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
final Method walksMethod = birdClass.getDeclaredMethod("walks");
final boolean walks = (boolean) walksMethod.invoke(bird);
assertFalse(walks);
assertFalse(bird.walks());
setWalksMethod.invoke(bird, true);
final boolean walks2 = (boolean) walksMethod.invoke(bird);
assertTrue(walks2);
assertTrue(bird.walks());
}
private static List<String> getFieldNames(Field[] fields) {
final List<String> fieldNames = new ArrayList<>();
for (final Field field : fields) {
fieldNames.add(field.getName());
}
return fieldNames;
}
private static List<String> getMethodNames(Method[] methods) {
final List<String> methodNames = new ArrayList<>();
for (final Method method : methods) {
methodNames.add(method.getName());
}
return methodNames;
}
}

View File

@@ -0,0 +1,107 @@
package com.baeldung.loops;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class WhenUsingLoops {
private LoopsInJava loops = new LoopsInJava();
private static List<String> list = new ArrayList<>();
private static Set<String> set = new HashSet<>();
private static Map<String, Integer> map = new HashMap<>();
@BeforeClass
public static void setUp() {
list.add("One");
list.add("Two");
list.add("Three");
set.add("Four");
set.add("Five");
set.add("Six");
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
}
@Test
public void shouldRunForLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.simple_for_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunEnhancedForeachLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.enhanced_for_each_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunWhileLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.while_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunDoWhileLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.do_while_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void whenUsingSimpleFor_shouldIterateList() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateList() {
for (String item : list) {
System.out.println(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateSet() {
for (String item : set) {
System.out.println(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateMap() {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue());
}
}
@Test
public void whenUsingSimpleFor_shouldRunLabelledLoop() {
aa: for (int i = 1; i <= 3; i++) {
if (i == 1)
continue;
bb: for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break aa;
}
System.out.println(i + " " + j);
}
}
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.nestedclass;
import org.junit.Test;
abstract class SimpleAbstractClass {
abstract void run();
}
public class AnonymousInner {
@Test
public void run() {
SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() {
void run() {
System.out.println("Running Anonymous Class...");
}
};
simpleAbstractClass.run();
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class Enclosing {
private static int x = 1;
public static class StaticNested {
private void run() {
System.out.println("x = " + x);
}
}
@Test
public void test() {
Enclosing.StaticNested nested = new Enclosing.StaticNested();
nested.run();
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class NewEnclosing {
private void run() {
class Local {
void run() {
System.out.println("Welcome to Baeldung!");
}
}
Local local = new Local();
local.run();
}
@Test
public void test() {
NewEnclosing newEnclosing = new NewEnclosing();
newEnclosing.run();
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class NewOuter {
int a = 1;
static int b = 2;
public class InnerClass {
int a = 3;
static final int b = 4;
public void run() {
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("NewOuter.this.a = " + NewOuter.this.a);
System.out.println("NewOuter.b = " + NewOuter.b);
System.out.println("NewOuter.this.b = " + NewOuter.this.b);
}
}
@Test
public void test() {
NewOuter outer = new NewOuter();
NewOuter.InnerClass inner = outer.new InnerClass();
inner.run();
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class Outer {
public class Inner {
public void run() {
System.out.println("Calling test...");
}
}
@Test
public void test() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.run();
}
}

View File

@@ -0,0 +1,126 @@
package com.baeldung.primitiveconversion;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
public class PrimitiveConversionsJUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(PrimitiveConversionsJUnitTest.class);
@Test
public void givenDataWithLessBits_whenAttributingToLargerSizeVariable_thenNoSpecialNotation() {
int myInt = 127;
long myLong = myInt;
assertEquals(127L, myLong);
float myFloat = myLong;
assertEquals(127.0f, myFloat, 0.00001f);
double myDouble = myLong;
assertEquals(127.0, myDouble,0.00001);
}
@Test
public void givenDataWithMoreBits_whenAttributingToSmallerSizeVariable_thenCastOperatorNeeded() {
long myLong = 127L;
double myDouble = 127.0;
float myFloat = (float) myDouble;
assertEquals(127.0f, myFloat, 0.00001f);
int myInt = (int) myLong;
assertEquals(127, myInt);
byte myByte = (byte) myInt;
assertEquals( ((byte)127), myByte);
}
@Test
public void givenPrimitiveData_whenAssiginingToWrapper_thenAutomaticBoxingHappens(){
int myInt = 127;
Integer myIntegerReference = myInt;
assertEquals(new Integer("127"), myIntegerReference);
}
@Test
public void givenWrapperObjectData_whenAssiginingToPrimitive_thenAutomaticUnboxingHappens(){
Integer myIntegerReference = new Integer("127");
int myOtherInt = myIntegerReference;
assertEquals(127, myOtherInt);
}
@Test
public void givenByteValue_whenConvertingToChar_thenWidenAndNarrowTakesPlace(){
byte myLargeValueByte = (byte) 130; //0b10000010
LOG.debug("{}", myLargeValueByte); //0b10000010 -126
assertEquals( -126, myLargeValueByte);
int myLargeValueInt = myLargeValueByte;
LOG.debug("{}", myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126
assertEquals( -126, myLargeValueInt);
char myLargeValueChar = (char) myLargeValueByte;
LOG.debug("{}", myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82
assertEquals(0xFF82, myLargeValueChar);
myLargeValueInt = myLargeValueChar;
LOG.debug("{}", myLargeValueInt); //0b11111111 10000010 65410
assertEquals(65410, myLargeValueInt);
byte myOtherByte = (byte) myLargeValueInt;
LOG.debug("{}", myOtherByte); //0b10000010 -126
assertEquals( -126, myOtherByte);
char myLargeValueChar2 = 130; //This is an int not a byte!
LOG.debug("{}", myLargeValueChar2);//0b00000000 10000010 unsigned 0x0082
assertEquals(0x0082, myLargeValueChar2);
int myLargeValueInt2 = myLargeValueChar2;
LOG.debug("{}", myLargeValueInt2); //0b00000000 10000010 130
assertEquals(130, myLargeValueInt2);
byte myOtherByte2 = (byte) myLargeValueInt2;
LOG.debug("{}", myOtherByte2); //0b10000010 -126
assertEquals( -126, myOtherByte2);
}
@Test
public void givenString_whenParsingWithWrappers_thenValuesAreReturned(){
String myString = "127";
byte myNewByte = Byte.parseByte(myString);
assertEquals( ((byte)127), myNewByte);
short myNewShort = Short.parseShort(myString);
assertEquals( ((short)127), myNewShort);
int myNewInt = Integer.parseInt(myString);
assertEquals( 127, myNewInt);
long myNewLong = Long.parseLong(myString);
assertEquals( 127L, myNewLong);
float myNewFloat = Float.parseFloat(myString);
assertEquals( 127.0f, myNewFloat, 0.00001f);
double myNewDouble = Double.parseDouble(myString);
assertEquals( 127.0, myNewDouble, 0.00001f);
boolean myNewBoolean = Boolean.parseBoolean(myString);
assertEquals( false, myNewBoolean); //numbers are not true!
char myNewChar = myString.charAt(0);
assertEquals( 49, myNewChar); //the value of '1'
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.staticdemo;
import static org.junit.Assert.*;
import org.junit.Test;
public class CarIntegrationTest {
@Test
public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() {
new Car("Jaguar", "V8");
new Car("Bugatti", "W16");
assertEquals(2, Car.numberOfCars);
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.staticdemo;
import org.junit.Assert;
import org.junit.Test;
public class SingletonIntegrationTest {
@Test
public void givenStaticInnerClass_whenMultipleTimesInstanceCalled_thenOnlyOneTimeInitialized() {
Singleton object1 = Singleton.getInstance();
Singleton object2 = Singleton.getInstance();
Assert.assertSame(object1, object2);
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.staticdemo;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.Test;
public class StaticBlockIntegrationTest {
@Test
public void whenAddedListElementsThroughStaticBlock_thenEnsureCorrectOrder() {
List<String> actualList = StaticBlock.getRanks();
assertThat(actualList, contains("Lieutenant", "Captain", "Major", "Colonel", "General"));
}
}

View File

@@ -0,0 +1,60 @@
package com.baeldung.varargs;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class FormatterUnitTest {
private final static String FORMAT = "%s %s %s";
@Test
public void givenNoArgument_thenEmptyAndTwoSpacesAreReturned() {
String actualResult = format();
assertThat(actualResult, is("empty "));
}
@Test
public void givenOneArgument_thenResultHasTwoTrailingSpace() {
String actualResult = format("baeldung");
assertThat(actualResult, is("baeldung "));
}
@Test
public void givenTwoArguments_thenOneTrailingSpaceExists() {
String actualResult = format("baeldung", "rocks");
assertThat(actualResult, is("baeldung rocks "));
}
@Test
public void givenMoreThanThreeArguments_thenTheFirstThreeAreUsed() {
String actualResult = formatWithVarArgs("baeldung", "rocks", "java", "and", "spring");
assertThat(actualResult, is("baeldung rocks java"));
}
public String format() {
return format("empty", "");
}
public String format(String value) {
return format(value, "");
}
public String format(String val1, String val2) {
return String.format(FORMAT, val1, val2, "");
}
public String formatWithVarArgs(String... values) {
if (values.length == 0) {
return "no arguments given";
}
return String.format(FORMAT, values);
}
}