Merge remote-tracking branch 'upstream/master'

This commit is contained in:
tschiman 2016-12-19 23:02:13 -07:00
commit 49970912ea
146 changed files with 181396 additions and 818 deletions

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

@ -0,0 +1,20 @@
<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>
<artifactId>cxf-aegis</artifactId>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<cxf.version>3.1.8</cxf.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-databinding-aegis</artifactId>
<version>${cxf.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,42 @@
package com.baeldung.cxf.aegis;
import java.util.Date;
public class Course {
private int id;
private String name;
private String instructor;
private Date enrolmentDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInstructor() {
return instructor;
}
public void setInstructor(String instructor) {
this.instructor = instructor;
}
public Date getEnrolmentDate() {
return enrolmentDate;
}
public void setEnrolmentDate(Date enrolmentDate) {
this.enrolmentDate = enrolmentDate;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.cxf.aegis;
import java.util.Map;
public interface CourseRepo {
String getGreeting();
void setGreeting(String greeting);
Map<Integer, Course> getCourses();
void setCourses(Map<Integer, Course> courses);
void addCourse(Course course);
}

View File

@ -0,0 +1,34 @@
package com.baeldung.cxf.aegis;
import java.util.HashMap;
import java.util.Map;
public class CourseRepoImpl implements CourseRepo {
private String greeting;
private Map<Integer, Course> courses = new HashMap<>();
@Override
public String getGreeting() {
return greeting;
}
@Override
public void setGreeting(String greeting) {
this.greeting = greeting;
}
@Override
public Map<Integer, Course> getCourses() {
return courses;
}
@Override
public void setCourses(Map<Integer, Course> courses) {
this.courses = courses;
}
@Override
public void addCourse(Course course) {
courses.put(course.getId(), course);
}
}

View File

@ -0,0 +1,5 @@
<mappings>
<mapping>
<property name="instructor" ignore="true"/>
</mapping>
</mappings>

View File

@ -0,0 +1,5 @@
<mappings xmlns:ns="http://courserepo.baeldung.com">
<mapping name="ns:Baeldung">
<property name="greeting" style="attribute"/>
</mapping>
</mappings>

View File

@ -0,0 +1,93 @@
package com.baeldung.cxf.aegis;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.apache.cxf.aegis.AegisContext;
import org.apache.cxf.aegis.AegisReader;
import org.apache.cxf.aegis.AegisWriter;
import org.apache.cxf.aegis.type.AegisType;
public class BaeldungTest {
private AegisContext context;
private String fileName = "baeldung.xml";
@Test
public void whenMarshalingAndUnmarshalingCourseRepo_thenCorrect() throws Exception {
initializeContext();
CourseRepo inputRepo = initCourseRepo();
marshalCourseRepo(inputRepo);
CourseRepo outputRepo = unmarshalCourseRepo();
Course restCourse = outputRepo.getCourses().get(1);
Course securityCourse = outputRepo.getCourses().get(2);
assertEquals("Welcome to Beldung!", outputRepo.getGreeting());
assertEquals("REST with Spring", restCourse.getName());
assertEquals(new Date(1234567890000L), restCourse.getEnrolmentDate());
assertNull(restCourse.getInstructor());
assertEquals("Learn Spring Security", securityCourse.getName());
assertEquals(new Date(1456789000000L), securityCourse.getEnrolmentDate());
assertNull(securityCourse.getInstructor());
}
private void initializeContext() {
context = new AegisContext();
Set<Type> rootClasses = new HashSet<Type>();
rootClasses.add(CourseRepo.class);
context.setRootClasses(rootClasses);
Map<Class<?>, String> beanImplementationMap = new HashMap<>();
beanImplementationMap.put(CourseRepoImpl.class, "CourseRepo");
context.setBeanImplementationMap(beanImplementationMap);
context.setWriteXsiTypes(true);
context.initialize();
}
private CourseRepoImpl initCourseRepo() {
Course restCourse = new Course();
restCourse.setId(1);
restCourse.setName("REST with Spring");
restCourse.setInstructor("Eugen");
restCourse.setEnrolmentDate(new Date(1234567890000L));
Course securityCourse = new Course();
securityCourse.setId(2);
securityCourse.setName("Learn Spring Security");
securityCourse.setInstructor("Eugen");
securityCourse.setEnrolmentDate(new Date(1456789000000L));
CourseRepoImpl courseRepo = new CourseRepoImpl();
courseRepo.setGreeting("Welcome to Beldung!");
courseRepo.addCourse(restCourse);
courseRepo.addCourse(securityCourse);
return courseRepo;
}
private void marshalCourseRepo(CourseRepo courseRepo) throws Exception {
AegisWriter<XMLStreamWriter> writer = context.createXMLStreamWriter();
AegisType aegisType = context.getTypeMapping().getType(CourseRepo.class);
XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(fileName));
writer.write(courseRepo, new QName("http://aegis.cxf.baeldung.com", "baeldung"), false, xmlWriter, aegisType);
xmlWriter.close();
}
private CourseRepo unmarshalCourseRepo() throws Exception {
AegisReader<XMLStreamReader> reader = context.createXMLStreamReader();
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(fileName));
CourseRepo courseRepo = (CourseRepo) reader.read(xmlReader, context.getTypeMapping().getType(CourseRepo.class));
xmlReader.close();
return courseRepo;
}
}

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

@ -10,6 +10,7 @@
<module>cxf-introduction</module> <module>cxf-introduction</module>
<module>cxf-spring</module> <module>cxf-spring</module>
<module>cxf-jaxrs-implementation</module> <module>cxf-jaxrs-implementation</module>
<module>cxf-aegis</module>
</modules> </modules>
<properties> <properties>

View File

@ -3,3 +3,6 @@
## Core Java 9 Examples ## Core Java 9 Examples
[Java 9 New Features](http://www.baeldung.com/new-java-9) [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

@ -14,3 +14,5 @@
# Files generated by integration tests # Files generated by integration tests
*.txt *.txt
/bin/
/temp

View File

@ -39,3 +39,10 @@
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) - [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) - [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) - [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,289 +1,314 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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"> 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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>core-java</artifactId> <artifactId>core-java</artifactId>
<version>0.1.0-SNAPSHOT</version> <version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>core-java</name> <name>core-java</name>
<dependencies> <dependencies>
<!-- utils --> <!-- utils -->
<dependency> <dependency>
<groupId>net.sourceforge.collections</groupId> <groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId> <artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version> <version>${collections-generic.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>${guava.version}</version> <version>${guava.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId> <artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version> <version>${commons-collections4.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>${commons-io.version}</version> <version>${commons-io.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version> <version>${commons-lang3.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId> <artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version> <version>${commons-math3.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bouncycastle</groupId> <groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId> <artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version> <version>${bouncycastle.version}</version>
</dependency> </dependency>
<!-- web -->
<!-- marshalling --> <dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.googlecode.grep4j</groupId>
<artifactId>jackson-databind</artifactId> <artifactId>grep4j</artifactId>
<version>${jackson.version}</version> <version>${grep4j.version}</version>
</dependency> </dependency>
<!-- web -->
<!-- logging --> <!-- marshalling -->
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>jackson-databind</artifactId>
<version>${org.slf4j.version}</version> <version>${jackson.version}</version>
</dependency> </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>
<!-- test scoped --> <!-- logging -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.slf4j</groupId>
<artifactId>junit</artifactId> <artifactId>slf4j-api</artifactId>
<version>${junit.version}</version> <version>${org.slf4j.version}</version>
<scope>test</scope> </dependency>
</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> <!-- test scoped -->
<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> <dependency>
<groupId>org.assertj</groupId> <groupId>org.hamcrest</groupId>
<artifactId>assertj-core</artifactId> <artifactId>hamcrest-all</artifactId>
<version>${assertj.version}</version> <version>1.3</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.testng</groupId> <groupId>junit</groupId>
<artifactId>testng</artifactId> <artifactId>junit</artifactId>
<version>${testng.version}</version> <version>${junit.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.hamcrest</groupId>
<artifactId>mockito-core</artifactId> <artifactId>hamcrest-core</artifactId>
<version>${mockito.version}</version> <version>${org.hamcrest.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>org.assertj</groupId>
<artifactId>commons-codec</artifactId> <artifactId>assertj-core</artifactId>
<version>${commons-codec.version}</version> <version>${assertj.version}</version>
</dependency> <scope>test</scope>
</dependency>
</dependencies> <dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<build> <dependency>
<finalName>core-java</finalName> <groupId>org.mockito</groupId>
<resources> <artifactId>mockito-core</artifactId>
<resource> <version>${mockito.version}</version>
<directory>src/main/resources</directory> <scope>test</scope>
<filtering>true</filtering> </dependency>
</resource>
</resources>
<plugins> <dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<plugin> </dependencies>
<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> <build>
<groupId>org.apache.maven.plugins</groupId> <finalName>core-java</finalName>
<artifactId>maven-surefire-plugin</artifactId> <resources>
<version>${maven-surefire-plugin.version}</version> <resource>
<configuration> <directory>src/main/resources</directory>
<excludes> <filtering>true</filtering>
<exclude>**/*IntegrationTest.java</exclude> </resource>
</resources>
<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>
<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>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude> <exclude>**/*ManualTest.java</exclude>
</excludes> </excludes>
</configuration> <testFailureIgnore>true</testFailureIgnore>
</plugin> </configuration>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<id>copy-dependencies</id> <id>copy-dependencies</id>
<phase>prepare-package</phase> <phase>prepare-package</phase>
<goals> <goals>
<goal>copy-dependencies</goal> <goal>copy-dependencies</goal>
</goals> </goals>
<configuration> <configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory> <outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>
<addClasspath>true</addClasspath> <addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix> <classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest> </manifest>
</archive> </archive>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>single</goal> <goal>single</goal>
</goals> </goals>
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest> </manifest>
</archive> </archive>
<descriptorRefs> <descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef> <descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs> </descriptorRefs>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>shade</goal> <goal>shade</goal>
</goals> </goals>
<configuration> <configuration>
<shadedArtifactAttached>true</shadedArtifactAttached> <shadedArtifactAttached>true</shadedArtifactAttached>
<transformers> <transformers>
<transformer <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> </transformer>
</transformer> </transformers>
</transformers> </configuration>
</configuration> </execution>
</execution> </executions>
</executions> </plugin>
</plugin>
<plugin> <plugin>
<groupId>com.jolira</groupId> <groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId> <artifactId>onejar-maven-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<configuration> <configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild> <attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename> <filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration> </configuration>
<goals> <goals>
<goal>one-jar</goal> <goal>one-jar</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>repackage</goal> <goal>repackage</goal>
</goals> </goals>
<configuration> <configuration>
<classifier>spring-boot</classifier> <classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<profiles> <profiles>
<profile> <profile>
<id>integration</id> <id>integration</id>
<build> <build>
@ -318,35 +343,38 @@
</profile> </profile>
</profiles> </profiles>
<properties> <properties>
<!-- marshalling --> <!-- marshalling -->
<jackson.version>2.8.5</jackson.version> <jackson.version>2.8.5</jackson.version>
<!-- logging --> <!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version> <org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version> <logback.version>1.1.7</logback.version>
<!-- util --> <!-- util -->
<guava.version>19.0</guava.version> <guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version> <bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version> <commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version> <commons-math3.version>3.6.1</commons-math3.version>
<commons-io.version>2.5</commons-io.version> <commons-io.version>2.5</commons-io.version>
<commons-collections4.version>4.1</commons-collections4.version> <commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.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>
<!-- testing --> <!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version> <org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version> <mockito.version>1.10.19</mockito.version>
<testng.version>6.10</testng.version> <testng.version>6.10</testng.version>
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<!-- maven plugins --> <!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-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-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties> </properties>
</project> </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,40 @@
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 < bestDistance) {
bestDistance = currentDistance;
} else if (Math.exp((bestDistance - currentDistance) / 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,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,2 @@
### Relevant Articles:
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)

View File

@ -0,0 +1,48 @@
package com.baeldung.scripting;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Nashorn {
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Object result = engine.eval(
"var greeting='hello world';" +
"print(greeting);" +
"greeting");
System.out.println(result);
Bindings bindings = engine.createBindings();
bindings.put("count", 3);
bindings.put("name", "baeldung");
String script = "var greeting='Hello ';" +
"for(var i=count;i>0;i--) { " +
"greeting+=name + ' '" +
"}" +
"greeting";
Object bindingsResult = engine.eval(script, bindings);
System.out.println(bindingsResult);
engine.eval("function composeGreeting(name) {" +
"return 'Hello ' + name" +
"}");
Invocable invocable = (Invocable) engine;
Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung");
System.out.println(funcResult);
Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" +
"var map = new HashMap();" +
"map.put('hello', 'world');" +
"map");
System.out.println(map);
}
}

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

@ -22,7 +22,6 @@ public class EncoderDecoderUnitTest {
private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253"; 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 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) { private String encodeValue(String value) {
String encoded = null; String encoded = null;
try { try {
@ -59,9 +58,7 @@ public class EncoderDecoderUnitTest {
requestParams.put("key2", "value@!$2"); requestParams.put("key2", "value@!$2");
requestParams.put("key3", "value%3"); requestParams.put("key3", "value%3");
String encodedURL = requestParams.keySet().stream() String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
.collect(joining("&", "http://www.baeldung.com?", ""));
Assert.assertThat(testUrl, is(encodedURL)); Assert.assertThat(testUrl, is(encodedURL));
} }
@ -103,12 +100,9 @@ public class EncoderDecoderUnitTest {
String path = "path+1"; String path = "path+1";
String encodedURL = requestParams.keySet().stream() String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com/" + encodePath(path) + "?", ""));
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
.collect(joining("&", "http://www.baeldung.com/" + encodePath(path) + "?", ""));
Assert.assertThat(testUrlWithPath, is(encodedURL)); Assert.assertThat(testUrlWithPath, is(encodedURL));
} }
} }

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

@ -17,9 +17,7 @@ public class Java8CollectionCleanupUnitTest {
@Test @Test
public void givenListContainsNulls_whenFilteringParallel_thenCorrect() { public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null); final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
final List<Integer> listWithoutNulls = list.parallelStream() final List<Integer> listWithoutNulls = list.parallelStream().filter(Objects::nonNull).collect(Collectors.toList());
.filter(Objects::nonNull)
.collect(Collectors.toList());
assertThat(listWithoutNulls, hasSize(3)); assertThat(listWithoutNulls, hasSize(3));
} }
@ -27,9 +25,7 @@ public class Java8CollectionCleanupUnitTest {
@Test @Test
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() { public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null); final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
final List<Integer> listWithoutNulls = list.stream() final List<Integer> listWithoutNulls = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
.filter(Objects::nonNull)
.collect(Collectors.toList());
assertThat(listWithoutNulls, hasSize(3)); assertThat(listWithoutNulls, hasSize(3));
} }
@ -45,9 +41,7 @@ public class Java8CollectionCleanupUnitTest {
@Test @Test
public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() { public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() {
final List<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3); final List<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3);
final List<Integer> listWithoutDuplicates = listWithDuplicates.parallelStream() final List<Integer> listWithoutDuplicates = listWithDuplicates.parallelStream().distinct().collect(Collectors.toList());
.distinct()
.collect(Collectors.toList());
assertThat(listWithoutDuplicates, hasSize(3)); assertThat(listWithoutDuplicates, 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

@ -93,6 +93,7 @@ public class OptionalTest {
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent(); boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
assertFalse(is2017); assertFalse(is2017);
} }
@Test @Test
public void whenFiltersWithoutOptional_thenCorrect() { public void whenFiltersWithoutOptional_thenCorrect() {
assertTrue(priceIsInRange1(new Modem(10.0))); assertTrue(priceIsInRange1(new Modem(10.0)));
@ -121,12 +122,9 @@ public class OptionalTest {
} }
public boolean priceIsInRange2(Modem modem2) { public boolean priceIsInRange2(Modem modem2) {
return Optional.ofNullable(modem2) return Optional.ofNullable(modem2).map(Modem::getPrice).filter(p -> p >= 10).filter(p -> p <= 15).isPresent();
.map(Modem::getPrice)
.filter(p -> p >= 10)
.filter(p -> p <= 15)
.isPresent();
} }
// Transforming Value With map() // Transforming Value With map()
@Test @Test
public void givenOptional_whenMapWorks_thenCorrect() { public void givenOptional_whenMapWorks_thenCorrect() {

View File

@ -2,6 +2,9 @@ package org.baeldung.java.collections;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Lists; 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.Assert;
import org.junit.Test; import org.junit.Test;
@ -107,4 +110,26 @@ public class CollectionsConcatenateUnitTest {
} }
return list; 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

@ -15,8 +15,7 @@ public class JoinSplitCollectionsUnitTest {
public void whenJoiningTwoArrays_thenJoined() { public void whenJoiningTwoArrays_thenJoined() {
String[] animals1 = new String[] { "Dog", "Cat" }; String[] animals1 = new String[] { "Dog", "Cat" };
String[] animals2 = new String[] { "Bird", "Cow" }; String[] animals2 = new String[] { "Bird", "Cow" };
String[] result = Stream.concat( String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2)).toArray(String[]::new);
Arrays.stream(animals1), Arrays.stream(animals2)).toArray(String[]::new);
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" }); assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
} }
@ -25,9 +24,7 @@ public class JoinSplitCollectionsUnitTest {
public void whenJoiningTwoCollections_thenJoined() { public void whenJoiningTwoCollections_thenJoined() {
Collection<String> collection1 = Arrays.asList("Dog", "Cat"); Collection<String> collection1 = Arrays.asList("Dog", "Cat");
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose"); Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
Collection<String> result = Stream.concat( Collection<String> result = Stream.concat(collection1.stream(), collection2.stream()).collect(Collectors.toList());
collection1.stream(), collection2.stream())
.collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow", "Moose"))); assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow", "Moose")));
} }
@ -36,10 +33,7 @@ public class JoinSplitCollectionsUnitTest {
public void whenJoiningTwoCollectionsWithFilter_thenJoined() { public void whenJoiningTwoCollectionsWithFilter_thenJoined() {
Collection<String> collection1 = Arrays.asList("Dog", "Cat"); Collection<String> collection1 = Arrays.asList("Dog", "Cat");
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose"); Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
Collection<String> result = Stream.concat( Collection<String> result = Stream.concat(collection1.stream(), collection2.stream()).filter(e -> e.length() == 3).collect(Collectors.toList());
collection1.stream(), collection2.stream())
.filter(e -> e.length() == 3)
.collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Cow"))); assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Cow")));
} }
@ -67,9 +61,7 @@ public class JoinSplitCollectionsUnitTest {
animals.put(2, "Cat"); animals.put(2, "Cat");
animals.put(3, "Cow"); animals.put(3, "Cow");
String result = animals.entrySet().stream() String result = animals.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue()).collect(Collectors.joining(", "));
.map(entry -> entry.getKey() + " = " + entry.getValue())
.collect(Collectors.joining(", "));
assertEquals(result, "1 = Dog, 2 = Cat, 3 = Cow"); assertEquals(result, "1 = Dog, 2 = Cat, 3 = Cow");
} }
@ -80,10 +72,7 @@ public class JoinSplitCollectionsUnitTest {
nested.add(Arrays.asList("Dog", "Cat")); nested.add(Arrays.asList("Dog", "Cat"));
nested.add(Arrays.asList("Cow", "Pig")); nested.add(Arrays.asList("Cow", "Pig"));
String result = nested.stream().map( String result = nested.stream().map(nextList -> nextList.stream().collect(Collectors.joining("-"))).collect(Collectors.joining("; "));
nextList -> nextList.stream()
.collect(Collectors.joining("-")))
.collect(Collectors.joining("; "));
assertEquals(result, "Dog-Cat; Cow-Pig"); assertEquals(result, "Dog-Cat; Cow-Pig");
} }
@ -91,17 +80,14 @@ public class JoinSplitCollectionsUnitTest {
@Test @Test
public void whenConvertCollectionToStringAndSkipNull_thenConverted() { public void whenConvertCollectionToStringAndSkipNull_thenConverted() {
Collection<String> animals = Arrays.asList("Dog", "Cat", null, "Moose"); Collection<String> animals = Arrays.asList("Dog", "Cat", null, "Moose");
String result = animals.stream() String result = animals.stream().filter(Objects::nonNull).collect(Collectors.joining(", "));
.filter(Objects::nonNull)
.collect(Collectors.joining(", "));
assertEquals(result, "Dog, Cat, Moose"); assertEquals(result, "Dog, Cat, Moose");
} }
@Test @Test
public void whenSplitCollectionHalf_thenConverted() { public void whenSplitCollectionHalf_thenConverted() {
Collection<String> animals = Arrays.asList( Collection<String> animals = Arrays.asList("Dog", "Cat", "Cow", "Bird", "Moose", "Pig");
"Dog", "Cat", "Cow", "Bird", "Moose", "Pig");
Collection<String> result1 = new ArrayList<>(); Collection<String> result1 = new ArrayList<>();
Collection<String> result2 = new ArrayList<>(); Collection<String> result2 = new ArrayList<>();
AtomicInteger count = new AtomicInteger(); AtomicInteger count = new AtomicInteger();
@ -122,9 +108,8 @@ public class JoinSplitCollectionsUnitTest {
@Test @Test
public void whenSplitArrayByWordLength_thenConverted() { public void whenSplitArrayByWordLength_thenConverted() {
String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow", "Pig", "Moose"}; String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow", "Pig", "Moose" };
Map<Integer, List<String>> result = Arrays.stream(animals) Map<Integer, List<String>> result = Arrays.stream(animals).collect(Collectors.groupingBy(String::length));
.collect(Collectors.groupingBy(String::length));
assertTrue(result.get(3).equals(Arrays.asList("Dog", "Cat", "Cow", "Pig"))); assertTrue(result.get(3).equals(Arrays.asList("Dog", "Cat", "Cow", "Pig")));
assertTrue(result.get(4).equals(Arrays.asList("Bird"))); assertTrue(result.get(4).equals(Arrays.asList("Bird")));
@ -151,9 +136,7 @@ public class JoinSplitCollectionsUnitTest {
public void whenConvertStringToMap_thenConverted() { public void whenConvertStringToMap_thenConverted() {
String animals = "1 = Dog, 2 = Cat, 3 = Bird"; String animals = "1 = Dog, 2 = Cat, 3 = Bird";
Map<Integer, String> result = Arrays.stream( Map<Integer, String> result = Arrays.stream(animals.split(", ")).map(next -> next.split(" = ")).collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1]));
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(1), "Dog");
assertEquals(result.get(2), "Cat"); assertEquals(result.get(2), "Cat");
@ -164,10 +147,7 @@ public class JoinSplitCollectionsUnitTest {
public void whenConvertCollectionToStringMultipleSeparators_thenConverted() { public void whenConvertCollectionToStringMultipleSeparators_thenConverted() {
String animals = "Dog. , Cat, Bird. Cow"; String animals = "Dog. , Cat, Bird. Cow";
Collection<String> result = Arrays.stream(animals.split("[,|.]")) Collection<String> result = Arrays.stream(animals.split("[,|.]")).map(String::trim).filter(next -> !next.isEmpty()).collect(Collectors.toList());
.map(String::trim)
.filter(next -> !next.isEmpty())
.collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow"))); assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow")));
} }

File diff suppressed because it is too large Load Diff

View File

@ -45,8 +45,7 @@ public class EJBClient {
final String distinctName = ""; final String distinctName = "";
final String beanName = "HelloWorld"; final String beanName = "HelloWorld";
final String viewClassName = HelloWorld.class.getName(); final String viewClassName = HelloWorld.class.getName();
final String toLookup = "ejb:" + appName + "/" + moduleName final String toLookup = String.format("ejb:%s/%s/%s/%s!%s", appName, moduleName, distinctName, beanName, viewClassName);
+ "/" + distinctName + "/" + beanName + "!" + viewClassName;
return (HelloWorld) context.lookup(toLookup); return (HelloWorld) context.lookup(toLookup);
} }

2
hazelcast/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Guide to Hazelcast with Java](http://www.baeldung.com/java-hazelcast)

19
imageprocessing/pom.xml Normal file
View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>imageprocessing</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>net.imagej</groupId>
<artifactId>ij</artifactId>
<version>1.51h</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,22 @@
package imagej;
import ij.IJ;
import ij.ImagePlus;
import ij.process.ImageProcessor;
import java.awt.*;
public class DrawRect {
public static void main(String[] args) {
ImagePlus imp = IJ.openImage(DrawRect.class.getClassLoader().getResource("lena.jpg").getPath());
drawRect(imp);
imp.show();
}
private static void drawRect(ImagePlus imp) {
ImageProcessor ip = imp.getProcessor();
ip.setColor(Color.BLUE);
ip.setLineWidth(4);
ip.drawRect(10, 10, imp.getWidth() - 20, imp.getHeight() - 20);
}
}

View File

@ -0,0 +1,40 @@
package swing;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class DrawRect {
public static void main(String[] args) throws IOException {
BufferedImage image = loadImage();
drawRectangle(image);
displayImage(image);
}
private static BufferedImage loadImage() throws IOException {
String imagePath = DrawRect.class.getClassLoader().getResource("lena.jpg").getPath();
return ImageIO.read(new File(imagePath));
}
private static void drawRectangle(BufferedImage image) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.setStroke(new BasicStroke(3));
g.setColor(Color.BLUE);
g.drawRect(10, 10, image.getWidth() - 20, image.getHeight() - 20);
}
private static void displayImage(BufferedImage image) {
JLabel picLabel = new JLabel(new ImageIcon(image));
JPanel jPanel = new JPanel();
jPanel.add(picLabel);
JFrame f = new JFrame();
f.setSize(new Dimension(image.getWidth(), image.getHeight()));
f.add(jPanel);
f.setVisible(true);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

View File

@ -0,0 +1,38 @@
<code_scheme name="updated-formatter">
<option name="RIGHT_MARGIN" value="260" />
<option name="ENABLE_JAVADOC_FORMATTING" value="false" />
<option name="FORMATTER_TAGS_ENABLED" value="true" />
<JavaCodeStyleSettings>
<option name="SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENT" value="true" />
<option name="DO_NOT_WRAP_AFTER_SINGLE_ANNOTATION" value="true" />
<option name="ALIGN_MULTILINE_ANNOTATION_PARAMETERS" value="true" />
</JavaCodeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="KEEP_LINE_BREAKS" value="false" />
<option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
<option name="KEEP_BLANK_LINES_IN_DECLARATIONS" value="1" />
<option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
<option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="1" />
<option name="INDENT_CASE_FROM_SWITCH" value="false" />
<option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
<option name="ALIGN_MULTILINE_RESOURCES" value="false" />
<option name="SPACE_WITHIN_ARRAY_INITIALIZER_BRACES" value="true" />
<option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
<option name="CALL_PARAMETERS_WRAP" value="1" />
<option name="METHOD_PARAMETERS_WRAP" value="1" />
<option name="RESOURCE_LIST_WRAP" value="5" />
<option name="EXTENDS_LIST_WRAP" value="1" />
<option name="THROWS_LIST_WRAP" value="1" />
<option name="EXTENDS_KEYWORD_WRAP" value="1" />
<option name="THROWS_KEYWORD_WRAP" value="1" />
<option name="METHOD_CALL_CHAIN_WRAP" value="1" />
<option name="BINARY_OPERATION_WRAP" value="1" />
<option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="ARRAY_INITIALIZER_WRAP" value="1" />
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="8" />
</indentOptions>
</codeStyleSettings>
</code_scheme>

2
java-cassandra/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [A Guide to Cassandra with Java](http://www.baeldung.com/cassandra-with-java)

View File

@ -1,2 +1,3 @@
### Relevant Articles: ### Relevant Articles:
- [The Basics of JUnit 5 A Preview](http://www.baeldung.com/junit-5-preview) - [The Basics of JUnit 5 A Preview](http://www.baeldung.com/junit-5-preview)
- [A Guide to JUnit 5](http://www.baeldung.com/junit-5)

View File

@ -1,5 +1,6 @@
### Relevant Articles: ### Relevant Articles:
- TBD - TBD
- [Improved Java Logging with Mapped Diagnostic Context (MDC)](http://www.baeldung.com/mdc-in-log4j-2-logback)
### References ### References

View File

@ -5,20 +5,37 @@
<artifactId>logmdc</artifactId> <artifactId>logmdc</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>logmdc</name> <name>logmdc</name>
<description>tutorial on logging with MDC</description> <packaging>war</packaging>
<description>tutorial on logging with MDC and NDC</description>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId> <artifactId>spring-core</artifactId>
<version>${springframework.version}</version> <version>${springframework.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId> <artifactId>spring-web</artifactId>
<version>${springframework.version}</version> <version>${springframework.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.library}</version>
</dependency>
<!--log4j dependencies --> <!--log4j dependencies -->
<dependency> <dependency>
@ -31,12 +48,12 @@
<dependency> <dependency>
<groupId>org.apache.logging.log4j</groupId> <groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId> <artifactId>log4j-api</artifactId>
<version>2.7</version> <version>${log4j2.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.logging.log4j</groupId> <groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId> <artifactId>log4j-core</artifactId>
<version>${log4j-api.version}</version> <version>${log4j2.version}</version>
</dependency> </dependency>
<!--disruptor for log4j2 async logging --> <!--disruptor for log4j2 async logging -->
@ -53,21 +70,64 @@
<version>${logback.version}</version> <version>${logback.version}</version>
</dependency> </dependency>
<!-- JBoss Logging (bridge) dependencies -->
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>${jbosslogging.version}</version>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>${junit.version}</version> <version>${junit.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springframework.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
<springframework.version>4.3.4.RELEASE</springframework.version> <springframework.version>4.3.4.RELEASE</springframework.version>
<log4j.version>1.2.17</log4j.version> <log4j.version>1.2.17</log4j.version>
<log4j-api.version>2.7</log4j-api.version> <log4j2.version>2.7</log4j2.version>
<disruptor.version>3.3.6</disruptor.version> <disruptor.version>3.3.6</disruptor.version>
<logback.version>1.1.7</logback.version> <logback.version>1.1.7</logback.version>
<jbosslogging.version>3.3.0.Final</jbosslogging.version>
<javax.servlet.version>3.1.0</javax.servlet.version>
<jackson.library>2.8.5</jackson.library>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
</properties> </properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>logging-service</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>logging-service</finalName>
</build>
</project> </project>

View File

@ -0,0 +1,19 @@
package com.baeldung.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.baeldung")
public class AppConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
}
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.ndc;
public class Investment {
private String transactionId;
private String owner;
private Long amount;
public Investment() {
}
public Investment(String transactionId, String owner, Long amount) {
this.transactionId = transactionId;
this.owner = owner;
this.amount = amount;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.ndc.controller;
import org.jboss.logging.NDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.ndc.Investment;
import com.baeldung.ndc.service.InvestmentService;
@RestController
public class JBossLoggingController {
@Autowired
@Qualifier("JBossLoggingInvestmentService")
private InvestmentService jbossLoggingBusinessService;
@RequestMapping(value = "/ndc/jboss-logging", method = RequestMethod.POST)
public ResponseEntity<Investment> postPayment(@RequestBody Investment investment) {
// Add transactionId and owner to NDC
NDC.push("tx.id=" + investment.getTransactionId());
NDC.push("tx.owner=" + investment.getOwner());
try {
jbossLoggingBusinessService.transfer(investment.getAmount());
} finally {
// take out owner from the NDC stack
NDC.pop();
// take out transactionId from the NDC stack
NDC.pop();
NDC.clear();
}
return new ResponseEntity<Investment>(investment, HttpStatus.OK);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.ndc.controller;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.ndc.Investment;
import com.baeldung.ndc.service.InvestmentService;
@RestController
public class Log4J2Controller {
@Autowired
@Qualifier("log4j2InvestmentService")
private InvestmentService log4j2BusinessService;
@RequestMapping(value = "/ndc/log4j2", method = RequestMethod.POST)
public ResponseEntity<Investment> postPayment(@RequestBody Investment investment) {
// Add transactionId and owner to NDC
ThreadContext.push("tx.id=" + investment.getTransactionId());
ThreadContext.push("tx.owner=" + investment.getOwner());
try {
log4j2BusinessService.transfer(investment.getAmount());
} finally {
// take out owner from the NDC stack
ThreadContext.pop();
// take out transactionId from the NDC stack
ThreadContext.pop();
ThreadContext.clearAll();
}
return new ResponseEntity<Investment>(investment, HttpStatus.OK);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.ndc.controller;
import org.apache.log4j.NDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.ndc.Investment;
import com.baeldung.ndc.service.InvestmentService;
@RestController
public class Log4JController {
@Autowired
@Qualifier("log4jInvestmentService")
private InvestmentService log4jBusinessService;
@RequestMapping(value = "/ndc/log4j", method = RequestMethod.POST)
public ResponseEntity<Investment> postPayment(@RequestBody Investment investment) {
// Add transactionId and owner to NDC
NDC.push("tx.id=" + investment.getTransactionId());
NDC.push("tx.owner=" + investment.getOwner());
try {
log4jBusinessService.transfer(investment.getAmount());
} finally {
// take out owner from the NDC stack
NDC.pop();
// take out transactionId from the NDC stack
NDC.pop();
NDC.remove();
}
return new ResponseEntity<Investment>(investment, HttpStatus.OK);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.ndc.service;
/**
* A fake investment service.
*/
public interface InvestmentService {
/**
* Sample service transferring a given amount of money.
* @param amount
* @return {@code true} when the transfer complete successfully, {@code false} otherwise.
*/
default public boolean transfer(long amount) {
beforeTransfer(amount);
// exchange messages with a remote system to transfer the money
try {
// let's pause randomly to properly simulate an actual system.
Thread.sleep((long) (500 + Math.random() * 500));
} catch (InterruptedException e) {
// should never happen
}
// let's simulate both failing and successful transfers
boolean outcome = Math.random() >= 0.25;
afterTransfer(amount, outcome);
return outcome;
}
void beforeTransfer(long amount);
void afterTransfer(long amount, boolean outcome);
}

View File

@ -0,0 +1,21 @@
package com.baeldung.ndc.service;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
@Qualifier("JBossLoggingInvestmentService")
public class JBossLoggingInvestmentService implements InvestmentService {
private static final Logger logger = Logger.getLogger(JBossLoggingInvestmentService.class);
@Override
public void beforeTransfer(long amount) {
logger.infov("Preparing to transfer {0}$.", amount);
}
@Override
public void afterTransfer(long amount, boolean outcome) {
logger.infov("Has transfer of {0}$ completed successfully ? {1}.", amount, outcome);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.ndc.service;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
@Qualifier("log4j2InvestmentService")
public class Log4J2InvestmentService implements InvestmentService {
private static final Logger logger = LogManager.getLogger();
@Override
public void beforeTransfer(long amount) {
logger.info("Preparing to transfer {}$.", amount);
}
@Override
public void afterTransfer(long amount, boolean outcome) {
logger.info("Has transfer of {}$ completed successfully ? {}.", amount, outcome);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.ndc.service;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
@Qualifier("log4jInvestmentService")
public class Log4JInvestmentService implements InvestmentService {
private Logger logger = Logger.getLogger(Log4JInvestmentService.class);
@Override
public void beforeTransfer(long amount) {
logger.info("Preparing to transfer " + amount + "$.");
}
@Override
public void afterTransfer(long amount, boolean outcome) {
logger.info("Has transfer of " + amount + "$ completed successfully ? " + outcome + ".");
}
}

View File

@ -3,6 +3,10 @@ log4j.appender.consoleAppender.layout=org.apache.log4j.PatternLayout
#note the %X{userName} - this is how you fetch data from Mapped Diagnostic Context (MDC) #note the %X{userName} - this is how you fetch data from Mapped Diagnostic Context (MDC)
#log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %5p %c{1} %x - %m%n #log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %5p %c{1} %x - %m%n
# %x is used to fetch data from NDC. So below setting uses both MDC and NDC
log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %5p %c{1} %x - %m - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %5p %c{1} %x - %m - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n
log4j.rootLogger = TRACE, consoleAppender # NDC only setting - %x is used to fetch data from NDC
#log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %5p %c{1} - %m - [%x]%n
log4j.rootLogger = INFO, consoleAppender

View File

@ -2,8 +2,15 @@
<Configuration status="INFO"> <Configuration status="INFO">
<Appenders> <Appenders>
<Console name="stdout" target="SYSTEM_OUT"> <Console name="stdout" target="SYSTEM_OUT">
<!-- MDC and NDC -->
<PatternLayout <PatternLayout
pattern="%-4r [%t] %5p %c{1} - %m - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n" /> pattern="%-4r [%t] %5p %c{1} - %m - %x - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n" />
<!-- MDC Only -->
<!-- <PatternLayout
pattern="%-4r [%t] %5p %c{1} - %m - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n" /> -->
<!-- NDC Only -->
<!-- <PatternLayout
pattern="%-4r [%t] %5p %c{1} - %m - %x%n" /> -->
</Console> </Console>
</Appenders> </Appenders>

View File

@ -0,0 +1,61 @@
package com.baeldung.ndc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.config.AppConfiguration;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfiguration.class)
@WebAppConfiguration
public class NDCLogTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
private Investment investment;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
investment = new Investment();
investment.setTransactionId("123");
investment.setOwner("Mark");
investment.setAmount(1000L);
}
@Test
public void givenLog4jLogger_whenNDCAdded_thenResponseOkAndNDCInLog() throws Exception {
mockMvc.perform(post("/ndc/log4j", investment).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(investment))).andExpect(status().is2xxSuccessful());
}
@Test
public void givenLog4j2Logger_whenNDCAdded_thenResponseOkAndNDCInLog() throws Exception {
mockMvc.perform(post("/ndc/log4j2", investment).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(investment))).andExpect(status().is2xxSuccessful());
}
@Test
public void givenJBossLoggerBridge_whenNDCAdded_thenResponseOkAndNDCInLog() throws Exception {
mockMvc.perform(post("/ndc/jboss-logging", investment).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(investment))).andExpect(status().is2xxSuccessful());
}
}

View File

@ -1,2 +1,6 @@
### Relevant Articles: ### Relevant Articles:
- [Introduction to Java Logging](http://www.baeldung.com/java-logging-intro) - [Introduction to Java Logging](http://www.baeldung.com/java-logging-intro)
- [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback)
- [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)
- [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback)

View File

@ -8,13 +8,24 @@
<artifactId>log4j</artifactId> <artifactId>log4j</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<dependencies> <dependencies>
<!--log4j dependencies--> <!--log4j dependencies -->
<dependency> <dependency>
<groupId>log4j</groupId> <groupId>log4j</groupId>
<artifactId>log4j</artifactId> <artifactId>log4j</artifactId>
<version>${log4j.version}</version> <version>${log4j.version}</version>
</dependency> </dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>apache-log4j-extras</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>apache-log4j-extras</artifactId>
<version>${log4j.version}</version>
</dependency>
<!--log4j2 dependencies--> <!--log4j2 dependencies-->
<dependency> <dependency>

View File

@ -0,0 +1,18 @@
package com.baeldung.log4j;
import java.util.stream.IntStream;
import org.apache.log4j.Logger;
public class Log4jRollingExample {
private final static Logger logger = Logger.getLogger(Log4jRollingExample.class);
public static void main(String[] args) throws InterruptedException {
for(int i = 0; i<2000; i++){
logger.info("This is the " + i + " time I say 'Hello World'.");
Thread.sleep(100);
}
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.log4j2;
import java.util.stream.IntStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4j2RollingExample {
private static final Logger logger = LogManager.getLogger(Log4j2RollingExample.class);
public static void main(String[] args) throws InterruptedException {
for(int i = 0; i<2000; i++){
logger.info("This is the {} time I say 'Hello World'.", i);
Thread.sleep(100);
}
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.logback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.stream.IntStream;
public class LogbackRollingExample {
private static final Logger logger = LoggerFactory.getLogger(LogbackRollingExample.class);
public static void main(String[] args) throws InterruptedException {
for(int i = 0; i<2000; i++){
logger.info("This is the {} time I say 'Hello World'.", i);
Thread.sleep(100);
}
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.stream.IntStream;
public class Slf4jRollingExample {
private static Logger logger = LoggerFactory.getLogger(Slf4jRollingExample.class);
public static void main(String[] args) throws InterruptedException {
for(int i = 0; i<2000; i++){
logger.info("This is the {} time I say 'Hello World'.", i);
Thread.sleep(100);
}
}
}

View File

@ -1,28 +1,95 @@
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" > <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false"> <log4j:configuration debug="false">
<!--Console appender--> <!--Console appender -->
<appender name="stdout" class="org.apache.log4j.ConsoleAppender"> <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout"> <layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
</layout> </layout>
</appender> </appender>
<!-- File appender--> <!-- File appender -->
<appender name="fout" class="org.apache.log4j.FileAppender"> <appender name="fout" class="org.apache.log4j.FileAppender">
<param name="file" value="log4j/target/baeldung-log4j.log"/> <param name="file" value="log4j/target/baeldung-log4j.log"/>
<param name="append" value="false"/> <param name="append" value="false"/>
<layout class="org.apache.log4j.PatternLayout"> <layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n"/> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n"/>
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
</layout> </layout>
</appender> </appender>
<!--Override log level for specified package--> <!-- Rolling appenders -->
<appender name="roll-by-size" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="target/log4j/roll-by-size/app.log"/>
<param name="MaxFileSize" value="5KB"/>
<param name="MaxBackupIndex" value="2"/> <!-- It's one by default. -->
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n"/>
</layout>
</appender>
<appender name="roll-by-size-2" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="target/log4j/roll-by-size-2/app.log"/>
<param name="MaxFileSize" value="5KB"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n"/>
</layout>
</appender>
<appender name="roll-by-window"
class="org.apache.log4j.rolling.RollingFileAppender">
<rollingPolicy
class="org.apache.log4j.rolling.FixedWindowRollingPolicy">
<param name="ActiveFileName" value="target/log4j/roll-by-window/app.log"/>
<param name="FileNamePattern"
value="target/log4j/roll-by-window/app.%i.log.gz"/>
<param name="MinIndex" value="7"/>
<param name="MaxIndex" value="17"/>
</rollingPolicy>
<triggeringPolicy
class="org.apache.log4j.rolling.SizeBasedTriggeringPolicy">
<param name="MaxFileSize" value="50000"/>
</triggeringPolicy>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n"/>
</layout>
</appender>
<appender name="roll-by-time"
class="org.apache.log4j.rolling.RollingFileAppender">
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern"
value="target/log4j/roll-by-time/app.%d{HH-mm}.log.gz"/>
</rollingPolicy>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n"/>
</layout>
</appender>
<appender name="roll-by-time-and-size"
class="org.apache.log4j.rolling.RollingFileAppender">
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern"
value="target/log4j/roll-by-time-and-size/app.%d{HH-mm}.%i.log.gz"/>
</rollingPolicy>
<triggeringPolicy
class="org.apache.log4j.rolling.SizeBasedTriggeringPolicy">
<param name="MaxFileSize" value="50000"/>
</triggeringPolicy>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n"/>
</layout>
</appender>
<!--Override log level for specified package -->
<category name="com.baeldung.log4j"> <category name="com.baeldung.log4j">
<priority value="TRACE"/> <priority value="TRACE"/>
</category> </category>
<category name="com.baeldung.log4j.Log4jRollingExample">
<priority value="TRACE"/>
<appender-ref ref="roll-by-size"/>
<appender-ref ref="roll-by-size-2"/>
<appender-ref ref="roll-by-window"/>
<appender-ref ref="roll-by-time"/>
<appender-ref ref="roll-by-time-and-size"/>
</category>
<root> <root>
<level value="DEBUG"/> <level value="DEBUG"/>
<appender-ref ref="stdout"/> <appender-ref ref="stdout"/>

View File

@ -8,16 +8,70 @@
</Console> </Console>
# File appender # File appender
<File name="fout" fileName="log4j/target/baeldung-log4j2.log" immediateFlush="false" append="false"> <File name="fout" fileName="log4j/target/baeldung-log4j2.log"
immediateFlush="false" append="false">
# Pattern of log message for file appender # Pattern of log message for file appender
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
</File> </File>
# Rolling appender
<RollingFile name="roll-by-size"
fileName="target/log4j2/roll-by-size/app.log" filePattern="target/log4j2/roll-by-size/app.%i.log.gz"
ignoreExceptions="false">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
</PatternLayout>
<Policies>
<OnStartupTriggeringPolicy/>
<SizeBasedTriggeringPolicy
size="5 KB"/>
</Policies>
</RollingFile>
<RollingFile name="roll-by-time"
fileName="target/log4j2/roll-by-time/app.log"
filePattern="target/log4j2/roll-by-time/app.%d{MM-dd-yyyy-HH-mm}.log.gz"
ignoreExceptions="false">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
</PatternLayout>
<TimeBasedTriggeringPolicy/>
</RollingFile>
<RollingFile name="roll-by-time-and-size"
fileName="target/log4j2/roll-by-time-and-size/app.log"
filePattern="target/log4j2/roll-by-time-and-size/app.%d{MM-dd-yyyy-HH-mm}.%i.log.gz"
ignoreExceptions="false">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
</PatternLayout>
<Policies>
<OnStartupTriggeringPolicy/>
<SizeBasedTriggeringPolicy
size="5 KB"/>
<TimeBasedTriggeringPolicy/>
</Policies>
<DefaultRolloverStrategy>
<Delete basePath="${baseDir}" maxDepth="2">
<IfFileName
glob="target/log4j2/roll-by-time-and-size/app.*.log.gz"/>
<IfLastModified age="20s"/>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
</Appenders> </Appenders>
<Loggers> <Loggers>
# Override log level for specified package # Override log level for specified package
<Logger name="com.baeldung.log4j2" level="TRACE"/> <Logger name="com.baeldung.log4j2" level="TRACE"/>
<Logger name="com.baeldung.log4j2.Log4j2RollingExample"
level="TRACE">
<AppenderRef ref="roll-by-size"/>
<AppenderRef ref="roll-by-time"/>
<AppenderRef ref="roll-by-time-and-size"/>
</Logger>
<AsyncRoot level="DEBUG"> <AsyncRoot level="DEBUG">
<AppenderRef ref="stdout"/> <AppenderRef ref="stdout"/>
<AppenderRef ref="fout"/> <AppenderRef ref="fout"/>

View File

@ -18,8 +18,65 @@
</encoder> </encoder>
</appender> </appender>
# Rolling appenders
<appender name="roll-by-size"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>target/slf4j/roll-by-size/app.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>target/slf4j/roll-by-size/app.%i.log.zip
</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>3</maxIndex>
<totalSizeCap>1MB</totalSizeCap>
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>5KB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n
</pattern>
</encoder>
</appender>
<appender name="roll-by-time"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>target/slf4j/roll-by-time/app.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>target/slf4j/roll-by-time/app.%d{yyyy-MM-dd-HH-mm}.log.zip
</fileNamePattern>
<maxHistory>20</maxHistory>
<totalSizeCap>1MB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</pattern>
</encoder>
</appender>
<appender name="roll-by-time-and-size"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>target/slf4j/roll-by-time-and-size/app.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>target/slf4j/roll-by-time-and-size/app.%d{yyyy-MM-dd-mm}.%i.log.zip
</fileNamePattern>
<maxFileSize>5KB</maxFileSize>
<maxHistory>20</maxHistory>
<totalSizeCap>1MB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</pattern>
</encoder>
</appender>
# Override log level for specified package # Override log level for specified package
<logger name="com.baeldung.logback" level="TRACE"/> <logger name="com.baeldung.slf4j.Slf4jRollingExample" level="TRACE">
<appender-ref ref="roll-by-size"/>
<appender-ref ref="roll-by-time"/>
<appender-ref ref="roll-by-time-and-size"/>
</logger>
<root level="DEBUG"> <root level="DEBUG">
<appender-ref ref="stdout"/> <appender-ref ref="stdout"/>

2
mapstruct/README.md Normal file
View File

@ -0,0 +1,2 @@
###Relevant Articles:
- [Quick Guide to MapStruct](http://www.baeldung.com/mapstruct)

View File

@ -94,6 +94,9 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version> <version>${maven-surefire-plugin.version}</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin> </plugin>
</plugins> </plugins>

3
patterns/README.md Normal file
View File

@ -0,0 +1,3 @@
###Relevant Articles:
- [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern)
- [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java)

2
pdf/README.md Normal file
View File

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

4
play-framework/README.md Normal file
View File

@ -0,0 +1,4 @@
###Relevant Articles:
- [REST API with Play Framework in Java](http://www.baeldung.com/rest-api-with-play)
- [Routing In Play Applications in Java](http://www.baeldung.com/routing-in-play)
- [Introduction To Play In Java](http://www.baeldung.com/java-intro-to-the-play-framework)

View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?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"> <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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
@ -117,6 +118,7 @@
<module>spring-mvc-velocity</module> <module>spring-mvc-velocity</module>
<module>spring-mvc-web-vs-initializer</module> <module>spring-mvc-web-vs-initializer</module>
<module>spring-mvc-xml</module> <module>spring-mvc-xml</module>
<module>spring-mvc-simple</module>
<module>spring-openid</module> <module>spring-openid</module>
<module>spring-protobuf</module> <module>spring-protobuf</module>
<module>spring-quartz</module> <module>spring-quartz</module>
@ -150,7 +152,7 @@
<module>xml</module> <module>xml</module>
<module>xmlunit2</module> <module>xmlunit2</module>
<module>xstream</module> <module>xstream</module>
<module>pdf</module> <module>pdf</module>
</modules> </modules>
</project> </project>

View File

@ -1,7 +1,6 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<project <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
@ -44,7 +43,20 @@
<target>1.8</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins> </plugins>
</pluginManagement> </pluginManagement>
</build> </build>

View File

@ -8,6 +8,7 @@ This article will demonstrate how to configure and use Apache Camel with Spring
<ul> <ul>
<li><a href="http://camel.apache.org/">Apache Camel</a></li> <li><a href="http://camel.apache.org/">Apache Camel</a></li>
<li><a href="http://www.enterpriseintegrationpatterns.com/patterns/messaging/toc.html">Enterprise Integration Patterns</a></li> <li><a href="http://www.enterpriseintegrationpatterns.com/patterns/messaging/toc.html">Enterprise Integration Patterns</a></li>
<li><a href="http://www.baeldung.com/apache-camel-intro">Introduction To Apache Camel</a></li>
</ul> </ul>
<b><h2>Framework Versions:</h2></b> <b><h2>Framework Versions:</h2></b>

View File

@ -11,7 +11,7 @@
<properties> <properties>
<env.camel.version>2.16.1</env.camel.version> <env.camel.version>2.16.1</env.camel.version>
<env.spring.version>4.3.4.RELEASE</env.spring.version> <env.spring.version>4.3.4.RELEASE</env.spring.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
</properties> </properties>
@ -48,7 +48,11 @@
<artifactId>spring-context</artifactId> <artifactId>spring-context</artifactId>
<version>${env.spring.version}</version> <version>${env.spring.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -1,8 +1,6 @@
package com.baeldung.camel.file; package com.baeldung.camel.file;
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel; import org.apache.camel.LoggingLevel;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder; import org.apache.camel.builder.RouteBuilder;
public class DeadLetterChannelFileRouter extends RouteBuilder { public class DeadLetterChannelFileRouter extends RouteBuilder {
@ -10,13 +8,11 @@ public class DeadLetterChannelFileRouter extends RouteBuilder {
@Override @Override
public void configure() throws Exception { public void configure() throws Exception {
errorHandler(deadLetterChannel("log:dead?level=ERROR").maximumRedeliveries(3).redeliveryDelay(1000).retryAttemptedLogLevel(LoggingLevel.ERROR)); errorHandler(deadLetterChannel("log:dead?level=ERROR").maximumRedeliveries(3)
.redeliveryDelay(1000).retryAttemptedLogLevel(LoggingLevel.ERROR));
from("file://" + SOURCE_FOLDER + "?delete=true").process(new Processor() { from("file://" + SOURCE_FOLDER + "?delete=true").process((exchange) -> {
@Override throw new IllegalArgumentException("Exception thrown!");
public void process(Exchange exchange) throws Exception {
throw new IllegalArgumentException("Exception thrown!");
}
}); });
} }
} }

View File

@ -4,7 +4,7 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="contentBasedFileRouter" class="org.baeldung.camel.file.ContentBasedFileRouter" /> <bean id="contentBasedFileRouter" class="com.baeldung.camel.file.ContentBasedFileRouter" />
<camelContext xmlns="http://camel.apache.org/schema/spring"> <camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="contentBasedFileRouter" /> <routeBuilder ref="contentBasedFileRouter" />

View File

@ -4,7 +4,7 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="deadLetterChannelFileRouter" class="org.baeldung.camel.file.DeadLetterChannelFileRouter" /> <bean id="deadLetterChannelFileRouter" class="com.baeldung.camel.file.DeadLetterChannelFileRouter" />
<camelContext xmlns="http://camel.apache.org/schema/spring"> <camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="deadLetterChannelFileRouter" /> <routeBuilder ref="deadLetterChannelFileRouter" />

View File

@ -4,7 +4,7 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="messageTranslatorFileRouter" class="org.baeldung.camel.file.MessageTranslatorFileRouter" /> <bean id="messageTranslatorFileRouter" class="com.baeldung.camel.file.MessageTranslatorFileRouter" />
<camelContext xmlns="http://camel.apache.org/schema/spring"> <camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="messageTranslatorFileRouter" /> <routeBuilder ref="messageTranslatorFileRouter" />

View File

@ -4,7 +4,7 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="multicastFileRouter" class="org.baeldung.camel.file.MulticastFileRouter" /> <bean id="multicastFileRouter" class="com.baeldung.camel.file.MulticastFileRouter" />
<camelContext xmlns="http://camel.apache.org/schema/spring"> <camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="multicastFileRouter" /> <routeBuilder ref="multicastFileRouter" />

View File

@ -4,7 +4,7 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="splitterFileRouter" class="org.baeldung.camel.file.SplitterFileRouter" /> <bean id="splitterFileRouter" class="com.baeldung.camel.file.SplitterFileRouter" />
<camelContext xmlns="http://camel.apache.org/schema/spring"> <camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="splitterFileRouter" /> <routeBuilder ref="splitterFileRouter" />

View File

@ -1,4 +1,4 @@
package org.apache.camel.file.processor; package com.apache.camel.file.processor;
import java.io.File; import java.io.File;

View File

@ -1,9 +1,8 @@
package org.apache.camel.file.processor; package com.apache.camel.file.processor;
import java.io.File; import java.io.File;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;

View File

@ -1,4 +1,4 @@
package org.apache.camel.file.processor; package com.apache.camel.file.processor;
import java.io.File; import java.io.File;

View File

@ -1,4 +1,4 @@
package org.apache.camel.file.processor; package com.apache.camel.file.processor;
import java.io.File; import java.io.File;

View File

@ -1,4 +1,4 @@
package org.apache.camel.file.processor; package com.apache.camel.file.processor;
import java.io.File; import java.io.File;

View File

@ -1,4 +1,4 @@
package org.apache.camel.file.processor; package com.apache.camel.file.processor;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;

View File

@ -1,4 +1,4 @@
package org.apache.camel.main; package com.apache.camel.main;
import com.baeldung.camel.main.App; import com.baeldung.camel.main.App;
import junit.framework.TestCase; import junit.framework.TestCase;

View File

@ -1,68 +0,0 @@
package org.apache.camel.file.processor;
import java.io.File;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baeldung.camel.file.FileProcessor;
public class FileProcessorTest {
private static final long DURATION_MILIS = 10000;
private static final String SOURCE_FOLDER = "src/test/source-folder";
private static final String DESTINATION_FOLDER = "src/test/destination-folder";
@Before
public void setUp() throws Exception {
File sourceFolder = new File(SOURCE_FOLDER);
File destinationFolder = new File(DESTINATION_FOLDER);
cleanFolder(sourceFolder);
cleanFolder(destinationFolder);
sourceFolder.mkdirs();
File file1 = new File(SOURCE_FOLDER + "/File1.txt");
File file2 = new File(SOURCE_FOLDER + "/File2.txt");
file1.createNewFile();
file2.createNewFile();
}
private void cleanFolder(File folder) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
file.delete();
}
}
}
}
@Test
public void moveFolderContentJavaDSLTest() throws Exception {
final CamelContext camelContext = new DefaultCamelContext();
camelContext.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("file://" + SOURCE_FOLDER + "?delete=true").process(new FileProcessor()).to("file://" + DESTINATION_FOLDER);
}
});
camelContext.start();
Thread.sleep(DURATION_MILIS);
camelContext.stop();
}
@Test
public void moveFolderContentSpringDSLTest() throws InterruptedException {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context-test.xml");
Thread.sleep(DURATION_MILIS);
applicationContext.close();
}
}

View File

@ -5,3 +5,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot) - [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot)
- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) - [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters)
- [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) - [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring)
- [Introduction to WebJars](http://www.baeldung.com/maven-webjars)

View File

@ -112,23 +112,4 @@
</profile> </profile>
</profiles> </profiles>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project> </project>

View File

@ -77,23 +77,4 @@
</plugins> </plugins>
</build> </build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project> </project>

View File

@ -1,15 +1,18 @@
<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"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<modelVersion>4.0.0</modelVersion> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>org.baeldung.spring.cloud</groupId> <modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-data-flow</artifactId> <groupId>org.baeldung.spring.cloud</groupId>
<version>0.0.1-SNAPSHOT</version> <artifactId>spring-cloud-data-flow</artifactId>
<packaging>pom</packaging> <version>0.0.1-SNAPSHOT</version>
<modules> <packaging>pom</packaging>
<module>data-flow-server</module>
<module>data-flow-shell</module> <modules>
<module>time-source</module> <module>data-flow-server</module>
<module>time-processor</module> <!-- <module>data-flow-shell</module> -->
<module>log-sink</module> <module>time-source</module>
<module>batch-job</module> <module>time-processor</module>
</modules> <module>log-sink</module>
<module>batch-job</module>
</modules>
</project> </project>

View File

@ -16,4 +16,5 @@
- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) - [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application)
- [Introduction to Spring Cloud Rest Client with Netflix Ribbon](http://www.baeldung.com/spring-cloud-rest-client-with-netflix-ribbon) - [Introduction to Spring Cloud Rest Client with Netflix Ribbon](http://www.baeldung.com/spring-cloud-rest-client-with-netflix-ribbon)
### Relevant Articles:
- [Introduction to Spring Cloud Rest Client with Netflix Ribbon](http://www.baeldung.com/spring-cloud-rest-client-with-netflix-ribbon)

View File

@ -1,80 +1,80 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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"> 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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>spring-cloud-ribbon</artifactId> <artifactId>spring-cloud-ribbon</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>spring-cloud-ribbon-client</name> <name>spring-cloud-ribbon-client</name>
<description>Introduction to Spring Cloud Rest Client with Netflix Ribbon</description> <description>Introduction to Spring Cloud Rest Client with Netflix Ribbon</description>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version> <version>1.4.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository --> <relativePath /> <!-- lookup parent from repository -->
</parent> </parent>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-cloud-dependencies.version>Brixton.SR7</spring-cloud-dependencies.version> <spring-cloud-dependencies.version>Brixton.SR7</spring-cloud-dependencies.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId> <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId> <artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud-dependencies.version}</version> <version>${spring-cloud-dependencies.version}</version>
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<repositories> <repositories>
<repository> <repository>
<id>spring-snapshots</id> <id>spring-snapshots</id>
<name>Spring Snapshots</name> <name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url> <url>https://repo.spring.io/snapshot</url>
<snapshots> <snapshots>
<enabled>true</enabled> <enabled>true</enabled>
</snapshots> </snapshots>
</repository> </repository>
<repository> <repository>
<id>spring-milestones</id> <id>spring-milestones</id>
<name>Spring Milestones</name> <name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url> <url>https://repo.spring.io/milestone</url>
<snapshots> <snapshots>
<enabled>false</enabled> <enabled>false</enabled>
</snapshots> </snapshots>
</repository> </repository>
</repositories> </repositories>
</project> </project>

View File

@ -20,7 +20,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = ServerLocationApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @SpringBootTest(classes = ServerLocationApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ServerLocationAppTests { public class ServerLocationAppIntegrationTest {
ConfigurableApplicationContext application2; ConfigurableApplicationContext application2;
ConfigurableApplicationContext application3; ConfigurableApplicationContext application3;

View File

@ -2,4 +2,4 @@
- [Wiring in Spring: @Autowired, @Resource and @Inject](http://www.baeldung.com/spring-annotations-resource-inject-autowire) - [Wiring in Spring: @Autowired, @Resource and @Inject](http://www.baeldung.com/spring-annotations-resource-inject-autowire)
- [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory) - [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory)
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) - [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
- [Constructor Dependency Injection in Spring](http://www.baeldung.com/constructor-injection-in-spring)

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