Merge branch 'master' of https://github.com/eugenp/tutorials into nguyennamthai-master

This commit is contained in:
Zeger Hendrikse 2016-12-19 19:18:14 +01:00
commit f1711af9ce
670 changed files with 197214 additions and 4266 deletions

View File

@ -15,7 +15,7 @@
<properties>
<auto-service.version>1.0-rc2</auto-service.version>
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
<dependencies>

View File

@ -13,6 +13,11 @@
<artifactId>annotation-user</artifactId>
<properties>
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
@ -24,7 +29,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
@ -37,7 +42,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>

2
apache-cxf/README.md Normal file
View File

@ -0,0 +1,2 @@
## Relevant Articles:
- [Introduction to Apache CXF Aegis Data Binding](http://www.baeldung.com/aegis-data-binding-in-apache-cxf)

View File

@ -4,15 +4,18 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>cxf-introduction</artifactId>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<cxf.version>3.1.6</cxf.version>
<cxf.version>3.1.8</cxf.version>
<surefire.version>2.19.1</surefire.version>
</properties>
<build>
<plugins>
<plugin>
@ -24,7 +27,7 @@
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<version>${surefire.version}</version>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
@ -33,6 +36,7 @@
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Apache CXF Support for RESTful Web Services](http://www.baeldung.com/apache-cxf-rest-api)

View File

@ -4,17 +4,20 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>cxf-jaxrs-implementation</artifactId>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<cxf.version>3.1.7</cxf.version>
<cxf.version>3.1.8</cxf.version>
<httpclient.version>4.5.2</httpclient.version>
<surefire.version>2.19.1</surefire.version>
</properties>
<build>
<plugins>
<plugin>
@ -26,7 +29,7 @@
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<version>${surefire.version}</version>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
@ -35,6 +38,7 @@
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>

View File

@ -33,7 +33,7 @@
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<version>${javax.servlet-api.version}</version>
</dependency>
</dependencies>
@ -41,7 +41,7 @@
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
@ -66,7 +66,7 @@
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.4.19</version>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<container>
<containerId>tomcat8x</containerId>
@ -121,9 +121,13 @@
</profiles>
<properties>
<cxf.version>3.1.6</cxf.version>
<spring.version>4.3.1.RELEASE</spring.version>
<cxf.version>3.1.8</cxf.version>
<spring.version>4.3.4.RELEASE</spring.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<surefire.version>2.19.1</surefire.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -5,20 +5,29 @@
<artifactId>apache-cxf</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>cxf-introduction</module>
<module>cxf-spring</module>
<module>cxf-jaxrs-implementation</module>
<module>cxf-aegis</module>
</modules>
<properties>
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<pluginManagement>
@ -26,7 +35,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@ -35,7 +44,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.5.0</version>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>

View File

@ -67,7 +67,7 @@
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>fop</artifactId>
<version>1.1</version>
<version>${fop.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.avalon.framework</groupId>
@ -83,18 +83,18 @@
<dependency>
<groupId>avalon-framework</groupId>
<artifactId>avalon-framework-api</artifactId>
<version>4.2.0</version>
<version>${avalon-framework.version}</version>
</dependency>
<dependency>
<groupId>avalon-framework</groupId>
<artifactId>avalon-framework-impl</artifactId>
<version>4.2.0</version>
<version>${avalon-framework.version}</version>
</dependency>
<dependency>
<groupId>org.dbdoclet</groupId>
<artifactId>dbdoclet</artifactId>
<version>8.0.2</version>
<version>${dbdoclet.version}</version>
</dependency>
<dependency>
@ -108,7 +108,7 @@
<dependency>
<groupId>net.sf.jtidy</groupId>
<artifactId>jtidy</artifactId>
<version>r938</version>
<version>${jtidy.version}</version>
</dependency>
</dependencies>
@ -187,40 +187,22 @@
</profiles>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<!-- marshalling -->
<jackson.version>2.7.2</jackson.version>
<fop.version>1.1</fop.version>
<avalon-framework.version>4.3</avalon-framework.version>
<dbdoclet.version>8.0.2</dbdoclet.version>
<jtidy.version>r938</jtidy.version>
<!-- logging -->
<org.slf4j.version>1.7.9</org.slf4j.version>
<logback.version>1.1.2</logback.version>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<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>
<httpcore.version>4.4</httpcore.version>
<httpclient.version>4.4</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>

132
aspectj/pom.xml Normal file
View File

@ -0,0 +1,132 @@
<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>aspectj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>aspectj</name>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!-- utils -->
<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>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- unit test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
</dependencies>
<build>
<finalName>aspectj</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${source.version}</source>
<target>${source.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<complianceLevel>${source.version}</complianceLevel>
<source>${source.version}</source>
<target>${source.version}</target>
<showWeaveInfo>true</showWeaveInfo>
<verbose>true</verbose>
<Xlint>ignore</Xlint>
<encoding>${project.build.sourceEncoding}</encoding>
<!-- Post-compile weaving -->
<!--
<weaveDependencies>
<weaveDependency>
<groupId>org.agroup</groupId>
<artifactId>to-weave</artifactId>
</weaveDependency>
<weaveDependency>
<groupId>org.anothergroup</groupId>
<artifactId>gen</artifactId>
</weaveDependency>
</weaveDependencies>
-->
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.10</version>
<configuration>
<argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
<useSystemClassLoader>true</useSystemClassLoader>
<forkMode>always</forkMode>
</configuration>
</plugin>
-->
</plugins>
</build>
<properties>
<source.version>1.8</source.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<aspectj.version>1.8.9</aspectj.version>
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<junit.version>4.12</junit.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung.aspectj;
public class Account {
int balance = 20;
public boolean withdraw(int amount) {
if (balance < amount) {
return false;
}
balance = balance - amount;
return true;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.aspectj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public aspect AccountAspect {
private static final Logger logger = LoggerFactory.getLogger(AccountAspect.class);
final int MIN_BALANCE = 10;
pointcut callWithDraw(int amount, Account account):
call(boolean Account.withdraw(int)) && args(amount) && target(account);
before(int amount, Account account) : callWithDraw(amount, account) {
logger.info(" Balance before withdrawal: {}", account.balance);
logger.info(" Withdraw ammout: {}", amount);
}
boolean around(int amount, Account account) : callWithDraw(amount, account) {
if (account.balance < amount) {
logger.info("Withdrawal Rejected!");
return false;
}
return proceed(amount, account);
}
after(int amount, Account balance) : callWithDraw(amount, balance) {
logger.info("Balance after withdrawal : {}", balance.balance);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.aspectj;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Secured {
public boolean isLocked() default false;
}

View File

@ -0,0 +1,23 @@
package com.baeldung.aspectj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SecuredMethod {
private static final Logger logger = LoggerFactory.getLogger(SecuredMethod.class);
@Secured(isLocked = true)
public void lockedMethod() throws Exception {
logger.info("lockedMethod");
}
@Secured(isLocked = false)
public void unlockedMethod() {
logger.info("unlockedMethod");
}
public static void main(String[] args) throws Exception {
SecuredMethod sv = new SecuredMethod();
sv.lockedMethod();
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.aspectj;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Aspect
public class SecuredMethodAspect {
private static final Logger logger = LoggerFactory.getLogger(SecuredMethodAspect.class);
@Pointcut("@annotation(secured)")
public void callAt(Secured secured) {
}
@Around("callAt(secured)")
public Object around(ProceedingJoinPoint pjp, Secured secured) throws Throwable {
if (secured.isLocked()) {
logger.info(pjp.getSignature().toLongString() + " is locked");
return null;
} else {
return pjp.proceed();
}
}
}

View File

@ -0,0 +1,8 @@
<aspectj>
<aspects>
<aspect name="com.baeldung.aspectj.SecuredMethodAspect"/>
<weaver options="-verbose -showWeaveInfo">
<include within="com.baeldung.aspectj.*"/>
</weaver>
</aspects>
</aspectj>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg %n</pattern>
</layout>
</appender>
<logger name="com.baeldung.hazelcast" level="INFO" additivity="false">
<appender-ref ref="STDOUT" />
</logger>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,27 @@
package com.baeldung.aspectj.test;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.aspectj.Account;
public class AccountTest {
private Account account;
@Before
public void before() {
account = new Account();
}
@Test
public void givenBalance20AndMinBalance10_whenWithdraw5_thenSuccess() {
assertTrue(account.withdraw(5));
}
@Test
public void givenBalance20AndMinBalance10_whenWithdraw100_thenFail() {
assertFalse(account.withdraw(100));
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.aspectj.test;
import org.junit.Test;
import com.baeldung.aspectj.SecuredMethod;
public class SecuredMethodTest {
@Test
public void testMethod() throws Exception {
SecuredMethod service = new SecuredMethod();
service.unlockedMethod();
service.lockedMethod();
}
}

View File

@ -23,13 +23,13 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.5.1</version>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
@ -40,7 +40,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@ -51,6 +51,11 @@
<properties>
<guava.version>19.0</guava.version>
<assertj-guava.version>3.1.0</assertj-guava.version>
<junit.version>4.12</junit.version>
<assertj-core.version>3.6.1</assertj-core.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -5,12 +5,13 @@
<artifactId>autovalue-tutorial</artifactId>
<version>1.0</version>
<name>AutoValue</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>7</source>
<target>7</target>
@ -19,19 +20,25 @@
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value</artifactId>
<version>1.2</version>
<version>${auto-value.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.3</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<auto-value.version>1.3</auto-value.version>
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -22,18 +22,18 @@
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
<version>${aspectjweaver.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>2.3.5.Final</version>
<version>${weld-se-core.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -97,7 +97,10 @@
</profile>
</profiles>
<properties>
<spring.version>4.3.1.RELEASE</spring.version>
<spring.version>4.3.4.RELEASE</spring.version>
<aspectjweaver.version>1.8.9</aspectjweaver.version>
<weld-se-core.version>2.4.1.Final</weld-se-core.version>
<junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>

View File

@ -2,4 +2,7 @@
## Core Java 9 Examples
http://inprogress.baeldung.com/java-9-new-features/
[Java 9 New Features](http://www.baeldung.com/new-java-9)
### Relevant Articles:
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)

View File

@ -76,9 +76,7 @@
<properties>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.0.13</logback.version>
<org.slf4j.version>1.7.21</org.slf4j.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>

View File

@ -13,4 +13,6 @@
*.ear
# Files generated by integration tests
*.txt
*.txt
/bin/
/temp

View File

@ -35,4 +35,14 @@
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
- [Introduction to Java Generics](http://www.baeldung.com/java-generics)
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
- [Sorting in Java](http://www.baeldung.com/java-sorting)
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
- [Grep in Java](http://www.baeldung.com/grep-in-java)
- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [Simulated Annealing for Travelling Salesman Problem](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)

View File

@ -1,286 +1,314 @@
<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>4.01</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>4.0</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>2.4</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>3.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<!-- marshalling -->
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<!-- logging -->
<!-- marshalling -->
<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>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- test scoped -->
<!-- logging -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</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>
<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>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.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.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.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.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.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>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</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>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<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-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
</excludes>
</configuration>
</plugin>
</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-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>
<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-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-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<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-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<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>
<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-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>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>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.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>
</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>
<profiles>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
@ -315,44 +343,38 @@
</profile>
</profiles>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<!-- marshalling -->
<jackson.version>2.7.8</jackson.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!-- util -->
<guava.version>19.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>
<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>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<testng.version>6.10</testng.version>
<assertj.version>3.6.1</assertj.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.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>
<testng.version>6.8</testng.version>
<assertj.version>3.5.1</assertj.version>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>
</properties>
</project>

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java)

View File

@ -0,0 +1,22 @@
package com.baeldung.algorithms;
import lombok.Data;
@Data
public class City {
private int x;
private int y;
public City() {
this.x = (int) (Math.random() * 500);
this.y = (int) (Math.random() * 500);
}
public double distanceToCity(City city) {
int x = Math.abs(getX() - city.getX());
int y = Math.abs(getY() - city.getY());
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.algorithms;
public class SimulatedAnnealing {
private static Travel travel = new Travel(10);
public static double simulateAnnealing(double startingTemperature, int numberOfIterations, double coolingRate) {
System.out.println("Starting SA with temperature: " + startingTemperature + ", # of iterations: " + numberOfIterations + " and colling rate: " + coolingRate);
double t = startingTemperature;
travel.generateInitialTravel();
double bestDistance = travel.getDistance();
System.out.println("Initial distance of travel: " + bestDistance);
Travel bestSolution = travel;
Travel currentSolution = bestSolution;
for (int i = 0; i < numberOfIterations; i++) {
if (t > 0.1) {
currentSolution.swapCities();
double currentDistance = currentSolution.getDistance();
if (currentDistance == 0)
continue;
if (currentDistance < bestDistance) {
bestDistance = currentDistance;
} else if (Math.exp((currentDistance - bestDistance) / t) < Math.random()) {
currentSolution.revertSwap();
}
t *= coolingRate;
} else {
continue;
}
if (i % 100 == 0) {
System.out.println("Iteration #" + i);
}
}
return bestDistance;
}
public static void main(String[] args) {
System.out.println("Optimized distance for travel: " + simulateAnnealing(10, 10000, 0.9995));
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.algorithms;
import java.util.ArrayList;
import java.util.Collections;
import lombok.Data;
@Data
public class Travel {
private ArrayList<City> travel = new ArrayList<>();
private ArrayList<City> previousTravel = new ArrayList<>();
public Travel(int numberOfCities) {
for (int i = 0; i < numberOfCities; i++) {
travel.add(new City());
}
}
public void generateInitialTravel() {
if (travel.isEmpty())
new Travel(10);
Collections.shuffle(travel);
}
public void swapCities() {
int a = generateRandomIndex();
int b = generateRandomIndex();
previousTravel = travel;
City x = travel.get(a);
City y = travel.get(b);
travel.set(a, y);
travel.set(b, x);
}
public void revertSwap() {
travel = previousTravel;
}
private int generateRandomIndex() {
return (int) (Math.random() * travel.size());
}
public City getCity(int index) {
return travel.get(index);
}
public int getDistance() {
int distance = 0;
for (int index = 0; index < travel.size(); index++) {
City starting = getCity(index);
City destination;
if (index + 1 < travel.size()) {
destination = getCity(index + 1);
} else {
destination = getCity(0);
}
distance += starting.distanceToCity(destination);
}
return distance;
}
}

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,46 @@
package com.baeldung.hashing;
import com.google.common.hash.Hashing;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.util.encoders.Hex;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA256Hashing {
public static String HashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
return bytesToHex(encodedhash);
}
public static String HashWithGuava(final String originalString) {
final String sha256hex = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
return sha256hex;
}
public static String HashWithApacheCommons(final String originalString) {
final String sha256hex = DigestUtils.sha256Hex(originalString);
return sha256hex;
}
public static String HashWithBouncyCastle(final String originalString) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final byte[] hash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
final String sha256hex = new String(Hex.encode(hash));
return sha256hex;
}
private static String bytesToHex(byte[] hash) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}

View File

@ -1,60 +0,0 @@
package com.baeldung.java.conversion;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import com.baeldung.datetime.UseLocalDateTime;
public class StringConversion {
public static int getInt(String str) {
return Integer.parseInt(str);
}
public static int getInteger(String str) {
return Integer.valueOf(str);
}
public static long getLongPrimitive(String str) {
return Long.parseLong(str);
}
public static Long getLong(String str) {
return Long.valueOf(str);
}
public static double getDouble(String str) {
return Double.parseDouble(str);
}
public static double getDoublePrimitive(String str) {
return Double.valueOf(str);
}
public static byte[] getByteArray(String str) {
return str.getBytes();
}
public static char[] getCharArray(String str) {
return str.toCharArray();
}
public static boolean getBooleanPrimitive(String str) {
return Boolean.parseBoolean(str);
}
public static boolean getBoolean(String str) {
return Boolean.valueOf(str);
}
public static Date getJava6Date(String str, String format) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(str);
}
public static LocalDateTime getJava8Date(String str) throws ParseException {
return new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
}
}

View File

@ -0,0 +1,5 @@
### Relevant Articles:
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
- [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java)
- [A Guide to the Java URL](http://www.baeldung.com/java-url)
- [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces)

View File

@ -0,0 +1,2 @@
###Relevant Articles:
- [Introduction to the Java NIO Selector](http://www.baeldung.com/java-nio-selector)

View File

@ -0,0 +1,56 @@
package com.baeldung.java.nio2.visitor;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.TERMINATE;
public class FileSearchExample implements FileVisitor<Path> {
private final String fileName;
private final Path startDir;
public FileSearchExample(String fileName, Path startingDir) {
this.fileName = fileName;
startDir = startingDir;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String fileName = file.getFileName().toString();
if (this.fileName.equals(fileName)) {
System.out.println("File found: " + file.toString());
return TERMINATE;
}
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println("Failed to access file: " + file.toString());
return CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
boolean finishedSearch = Files.isSameFile(dir, startDir);
if (finishedSearch) {
System.out.println("File:" + fileName + " not found");
return TERMINATE;
}
return CONTINUE;
}
public static void main(String[] args) throws IOException {
Path startingDir = Paths.get("C:/Users/new/Desktop");
FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir);
Files.walkFileTree(startingDir, crawler);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.java.nio2.visitor;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
public class FileVisitorImpl implements FileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return null;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
return null;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
return null;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return null;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.java.nio2.watcher;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class DirectoryWatcherExample {
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(System.getProperty("user.home"));
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
}
key.reset();
}
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.optional;
public class Modem {
private Double price;
public Modem(Double price) {
this.price = price;
}
public Double getPrice() {
return price;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.optional;
import java.util.Optional;
public class Person {
private String name;
private int age;
private String password;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Optional<String> getName() {
return Optional.ofNullable(name);
}
public void setName(String name) {
this.name = name;
}
public Optional<Integer> getAge() {
return Optional.ofNullable(age);
}
public void setAge(int age) {
this.age = age;
}
public void setPassword(String password) {
this.password = password;
}
public Optional<String> getPassword() {
return Optional.ofNullable(password);
}
}

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)

View File

@ -16,10 +16,10 @@ public class ExitingExecutorServiceExample {
public static void main(String... args) {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);
final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
final ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);
executorService.submit(() -> {
executorService.submit((Runnable) () -> {
while (true) {
}
});

View File

@ -0,0 +1,63 @@
package org.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 org.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 org.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 org.baeldung.equalshashcode.entities;
public abstract class Shape {
public abstract double area();
public abstract double perimeter();
}

View File

@ -0,0 +1,58 @@
package org.baeldung.equalshashcode.entities;
import java.awt.Color;
public class Square extends Rectangle {
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,11 @@
package org.baeldung.executable;
import javax.swing.JOptionPane;
public class ExecutableMavenJar {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
public class SimulatedAnnealingTest {
@Test
public void testSimulateAnnealing() {
Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
}
}

View File

@ -7,20 +7,20 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.*;
public class EncoderDecoderUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class);
private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
private static final String testUrlWithPath = "http://www.baeldung.com/path+1?key1=value+1&key2=value%40%21%242&key3=value%253";
private String encodeValue(String value) {
String encoded = null;
@ -46,9 +46,9 @@ public class EncoderDecoderUnitTest {
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
URL url = new URL(testUrl);
Assert.assertThat(url.getProtocol(), CoreMatchers.is("http"));
Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com"));
Assert.assertThat(url.getQuery(), CoreMatchers.is("key1=value+1&key2=value%40%21%242&key3=value%253"));
Assert.assertThat(url.getProtocol(), is("http"));
Assert.assertThat(url.getHost(), is("www.baeldung.com"));
Assert.assertThat(url.getQuery(), is("key1=value+1&key2=value%40%21%242&key3=value%253"));
}
@Test
@ -60,7 +60,7 @@ public class EncoderDecoderUnitTest {
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
Assert.assertThat(testUrl, is(encodedURL));
}
@Test
@ -74,4 +74,35 @@ public class EncoderDecoderUnitTest {
Assert.assertEquals("http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
}
private String encodePath(String path) {
try {
path = new URI(null, null, path, null).getPath();
} catch (URISyntaxException e) {
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
}
return path;
}
@Test
public void givenPath_thenEncodeDecodePath() throws URISyntaxException {
URI uri = new URI(null, null, "/Path 1/Path+2", null);
Assert.assertEquals("/Path 1/Path+2", uri.getPath());
Assert.assertEquals("/Path%201/Path+2", uri.getRawPath());
}
@Test
public void givenPathAndRequestParam_whenUTF8Scheme_thenEncode() throws Exception {
Map<String, String> requestParams = new HashMap<>();
requestParams.put("key1", "value 1");
requestParams.put("key2", "value@!$2");
requestParams.put("key3", "value%3");
String path = "path+1";
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com/" + encodePath(path) + "?", ""));
Assert.assertThat(testUrlWithPath, is(encodedURL));
}
}

View File

@ -1,11 +1,12 @@
package com.baeldung.file;
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 org.apache.commons.io.FileUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
@ -14,12 +15,6 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import org.apache.commons.io.FileUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
public class FileOperationsUnitTest {
@Test
@ -58,9 +53,9 @@ public class FileOperationsUnitTest {
@Test
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
String expectedData = "Baeldung";
String expectedData = "Example Domain";
URL urlObject = new URL("http://www.baeldung.com/");
URL urlObject = new URL("http://www.example.com/");
URLConnection urlConnection = urlObject.openConnection();

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 GenericsTest {
// 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,55 @@
package com.baeldung.grep;
import java.io.File;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.unix4j.Unix4j;
import static org.unix4j.Unix4j.*;
import static org.junit.Assert.assertEquals;
import org.unix4j.line.Line;
import static org.unix4j.unix.Grep.*;
import static org.unix4j.unix.cut.CutOption.*;
public class GrepWithUnix4JTest {
private File fileToGrep;
@Before
public void init() {
final String separator = File.separator;
final String filePath = String.join(separator, new String[] { "src", "test", "resources", "dictionary.in" });
fileToGrep = new File(filePath);
}
@Test
public void whenGrepWithSimpleString_thenCorrect() {
int expectedLineCount = 4;
// grep "NINETEEN" dictionary.txt
List<Line> lines = Unix4j.grep("NINETEEN", fileToGrep).toLineList();
assertEquals(expectedLineCount, lines.size());
}
@Test
public void whenInverseGrepWithSimpleString_thenCorrect() {
int expectedLineCount = 178687;
// grep -v "NINETEEN" dictionary.txt
List<Line> lines = grep(Options.v, "NINETEEN", fileToGrep).toLineList();
assertEquals(expectedLineCount, lines.size());
}
@Test
public void whenGrepWithRegex_thenCorrect() {
int expectedLineCount = 151;
// grep -c ".*?NINE.*?" dictionary.txt
String patternCount = grep(Options.c, ".*?NINE.*?", fileToGrep).cut(fields, ":", 1).toStringResult();
assertEquals(expectedLineCount, Integer.parseInt(patternCount));
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.hashing;
import org.junit.Test;
import static org.junit.Assert.*;
public class SHA256HashingTest {
private static String originalValue = "abc123";
private static String hashedValue = "6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
@Test
public void testHashWithJavaMessageDigest() throws Exception {
final String currentHashedValue = SHA256Hashing.HashWithJavaMessageDigest(originalValue);
assertEquals(currentHashedValue, hashedValue);
}
@Test
public void testHashWithGuava() throws Exception {
final String currentHashedValue = SHA256Hashing.HashWithApacheCommons(originalValue);
assertEquals(currentHashedValue, hashedValue);
}
@Test
public void testHashWithApacheCommans() throws Exception {
final String currentHashedValue = SHA256Hashing.HashWithGuava(originalValue);
assertEquals(currentHashedValue, hashedValue);
}
@Test
public void testHashWithBouncyCastle() throws Exception {
final String currentHashedValue = SHA256Hashing.HashWithBouncyCastle(originalValue);
assertEquals(currentHashedValue, hashedValue);
}
}

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Convert Hex to ASCII in Java](http://www.baeldung.com/java-convert-hex-to-ascii)

View File

@ -0,0 +1,2 @@
Relevant Articles:
- [Java String Conversions](http://www.baeldung.com/java-string-conversions)

View File

@ -0,0 +1,128 @@
package com.baeldung.java.conversion;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.junit.Test;
import com.baeldung.datetime.UseLocalDateTime;
public class StringConversionTest {
@Test
public void whenConvertedToInt_thenCorrect() {
String beforeConvStr = "1";
int afterConvInt = 1;
assertEquals(Integer.parseInt(beforeConvStr), afterConvInt);
}
@Test
public void whenConvertedToInteger_thenCorrect() {
String beforeConvStr = "12";
Integer afterConvInteger = 12;
assertEquals(Integer.valueOf(beforeConvStr).equals(afterConvInteger), true);
}
@Test
public void whenConvertedTolong_thenCorrect() {
String beforeConvStr = "12345";
long afterConvLongPrimitive = 12345;
assertEquals(Long.parseLong(beforeConvStr), afterConvLongPrimitive);
}
@Test
public void whenConvertedToLong_thenCorrect() {
String beforeConvStr = "14567";
Long afterConvLong = 14567l;
assertEquals(Long.valueOf(beforeConvStr).equals(afterConvLong), true);
}
@Test
public void whenConvertedTodouble_thenCorrect() {
String beforeConvStr = "1.4";
double afterConvDoublePrimitive = 1.4;
assertEquals(Double.parseDouble(beforeConvStr), afterConvDoublePrimitive, 0.0);
}
@Test
public void whenConvertedToDouble_thenCorrect() {
String beforeConvStr = "145.67";
double afterConvDouble = 145.67d;
assertEquals(Double.valueOf(beforeConvStr).equals(afterConvDouble), true);
}
@Test
public void whenConvertedToByteArr_thenCorrect() {
String beforeConvStr = "abc";
byte[] afterConvByteArr = new byte[] { 'a', 'b', 'c' };
assertEquals(Arrays.equals(beforeConvStr.getBytes(), afterConvByteArr), true);
}
@Test
public void whenConvertedToboolean_thenCorrect() {
String beforeConvStr = "true";
boolean afterConvBooleanPrimitive = true;
assertEquals(Boolean.parseBoolean(beforeConvStr), afterConvBooleanPrimitive);
}
@Test
public void whenConvertedToBoolean_thenCorrect() {
String beforeConvStr = "true";
Boolean afterConvBoolean = true;
assertEquals(Boolean.valueOf(beforeConvStr), afterConvBoolean);
}
@Test
public void whenConvertedToCharArr_thenCorrect() {
String beforeConvStr = "hello";
char[] afterConvCharArr = { 'h', 'e', 'l', 'l', 'o' };
assertEquals(Arrays.equals(beforeConvStr.toCharArray(), afterConvCharArr), true);
}
@Test
public void whenConvertedToDate_thenCorrect() throws ParseException {
String beforeConvStr = "15/10/2013";
int afterConvCalendarDay = 15;
int afterConvCalendarMonth = 9;
int afterConvCalendarYear = 2013;
SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yyyy");
Date afterConvDate = formatter.parse(beforeConvStr);
Calendar calendar = new GregorianCalendar();
calendar.setTime(afterConvDate);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), afterConvCalendarDay);
assertEquals(calendar.get(Calendar.MONTH), afterConvCalendarMonth);
assertEquals(calendar.get(Calendar.YEAR), afterConvCalendarYear);
}
@Test
public void whenConvertedToLocalDateTime_thenCorrect() {
String str = "2007-12-03T10:15:30";
int afterConvCalendarDay = 03;
Month afterConvCalendarMonth = Month.DECEMBER;
int afterConvCalendarYear = 2007;
LocalDateTime afterConvDate = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay);
assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth);
assertEquals(afterConvDate.getYear(), afterConvCalendarYear);
}
}

View File

@ -1,64 +1,72 @@
package com.baeldung.java.nio2;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.UUID;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
import org.junit.Test;
public class FileTest {
private static final String HOME = System.getProperty("user.home");
private static final String TEMP_DIR = String.format("%s/temp%s", System.getProperty("user.home"), UUID.randomUUID().toString());
@BeforeClass
public static void setup() throws IOException {
Files.createDirectory(Paths.get(TEMP_DIR));
}
@AfterClass
public static void cleanup() throws IOException {
FileUtils.deleteDirectory(new File(TEMP_DIR));
}
// checking file or dir
@Test
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
Path p = Paths.get(HOME);
Path p = Paths.get(TEMP_DIR);
assertTrue(Files.exists(p));
}
@Test
public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
Path p = Paths.get(HOME + "/inexistent_file.txt");
Path p = Paths.get(TEMP_DIR + "/inexistent_file.txt");
assertTrue(Files.notExists(p));
}
@Test
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
Path p = Paths.get(HOME);
Path p = Paths.get(TEMP_DIR);
assertFalse(Files.isRegularFile(p));
}
@Test
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
Path p = Paths.get(HOME);
Path p = Paths.get(TEMP_DIR);
assertTrue(Files.isReadable(p));
}
@Test
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
Path p = Paths.get(HOME);
Path p = Paths.get(System.getProperty("user.home"));
assertTrue(Files.isWritable(p));
}
@Test
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
Path p = Paths.get(HOME);
Path p = Paths.get(System.getProperty("user.home"));
assertTrue(Files.isExecutable(p));
}
@Test
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
Path p1 = Paths.get(HOME);
Path p2 = Paths.get(HOME);
Path p1 = Paths.get(TEMP_DIR);
Path p2 = Paths.get(TEMP_DIR);
assertTrue(Files.isSameFile(p1, p2));
}
@ -67,7 +75,7 @@ public class FileTest {
@Test
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
Path p = Paths.get(HOME + "/" + fileName);
Path p = Paths.get(TEMP_DIR + "/" + fileName);
assertFalse(Files.exists(p));
Files.createFile(p);
assertTrue(Files.exists(p));
@ -77,7 +85,7 @@ public class FileTest {
@Test
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
String dirName = "myDir_" + UUID.randomUUID().toString();
Path p = Paths.get(HOME + "/" + dirName);
Path p = Paths.get(TEMP_DIR + "/" + dirName);
assertFalse(Files.exists(p));
Files.createDirectory(p);
assertTrue(Files.exists(p));
@ -89,7 +97,7 @@ public class FileTest {
@Test(expected = NoSuchFileException.class)
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
Path p = Paths.get(HOME + "/" + dirName);
Path p = Paths.get(TEMP_DIR + "/" + dirName);
assertFalse(Files.exists(p));
Files.createDirectory(p);
@ -97,7 +105,7 @@ public class FileTest {
@Test
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
Path dir = Paths.get(HOME + "/myDir_" + UUID.randomUUID().toString());
Path dir = Paths.get(TEMP_DIR + "/myDir_" + UUID.randomUUID().toString());
Path subdir = dir.resolve("subdir");
assertFalse(Files.exists(dir));
assertFalse(Files.exists(subdir));
@ -110,7 +118,7 @@ public class FileTest {
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
String prefix = "log_";
String suffix = ".txt";
Path p = Paths.get(HOME + "/");
Path p = Paths.get(TEMP_DIR + "/");
p = Files.createTempFile(p, prefix, suffix);
// like log_8821081429012075286.txt
assertTrue(Files.exists(p));
@ -119,7 +127,7 @@ public class FileTest {
@Test
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
Path p = Paths.get(HOME + "/");
Path p = Paths.get(TEMP_DIR + "/");
p = Files.createTempFile(p, null, null);
// like 8600179353689423985.tmp
assertTrue(Files.exists(p));
@ -136,7 +144,7 @@ public class FileTest {
// delete file
@Test
public void givenPath_whenDeletes_thenCorrect() throws IOException {
Path p = Paths.get(HOME + "/fileToDelete.txt");
Path p = Paths.get(TEMP_DIR + "/fileToDelete.txt");
assertFalse(Files.exists(p));
Files.createFile(p);
assertTrue(Files.exists(p));
@ -147,7 +155,7 @@ public class FileTest {
@Test(expected = DirectoryNotEmptyException.class)
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
Path dir = Paths.get(HOME + "/emptyDir" + UUID.randomUUID().toString());
Path dir = Paths.get(TEMP_DIR + "/emptyDir" + UUID.randomUUID().toString());
Files.createDirectory(dir);
assertTrue(Files.exists(dir));
Path file = dir.resolve("file.txt");
@ -160,7 +168,7 @@ public class FileTest {
@Test(expected = NoSuchFileException.class)
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
Path p = Paths.get(HOME + "/inexistentFile.txt");
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
assertFalse(Files.exists(p));
Files.delete(p);
@ -168,7 +176,7 @@ public class FileTest {
@Test
public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
Path p = Paths.get(HOME + "/inexistentFile.txt");
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
assertFalse(Files.exists(p));
Files.deleteIfExists(p);
@ -177,8 +185,8 @@ public class FileTest {
// copy file
@Test
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
Files.createDirectory(dir1);
Files.createDirectory(dir2);
Path file1 = dir1.resolve("filetocopy.txt");
@ -193,8 +201,8 @@ public class FileTest {
@Test(expected = FileAlreadyExistsException.class)
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
Files.createDirectory(dir1);
Files.createDirectory(dir2);
Path file1 = dir1.resolve("filetocopy.txt");
@ -210,8 +218,8 @@ public class FileTest {
// moving files
@Test
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
Files.createDirectory(dir1);
Files.createDirectory(dir2);
Path file1 = dir1.resolve("filetocopy.txt");
@ -227,8 +235,8 @@ public class FileTest {
@Test(expected = FileAlreadyExistsException.class)
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
Files.createDirectory(dir1);
Files.createDirectory(dir2);
Path file1 = dir1.resolve("filetocopy.txt");

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)

View File

@ -0,0 +1,86 @@
package com.baeldung.java.nio2.async;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class AsyncEchoClient {
private AsynchronousSocketChannel client;
private Future<Void> future;
private static AsyncEchoClient instance;
private AsyncEchoClient() {
try {
client = AsynchronousSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
future = client.connect(hostAddress);
start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static AsyncEchoClient getInstance() {
if (instance == null)
instance = new AsyncEchoClient();
return instance;
}
private void start() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
public String sendMessage(String message) {
byte[] byteMsg = message.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
Future<Integer> writeResult = client.write(buffer);
try {
writeResult.get();
} catch (Exception e) {
e.printStackTrace();
}
buffer.flip();
Future<Integer> readResult = client.read(buffer);
try {
readResult.get();
} catch (Exception e) {
e.printStackTrace();
}
String echo = new String(buffer.array()).trim();
buffer.clear();
return echo;
}
public void stop() {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
AsyncEchoClient client = AsyncEchoClient.getInstance();
client.start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
System.out.println("Message to server:");
while ((line = br.readLine()) != null) {
String response = client.sendMessage(line);
System.out.println("response from server: " + response);
System.out.println("Message to server:");
}
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.java.nio2.async;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class AsyncEchoServer {
private AsynchronousServerSocketChannel serverChannel;
private Future<AsynchronousSocketChannel> acceptResult;
private AsynchronousSocketChannel clientChannel;
public AsyncEchoServer() {
try {
serverChannel = AsynchronousServerSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
serverChannel.bind(hostAddress);
acceptResult = serverChannel.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
public void runServer() {
try {
clientChannel = acceptResult.get();
if ((clientChannel != null) && (clientChannel.isOpen())) {
while (true) {
ByteBuffer buffer = ByteBuffer.allocate(32);
Future<Integer> readResult = clientChannel.read(buffer);
// do some computation
readResult.get();
buffer.flip();
String message = new String(buffer.array()).trim();
if (message.equals("bye")) {
break; // while loop
}
buffer = ByteBuffer.wrap(new String(message).getBytes());
Future<Integer> writeResult = clientChannel.write(buffer);
// do some computation
writeResult.get();
buffer.clear();
} // while()
clientChannel.close();
serverChannel.close();
}
} catch (InterruptedException | ExecutionException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
AsyncEchoServer server = new AsyncEchoServer();
server.runServer();
}
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = AsyncEchoServer.class.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
return builder.start();
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.java.nio2.async;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.HashMap;
import java.util.Map;
public class AsyncEchoServer2 {
private AsynchronousServerSocketChannel serverChannel;
private AsynchronousSocketChannel clientChannel;
public AsyncEchoServer2() {
try {
serverChannel = AsynchronousServerSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
serverChannel.bind(hostAddress);
while (true) {
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public void completed(AsynchronousSocketChannel result, Object attachment) {
if (serverChannel.isOpen())
serverChannel.accept(null, this);
clientChannel = result;
if ((clientChannel != null) && (clientChannel.isOpen())) {
ReadWriteHandler handler = new ReadWriteHandler();
ByteBuffer buffer = ByteBuffer.allocate(32);
Map<String, Object> readInfo = new HashMap<>();
readInfo.put("action", "read");
readInfo.put("buffer", buffer);
clientChannel.read(buffer, readInfo, handler);
}
}
@Override
public void failed(Throwable exc, Object attachment) {
// process error
}
});
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
class ReadWriteHandler implements CompletionHandler<Integer, Map<String, Object>> {
@Override
public void completed(Integer result, Map<String, Object> attachment) {
Map<String, Object> actionInfo = attachment;
String action = (String) actionInfo.get("action");
if ("read".equals(action)) {
ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer");
buffer.flip();
actionInfo.put("action", "write");
clientChannel.write(buffer, actionInfo, this);
buffer.clear();
} else if ("write".equals(action)) {
ByteBuffer buffer = ByteBuffer.allocate(32);
actionInfo.put("action", "read");
actionInfo.put("buffer", buffer);
clientChannel.read(buffer, actionInfo, this);
}
}
@Override
public void failed(Throwable exc, Map<String, Object> attachment) {
}
}
public static void main(String[] args) {
new AsyncEchoServer2();
}
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = AsyncEchoServer2.class.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
return builder.start();
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.java.nio2.async;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class AsyncEchoTest {
Process server;
AsyncEchoClient client;
@Before
public void setup() throws IOException, InterruptedException {
server = AsyncEchoServer2.start();
client = AsyncEchoClient.getInstance();
}
@Test
public void givenServerClient_whenServerEchosMessage_thenCorrect() throws Exception {
String resp1 = client.sendMessage("hello");
String resp2 = client.sendMessage("world");
assertEquals("hello", resp1);
assertEquals("world", resp2);
}
@After
public void teardown() throws IOException {
server.destroy();
client.stop();
}
}

View File

@ -0,0 +1,126 @@
package com.baeldung.java.nio2.async;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
public class AsyncFileTest {
@Test
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> operation = fileChannel.read(buffer, 0);
operation.get();
String fileContent = new String(buffer.array()).trim();
buffer.clear();
assertEquals(fileContent, "baeldung.com");
}
@Test
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
Path path = Paths.get(URI.create(AsyncFileTest.class.getResource("/file.txt").toString()));
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
// result is number of bytes read
// attachment is the buffer
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
}
});
}
@Test
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
String fileName = "temp";
Path path = Paths.get(fileName);
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;
buffer.put("hello world".getBytes());
buffer.flip();
Future<Integer> operation = fileChannel.write(buffer, position);
buffer.clear();
operation.get();
String content = readContent(path);
assertEquals("hello world", content);
}
@Test
public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException {
String fileName = UUID.randomUUID().toString();
Path path = Paths.get(fileName);
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("hello world".getBytes());
buffer.flip();
fileChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
// result is number of bytes written
// attachment is the buffer
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
}
});
}
public static String readContent(Path file) throws ExecutionException, InterruptedException {
AsynchronousFileChannel fileChannel = null;
try {
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> operation = fileChannel.read(buffer, 0);
operation.get();
String fileContent = new String(buffer.array()).trim();
buffer.clear();
return fileContent;
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.java.nio2.attributes;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BasicAttribsTest {
private static final String HOME = System.getProperty("user.home");
private static BasicFileAttributes basicAttribs;
@BeforeClass
public static void setup() throws IOException {
Path home = Paths.get(HOME);
BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class);
basicAttribs = basicView.readAttributes();
}
@Test
public void givenFileTimes_whenComparesThem_ThenCorrect() {
FileTime created = basicAttribs.creationTime();
FileTime modified = basicAttribs.lastModifiedTime();
FileTime accessed = basicAttribs.lastAccessTime();
System.out.println("Created: " + created);
System.out.println("Modified: " + modified);
System.out.println("Accessed: " + accessed);
}
@Test
public void givenPath_whenGetsFileSize_thenCorrect() {
long size = basicAttribs.size();
assertTrue(size > 0);
}
@Test
public void givenPath_whenChecksIfDirectory_thenCorrect() {
boolean isDir = basicAttribs.isDirectory();
assertTrue(isDir);
}
@Test
public void givenPath_whenChecksIfFile_thenCorrect() {
boolean isFile = basicAttribs.isRegularFile();
assertFalse(isFile);
}
@Test
public void givenPath_whenChecksIfSymLink_thenCorrect() {
boolean isSymLink = basicAttribs.isSymbolicLink();
assertFalse(isSymLink);
}
@Test
public void givenPath_whenChecksIfOther_thenCorrect() {
boolean isOther = basicAttribs.isOther();
assertFalse(isOther);
}
}

View File

@ -4,6 +4,7 @@ import com.google.common.collect.Lists;
import org.junit.Test;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.hasSize;
@ -16,7 +17,7 @@ public class Java8CollectionCleanupUnitTest {
@Test
public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
final List<Integer> listWithoutNulls = list.parallelStream().filter(i -> i != null).collect(Collectors.toList());
final List<Integer> listWithoutNulls = list.parallelStream().filter(Objects::nonNull).collect(Collectors.toList());
assertThat(listWithoutNulls, hasSize(3));
}
@ -24,7 +25,7 @@ public class Java8CollectionCleanupUnitTest {
@Test
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
final List<Integer> listWithoutNulls = list.stream().filter(i -> i != null).collect(Collectors.toList());
final List<Integer> listWithoutNulls = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
assertThat(listWithoutNulls, hasSize(3));
}
@ -32,7 +33,7 @@ public class Java8CollectionCleanupUnitTest {
@Test
public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
final List<Integer> listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null);
listWithoutNulls.removeIf(p -> p == null);
listWithoutNulls.removeIf(Objects::isNull);
assertThat(listWithoutNulls, hasSize(3));
}

View File

@ -0,0 +1,65 @@
package com.baeldung.java8;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
public class JavaFileSizeUnitTest {
private static final long EXPECTED_FILE_SIZE_IN_BYTES = 11;
private String filePath;
@Before
public void init() {
final String separator = File.separator;
filePath = String.join(separator, new String[] { "src", "test", "resources", "testFolder", "sample_file_1.in" });
}
@Test
public void whenGetFileSize_thenCorrect() {
final File file = new File(filePath);
final long size = getFileSize(file);
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
}
@Test
public void whenGetFileSizeUsingNioApi_thenCorrect() throws IOException {
final Path path = Paths.get(this.filePath);
final FileChannel fileChannel = FileChannel.open(path);
final long fileSize = fileChannel.size();
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, fileSize);
}
@Test
public void whenGetFileSizeUsingApacheCommonsIO_thenCorrect() {
final File file = new File(filePath);
final long size = FileUtils.sizeOf(file);
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
}
@Test
public void whenGetReadableFileSize_thenCorrect() {
final File file = new File(filePath);
final long size = getFileSize(file);
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES + " bytes", FileUtils.byteCountToDisplaySize(size));
}
private long getFileSize(final File file) {
final long length = file.length();
return length;
}
}

View File

@ -8,7 +8,7 @@ import java.io.StringWriter;
import java.util.Date;
import java.util.Scanner;
public class JavaTryWithResourcesUnitTest {
public class JavaTryWithResourcesLongRunningUnitTest {
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
private Date resource1Date, resource2Date;

View File

@ -0,0 +1,235 @@
package com.baeldung.java8.optional;
import com.baeldung.optional.Modem;
import com.baeldung.optional.Person;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import static org.junit.Assert.*;
public class OptionalTest {
// creating Optional
@Test
public void whenCreatesEmptyOptional_thenCorrect() {
Optional<String> empty = Optional.empty();
assertFalse(empty.isPresent());
}
@Test
public void givenNonNull_whenCreatesNonNullable_thenCorrect() {
String name = "baeldung";
Optional.of(name);
}
@Test(expected = NullPointerException.class)
public void givenNull_whenThrowsErrorOnCreate_thenCorrect() {
String name = null;
Optional<String> opt = Optional.of(name);
}
@Test
public void givenNonNull_whenCreatesOptional_thenCorrect() {
String name = "baeldung";
Optional<String> opt = Optional.of(name);
assertEquals("Optional[baeldung]", opt.toString());
}
@Test
public void givenNonNull_whenCreatesNullable_thenCorrect() {
String name = "baeldung";
Optional<String> opt = Optional.ofNullable(name);
assertEquals("Optional[baeldung]", opt.toString());
}
@Test
public void givenNull_whenCreatesNullable_thenCorrect() {
String name = null;
Optional<String> opt = Optional.ofNullable(name);
assertEquals("Optional.empty", opt.toString());
}
// Checking Value With isPresent()
@Test
public void givenOptional_whenIsPresentWorks_thenCorrect() {
Optional<String> opt = Optional.of("Baeldung");
assertTrue(opt.isPresent());
opt = Optional.ofNullable(null);
assertFalse(opt.isPresent());
}
// Condition Action With ifPresent()
@Test
public void givenOptional_whenIfPresentWorks_thenCorrect() {
Optional<String> opt = Optional.of("baeldung");
opt.ifPresent(name -> System.out.println(name.length()));
}
// returning Value With get()
@Test
public void givenOptional_whenGetsValue_thenCorrect() {
Optional<String> opt = Optional.of("baeldung");
String name = opt.get();
assertEquals("baeldung", name);
}
@Test(expected = NoSuchElementException.class)
public void givenOptionalWithNull_whenGetThrowsException_thenCorrect() {
Optional<String> opt = Optional.ofNullable(null);
String name = opt.get();
}
// Conditional Return With filter()
@Test
public void whenOptionalFilterWorks_thenCorrect() {
Integer year = 2016;
Optional<Integer> yearOptional = Optional.of(year);
boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent();
assertTrue(is2016);
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
assertFalse(is2017);
}
@Test
public void whenFiltersWithoutOptional_thenCorrect() {
assertTrue(priceIsInRange1(new Modem(10.0)));
assertFalse(priceIsInRange1(new Modem(9.9)));
assertFalse(priceIsInRange1(new Modem(null)));
assertFalse(priceIsInRange1(new Modem(15.5)));
assertFalse(priceIsInRange1(null));
}
@Test
public void whenFiltersWithOptional_thenCorrect() {
assertTrue(priceIsInRange2(new Modem(10.0)));
assertFalse(priceIsInRange2(new Modem(9.9)));
assertFalse(priceIsInRange2(new Modem(null)));
assertFalse(priceIsInRange2(new Modem(15.5)));
assertFalse(priceIsInRange1(null));
}
public boolean priceIsInRange1(Modem modem) {
boolean isInRange = false;
if (modem != null && modem.getPrice() != null && (modem.getPrice() >= 10 && modem.getPrice() <= 15)) {
isInRange = true;
}
return isInRange;
}
public boolean priceIsInRange2(Modem modem2) {
return Optional.ofNullable(modem2).map(Modem::getPrice).filter(p -> p >= 10).filter(p -> p <= 15).isPresent();
}
// Transforming Value With map()
@Test
public void givenOptional_whenMapWorks_thenCorrect() {
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
Optional<List<String>> listOptional = Optional.of(companyNames);
int size = listOptional.map(List::size).orElse(0);
assertEquals(6, size);
}
@Test
public void givenOptional_whenMapWorks_thenCorrect2() {
String name = "baeldung";
Optional<String> nameOptional = Optional.of(name);
int len = nameOptional.map(String::length).orElse(0);
assertEquals(8, len);
}
@Test
public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
String password = " password ";
Optional<String> passOpt = Optional.of(password);
boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent();
assertFalse(correctPassword);
correctPassword = passOpt.map(String::trim).filter(pass -> pass.equals("password")).isPresent();
assertTrue(correctPassword);
}
// Transforming Value With flatMap()
@Test
public void givenOptional_whenFlatMapWorks_thenCorrect2() {
Person person = new Person("john", 26);
Optional<Person> personOptional = Optional.of(person);
Optional<Optional<String>> nameOptionalWrapper = personOptional.map(Person::getName);
Optional<String> nameOptional = nameOptionalWrapper.orElseThrow(IllegalArgumentException::new);
String name1 = nameOptional.orElseThrow(IllegalArgumentException::new);
assertEquals("john", name1);
String name = personOptional.flatMap(Person::getName).orElseThrow(IllegalArgumentException::new);
assertEquals("john", name);
}
@Test
public void givenOptional_whenFlatMapWorksWithFilter_thenCorrect() {
Person person = new Person("john", 26);
person.setPassword("password");
Optional<Person> personOptional = Optional.of(person);
String password = personOptional.flatMap(Person::getPassword).filter(cleanPass -> cleanPass.equals("password")).orElseThrow(IllegalArgumentException::new);
assertEquals("password", password);
}
// Default Value With orElse
@Test
public void whenOrElseWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElse("john");
assertEquals("john", name);
}
// Default Value With orElseGet
@Test
public void whenOrElseGetWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseGet(() -> "john");
assertEquals("john", name);
}
@Test
public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
String text = null;
System.out.println("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
assertEquals("Default Value", defaultText);
System.out.println("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
assertEquals("Default Value", defaultText);
}
@Test
public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
String text = "Text present";
System.out.println("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
assertEquals("Text present", defaultText);
System.out.println("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
assertEquals("Text present", defaultText);
}
// Exceptions With orElseThrow
@Test(expected = IllegalArgumentException.class)
public void whenOrElseThrowWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new);
}
public String getMyDefault() {
System.out.println("Getting default value...");
return "Default Value";
}
}

View File

@ -0,0 +1,135 @@
package org.baeldung.java.collections;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.IterableUtils;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
public class CollectionsConcatenateUnitTest {
@Test
public void givenUsingJava8_whenConcatenatingUsingConcat_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Collection<String> collectionC = asList("W", "X");
Stream<String> combinedStream = Stream.concat(Stream.concat(collectionA.stream(), collectionB.stream()), collectionC.stream());
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
Assert.assertEquals(asList("S", "T", "U", "V", "W", "X"), collectionCombined);
}
@Test
public void givenUsingJava8_whenConcatenatingUsingflatMap_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Stream<String> combinedStream = Stream.of(collectionA, collectionB).flatMap(Collection::stream);
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
@Test
public void givenUsingGuava_whenConcatenatingUsingIterables_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = Iterables.unmodifiableIterable(Iterables.concat(collectionA, collectionB));
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
@Test
public void givenUsingJava7_whenConcatenatingUsingIterables_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = concat(collectionA, collectionB);
Collection<String> collectionCombined = makeListFromIterable(combinedIterables);
Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined);
}
public static <E> Iterable<E> concat(Iterable<? extends E> i1, Iterable<? extends E> i2) {
return new Iterable<E>() {
public Iterator<E> iterator() {
return new Iterator<E>() {
Iterator<? extends E> listIterator = i1.iterator();
Boolean checkedHasNext;
E nextValue;
private boolean startTheSecond;
void theNext() {
if (listIterator.hasNext()) {
checkedHasNext = true;
nextValue = listIterator.next();
} else if (startTheSecond)
checkedHasNext = false;
else {
startTheSecond = true;
listIterator = i2.iterator();
theNext();
}
}
public boolean hasNext() {
if (checkedHasNext == null)
theNext();
return checkedHasNext;
}
public E next() {
if (!hasNext())
throw new NoSuchElementException();
checkedHasNext = null;
return nextValue;
}
public void remove() {
listIterator.remove();
}
};
}
};
}
public static <E> List<E> makeListFromIterable(Iterable<E> iter) {
List<E> list = new ArrayList<>();
for (E item : iter) {
list.add(item);
}
return list;
}
@Test
public void givenUsingApacheCommons_whenConcatenatingUsingUnion_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = CollectionUtils.union(collectionA, collectionB);
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
@Test
public void givenUsingApacheCommons_whenConcatenatingUsingChainedIterable_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = IterableUtils.chainedIterable(collectionA, collectionB);
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
}

View File

@ -0,0 +1,154 @@
package org.baeldung.java.collections;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.*;
public class JoinSplitCollectionsUnitTest {
@Test
public void whenJoiningTwoArrays_thenJoined() {
String[] animals1 = new String[] { "Dog", "Cat" };
String[] animals2 = new String[] { "Bird", "Cow" };
String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2)).toArray(String[]::new);
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
}
@Test
public void whenJoiningTwoCollections_thenJoined() {
Collection<String> collection1 = Arrays.asList("Dog", "Cat");
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
Collection<String> result = Stream.concat(collection1.stream(), collection2.stream()).collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow", "Moose")));
}
@Test
public void whenJoiningTwoCollectionsWithFilter_thenJoined() {
Collection<String> collection1 = Arrays.asList("Dog", "Cat");
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
Collection<String> result = Stream.concat(collection1.stream(), collection2.stream()).filter(e -> e.length() == 3).collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Cow")));
}
@Test
public void whenConvertArrayToString_thenConverted() {
String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow" };
String result = Arrays.stream(animals).collect(Collectors.joining(", "));
assertEquals(result, "Dog, Cat, Bird, Cow");
}
@Test
public void whenConvertCollectionToString_thenConverted() {
Collection<String> animals = Arrays.asList("Dog", "Cat", "Bird", "Cow");
String result = animals.stream().collect(Collectors.joining(", "));
assertEquals(result, "Dog, Cat, Bird, Cow");
}
@Test
public void whenConvertMapToString_thenConverted() {
Map<Integer, String> animals = new HashMap<>();
animals.put(1, "Dog");
animals.put(2, "Cat");
animals.put(3, "Cow");
String result = animals.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue()).collect(Collectors.joining(", "));
assertEquals(result, "1 = Dog, 2 = Cat, 3 = Cow");
}
@Test
public void whenConvertNestedCollectionToString_thenConverted() {
Collection<List<String>> nested = new ArrayList<>();
nested.add(Arrays.asList("Dog", "Cat"));
nested.add(Arrays.asList("Cow", "Pig"));
String result = nested.stream().map(nextList -> nextList.stream().collect(Collectors.joining("-"))).collect(Collectors.joining("; "));
assertEquals(result, "Dog-Cat; Cow-Pig");
}
@Test
public void whenConvertCollectionToStringAndSkipNull_thenConverted() {
Collection<String> animals = Arrays.asList("Dog", "Cat", null, "Moose");
String result = animals.stream().filter(Objects::nonNull).collect(Collectors.joining(", "));
assertEquals(result, "Dog, Cat, Moose");
}
@Test
public void whenSplitCollectionHalf_thenConverted() {
Collection<String> animals = Arrays.asList("Dog", "Cat", "Cow", "Bird", "Moose", "Pig");
Collection<String> result1 = new ArrayList<>();
Collection<String> result2 = new ArrayList<>();
AtomicInteger count = new AtomicInteger();
int midpoint = Math.round(animals.size() / 2);
animals.forEach(next -> {
int index = count.getAndIncrement();
if (index < midpoint) {
result1.add(next);
} else {
result2.add(next);
}
});
assertTrue(result1.equals(Arrays.asList("Dog", "Cat", "Cow")));
assertTrue(result2.equals(Arrays.asList("Bird", "Moose", "Pig")));
}
@Test
public void whenSplitArrayByWordLength_thenConverted() {
String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow", "Pig", "Moose" };
Map<Integer, List<String>> result = Arrays.stream(animals).collect(Collectors.groupingBy(String::length));
assertTrue(result.get(3).equals(Arrays.asList("Dog", "Cat", "Cow", "Pig")));
assertTrue(result.get(4).equals(Arrays.asList("Bird")));
assertTrue(result.get(5).equals(Arrays.asList("Moose")));
}
@Test
public void whenConvertStringToArray_thenConverted() {
String animals = "Dog, Cat, Bird, Cow";
String[] result = animals.split(", ");
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
}
@Test
public void whenConvertStringToCollection_thenConverted() {
String animals = "Dog, Cat, Bird, Cow";
Collection<String> result = Arrays.asList(animals.split(", "));
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow")));
}
@Test
public void whenConvertStringToMap_thenConverted() {
String animals = "1 = Dog, 2 = Cat, 3 = Bird";
Map<Integer, String> result = Arrays.stream(animals.split(", ")).map(next -> next.split(" = ")).collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1]));
assertEquals(result.get(1), "Dog");
assertEquals(result.get(2), "Cat");
assertEquals(result.get(3), "Bird");
}
@Test
public void whenConvertCollectionToStringMultipleSeparators_thenConverted() {
String animals = "Dog. , Cat, Bird. Cow";
Collection<String> result = Arrays.stream(animals.split("[,|.]")).map(String::trim).filter(next -> !next.isEmpty()).collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow")));
}
}

View File

@ -1,7 +1,9 @@
package org.baeldung.java.io;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertTrue;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
@ -9,17 +11,28 @@ import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertTrue;
public class JavaFileUnitTest {
// create a file
private static final String TEMP_DIR = "src/test/resources/temp" + UUID.randomUUID().toString();
@BeforeClass
public static void setup() throws IOException {
Files.createDirectory(Paths.get(TEMP_DIR));
}
@AfterClass
public static void cleanup() throws IOException {
FileUtils.deleteDirectory(new File(TEMP_DIR));
}
@Test
public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
final File newFile = new File("src/test/resources/newFile_jdk6.txt");
final File newFile = new File(TEMP_DIR + "/newFile_jdk6.txt");
final boolean success = newFile.createNewFile();
assertTrue(success);
@ -27,48 +40,48 @@ public class JavaFileUnitTest {
@Test
public final void givenUsingJDK7nio2_whenCreatingFile_thenCorrect() throws IOException {
final Path newFilePath = Paths.get("src/test/resources/newFile_jdk7.txt");
final Path newFilePath = Paths.get(TEMP_DIR + "/newFile_jdk7.txt");
Files.createFile(newFilePath);
}
@Test
public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt"));
FileUtils.touch(new File(TEMP_DIR + "/newFile_commonsio.txt"));
}
@Test
public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
com.google.common.io.Files.touch(new File("src/test/resources/newFile_guava.txt"));
com.google.common.io.Files.touch(new File(TEMP_DIR + "/newFile_guava.txt"));
}
// move a file
@Test
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt");
final File fileToMove = new File(TEMP_DIR + "/toMoveFile_jdk6.txt");
fileToMove.createNewFile();// .exists();
final File destDir = new File("src/test/resources/");
final File destDir = new File(TEMP_DIR + "/");
destDir.mkdir();
final boolean isMoved = fileToMove.renameTo(new File("src/test/resources/movedFile_jdk6.txt"));
final boolean isMoved = fileToMove.renameTo(new File(TEMP_DIR + "/movedFile_jdk6.txt"));
if (!isMoved) {
throw new FileSystemException("src/test/resources/movedFile_jdk6.txt");
throw new FileSystemException(TEMP_DIR + "/movedFile_jdk6.txt");
}
}
@Test
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt"));
final Path targetPath = Paths.get("src/main/resources/");
final Path fileToMovePath = Files.createFile(Paths.get(TEMP_DIR + "/" + randomAlphabetic(5) + ".txt"));
final Path targetPath = Paths.get(TEMP_DIR + "/");
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
}
@Test
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
final File fileToMove = new File("src/test/resources/fileToMove.txt");
final File fileToMove = new File(TEMP_DIR + "/fileToMove.txt");
fileToMove.createNewFile();
final File destDir = new File("src/main/resources/");
final File destDir = new File(TEMP_DIR + "/temp");
final File targetFile = new File(destDir, fileToMove.getName());
com.google.common.io.Files.createParentDirs(targetFile);
com.google.common.io.Files.move(fileToMove, targetFile);
@ -76,23 +89,24 @@ public class JavaFileUnitTest {
@Test
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt"));
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
FileUtils.moveFile(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/fileMoved_apache2.txt"));
}
@Test
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true);
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
Files.createDirectory(Paths.get(TEMP_DIR + "/temp"));
FileUtils.moveFileToDirectory(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/temp"), true);
}
// delete a file
@Test
public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException {
new File("src/test/resources/fileToDelete_jdk6.txt").createNewFile();
new File(TEMP_DIR + "/fileToDelete_jdk6.txt").createNewFile();
final File fileToDelete = new File("src/test/resources/fileToDelete_jdk6.txt");
final File fileToDelete = new File(TEMP_DIR + "/fileToDelete_jdk6.txt");
final boolean success = fileToDelete.delete();
assertTrue(success);
@ -100,17 +114,17 @@ public class JavaFileUnitTest {
@Test
public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt"));
Files.createFile(Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt"));
final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt");
final Path fileToDeletePath = Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt");
Files.delete(fileToDeletePath);
}
@Test
public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/fileToDelete_commonsIo.txt"));
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete_commonsIo.txt"));
final File fileToDelete = FileUtils.getFile("src/test/resources/fileToDelete_commonsIo.txt");
final File fileToDelete = FileUtils.getFile(TEMP_DIR + "/fileToDelete_commonsIo.txt");
final boolean success = FileUtils.deleteQuietly(fileToDelete);
assertTrue(success);
@ -118,9 +132,9 @@ public class JavaFileUnitTest {
@Test
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/fileToDelete.txt"));
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete.txt"));
FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt"));
FileUtils.forceDelete(FileUtils.getFile(TEMP_DIR + "/fileToDelete.txt"));
}
}

View File

@ -0,0 +1,55 @@
package org.baeldung.java.sorting;
public class Employee implements Comparable {
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
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;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public boolean equals(Object obj) {
return ((Employee) obj).getName().equals(getName());
}
@Override
public int compareTo(Object o) {
Employee e = (Employee) o;
return getName().compareTo(e.getName());
}
@Override
public String toString() {
return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString();
}
}

View File

@ -0,0 +1,186 @@
package org.baeldung.java.sorting;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Before;
import org.junit.Test;
import com.google.common.primitives.Ints;
public class JavaSorting {
private int[] toSort;
private int[] sortedInts;
private int[] sortedRangeInts;
// private Integer [] integers;
// private Integer [] sortedIntegers;
// private List<Integer> integersList;
// private List<Integer> sortedIntegersList;
private Employee[] employees;
private Employee[] employeesSorted;
private Employee[] employeesSortedByAge;
private HashMap<Integer, String> map;
@Before
public void initVariables() {
toSort = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 };
sortedInts = new int[] { 1, 5, 7, 66, 88, 89, 123, 200, 255 };
sortedRangeInts = new int[] { 5, 1, 89, 7, 88, 200, 255, 123, 66 };
// integers = new Integer[]
// { 5, 1, 89, 255, 7, 88, 200, 123, 66 };
// sortedIntegers = new Integer[]
// {1, 5, 7, 66, 88, 89, 123, 200, 255};
//
// integersList = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 });
// sortedIntegersList = Arrays.asList(new Integer[] {1, 5, 7, 66, 88, 89, 123, 200, 255});
employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) };
employeesSorted = new Employee[] { new Employee("Earl", 43, 10000), new Employee("Frank", 33, 70000), new Employee("Jessica", 23, 4000), new Employee("John", 23, 5000), new Employee("Pearl", 33, 4000), new Employee("Steve", 26, 6000) };
employeesSortedByAge = new Employee[] { new Employee("John", 23, 5000), new Employee("Jessica", 23, 4000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 70000), new Employee("Pearl", 33, 4000), new Employee("Earl", 43, 10000) };
HashMap<Integer, String> map = new HashMap<>();
map.put(55, "John");
map.put(22, "Apple");
map.put(66, "Earl");
map.put(77, "Pearl");
map.put(12, "George");
map.put(6, "Rocky");
}
@Test
public void givenIntArray_whenUsingSort_thenSortedArray() {
Arrays.sort(toSort);
assertTrue(Arrays.equals(toSort, sortedInts));
}
@Test
public void givenIntegerArray_whenUsingSort_thenSortedArray() {
Integer[] integers = ArrayUtils.toObject(toSort);
Arrays.sort(integers, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return a - b;
}
});
assertTrue(Arrays.equals(integers, ArrayUtils.toObject(sortedInts)));
}
@Test
public void givenArray_whenUsingSortWithLambdas_thenSortedArray() {
Integer[] integersToSort = ArrayUtils.toObject(toSort);
Arrays.sort(integersToSort, (a, b) -> {
return a - b;
});
assertTrue(Arrays.equals(integersToSort, ArrayUtils.toObject(sortedInts)));
}
@Test
public void givenEmpArray_SortEmpArray_thenSortedArrayinNaturalOrder() {
Arrays.sort(employees);
assertTrue(Arrays.equals(employees, employeesSorted));
}
@Test
public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() {
Arrays.sort(toSort, 3, 7);
assertTrue(Arrays.equals(toSort, sortedRangeInts));
}
@Test
public void givenIntArray_whenUsingParallelSort_thenArraySorted() {
Arrays.parallelSort(toSort);
assertTrue(Arrays.equals(toSort, sortedInts));
}
@Test
public void givenArrayObjects_whenUsingComparing_thenSortedArrayObjects() {
List<Employee> employeesList = Arrays.asList(employees);
employeesList.sort(Comparator.comparing(Employee::getAge));// .thenComparing(Employee::getName));
assertTrue(Arrays.equals(employeesList.toArray(), employeesSortedByAge));
}
@Test
public void givenList_whenUsingSort_thenSortedList() {
List<Integer> toSortList = Ints.asList(toSort);
Collections.sort(toSortList);
assertTrue(Arrays.equals(toSortList.toArray(), ArrayUtils.toObject(sortedInts)));
}
@Test
public void givenMap_whenSortingByKeys_thenSortedMap() {
Integer[] sortedKeys = new Integer[] { 6, 12, 22, 55, 66, 77 };
List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
Collections.sort(entries, new Comparator<Entry<Integer, String>>() {
@Override
public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
for (Map.Entry<Integer, String> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys));
}
@Test
public void givenMap_whenSortingByValues_thenSortedMap() {
String[] sortedValues = new String[] { "Apple", "Earl", "George", "John", "Pearl", "Rocky" };
List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
Collections.sort(entries, new Comparator<Entry<Integer, String>>() {
@Override
public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
for (Map.Entry<Integer, String> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues));
}
@Test
public void givenSet_whenUsingSort_thenSortedSet() {
HashSet<Integer> integersSet = new LinkedHashSet<>(Ints.asList(toSort));
HashSet<Integer> descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(new Integer[] { 255, 200, 123, 89, 88, 66, 7, 5, 1 }));
ArrayList<Integer> list = new ArrayList<Integer>(integersSet);
Collections.sort(list, (i1, i2) -> {
return i2 - i1;
});
integersSet = new LinkedHashSet<>(list);
assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
baeldung.com

View File

@ -79,10 +79,10 @@
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
@ -100,14 +100,15 @@
</build>
<properties>
<java.version>1.7</java.version>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<couchbase.client.version>2.2.6</couchbase.client.version>
<spring-framework.version>4.2.4.RELEASE</spring-framework.version>
<logback.version>1.1.3</logback.version>
<org.slf4j.version>1.7.12</org.slf4j.version>
<junit.version>4.11</junit.version>
<commons-lang3.version>3.4</commons-lang3.version>
<couchbase.client.version>2.3.6</couchbase.client.version>
<spring-framework.version>4.3.4.RELEASE</spring-framework.version>
<logback.version>1.1.7</logback.version>
<org.slf4j.version>1.7.21</org.slf4j.version>
<junit.version>4.12</junit.version>
<commons-lang3.version>3.5</commons-lang3.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>

View File

@ -25,17 +25,22 @@
resources, i.e. build is platform dependent! -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<slf4j.version>1.7.21</slf4j.version>
<querydsl.version>3.7.4</querydsl.version>
<deltaspike.version>1.7.2</deltaspike.version>
<!-- JBoss dependency versions -->
<version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>
<wildfly.maven.plugin.version>1.0.2.Final</wildfly.maven.plugin.version>
<!-- Define the version of the JBoss BOMs we want to import to specify
tested stacks. -->
<version.jboss.bom>8.2.1.Final</version.jboss.bom>
<jboss.bom.version>8.2.2.Final</jboss.bom.version>
<!-- other plugin versions -->
<version.compiler.plugin>3.1</version.compiler.plugin>
<version.surefire.plugin>2.16</version.surefire.plugin>
<version.war.plugin>2.5</version.war.plugin>
<version.compiler.plugin>3.6.0</version.compiler.plugin>
<surefire.plugin.version>2.19.1</surefire.plugin.version>
<war.plugin.version>2.6</war.plugin.version>
<apt-maven-plugin.version>1.1.3</apt-maven-plugin.version>
<!-- maven-compiler-plugin -->
<maven.compiler.target>1.7</maven.compiler.target>
@ -56,14 +61,14 @@
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
<version>${version.jboss.bom}</version>
<version>${jboss.bom.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
<version>${version.jboss.bom}</version>
<version>${jboss.bom.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -187,14 +192,14 @@
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-data-module-api</artifactId>
<version>1.7.1</version>
<version>${deltaspike.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-data-module-impl</artifactId>
<version>1.7.1</version>
<version>${deltaspike.version}</version>
<scope>runtime</scope>
</dependency>
@ -202,20 +207,20 @@
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>3.7.4</version>
<version>${querydsl.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>3.7.4</version>
<version>${querydsl.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
@ -226,7 +231,7 @@
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<version>${war.plugin.version}</version>
<configuration>
<!-- Java EE 7 doesn't require web.xml, Maven needs to catch up! -->
<failOnMissingWebXml>false</failOnMissingWebXml>
@ -235,7 +240,7 @@
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.0.9</version>
<version>${apt-maven-plugin.version}</version>
<executions>
<execution>
<goals>
@ -253,7 +258,7 @@
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>${version.wildfly.maven.plugin}</version>
<version>${wildfly.maven.plugin.version}</version>
</plugin>
</plugins>
</build>
@ -272,7 +277,7 @@
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${version.surefire.plugin}</version>
<version>${surefire.plugin.version}</version>
<configuration>
<skip>true</skip>
</configuration>

View File

@ -13,7 +13,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>7</source>
<target>7</target>
@ -26,33 +26,41 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.5</version>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.2.1</version>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.5.1</version>
<version>${dozer.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.3</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<slf4j.version>1.7.21</slf4j.version>
<commons-lang3.version>3.5</commons-lang3.version>
<dozer.version>5.5.1</dozer.version>
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
</project>

53
ejb/ejb-client/pom.xml Executable file
View File

@ -0,0 +1,53 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-client</artifactId>
<name>EJB3 Client Maven</name>
<description>EJB3 Client Maven</description>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb-remote</artifactId>
<type>ejb</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*EJBSetupTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,70 @@
package com.baeldung.ejb.client;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.baeldung.ejb.tutorial.HelloWorld;
public class EJBClient {
public EJBClient() {
}
private Context context = null;
public String getEJBRemoteMessage() {
EJBClient main = new EJBClient();
try {
// 1. Obtaining Context
main.createInitialContext();
// 2. Generate JNDI Lookup name and caste
HelloWorld helloWorld = main.lookup();
return helloWorld.getHelloWorld();
} catch (NamingException e) {
e.printStackTrace();
return "";
} finally {
try {
main.closeContext();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
public HelloWorld lookup() throws NamingException {
// The app name is the EAR name of the deployed EJB without .ear suffix.
// Since we haven't deployed the application as a .ear, the app name for
// us will be an empty string
final String appName = "";
final String moduleName = "remote";
final String distinctName = "";
final String beanName = "HelloWorld";
final String viewClassName = HelloWorld.class.getName();
final String toLookup = String.format("ejb:%s/%s/%s/%s!%s", appName, moduleName, distinctName, beanName, viewClassName);
return (HelloWorld) context.lookup(toLookup);
}
public void createInitialContext() throws NamingException {
Properties prop = new Properties();
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
prop.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:8080");
prop.put(Context.SECURITY_PRINCIPAL, "testUser");
prop.put(Context.SECURITY_CREDENTIALS, "admin1234!");
prop.put("jboss.naming.client.ejb.context", false);
context = new InitialContext(prop);
}
public void closeContext() throws NamingException {
if (context != null) {
context.close();
}
}
}

View File

@ -0,0 +1,8 @@
remote.connections=default
remote.connection.default.host=127.0.0.1
remote.connection.default.port=8080
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER}
remote.connection.default.username=testUser
remote.connection.default.password=admin1234!

View File

@ -0,0 +1,16 @@
package com.baeldung.ejb.setup.test;
import static org.junit.Assert.*;
import org.junit.Test;
import com.baeldung.ejb.client.EJBClient;
import com.baeldung.ejb.tutorial.HelloWorldBean;
public class EJBSetupTest {
@Test
public void testEJBClient() {
EJBClient ejbClient = new EJBClient();
HelloWorldBean bean = new HelloWorldBean();
assertEquals(bean.getHelloWorld(), ejbClient.getEJBRemoteMessage());
}
}

45
ejb/ejb-remote/pom.xml Executable file
View File

@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-remote</artifactId>
<packaging>ejb</packaging>
<!-- <name>ejb-remote</name> -->
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>${wildfly-maven-plugin.version}</version>
<configuration>
<hostname>127.0.0.1</hostname>
<port>9990</port>
<username>testUser</username>
<password>admin1234!</password>
<filename>${build.finalName}.jar</filename>
</configuration>
</plugin>
</plugins>
<!-- <finalName>ejb-remote</finalName> -->
</build>
<properties>
<javaee-api.version>7.0</javaee-api.version>
<wildfly-maven-plugin.version>1.1.0.Beta1</wildfly-maven-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,8 @@
package com.baeldung.ejb.tutorial;
import javax.ejb.Remote;
@Remote
public interface HelloWorld {
String getHelloWorld();
}

View File

@ -0,0 +1,19 @@
package com.baeldung.ejb.tutorial;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
@Stateless(name = "HelloWorld")
public class HelloWorldBean implements HelloWorld {
@Resource
private SessionContext context;
@Override
public String getHelloWorld() {
return "Welcome to EJB Tutorial!";
}
}

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd"
version="3.2">
<module-name>remote</module-name>
</ejb-jar>

89
ejb/pom.xml Executable file
View File

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>ejb</name>
<description>EJB Tutorial</description>
<repositories>
<repository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Maven Repository Group</name>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb-remote</artifactId>
<version>1.0-SNAPSHOT</version>
<type>ejb</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId>
<version>${wildfly.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-ejb-plugin</artifactId>
<version>${maven-ejb-plugin.version}</version>
<configuration>
<ejbVersion>3.2</ejbVersion>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>ejb-remote</module>
<module>ejb-client</module>
</modules>
<properties>
<javaee-api.version>7.0</javaee-api.version>
<wildfly.version>10.1.0.Final</wildfly.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-ejb-plugin.version>2.5.1</maven-ejb-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,25 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class AuditFilter extends BaseFilter {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpSession session = httpServletRequest.getSession(false);
if (session != null && session.getAttribute("username") != null) {
request.setAttribute("username", session.getAttribute("username"));
}
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(servletNames = "front-controller")
public class VisitorCounterFilter extends BaseFilter {
private int counter;
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
request.setAttribute("counter", ++counter);
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.enterprise.patterns</groupId>
<artifactId>enterprise-patterns-parent</artifactId>
<packaging>pom</packaging>
<modules>
<module>spring-dispatcher-servlet</module>
</modules>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<build>
<pluginManagement>
<plugins>
<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>
</pluginManagement>
</build>
<properties>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -16,54 +16,62 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<feign.version>9.4.0</feign.version>
<slf4j.version>1.7.21</slf4j.version>
<log4j.version>2.7</log4j.version>
<lombok.version>1.16.12</lombok.version>
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<spring-boot-maven-plugin.version>1.4.2.RELEASE</spring-boot-maven-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>9.3.1</version>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>9.3.1</version>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
<version>9.3.1</version>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>9.3.1</version>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6.2</version>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.6.2</version>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -74,7 +82,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@ -83,7 +91,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
@ -91,9 +99,10 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.0.RELEASE</version>
<version>${spring-boot-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -10,7 +10,7 @@
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
<version>${mysql.version}</version>
</dependency>
</dependencies>
<build>
@ -18,12 +18,12 @@
<plugin>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>4.0.3</version>
<version>${flyway-maven-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@ -31,4 +31,9 @@
</plugin>
</plugins>
</build>
<properties>
<mysql.version>6.0.5</mysql.version>
<flyway-maven-plugin.version>4.0.3</flyway-maven-plugin.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -13,7 +13,7 @@
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.4</version>
<version>${joda-time.version}</version>
</dependency>
<dependency>
@ -24,13 +24,13 @@
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
@ -39,8 +39,6 @@
<version>${commons-lang3.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
<dependency>
@ -112,40 +110,24 @@
</build>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<!-- marshalling -->
<gson.version>2.3</gson.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<gson.version>2.8.0</gson.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-io.version>2.5</commons-io.version>
<joda-time.version>2.9.6</joda-time.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>

View File

@ -19,7 +19,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
@ -28,8 +28,6 @@
<version>${commons-lang3.version}</version>
</dependency>
<!-- web -->
<!-- test scoped -->
<dependency>
@ -93,37 +91,19 @@
</build>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>

View File

@ -11,13 +11,13 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -26,7 +26,7 @@
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<debug>true</debug>
<optimize>true</optimize>
@ -39,5 +39,10 @@
</plugin>
</plugins>
</build>
<properties>
<guava.version>18.0</guava.version>
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -17,13 +17,13 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -32,7 +32,7 @@
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<debug>true</debug>
<optimize>true</optimize>
@ -48,6 +48,9 @@
<properties>
<guava.version>19.0</guava.version>
<junit.version>4.12</junit.version>
<hamcrest.version>1.3</hamcrest.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
</project>

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