Merge branch 'master' into hemantvsn_SpringBootNonWebApp_30May18

This commit is contained in:
Grzegorz Piwowarek 2018-06-06 07:33:08 +02:00 committed by GitHub
commit 1395211756
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2820 changed files with 377694 additions and 18480 deletions

2
.gitignore vendored
View File

@ -34,8 +34,6 @@ spring-security-openid/src/main/resources/application.properties
spring-all/*.log
*.jar
SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties
spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties

View File

@ -4,7 +4,7 @@ before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: skip
script: travis_wait 60 mvn -q test -fae
script: travis_wait 60 mvn -q install
sudo: required

View File

@ -11,41 +11,42 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
</parent>
<repositories>
<repository>
<id>jgit-repository</id>
<url>https://repo.eclipse.org/content/groups/releases/</url>
</repository>
</repositories>
<!-- Core Library -->
<dependencies>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>${org.eclipse.jgit.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit.archive</artifactId>
<version>${org.eclipse.jgit.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<org.eclipse.jgit.version>4.5.0.201609210915-r</org.eclipse.jgit.version>
</properties>
<repositories>
<repository>
<id>jgit-repository</id>
<url>https://repo.eclipse.org/content/groups/releases/</url>
</repository>
</repositories>
<!-- Core Library -->
<dependencies>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>4.5.0.201609210915-r</version>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit.archive</artifactId>
<version>4.5.0.201609210915-r</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
</dependencies>
</project>

View File

@ -17,6 +17,10 @@ This project is **a collection of small and focused tutorials** each covering a
Most of the tutorial projects are focused on the `Spring Framework` (and `Spring Security`).
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
Building the project
====================
To do the full build, do: `mvn install -Dgib.enabled=false`
Working with the code in Eclipse
================================
@ -29,3 +33,12 @@ Any IDE can be used to work with the projects, but if you're using Eclipse, cons
CI - Jenkins
================================
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**
### Relevant Articles:
================================
- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
- [Apache Maven Tutorial](http://www.baeldung.com/maven)
- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)
- [Java Service Provider Interface](http://www.baeldung.com/java-spi)
- [Java Streams vs Vavr Streams](http://www.baeldung.com/vavr-java-streams)

View File

@ -1,52 +1,52 @@
<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>
<groupId>com.mabsisa</groupId>
<artifactId>Twitter4J</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Twitter4J</name>
<url>http://maven.apache.org</url>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mabsisa</groupId>
<artifactId>Twitter4J</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Twitter4J</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-stream</artifactId>
<version>4.0.6</version>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-stream</artifactId>
<version>4.0.6</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/ApplicationTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/ApplicationTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

2
activejdbc/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to ActiveJDBC](http://www.baeldung.com/active-jdbc)

View File

@ -1,129 +1,143 @@
<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>activejdbc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>activejdbc</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<activejdbc.version>1.4.13</activejdbc.version>
<environments>development.test,development</environments>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.javalite</groupId>
<artifactId>activejdbc-instrumentation</artifactId>
<version>${activejdbc.version}</version>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>instrument</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.javalite</groupId>
<artifactId>db-migrator-maven-plugin</artifactId>
<version>${activejdbc.version}</version>
<configuration>
<configFile>${project.basedir}/src/main/resources/database.properties</configFile>
<environments>${environments}</environments>
</configuration>
<dependencies>
<dependency>
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>activejdbc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>activejdbc</name>
<url>http://maven.apache.org</url>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.javalite</groupId>
<artifactId>activejdbc</artifactId>
<version>${activejdbc.version}</version>
<exclusions>
<exclusion>
<groupId>opensymphony</groupId>
<artifactId>oscache</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<reportFormat>brief</reportFormat>
<trimStackTrace>true</trimStackTrace>
<useFile>false</useFile>
<includes>
<include>**/*Spec*.java</include>
<include>**/*Test*.java</include>
</includes>
<excludes>
<exclude>**/helpers/*</exclude>
<exclude>**/*$*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.javalite</groupId>
<artifactId>activejdbc</artifactId>
<version>${activejdbc.version}</version>
<exclusions>
<exclusion>
<groupId>opensymphony</groupId>
<artifactId>oscache</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.9</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>snapshots1</id>
<name>JavaLite Snapshots1</name>
<url>http://repo.javalite.io/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>warn</checksumPolicy>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>snapshots2</id>
<name>JavaLite Snapshots2</name>
<url>http://repo.javalite.io/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>warn</checksumPolicy>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
<version>${mysql.connector.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.javalite</groupId>
<artifactId>activejdbc-instrumentation</artifactId>
<version>${activejdbc.version}</version>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>instrument</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.javalite</groupId>
<artifactId>db-migrator-maven-plugin</artifactId>
<version>${activejdbc.version}</version>
<configuration>
<configFile>${project.basedir}/src/main/resources/database.properties</configFile>
<environments>${environments}</environments>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<reportFormat>brief</reportFormat>
<trimStackTrace>true</trimStackTrace>
<useFile>false</useFile>
<includes>
<include>**/*Spec*.java</include>
<include>**/*Test*.java</include>
</includes>
<excludes>
<exclude>**/helpers/*</exclude>
<exclude>**/*$*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>snapshots1</id>
<name>JavaLite Snapshots1</name>
<url>http://repo.javalite.io/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>warn</checksumPolicy>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>snapshots2</id>
<name>JavaLite Snapshots2</name>
<url>http://repo.javalite.io/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>warn</checksumPolicy>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<activejdbc.version>1.4.13</activejdbc.version>
<environments>development.test,development</environments>
<org.slf4j.version>1.7.9</org.slf4j.version>
<mysql.connector.version>5.1.34</mysql.connector.version>
</properties>
</project>

View File

@ -1,15 +1,15 @@
<?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"
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>akka-streams</artifactId>
<name>akka-streams</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>akka-streams</artifactId>
<name>akka-streams</name>
<dependencies>
<dependency>
@ -23,6 +23,7 @@
<version>${akkastreams.version}</version>
</dependency>
</dependencies>
<properties>
<akkastreams.version>2.5.2</akkastreams.version>
</properties>

View File

@ -16,3 +16,9 @@
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
- [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze)
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum)

View File

@ -1,16 +1,10 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>algorithms</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
</properties>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
@ -32,17 +26,22 @@
<dependency>
<groupId>io.jenetics</groupId>
<artifactId>jenetics</artifactId>
<version>3.7.0</version>
<version>${io.jenetics.version}</version>
</dependency>
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-core</artifactId>
<version>1.0.1</version>
<version>${org.jgrapht.core.version}</version>
</dependency>
<dependency>
<groupId>pl.allegro.finance</groupId>
<artifactId>tradukisto</artifactId>
<version>${tradukisto.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.9.0</version>
<version>${org.assertj.core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -58,6 +57,7 @@
</plugins>
</pluginManagement>
</build>
<reporting>
<plugins>
<plugin>
@ -77,4 +77,15 @@
</plugin>
</plugins>
</reporting>
</project>
<properties>
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<tradukisto.version>1.0.1</tradukisto.version>
<io.jenetics.version>3.7.0</io.jenetics.version>
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
</properties>
</project>

View File

@ -6,6 +6,7 @@ import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
import com.baeldung.algorithms.slope_one.SlopeOne;
import com.baeldung.algorithms.pairsaddupnumber.FindPairs;
public class RunAlgorithm {
@ -17,6 +18,7 @@ public class RunAlgorithm {
System.out.println("3 - Simple Genetic Algorithm");
System.out.println("4 - Ant Colony");
System.out.println("5 - Dijkstra");
System.out.println("6 - All pairs in an array that add up to a given sum");
int decision = in.nextInt();
switch (decision) {
case 1:
@ -37,6 +39,12 @@ public class RunAlgorithm {
case 5:
System.out.println("Please run the DijkstraAlgorithmTest.");
break;
case 6:
final FindPairs findPairs = new FindPairs();
final int[] input = {1, 4, 3, 2, 1, 4, 4, 3, 3};
final int sum = 6;
findPairs.execute(input, sum);
break;
default:
System.out.println("Unknown option");
break;

View File

@ -0,0 +1,47 @@
package com.baeldung.algorithms.multiswarm;
/**
* Constants used by the Multi-swarm optimization algorithms.
*
* @author Donato Rimenti
*
*/
public class Constants {
/**
* The inertia factor encourages a particle to continue moving in its
* current direction.
*/
public static final double INERTIA_FACTOR = 0.729;
/**
* The cognitive weight encourages a particle to move toward its historical
* best-known position.
*/
public static final double COGNITIVE_WEIGHT = 1.49445;
/**
* The social weight encourages a particle to move toward the best-known
* position found by any of the particles swarm-mates.
*/
public static final double SOCIAL_WEIGHT = 1.49445;
/**
* The global weight encourages a particle to move toward the best-known
* position found by any particle in any swarm.
*/
public static final double GLOBAL_WEIGHT = 0.3645;
/**
* Upper bound for the random generation. We use it to reduce the
* computation time since we can rawly estimate it.
*/
public static final int PARTICLE_UPPER_BOUND = 10000000;
/**
* Private constructor for utility class.
*/
private Constants() {
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.algorithms.multiswarm;
/**
* Interface for a fitness function, used to decouple the main algorithm logic
* from the specific problem solution.
*
* @author Donato Rimenti
*
*/
public interface FitnessFunction {
/**
* Returns the fitness of a particle given its position.
*
* @param particlePosition
* the position of the particle
* @return the fitness of the particle
*/
public double getFitness(long[] particlePosition);
}

View File

@ -0,0 +1,227 @@
package com.baeldung.algorithms.multiswarm;
import java.util.Arrays;
import java.util.Random;
/**
* Represents a collection of {@link Swarm}.
*
* @author Donato Rimenti
*
*/
public class Multiswarm {
/**
* The swarms managed by this multiswarm.
*/
private Swarm[] swarms;
/**
* The best position found within all the {@link #swarms}.
*/
private long[] bestPosition;
/**
* The best fitness score found within all the {@link #swarms}.
*/
private double bestFitness = Double.NEGATIVE_INFINITY;
/**
* A random generator.
*/
private Random random = new Random();
/**
* The fitness function used to determine how good is a particle.
*/
private FitnessFunction fitnessFunction;
/**
* Instantiates a new Multiswarm.
*
* @param numSwarms
* the number of {@link #swarms}
* @param particlesPerSwarm
* the number of particle for each {@link #swarms}
* @param fitnessFunction
* the {@link #fitnessFunction}
*/
public Multiswarm(int numSwarms, int particlesPerSwarm, FitnessFunction fitnessFunction) {
this.fitnessFunction = fitnessFunction;
this.swarms = new Swarm[numSwarms];
for (int i = 0; i < numSwarms; i++) {
swarms[i] = new Swarm(particlesPerSwarm);
}
}
/**
* Main loop of the algorithm. Iterates all particles of all
* {@link #swarms}. For each particle, computes the new fitness and checks
* if a new best position has been found among itself, the swarm and all the
* swarms and finally updates the particle position and speed.
*/
public void mainLoop() {
for (Swarm swarm : swarms) {
for (Particle particle : swarm.getParticles()) {
long[] particleOldPosition = particle.getPosition().clone();
// Calculate the particle fitness.
particle.setFitness(fitnessFunction.getFitness(particleOldPosition));
// Check if a new best position has been found for the particle
// itself, within the swarm and the multiswarm.
if (particle.getFitness() > particle.getBestFitness()) {
particle.setBestFitness(particle.getFitness());
particle.setBestPosition(particleOldPosition);
if (particle.getFitness() > swarm.getBestFitness()) {
swarm.setBestFitness(particle.getFitness());
swarm.setBestPosition(particleOldPosition);
if (swarm.getBestFitness() > bestFitness) {
bestFitness = swarm.getBestFitness();
bestPosition = swarm.getBestPosition().clone();
}
}
}
// Updates the particle position by adding the speed to the
// actual position.
long[] position = particle.getPosition();
long[] speed = particle.getSpeed();
position[0] += speed[0];
position[1] += speed[1];
// Updates the particle speed.
speed[0] = getNewParticleSpeedForIndex(particle, swarm, 0);
speed[1] = getNewParticleSpeedForIndex(particle, swarm, 1);
}
}
}
/**
* Computes a new speed for a given particle of a given swarm on a given
* axis. The new speed is computed using the formula:
*
* <pre>
* ({@link Constants#INERTIA_FACTOR} * {@link Particle#getSpeed()}) +
* (({@link Constants#COGNITIVE_WEIGHT} * random(0,1)) * ({@link Particle#getBestPosition()} - {@link Particle#getPosition()})) +
* (({@link Constants#SOCIAL_WEIGHT} * random(0,1)) * ({@link Swarm#getBestPosition()} - {@link Particle#getPosition()})) +
* (({@link Constants#GLOBAL_WEIGHT} * random(0,1)) * ({@link #bestPosition} - {@link Particle#getPosition()}))
* </pre>
*
* @param particle
* the particle whose new speed needs to be computed
* @param swarm
* the swarm which contains the particle
* @param index
* the index of the particle axis whose speeds needs to be
* computed
* @return the new speed of the particle passed on the given axis
*/
private int getNewParticleSpeedForIndex(Particle particle, Swarm swarm, int index) {
return (int) ((Constants.INERTIA_FACTOR * particle.getSpeed()[index])
+ (randomizePercentage(Constants.COGNITIVE_WEIGHT)
* (particle.getBestPosition()[index] - particle.getPosition()[index]))
+ (randomizePercentage(Constants.SOCIAL_WEIGHT)
* (swarm.getBestPosition()[index] - particle.getPosition()[index]))
+ (randomizePercentage(Constants.GLOBAL_WEIGHT)
* (bestPosition[index] - particle.getPosition()[index])));
}
/**
* Returns a random number between 0 and the value passed as argument.
*
* @param value
* the value to randomize
* @return a random value between 0 and the one passed as argument
*/
private double randomizePercentage(double value) {
return random.nextDouble() * value;
}
/**
* Gets the {@link #bestPosition}.
*
* @return the {@link #bestPosition}
*/
public long[] getBestPosition() {
return bestPosition;
}
/**
* Gets the {@link #bestFitness}.
*
* @return the {@link #bestFitness}
*/
public double getBestFitness() {
return bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
result = prime * result + ((fitnessFunction == null) ? 0 : fitnessFunction.hashCode());
result = prime * result + ((random == null) ? 0 : random.hashCode());
result = prime * result + Arrays.hashCode(swarms);
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Multiswarm other = (Multiswarm) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (fitnessFunction == null) {
if (other.fitnessFunction != null)
return false;
} else if (!fitnessFunction.equals(other.fitnessFunction))
return false;
if (random == null) {
if (other.random != null)
return false;
} else if (!random.equals(other.random))
return false;
if (!Arrays.equals(swarms, other.swarms))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Multiswarm [swarms=" + Arrays.toString(swarms) + ", bestPosition=" + Arrays.toString(bestPosition)
+ ", bestFitness=" + bestFitness + ", random=" + random + ", fitnessFunction=" + fitnessFunction + "]";
}
}

View File

@ -0,0 +1,204 @@
package com.baeldung.algorithms.multiswarm;
import java.util.Arrays;
/**
* Represents a particle, the basic component of a {@link Swarm}.
*
* @author Donato Rimenti
*
*/
public class Particle {
/**
* The current position of this particle.
*/
private long[] position;
/**
* The speed of this particle.
*/
private long[] speed;
/**
* The fitness of this particle for the current position.
*/
private double fitness;
/**
* The best position found by this particle.
*/
private long[] bestPosition;
/**
* The best fitness found by this particle.
*/
private double bestFitness = Double.NEGATIVE_INFINITY;
/**
* Instantiates a new Particle.
*
* @param initialPosition
* the initial {@link #position}
* @param initialSpeed
* the initial {@link #speed}
*/
public Particle(long[] initialPosition, long[] initialSpeed) {
this.position = initialPosition;
this.speed = initialSpeed;
}
/**
* Gets the {@link #position}.
*
* @return the {@link #position}
*/
public long[] getPosition() {
return position;
}
/**
* Gets the {@link #speed}.
*
* @return the {@link #speed}
*/
public long[] getSpeed() {
return speed;
}
/**
* Gets the {@link #fitness}.
*
* @return the {@link #fitness}
*/
public double getFitness() {
return fitness;
}
/**
* Gets the {@link #bestPosition}.
*
* @return the {@link #bestPosition}
*/
public long[] getBestPosition() {
return bestPosition;
}
/**
* Gets the {@link #bestFitness}.
*
* @return the {@link #bestFitness}
*/
public double getBestFitness() {
return bestFitness;
}
/**
* Sets the {@link #position}.
*
* @param position
* the new {@link #position}
*/
public void setPosition(long[] position) {
this.position = position;
}
/**
* Sets the {@link #speed}.
*
* @param speed
* the new {@link #speed}
*/
public void setSpeed(long[] speed) {
this.speed = speed;
}
/**
* Sets the {@link #fitness}.
*
* @param fitness
* the new {@link #fitness}
*/
public void setFitness(double fitness) {
this.fitness = fitness;
}
/**
* Sets the {@link #bestPosition}.
*
* @param bestPosition
* the new {@link #bestPosition}
*/
public void setBestPosition(long[] bestPosition) {
this.bestPosition = bestPosition;
}
/**
* Sets the {@link #bestFitness}.
*
* @param bestFitness
* the new {@link #bestFitness}
*/
public void setBestFitness(double bestFitness) {
this.bestFitness = bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
temp = Double.doubleToLongBits(fitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(position);
result = prime * result + Arrays.hashCode(speed);
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Particle other = (Particle) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (Double.doubleToLongBits(fitness) != Double.doubleToLongBits(other.fitness))
return false;
if (!Arrays.equals(position, other.position))
return false;
if (!Arrays.equals(speed, other.speed))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Particle [position=" + Arrays.toString(position) + ", speed=" + Arrays.toString(speed) + ", fitness="
+ fitness + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + "]";
}
}

View File

@ -0,0 +1,155 @@
package com.baeldung.algorithms.multiswarm;
import java.util.Arrays;
import java.util.Random;
/**
* Represents a collection of {@link Particle}.
*
* @author Donato Rimenti
*
*/
public class Swarm {
/**
* The particles of this swarm.
*/
private Particle[] particles;
/**
* The best position found within the particles of this swarm.
*/
private long[] bestPosition;
/**
* The best fitness score found within the particles of this swarm.
*/
private double bestFitness = Double.NEGATIVE_INFINITY;
/**
* A random generator.
*/
private Random random = new Random();
/**
* Instantiates a new Swarm.
*
* @param numParticles
* the number of particles of the swarm
*/
public Swarm(int numParticles) {
particles = new Particle[numParticles];
for (int i = 0; i < numParticles; i++) {
long[] initialParticlePosition = { random.nextInt(Constants.PARTICLE_UPPER_BOUND),
random.nextInt(Constants.PARTICLE_UPPER_BOUND) };
long[] initialParticleSpeed = { random.nextInt(Constants.PARTICLE_UPPER_BOUND),
random.nextInt(Constants.PARTICLE_UPPER_BOUND) };
particles[i] = new Particle(initialParticlePosition, initialParticleSpeed);
}
}
/**
* Gets the {@link #particles}.
*
* @return the {@link #particles}
*/
public Particle[] getParticles() {
return particles;
}
/**
* Gets the {@link #bestPosition}.
*
* @return the {@link #bestPosition}
*/
public long[] getBestPosition() {
return bestPosition;
}
/**
* Gets the {@link #bestFitness}.
*
* @return the {@link #bestFitness}
*/
public double getBestFitness() {
return bestFitness;
}
/**
* Sets the {@link #bestPosition}.
*
* @param bestPosition
* the new {@link #bestPosition}
*/
public void setBestPosition(long[] bestPosition) {
this.bestPosition = bestPosition;
}
/**
* Sets the {@link #bestFitness}.
*
* @param bestFitness
* the new {@link #bestFitness}
*/
public void setBestFitness(double bestFitness) {
this.bestFitness = bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
result = prime * result + Arrays.hashCode(particles);
result = prime * result + ((random == null) ? 0 : random.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Swarm other = (Swarm) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (!Arrays.equals(particles, other.particles))
return false;
if (random == null) {
if (other.random != null)
return false;
} else if (!random.equals(other.random))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Swarm [particles=" + Arrays.toString(particles) + ", bestPosition=" + Arrays.toString(bestPosition)
+ ", bestFitness=" + bestFitness + ", random=" + random + "]";
}
}

View File

@ -0,0 +1,75 @@
package com.baeldung.algorithms.numberwordconverter;
import java.math.BigDecimal;
import pl.allegro.finance.tradukisto.MoneyConverters;
public class NumberWordConverter {
public static final String INVALID_INPUT_GIVEN = "Invalid input given";
public static final String[] ones = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
public static final String[] tens = {
"", // 0
"", // 1
"twenty", // 2
"thirty", // 3
"forty", // 4
"fifty", // 5
"sixty", // 6
"seventy", // 7
"eighty", // 8
"ninety" // 9
};
public static String getMoneyIntoWords(String input) {
MoneyConverters converter = MoneyConverters.ENGLISH_BANKING_MONEY_VALUE;
return converter.asWords(new BigDecimal(input));
}
public static String getMoneyIntoWords(final double money) {
long dollar = (long) money;
long cents = Math.round((money - dollar) * 100);
if (money == 0D) {
return "";
}
if (money < 0) {
return INVALID_INPUT_GIVEN;
}
String dollarPart = "";
if (dollar > 0) {
dollarPart = convert(dollar) + " dollar" + (dollar == 1 ? "" : "s");
}
String centsPart = "";
if (cents > 0) {
if (dollarPart.length() > 0) {
centsPart = " and ";
}
centsPart += convert(cents) + " cent" + (cents == 1 ? "" : "s");
}
return dollarPart + centsPart;
}
private static String convert(final long n) {
if (n < 0) {
return INVALID_INPUT_GIVEN;
}
if (n < 20) {
return ones[(int) n];
}
if (n < 100) {
return tens[(int) n / 10] + ((n % 10 != 0) ? " " : "") + ones[(int) n % 10];
}
if (n < 1000) {
return ones[(int) n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
}
if (n < 1_000_000) {
return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000);
}
if (n < 1_000_000_000) {
return convert(n / 1_000_000) + " million" + ((n % 1_000_000 != 0) ? " " : "") + convert(n % 1_000_000);
}
return convert(n / 1_000_000_000) + " billion" + ((n % 1_000_000_000 != 0) ? " " : "") + convert(n % 1_000_000_000);
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.algorithms.pairsaddupnumber;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
/**
* Find all different pairs of numbers in an array that add up to a given sum - Complexity O(n)
*/
public class DifferentPairs {
/**
* Show all different pairs using traditional "for" loop
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithForLoop(int[] input, int sum) {
final List<Integer> allDifferentPairs = new ArrayList<>();
// Aux. hash map
final Map<Integer, Integer> pairs = new HashMap();
for (int i : input) {
if (pairs.containsKey(i)) {
if (pairs.get(i) != null) {
// Add pair to returned list
allDifferentPairs.add(i);
}
// Mark pair as added to prevent duplicates
pairs.put(sum - i, null);
} else if (!pairs.containsValue(i)) {
// Add pair to aux. hash map
pairs.put(sum - i, i);
}
}
return allDifferentPairs;
}
/**
* Show all different pairs using Java 8 stream API
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithStreamApi(int[] input, int sum) {
final List<Integer> allDifferentPairs = new ArrayList<>();
// Aux. hash map
final Map<Integer, Integer> pairs = new HashMap();
IntStream.range(0, input.length).forEach(i -> {
if (pairs.containsKey(input[i])) {
if (pairs.get(input[i]) != null) {
// Add pair to returned list
allDifferentPairs.add(input[i]);
}
// Mark pair as added to prevent duplicates
pairs.put(sum - input[i], null);
} else if (!pairs.containsValue(input[i])) {
// Add pair to aux. hash map
pairs.put(sum - input[i], input[i]);
}
}
);
return allDifferentPairs;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.algorithms.pairsaddupnumber;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
/**
* Find all existing pairs of numbers in an array that add up to a given sum - Complexity O(n^2) "Brute force"
*/
public class ExistingPairs {
/**
* Show all existing pairs using traditional "for" loop
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithForLoop(int[] input, int sum) {
final List<Integer> allExistingPairs = new ArrayList<>();
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input.length; j++) {
if (j != i && (input[i] + input[j]) == sum) {
allExistingPairs.add(input[i]);
}
}
}
return allExistingPairs;
}
/**
* Show all existing pairs using Java 8 stream API
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithStreamApi(int[] input, int sum) {
final List<Integer> allExistingPairs = new ArrayList<>();
IntStream.range(0, input.length).forEach(i ->
IntStream.range(0, input.length)
.filter(j -> i != j && input[i] + input[j] == sum)
.forEach(j -> allExistingPairs.add(input[i]))
);
return allExistingPairs;
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.algorithms.pairsaddupnumber;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class FindPairs {
public void execute(int[] input, int sum) {
final StringBuilder inputArray = new StringBuilder();
inputArray.append("{");
IntStream.range(0, input.length).forEach(i -> inputArray.append(input[i] + ", "));
inputArray.append("}");
System.out.println(" Given number array: " + inputArray.toString());
System.out.println(" Given sum: " + sum);
/* Call services */
getDifferentPairs(input, sum);
getExistingPairs(input, sum);
}
/**
* Print all existing pairs for the given inputs: input array & sum number
*/
private static void getExistingPairs(int[] input, int sum) {
List<Integer> pairs = new ArrayList<>();
System.out.println("~ All existing pairs ~");
/* Traditional FOR loop */
// Call method
pairs = ExistingPairs.findPairsWithForLoop(input, sum);
// Create a pretty printing
final StringBuilder output1 = new StringBuilder();
pairs.forEach((pair) -> output1.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Traditional \"for\" loop: " + output1.toString().substring(0, output1.length() - 2));
/* Java 8 stream API */
// Call the method
pairs = ExistingPairs.findPairsWithStreamApi(input, sum);
// Create a pretty printing
final StringBuilder output2 = new StringBuilder();
pairs.forEach((pair) -> output2.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Java 8 streams API: " + output2.toString().substring(0, output2.length() - 2));
}
/**
* Print all different pairs for the given inputs: input array & sum number
*/
private static void getDifferentPairs(int[] input, int sum) {
List<Integer> pairs = new ArrayList<>();
System.out.println("~ All different pairs ~");
/* Traditional FOR loop */
// Call method
pairs = DifferentPairs.findPairsWithForLoop(input, sum);
// Create a pretty printing
final StringBuilder output3 = new StringBuilder();
pairs.forEach((pair) -> output3.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Traditional \"for\" loop: " + output3.toString().substring(0, output3.length() - 2));
/* Java 8 stream API */
// Call method
pairs = DifferentPairs.findPairsWithStreamApi(input, sum);
// Create a pretty printing
final StringBuilder output4 = new StringBuilder();
pairs.forEach((pair) -> output4.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Java 8 streams API: " + output4.toString().substring(0, output4.length() - 2));
}
}

View File

@ -40,15 +40,15 @@ public class BacktrackingAlgorithm {
}
private boolean solve(int[][] board) {
for (int r = BOARD_START_INDEX; r < BOARD_SIZE; r++) {
for (int c = BOARD_START_INDEX; c < BOARD_SIZE; c++) {
if (board[r][c] == NO_VALUE) {
for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
if (board[row][column] == NO_VALUE) {
for (int k = MIN_VALUE; k <= MAX_VALUE; k++) {
board[r][c] = k;
if (isValid(board, r, c) && solve(board)) {
board[row][column] = k;
if (isValid(board, row, column) && solve(board)) {
return true;
}
board[r][c] = NO_VALUE;
board[row][column] = NO_VALUE;
}
return false;
}
@ -57,44 +57,44 @@ public class BacktrackingAlgorithm {
return true;
}
private boolean isValid(int[][] board, int r, int c) {
return rowConstraint(board, r) &&
columnConstraint(board, c) &&
subsectionConstraint(board, r, c);
private boolean isValid(int[][] board, int row, int column) {
return rowConstraint(board, row) &&
columnConstraint(board, column) &&
subsectionConstraint(board, row, column);
}
private boolean subsectionConstraint(int[][] board, int r, int c) {
private boolean subsectionConstraint(int[][] board, int row, int column) {
boolean[] constraint = new boolean[BOARD_SIZE];
int subsectionRowStart = (r / SUBSECTION_SIZE) * SUBSECTION_SIZE;
int subsectionRowStart = (row / SUBSECTION_SIZE) * SUBSECTION_SIZE;
int subsectionRowEnd = subsectionRowStart + SUBSECTION_SIZE;
int subsectionColumnStart = (c / SUBSECTION_SIZE) * SUBSECTION_SIZE;
int subsectionColumnStart = (column / SUBSECTION_SIZE) * SUBSECTION_SIZE;
int subsectionColumnEnd = subsectionColumnStart + SUBSECTION_SIZE;
for (int i = subsectionRowStart; i < subsectionRowEnd; i++) {
for (int j = subsectionColumnStart; j < subsectionColumnEnd; j++) {
if (!checkConstraint(board, i, constraint, j)) return false;
for (int r = subsectionRowStart; r < subsectionRowEnd; r++) {
for (int c = subsectionColumnStart; c < subsectionColumnEnd; c++) {
if (!checkConstraint(board, r, constraint, c)) return false;
}
}
return true;
}
private boolean columnConstraint(int[][] board, int c) {
private boolean columnConstraint(int[][] board, int column) {
boolean[] constraint = new boolean[BOARD_SIZE];
return IntStream.range(BOARD_START_INDEX, BOARD_SIZE)
.allMatch(i -> checkConstraint(board, i, constraint, c));
.allMatch(row -> checkConstraint(board, row, constraint, column));
}
private boolean rowConstraint(int[][] board, int r) {
private boolean rowConstraint(int[][] board, int row) {
boolean[] constraint = new boolean[BOARD_SIZE];
return IntStream.range(BOARD_START_INDEX, BOARD_SIZE)
.allMatch(i -> checkConstraint(board, r, constraint, i));
.allMatch(column -> checkConstraint(board, row, constraint, column));
}
private boolean checkConstraint(int[][] board, int r, boolean[] constraint, int c) {
if (board[r][c] != NO_VALUE) {
if (!constraint[board[r][c] - 1]) {
constraint[board[r][c] - 1] = true;
private boolean checkConstraint(int[][] board, int row, boolean[] constraint, int column) {
if (board[row][column] != NO_VALUE) {
if (!constraint[board[row][column] - 1]) {
constraint[board[row][column] - 1] = true;
} else {
return false;
}

View File

@ -34,8 +34,8 @@ public class DancingLinksAlgorithm {
dlx.runSolver();
}
private int getIndex(int row, int col, int num) {
return (row - 1) * BOARD_SIZE * BOARD_SIZE + (col - 1) * BOARD_SIZE + (num - 1);
private int getIndex(int row, int column, int num) {
return (row - 1) * BOARD_SIZE * BOARD_SIZE + (column - 1) * BOARD_SIZE + (num - 1);
}
private boolean[][] createExactCoverBoard() {
@ -51,12 +51,12 @@ public class DancingLinksAlgorithm {
}
private int checkSubsectionConstraint(boolean[][] coverBoard, int hBase) {
for (int br = COVER_START_INDEX; br <= BOARD_SIZE; br += SUBSECTION_SIZE) {
for (int bc = COVER_START_INDEX; bc <= BOARD_SIZE; bc += SUBSECTION_SIZE) {
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row += SUBSECTION_SIZE) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column += SUBSECTION_SIZE) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int rDelta = 0; rDelta < SUBSECTION_SIZE; rDelta++) {
for (int cDelta = 0; cDelta < SUBSECTION_SIZE; cDelta++) {
int index = getIndex(br + rDelta, bc + cDelta, n);
for (int rowDelta = 0; rowDelta < SUBSECTION_SIZE; rowDelta++) {
for (int columnDelta = 0; columnDelta < SUBSECTION_SIZE; columnDelta++) {
int index = getIndex(row + rowDelta, column + columnDelta, n);
coverBoard[index][hBase] = true;
}
}
@ -67,10 +67,10 @@ public class DancingLinksAlgorithm {
}
private int checkColumnConstraint(boolean[][] coverBoard, int hBase) {
for (int c = COVER_START_INDEX; c <= BOARD_SIZE; c++) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int r1 = COVER_START_INDEX; r1 <= BOARD_SIZE; r1++) {
int index = getIndex(r1, c, n);
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
int index = getIndex(row, column, n);
coverBoard[index][hBase] = true;
}
}
@ -79,10 +79,10 @@ public class DancingLinksAlgorithm {
}
private int checkRowConstraint(boolean[][] coverBoard, int hBase) {
for (int r = COVER_START_INDEX; r <= BOARD_SIZE; r++) {
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int c1 = COVER_START_INDEX; c1 <= BOARD_SIZE; c1++) {
int index = getIndex(r, c1, n);
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
int index = getIndex(row, column, n);
coverBoard[index][hBase] = true;
}
}
@ -91,10 +91,10 @@ public class DancingLinksAlgorithm {
}
private int checkCellConstraint(boolean[][] coverBoard, int hBase) {
for (int r = COVER_START_INDEX; r <= BOARD_SIZE; r++) {
for (int c = COVER_START_INDEX; c <= BOARD_SIZE; c++, hBase++) {
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++, hBase++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++) {
int index = getIndex(r, c, n);
int index = getIndex(row, column, n);
coverBoard[index][hBase] = true;
}
}
@ -104,13 +104,13 @@ public class DancingLinksAlgorithm {
private boolean[][] initializeExactCoverBoard(int[][] board) {
boolean[][] coverBoard = createExactCoverBoard();
for (int i = COVER_START_INDEX; i <= BOARD_SIZE; i++) {
for (int j = COVER_START_INDEX; j <= BOARD_SIZE; j++) {
int n = board[i - 1][j - 1];
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
int n = board[row - 1][column - 1];
if (n != NO_VALUE) {
for (int num = MIN_VALUE; num <= MAX_VALUE; num++) {
if (num != n) {
Arrays.fill(coverBoard[getIndex(i, j, num)], false);
Arrays.fill(coverBoard[getIndex(row, column, num)], false);
}
}
}

View File

@ -4,21 +4,21 @@ class DancingNode {
DancingNode L, R, U, D;
ColumnNode C;
DancingNode hookDown(DancingNode n1) {
assert (this.C == n1.C);
n1.D = this.D;
n1.D.U = n1;
n1.U = this;
this.D = n1;
return n1;
DancingNode hookDown(DancingNode node) {
assert (this.C == node.C);
node.D = this.D;
node.D.U = node;
node.U = this;
this.D = node;
return node;
}
DancingNode hookRight(DancingNode n1) {
n1.R = this.R;
n1.R.L = n1;
n1.L = this;
this.R = n1;
return n1;
DancingNode hookRight(DancingNode node) {
node.R = this.R;
node.R.L = node;
node.L = this;
this.R = node;
return node;
}
void unlinkLR() {

View File

@ -13,7 +13,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class HillClimbingAlgorithmTest {
public class HillClimbingAlgorithmUnitTest {
private Stack<String> initStack;
private Stack<String> goalStack;

View File

@ -6,7 +6,7 @@ import org.junit.Test;
import com.baeldung.algorithms.string.search.StringSearchAlgorithms;
public class StringSearchAlgorithmsTest {
public class StringSearchAlgorithmsUnitTest {
@Test

View File

@ -7,7 +7,7 @@ import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.binarysearch.BinarySearch;
public class BinarySearchTest {
public class BinarySearchUnitTest {
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6;

View File

@ -15,7 +15,7 @@ import com.baeldung.algorithms.mcts.tictactoe.Board;
import com.baeldung.algorithms.mcts.tictactoe.Position;
import com.baeldung.algorithms.mcts.tree.Tree;
public class MCTSTest {
public class MCTSUnitTest {
private Tree gameTree;
private MonteCarloTreeSearch mcts;

View File

@ -7,7 +7,7 @@ import static org.junit.Assert.*;
import com.baeldung.algorithms.minimax.MiniMax;
import com.baeldung.algorithms.minimax.Tree;
public class MinimaxTest {
public class MinimaxUnitTest {
private Tree gameTree;
private MiniMax miniMax;

View File

@ -4,7 +4,7 @@ import static org.junit.Assert.*;
import org.junit.Test;
public class BubbleSortTest {
public class BubbleSortUnitTest {
@Test
public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() {

View File

@ -7,13 +7,13 @@ import org.junit.runners.Parameterized;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class EditDistanceTest extends EditDistanceDataProvider {
public class EditDistanceUnitTest extends EditDistanceDataProvider {
private String x;
private String y;
private int result;
public EditDistanceTest(String a, String b, int res) {
public EditDistanceUnitTest(String a, String b, int res) {
super();
x = a;
y = b;

View File

@ -6,11 +6,11 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleDetectionBruteForceTest extends CycleDetectionTestBase {
public class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleDetectionBruteForceTest(Node<Integer> head, boolean cycleExists) {
public CycleDetectionBruteForceUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;

View File

@ -6,11 +6,11 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleDetectionByFastAndSlowIteratorsTest extends CycleDetectionTestBase {
public class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleDetectionByFastAndSlowIteratorsTest(Node<Integer> head, boolean cycleExists) {
public CycleDetectionByFastAndSlowIteratorsUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;

View File

@ -6,11 +6,11 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleDetectionByHashingTest extends CycleDetectionTestBase {
public class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleDetectionByHashingTest(Node<Integer> head, boolean cycleExists) {
public CycleDetectionByHashingUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;

View File

@ -6,11 +6,11 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleRemovalBruteForceTest extends CycleDetectionTestBase {
public class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleRemovalBruteForceTest(Node<Integer> head, boolean cycleExists) {
public CycleRemovalBruteForceUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;

View File

@ -6,11 +6,11 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleRemovalByCountingLoopNodesTest extends CycleDetectionTestBase {
public class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleRemovalByCountingLoopNodesTest(Node<Integer> head, boolean cycleExists) {
public CycleRemovalByCountingLoopNodesUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;

View File

@ -6,11 +6,11 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleRemovalWithoutCountingLoopNodesTest extends CycleDetectionTestBase {
public class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleRemovalWithoutCountingLoopNodesTest(Node<Integer> head, boolean cycleExists) {
public CycleRemovalWithoutCountingLoopNodesUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;

View File

@ -0,0 +1,84 @@
package com.baeldung.algorithms.moneywords;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.algorithms.numberwordconverter.NumberWordConverter;
public class NumberWordConverterUnitTest {
@Test
public void whenMoneyNegative_thenReturnInvalidInput() {
assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13));
}
@Test
public void whenZeroDollarsGiven_thenReturnEmptyString() {
assertEquals("", NumberWordConverter.getMoneyIntoWords(0));
}
@Test
public void whenOnlyDollarsGiven_thenReturnWords() {
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
}
@Test
public void whenOnlyCentsGiven_thenReturnWords() {
assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6));
}
@Test
public void whenAlmostAMillioDollarsGiven_thenReturnWords() {
String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999));
}
@Test
public void whenThirtyMillionDollarsGiven_thenReturnWords() {
String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978));
}
@Test
public void whenTwoBillionDollarsGiven_thenReturnWords() {
String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810));
}
@Test
public void whenGivenDollarsAndCents_thenReturnWords() {
String expectedResult = "nine hundred twenty four dollars and sixty cents";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6));
}
@Test
public void whenOneDollarAndNoCents_thenReturnDollarSingular() {
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
}
@Test
public void whenNoDollarsAndOneCent_thenReturnCentSingular() {
assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01));
}
@Test
public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() {
assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02));
}
@Test
public void whenNoDollarsAndNinetyNineCents_thenReturnWords() {
assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99));
}
@Test
public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() {
assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959));
}
@Test
public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() {
assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310"));
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.algorithms.multiswarm;
/**
* Specific fitness function implementation to solve the League of Legends
* problem. This is the problem statement: <br>
* <br>
* In League of Legends, a player's Effective Health when defending against
* physical damage is given by E=H(100+A)/100, where H is health and A is armor.
* Health costs 2.5 gold per unit, and Armor costs 18 gold per unit. You have
* 3600 gold, and you need to optimize the effectiveness E of your health and
* armor to survive as long as possible against the enemy team's attacks. How
* much of each should you buy? <br>
* <br>
*
* @author Donato Rimenti
*
*/
public class LolFitnessFunction implements FitnessFunction {
/*
* (non-Javadoc)
*
* @see
* com.baeldung.algorithms.multiswarm.FitnessFunction#getFitness(long[])
*/
@Override
public double getFitness(long[] particlePosition) {
long health = particlePosition[0];
long armor = particlePosition[1];
// No negatives values accepted.
if (health < 0 && armor < 0) {
return -(health * armor);
} else if (health < 0) {
return health;
} else if (armor < 0) {
return armor;
}
// Checks if the solution is actually feasible provided our gold.
double cost = (health * 2.5) + (armor * 18);
if (cost > 3600) {
return 3600 - cost;
} else {
// Check how good is the solution.
long fitness = (health * (100 + armor)) / 100;
return fitness;
}
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.algorithms.multiswarm;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import com.baeldung.algorithms.support.MayFailRule;
/**
* Test for {@link Multiswarm}.
*
* @author Donato Rimenti
*
*/
public class MultiswarmUnitTest {
/**
* Rule for handling expected failures. We use this since this test may
* actually fail due to bad luck in the random generation.
*/
@Rule
public MayFailRule mayFailRule = new MayFailRule();
/**
* Tests the multiswarm algorithm with a generic problem. The problem is the
* following: <br>
* <br>
* In League of Legends, a player's Effective Health when defending against
* physical damage is given by E=H(100+A)/100, where H is health and A is
* armor. Health costs 2.5 gold per unit, and Armor costs 18 gold per unit.
* You have 3600 gold, and you need to optimize the effectiveness E of your
* health and armor to survive as long as possible against the enemy team's
* attacks. How much of each should you buy? <br>
* <br>
* The solution is H = 1080, A = 50 for a total fitness of 1620. Tested with
* 50 swarms each with 1000 particles.
*/
@Test
public void givenMultiswarm_whenThousandIteration_thenSolutionFound() {
Multiswarm multiswarm = new Multiswarm(50, 1000, new LolFitnessFunction());
// Iterates 1000 times through the main loop and prints the result.
for (int i = 0; i < 1000; i++) {
multiswarm.mainLoop();
}
System.out.println("Best fitness found: " + multiswarm.getBestFitness() + "[" + multiswarm.getBestPosition()[0]
+ "," + multiswarm.getBestPosition()[1] + "]");
Assert.assertEquals(1080, multiswarm.getBestPosition()[0]);
Assert.assertEquals(50, multiswarm.getBestPosition()[1]);
Assert.assertEquals(1620, (int) multiswarm.getBestFitness());
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.algorithms.pairsaddupnumber;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class DifferentPairsUnitTest {
/* All different pairs */
@Test
public void whenTraditionalLoop_thenReturnAllDifferentPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = DifferentPairs.findPairsWithForLoop(input, sum);
/* Check results */
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
}
@Test
public void whenStreamApi_thenReturnAllDifferentPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = DifferentPairs.findPairsWithStreamApi(input, sum);
/* Check results */
assertNotNull(pairs);
assertEquals(pairs.size(),2);
assertEquals(pairs.get(0), new Integer(4));
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.algorithms.pairsaddupnumber;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ExistingPairsUnitTest {
/* All existing pairs */
@Test
public void whenTraditionalLoop_thenReturnAllExistingPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = ExistingPairs.findPairsWithForLoop(input, sum);
/* Check results */
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
}
@Test
public void whenStreamApi_thenReturnAllExistingPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = ExistingPairs.findPairsWithStreamApi(input, sum);
/* Check results */
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
}
}

View File

@ -7,7 +7,7 @@ import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
public class PrimeGeneratorTest {
public class PrimeGeneratorUnitTest {
@Test
public void whenBruteForced_returnsSuccessfully() {
final List<Integer> primeNumbers = primeNumbersBruteForce(20);

View File

@ -0,0 +1,38 @@
package com.baeldung.algorithms.support;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* JUnit custom rule for managing tests that may fail due to heuristics or
* randomness. In order to use this, just instantiate this object as a public
* field inside the test class and annotate it with {@link Rule}.
*
* @author Donato Rimenti
*
*/
public class MayFailRule implements TestRule {
/*
* (non-Javadoc)
*
* @see org.junit.rules.TestRule#apply(org.junit.runners.model.Statement,
* org.junit.runner.Description)
*/
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
base.evaluate();
} catch (Throwable e) {
// Ignore the exception since we expect this.
}
}
};
}
}

View File

@ -12,7 +12,7 @@ import org.jgrapht.graph.SimpleWeightedGraph;
import org.junit.Before;
import org.junit.Test;
public class CompleteGraphTest {
public class CompleteGraphUnitTest {
static SimpleWeightedGraph<String, DefaultEdge> completeGraph;
static int size = 10;

View File

@ -24,7 +24,7 @@ import org.jgrapht.traverse.DepthFirstIterator;
import org.junit.Before;
import org.junit.Test;
public class DirectedGraphTests {
public class DirectedGraphUnitTest {
DirectedGraph<String, DefaultEdge> directedGraph;
@Before

View File

@ -12,7 +12,7 @@ import org.jgrapht.graph.SimpleWeightedGraph;
import org.junit.Before;
import org.junit.Test;
public class EulerianCircuitTest {
public class EulerianCircuitUnitTest {
SimpleWeightedGraph<String, DefaultEdge> simpleGraph;
@Before

View File

@ -1,57 +1,56 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>animal-sniffer-mvn-plugin</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>example-animal-sniffer-mvn-plugin</name>
<url>http://maven.apache.org</url>
<properties>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
<version>1.16</version>
<configuration>
<signature>
<groupId>org.codehaus.mojo.signature</groupId>
<artifactId>java16</artifactId>
<version>1.0</version>
</signature>
</configuration>
<executions>
<execution>
<id>animal-sniffer</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>animal-sniffer-mvn-plugin</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>example-animal-sniffer-mvn-plugin</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
<version>${animal-sniffer-maven-plugin.version}</version>
<configuration>
<signature>
<groupId>org.codehaus.mojo.signature</groupId>
<artifactId>java16</artifactId>
<version>${org.codehaus.mojo.signature.java16.version}</version>
</signature>
</configuration>
<executions>
<execution>
<id>animal-sniffer</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<animal-sniffer-maven-plugin.version>1.16</animal-sniffer-maven-plugin.version>
<org.codehaus.mojo.signature.java16.version>1.0</org.codehaus.mojo.signature.java16.version>
</properties>
</project>

View File

@ -1,8 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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="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">
<modelVersion>4.0.0</modelVersion>
<artifactId>annotation-processing</artifactId>
<parent>
<groupId>com.baeldung</groupId>
@ -11,40 +12,17 @@
<relativePath>../</relativePath>
</parent>
<artifactId>annotation-processing</artifactId>
<properties>
<auto-service.version>1.0-rc2</auto-service.version>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service</artifactId>
<version>${auto-service.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<auto-service.version>1.0-rc2</auto-service.version>
</properties>
</project>

View File

@ -1,7 +1,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">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>annotation-user</artifactId>
<parent>
<artifactId>annotations</artifactId>
@ -10,16 +11,12 @@
<relativePath>../</relativePath>
</parent>
<artifactId>annotation-user</artifactId>
<dependencies>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>annotation-processing</artifactId>
<version>${project.parent.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -1,15 +1,15 @@
<?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">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>annotations</artifactId>
<packaging>pom</packaging>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>annotations</artifactId>
<packaging>pom</packaging>
<modules>
<module>annotation-processing</module>

View File

@ -1,34 +1,37 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>apache-bval</groupId>
<artifactId>apache-bval</artifactId>
<version>0.0.1-SNAPSHOT</version>
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>apache-bval</groupId>
<artifactId>apache-bval</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-jsr</artifactId>
<version>${bval.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-extras</artifactId>
<version>${bval.version}</version>
</dependency>
</dependencies>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-jsr</artifactId>
<version>${bval.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation.validation-api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-extras</artifactId>
<version>${bval.version}</version>
</dependency>
</dependencies>
<properties>
<bval.version>1.1.2</bval.version>
<javax.validation.validation-api.version>1.1.0.Final</javax.validation.validation-api.version>
</properties>
<properties>
<bval.version>1.1.2</bval.version>
</properties>
</project>

View File

@ -1,42 +1,32 @@
<?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>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-cayenne</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<artifactId>apache-cayenne</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>apache-cayenne</name>
<description>Introduction to Apache Cayenne</description>
<name>apache-cayenne</name>
<description>Introduction to Apache Cayenne</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<mysql.connector.version>5.1.44</mysql.connector.version>
<cayenne.version>4.0.M5</cayenne.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.cayenne</groupId>
<artifactId>cayenne-server</artifactId>
<version>${cayenne.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
<scope>runtime</scope>
</dependency>
<dependencies>
<dependency>
<groupId>org.apache.cayenne</groupId>
<artifactId>cayenne-server</artifactId>
<version>${cayenne.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
@ -46,14 +36,23 @@
</dependency>
</dependencies>
<build>
<plugins>
<build>
<plugins>
<plugin>
<groupId>org.apache.cayenne.plugins</groupId>
<artifactId>cayenne-modeler-maven-plugin</artifactId>
<version>${cayenne.version}</version>
</plugin>
</plugins>
</build>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<mysql.connector.version>5.1.44</mysql.connector.version>
<cayenne.version>4.0.M5</cayenne.version>
<junit.version>4.12</junit.version>
</properties>
</project>

View File

@ -19,7 +19,7 @@ import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class CayenneAdvancedOperationTests {
public class CayenneAdvancedOperationLiveTest {
private static ObjectContext context = null;
@BeforeClass

View File

@ -16,7 +16,7 @@ import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class CayenneOperationTests {
public class CayenneOperationLiveTest {
private static ObjectContext context = null;
@BeforeClass

3
apache-curator/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to Apache Curator](http://www.baeldung.com/apache-curator)

67
apache-curator/pom.xml Normal file
View File

@ -0,0 +1,67 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-curator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- curator -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-x-async</artifactId>
<version>${curator.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>${curator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<curator.version>4.0.1</curator.version>
<zookeeper.version>3.4.11</zookeeper.version>
<jackson-databind.version>2.9.4</jackson-databind.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
</properties>
</project>

View File

@ -0,0 +1,31 @@
package com.baeldung.apache.curator.modeled;
public class HostConfig {
private String hostname;
private int port;
public HostConfig() {
}
public HostConfig(String hostname, int port) {
this.hostname = hostname;
this.port = port;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.apache.curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.junit.Before;
public abstract class BaseManualTest {
@Before
public void setup() {
org.apache.log4j.BasicConfigurator.configure();
}
protected CuratorFramework newClient() {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries);
return CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
}
}

View File

@ -0,0 +1,89 @@
package com.baeldung.apache.curator.configuration;
import static com.jayway.awaitility.Awaitility.await;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.junit.Test;
import com.baeldung.apache.curator.BaseManualTest;
public class ConfigurationManagementManualTest extends BaseManualTest {
private static final String KEY_FORMAT = "/%s";
@Test
public void givenPath_whenCreateKey_thenValueIsStored() throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
String key = getKey();
String expected = "my_value";
// Create key nodes structure
client.create()
.forPath(key);
// Set data value for our key
async.setData()
.forPath(key, expected.getBytes());
// Get data value
AtomicBoolean isEquals = new AtomicBoolean();
async.getData()
.forPath(key)
.thenAccept(
data -> isEquals.set(new String(data).equals(expected)));
await().until(() -> assertThat(isEquals.get()).isTrue());
}
}
@Test
public void givenPath_whenWatchAKeyAndStoreAValue_thenWatcherIsTriggered()
throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
String key = getKey();
String expected = "my_value";
// Create key structure
async.create()
.forPath(key);
List<String> changes = new ArrayList<>();
// Watch data value
async.watched()
.getData()
.forPath(key)
.event()
.thenAccept(watchedEvent -> {
try {
changes.add(new String(client.getData()
.forPath(watchedEvent.getPath())));
} catch (Exception e) {
// fail ...
}
});
// Set data value for our key
async.setData()
.forPath(key, expected.getBytes());
await().until(() -> assertThat(changes.size() > 0).isTrue());
}
}
private String getKey() {
return String.format(KEY_FORMAT, UUID.randomUUID()
.toString());
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.apache.curator.connection;
import static com.jayway.awaitility.Awaitility.await;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.junit.Test;
public class ConnectionManagementManualTest {
@Test
public void givenRunningZookeeper_whenOpenConnection_thenClientIsOpened()
throws Exception {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
sleepMsBetweenRetries);
try (CuratorFramework client = CuratorFrameworkFactory
.newClient("127.0.0.1:2181", retryPolicy)) {
client.start();
assertThat(client.checkExists()
.forPath("/")).isNotNull();
}
}
@Test
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncNotBlocking_thenClientIsOpened()
throws InterruptedException {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
sleepMsBetweenRetries);
try (CuratorFramework client = CuratorFrameworkFactory
.newClient("127.0.0.1:2181", retryPolicy)) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
AtomicBoolean exists = new AtomicBoolean(false);
async.checkExists()
.forPath("/")
.thenAcceptAsync(s -> exists.set(s != null));
await().until(() -> assertThat(exists.get()).isTrue());
}
}
@Test
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncBlocking_thenClientIsOpened()
throws InterruptedException {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
sleepMsBetweenRetries);
try (CuratorFramework client = CuratorFrameworkFactory
.newClient("127.0.0.1:2181", retryPolicy)) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
AtomicBoolean exists = new AtomicBoolean(false);
async.checkExists()
.forPath("/")
.thenAccept(s -> exists.set(s != null));
await().until(() -> assertThat(exists.get()).isTrue());
}
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.apache.curator.modeled;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.apache.curator.x.async.modeled.JacksonModelSerializer;
import org.apache.curator.x.async.modeled.ModelSpec;
import org.apache.curator.x.async.modeled.ModeledFramework;
import org.apache.curator.x.async.modeled.ZPath;
import org.junit.Test;
import com.baeldung.apache.curator.BaseManualTest;
public class ModelTypedExamplesManualTest extends BaseManualTest {
@Test
public void givenPath_whenStoreAModel_thenNodesAreCreated()
throws InterruptedException {
ModelSpec<HostConfig> mySpec = ModelSpec
.builder(ZPath.parseWithIds("/config/dev"),
JacksonModelSerializer.build(HostConfig.class))
.build();
try (CuratorFramework client = newClient()) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
ModeledFramework<HostConfig> modeledClient = ModeledFramework
.wrap(async, mySpec);
modeledClient.set(new HostConfig("host-name", 8080));
modeledClient.read()
.whenComplete((value, e) -> {
if (e != null) {
fail("Cannot read host config", e);
} else {
assertThat(value).isNotNull();
assertThat(value.getHostname()).isEqualTo("host-name");
assertThat(value.getPort()).isEqualTo(8080);
}
});
}
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.apache.curator.recipes;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.apache.curator.framework.recipes.shared.SharedCount;
import org.apache.curator.framework.state.ConnectionState;
import org.junit.Test;
import com.baeldung.apache.curator.BaseManualTest;
public class RecipesManualTest extends BaseManualTest {
@Test
public void givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors() {
try (CuratorFramework client = newClient()) {
client.start();
LeaderSelector leaderSelector = new LeaderSelector(client, "/mutex/select/leader/for/job/A", new LeaderSelectorListener() {
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
}
@Override
public void takeLeadership(CuratorFramework client) throws Exception {
// I'm the leader of the job A !
}
});
leaderSelector.start();
// Wait until the job A is done among all the members
leaderSelector.close();
}
}
@Test
public void givenRunningZookeeper_whenUsingSharedLock_thenNoErrors() throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
InterProcessSemaphoreMutex sharedLock = new InterProcessSemaphoreMutex(client, "/mutex/process/A");
sharedLock.acquire();
// Do process A
sharedLock.release();
}
}
@Test
public void givenRunningZookeeper_whenUsingSharedCounter_thenCounterIsIncrement() throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
try (SharedCount counter = new SharedCount(client, "/counters/A", 0)) {
counter.start();
counter.setCount(0);
counter.setCount(counter.getCount() + 1);
assertThat(counter.getCount()).isEqualTo(1);
}
}
}
}

View File

@ -1,15 +1,14 @@
<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">
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>
@ -17,4 +16,9 @@
<version>${cxf.version}</version>
</dependency>
</dependencies>
<properties>
<cxf.version>3.1.8</cxf.version>
</properties>
</project>

View File

@ -1,7 +1,7 @@
<?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/maven-v4_0_0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>cxf-introduction</artifactId>
@ -11,32 +11,6 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<cxf.version>3.1.8</cxf.version>
<surefire.version>2.19.1</surefire.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.cxf.introduction.Server</mainClass>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
@ -50,4 +24,21 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.cxf.introduction.Server</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<cxf.version>3.1.8</cxf.version>
<surefire.version>2.19.1</surefire.version>
</properties>
</project>

View File

@ -1,7 +1,7 @@
<?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/maven-v4_0_0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>cxf-jaxrs-implementation</artifactId>
@ -11,34 +11,6 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<cxf.version>3.1.8</cxf.version>
<httpclient.version>4.5.2</httpclient.version>
<surefire.version>2.19.1</surefire.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.cxf.jaxrs.implementation.RestfulServer</mainClass>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
@ -62,4 +34,24 @@
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.cxf.jaxrs.implementation.RestfulServer</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<cxf.version>3.1.8</cxf.version>
<httpclient.version>4.5.2</httpclient.version>
<surefire.version>2.19.1</surefire.version>
</properties>
</project>

View File

@ -1,8 +1,9 @@
<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">
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-spring</artifactId>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId>
@ -52,15 +53,6 @@
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
@ -102,24 +94,6 @@
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
@ -130,7 +104,6 @@
<cxf.version>3.1.8</cxf.version>
<spring.version>4.3.4.RELEASE</spring.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<surefire.version>2.19.1</surefire.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>

View File

@ -1,5 +1,5 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId>
@ -19,10 +19,6 @@
<module>cxf-aegis</module>
</modules>
<properties>
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
</properties>
<build>
<defaultGoal>install</defaultGoal>
<pluginManagement>
@ -35,4 +31,9 @@
</plugins>
</pluginManagement>
</build>
<properties>
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
</properties>
</project>

View File

@ -1,10 +1,9 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>apache-fop</artifactId>
<version>0.1-SNAPSHOT</version>
<name>apache-fop</name>
<parent>
@ -61,7 +60,7 @@
<dependency>
<groupId>org.dbdoclet</groupId>
<artifactId>herold</artifactId>
<version>8.0.4</version>
<version>${org.dbdoclet.herold.version}</version>
</dependency>
<dependency>
@ -69,7 +68,6 @@
<artifactId>jtidy</artifactId>
<version>${jtidy.version}</version>
</dependency>
</dependencies>
<build>
@ -82,47 +80,12 @@
</resources>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<exclude>**/*LiveTest.java</exclude>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<fop.version>1.1</fop.version>
<avalon-framework.version>4.3</avalon-framework.version>
<dbdoclet.version>8.0.2</dbdoclet.version>
<jtidy.version>r938</jtidy.version>
<org.dbdoclet.herold.version>8.0.4</org.dbdoclet.herold.version>
</properties>
</project>

3
apache-opennlp/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles
- [Intro to Apache OpenNLP](http://www.baeldung.com/apache-open-nlp)

40
apache-opennlp/pom.xml Normal file
View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-opennlp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.opennlp</groupId>
<artifactId>opennlp-tools</artifactId>
<version>${org.apache.opennlp.opennlp-tools.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${org.assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<org.assertj.version>3.9.0</org.assertj.version>
<org.apache.opennlp.opennlp-tools.version>1.8.4</org.apache.opennlp.opennlp-tools.version>
</properties>
</project>

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,32 @@
package com.baeldung.apache.opennlp;
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.chunker.ChunkerME;
import opennlp.tools.chunker.ChunkerModel;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.tokenize.SimpleTokenizer;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class ChunkerUnitTest {
@Test
public void givenChunkerModel_whenChunk_thenChunksAreDetected() throws Exception {
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
String[] tokens = tokenizer.tokenize("He reckons the current account deficit will narrow to only 8 billion.");
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
POSModel posModel = new POSModel(inputStreamPOSTagger);
POSTaggerME posTagger = new POSTaggerME(posModel);
String tags[] = posTagger.tag(tokens);
InputStream inputStreamChunker = new FileInputStream("src/main/resources/models/en-chunker.bin");
ChunkerModel chunkerModel = new ChunkerModel(inputStreamChunker);
ChunkerME chunker = new ChunkerME(chunkerModel);
String[] chunks = chunker.chunk(tokens, tags);
assertThat(chunks).contains("B-NP", "B-VP", "B-NP", "I-NP", "I-NP", "I-NP", "B-VP", "I-VP", "B-PP", "B-NP", "I-NP", "I-NP", "O");
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.apache.opennlp;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import opennlp.tools.langdetect.Language;
import opennlp.tools.langdetect.LanguageDetector;
import opennlp.tools.langdetect.LanguageDetectorFactory;
import opennlp.tools.langdetect.LanguageDetectorME;
import opennlp.tools.langdetect.LanguageDetectorModel;
import opennlp.tools.langdetect.LanguageDetectorSampleStream;
import opennlp.tools.util.InputStreamFactory;
import opennlp.tools.util.MarkableFileInputStreamFactory;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.PlainTextByLineStream;
import opennlp.tools.util.TrainingParameters;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import org.junit.Test;
public class LanguageDetectorAndTrainingDataUnitTest {
@Test
public void givenLanguageDictionary_whenLanguageDetect_thenLanguageIsDetected() throws FileNotFoundException, IOException {
InputStreamFactory dataIn = new MarkableFileInputStreamFactory(new File("src/main/resources/models/DoccatSample.txt"));
ObjectStream lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
LanguageDetectorSampleStream sampleStream = new LanguageDetectorSampleStream(lineStream);
TrainingParameters params = new TrainingParameters();
params.put(TrainingParameters.ITERATIONS_PARAM, 100);
params.put(TrainingParameters.CUTOFF_PARAM, 5);
params.put("DataIndexer", "TwoPass");
params.put(TrainingParameters.ALGORITHM_PARAM, "NAIVEBAYES");
LanguageDetectorModel model = LanguageDetectorME.train(sampleStream, params, new LanguageDetectorFactory());
LanguageDetector ld = new LanguageDetectorME(model);
Language[] languages = ld.predictLanguages("estava em uma marcenaria na Rua Bruno");
assertThat(Arrays.asList(languages)).extracting("lang", "confidence").contains(tuple("pob", 0.9999999950605625),
tuple("ita", 4.939427661577956E-9), tuple("spa", 9.665954064665144E-15),
tuple("fra", 8.250349924885834E-25));
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.apache.opennlp;
import java.io.InputStream;
import opennlp.tools.lemmatizer.DictionaryLemmatizer;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.tokenize.SimpleTokenizer;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class LemmetizerUnitTest {
@Test
public void givenEnglishDictionary_whenLemmatize_thenLemmasAreDetected() throws Exception {
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
String[] tokens = tokenizer.tokenize("John has a sister named Penny.");
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
POSModel posModel = new POSModel(inputStreamPOSTagger);
POSTaggerME posTagger = new POSTaggerME(posModel);
String tags[] = posTagger.tag(tokens);
InputStream dictLemmatizer = getClass().getResourceAsStream("/models/en-lemmatizer.dict");
DictionaryLemmatizer lemmatizer = new DictionaryLemmatizer(dictLemmatizer);
String[] lemmas = lemmatizer.lemmatize(tokens, tags);
assertThat(lemmas).contains("O", "have", "a", "sister", "name", "O", "O");
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.apache.opennlp;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.tokenize.SimpleTokenizer;
import opennlp.tools.util.Span;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class NamedEntityRecognitionUnitTest {
@Test
public void givenEnglishPersonModel_whenNER_thenPersonsAreDetected() throws Exception {
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
String[] tokens = tokenizer.tokenize("John is 26 years old. His best friend's name is Leonard. He has a sister named Penny.");
InputStream inputStreamNameFinder = getClass().getResourceAsStream("/models/en-ner-person.bin");
TokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder);
NameFinderME nameFinderME = new NameFinderME(model);
List<Span> spans = Arrays.asList(nameFinderME.find(tokens));
assertThat(spans.toString()).isEqualTo("[[0..1) person, [13..14) person, [20..21) person]");
List<String> names = new ArrayList<String>();
int k = 0;
for (Span s : spans) {
names.add("");
for (int index = s.getStart(); index < s.getEnd(); index++) {
names.set(k, names.get(k) + tokens[index]);
}
k++;
}
assertThat(names).contains("John","Leonard","Penny");
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.apache.opennlp;
import java.io.InputStream;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.tokenize.SimpleTokenizer;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class POSTaggerUnitTest {
@Test
public void givenPOSModel_whenPOSTagging_thenPOSAreDetected() throws Exception {
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
String[] tokens = tokenizer.tokenize("John has a sister named Penny.");
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
POSModel posModel = new POSModel(inputStreamPOSTagger);
POSTaggerME posTagger = new POSTaggerME(posModel);
String tags[] = posTagger.tag(tokens);
assertThat(tags).contains("NNP", "VBZ", "DT", "NN", "VBN", "NNP", ".");
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.apache.opennlp;
import java.io.InputStream;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class SentenceDetectionUnitTest {
@Test
public void givenEnglishModel_whenDetect_thenSentencesAreDetected() throws Exception {
String paragraph = "This is a statement. This is another statement. Now is an abstract word for time, "
+ "that is always flying. And my email address is google@gmail.com.";
InputStream is = getClass().getResourceAsStream("/models/en-sent.bin");
SentenceModel model = new SentenceModel(is);
SentenceDetectorME sdetector = new SentenceDetectorME(model);
String sentences[] = sdetector.sentDetect(paragraph);
assertThat(sentences).contains("This is a statement.",
"This is another statement.",
"Now is an abstract word for time, that is always flying.",
"And my email address is google@gmail.com.");
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.apache.opennlp;
import java.io.InputStream;
import opennlp.tools.tokenize.SimpleTokenizer;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.tokenize.WhitespaceTokenizer;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class TokenizerUnitTest {
@Test
public void givenEnglishModel_whenTokenize_thenTokensAreDetected() throws Exception {
InputStream inputStream = getClass().getResourceAsStream("/models/en-token.bin");
TokenizerModel model = new TokenizerModel(inputStream);
TokenizerME tokenizer = new TokenizerME(model);
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", ".");
}
@Test
public void givenWhitespaceTokenizer_whenTokenize_thenTokensAreDetected() throws Exception {
WhitespaceTokenizer tokenizer = WhitespaceTokenizer.INSTANCE;
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource.");
}
@Test
public void givenSimpleTokenizer_whenTokenize_thenTokensAreDetected() throws Exception {
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", ".");
}
}

View File

@ -1,4 +1,4 @@
### Relevant Articles:
- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel)
- [Creating a MS PowerPoint Presentation in Java](https://github.com/eugenp/tutorials/tree/master/apache-poi)
- [Creating a MS PowerPoint Presentation in Java](http://www.baeldung.com/apache-poi-slideshow)

View File

@ -1,5 +1,5 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>apache-poi</artifactId>
@ -11,11 +11,6 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<poi.version>3.15</poi.version>
<jexcel.version>1.0.6</jexcel.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
@ -34,4 +29,10 @@
</exclusions>
</dependency>
</dependencies>
<properties>
<poi.version>3.15</poi.version>
<jexcel.version>1.0.6</jexcel.version>
</properties>
</project>

View File

@ -3,7 +3,6 @@
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>apache-shiro</artifactId>
<version>1.0-SNAPSHOT</version>
@ -11,15 +10,9 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<version>${org.springframework.boot.spring-boot-starter-parent.version}</version>
</parent>
<properties>
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
<log4j-version>1.2.17</log4j-version>
<slf4j-version>1.7.25</slf4j-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -57,7 +50,6 @@
<version>${log4j-version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
@ -74,5 +66,11 @@
</plugins>
</build>
<properties>
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
<log4j-version>1.2.17</log4j-version>
<slf4j-version>1.7.25</slf4j-version>
<org.springframework.boot.spring-boot-starter-parent.version>1.5.2.RELEASE</org.springframework.boot.spring-boot-starter-parent.version>
</properties>
</project>

View File

@ -1,5 +1,5 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>apache-solrj</artifactId>
@ -17,7 +17,12 @@
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>6.4.0</version>
<version>${org.apache.solr.solr-solrj.version}</version>
</dependency>
</dependencies>
<properties>
<org.apache.solr.solr-solrj.version>6.4.0</org.apache.solr.solr-solrj.version>
</properties>
</project>

View File

@ -1,44 +1,37 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
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>apache-spark</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>apache-spark</name>
<url>http://maven.apache.org</url>
<groupId>com.baeldung</groupId>
<artifactId>apache-spark</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<name>apache-spark</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.10 -->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<version>${org.apache.spark.spark-core.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.apache.spark.spark-core.version>2.2.0</org.apache.spark.spark-core.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.10 -->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,5 +1,5 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>apache-thrift</artifactId>
@ -12,12 +12,6 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<java.versin>1.8</java.versin>
<thrift.version>0.10.0</thrift.version>
<maven-thrift.version>0.1.11</maven-thrift.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.thrift</groupId>
@ -34,7 +28,7 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.12</version>
<version>${org.slf4j.slf4j-simple.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -61,4 +55,11 @@
</plugin>
</plugins>
</build>
<properties>
<thrift.version>0.10.0</thrift.version>
<maven-thrift.version>0.1.11</maven-thrift.version>
<org.slf4j.slf4j-simple.version>1.7.12</org.slf4j.slf4j-simple.version>
</properties>
</project>

3
apache-tika/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Content Analysis with Apache Tika](http://www.baeldung.com/apache-tika)

26
apache-tika/pom.xml Normal file
View File

@ -0,0 +1,26 @@
<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>apache-tika</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-parsers</artifactId>
<version>${tika.version}</version>
</dependency>
</dependencies>
<properties>
<tika.version>1.17</tika.version>
</properties>
</project>

View File

@ -0,0 +1,67 @@
package com.baeldung.tika;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.Tika;
import org.apache.tika.detect.DefaultDetector;
import org.apache.tika.detect.Detector;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
public class TikaAnalysis {
public static String detectDocTypeUsingDetector(InputStream stream) throws IOException {
Detector detector = new DefaultDetector();
Metadata metadata = new Metadata();
MediaType mediaType = detector.detect(stream, metadata);
return mediaType.toString();
}
public static String detectDocTypeUsingFacade(InputStream stream) throws IOException {
Tika tika = new Tika();
String mediaType = tika.detect(stream);
return mediaType;
}
public static String extractContentUsingParser(InputStream stream) throws IOException, TikaException, SAXException {
Parser parser = new AutoDetectParser();
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
ParseContext context = new ParseContext();
parser.parse(stream, handler, metadata, context);
return handler.toString();
}
public static String extractContentUsingFacade(InputStream stream) throws IOException, TikaException {
Tika tika = new Tika();
String content = tika.parseToString(stream);
return content;
}
public static Metadata extractMetadatatUsingParser(InputStream stream) throws IOException, SAXException, TikaException {
Parser parser = new AutoDetectParser();
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
ParseContext context = new ParseContext();
parser.parse(stream, handler, metadata, context);
return metadata;
}
public static Metadata extractMetadatatUsingFacade(InputStream stream) throws IOException, TikaException {
Tika tika = new Tika();
Metadata metadata = new Metadata();
tika.parse(stream, metadata);
return metadata;
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.tika;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.junit.Test;
import org.xml.sax.SAXException;
public class TikaUnitTest {
@Test
public void whenUsingDetector_thenDocumentTypeIsReturned() throws IOException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.txt");
String mediaType = TikaAnalysis.detectDocTypeUsingDetector(stream);
assertEquals("application/pdf", mediaType);
stream.close();
}
@Test
public void whenUsingFacade_thenDocumentTypeIsReturned() throws IOException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.txt");
String mediaType = TikaAnalysis.detectDocTypeUsingFacade(stream);
assertEquals("application/pdf", mediaType);
stream.close();
}
@Test
public void whenUsingParser_thenContentIsReturned() throws IOException, TikaException, SAXException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.docx");
String content = TikaAnalysis.extractContentUsingParser(stream);
assertThat(content, containsString("Apache Tika - a content analysis toolkit"));
assertThat(content, containsString("detects and extracts metadata and text"));
stream.close();
}
@Test
public void whenUsingFacade_thenContentIsReturned() throws IOException, TikaException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.docx");
String content = TikaAnalysis.extractContentUsingFacade(stream);
assertThat(content, containsString("Apache Tika - a content analysis toolkit"));
assertThat(content, containsString("detects and extracts metadata and text"));
stream.close();
}
@Test
public void whenUsingParser_thenMetadataIsReturned() throws IOException, TikaException, SAXException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.xlsx");
Metadata metadata = TikaAnalysis.extractMetadatatUsingParser(stream);
assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By"));
assertEquals("Microsoft Office User", metadata.get("Author"));
stream.close();
}
@Test
public void whenUsingFacade_thenMetadataIsReturned() throws IOException, TikaException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.xlsx");
Metadata metadata = TikaAnalysis.extractMetadatatUsingFacade(stream);
assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By"));
assertEquals("Microsoft Office User", metadata.get("Author"));
stream.close();
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,11 +1,9 @@
<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">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<version>0.1-SNAPSHOT</version>
<artifactId>apache-velocity</artifactId>
<packaging>war</packaging>
<name>apache-velocity</name>
@ -15,15 +13,6 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<jdk.version>1.8</jdk.version>
<jstl.version>1.2</jstl.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<org.apache.httpcomponents.version>4.5.2</org.apache.httpcomponents.version>
<velocity-version>1.7</velocity-version>
<velocity-tools-version>2.0</velocity-tools-version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.velocity</groupId>
@ -48,6 +37,7 @@
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>apache-velocity</finalName>
<resources>
@ -67,4 +57,13 @@
</plugin>
</plugins>
</build>
</project>
<properties>
<jstl.version>1.2</jstl.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<org.apache.httpcomponents.version>4.5.2</org.apache.httpcomponents.version>
<velocity-version>1.7</velocity-version>
<velocity-tools-version>2.0</velocity-tools-version>
</properties>
</project>

View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Getting Started with Java and Zookeeper](http://www.baeldung.com/java-zookeeper)

28
apache-zookeeper/pom.xml Normal file
View File

@ -0,0 +1,28 @@
<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>apache-zookeeper</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${org.apache.zookeeper.version}</version>
</dependency>
</dependencies>
<properties>
<org.apache.zookeeper.version>3.4.11</org.apache.zookeeper.version>
</properties>
</project>

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