Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
e8c4bb6308
|
@ -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 test
|
||||
|
||||
sudo: required
|
||||
|
||||
|
|
|
@ -16,3 +16,4 @@
|
|||
- [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)
|
||||
|
|
|
@ -9,6 +9,7 @@
|
|||
<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>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
|
@ -39,6 +40,11 @@
|
|||
<artifactId>jgrapht-core</artifactId>
|
||||
<version>1.0.1</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>
|
||||
|
@ -46,7 +52,6 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
|
@ -77,4 +82,4 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</reporting>
|
||||
</project>
|
||||
</project>
|
|
@ -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 particle’s 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() {
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
|
||||
}
|
|
@ -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 + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -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 + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -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 + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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 NumberWordConverterTest {
|
||||
|
||||
@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"));
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
|
@ -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.
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
<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>
|
||||
|
||||
<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>
|
||||
|
||||
<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>
|
||||
</project>
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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 BaseTest {
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
|
@ -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.BaseTest;
|
||||
|
||||
public class ConfigurationManagementManualTest extends BaseTest {
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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.BaseTest;
|
||||
|
||||
public class ModelTypedExamplesManualTest extends BaseTest {
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -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.BaseTest;
|
||||
|
||||
public class RecipesManualTest extends BaseTest {
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
<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>
|
||||
|
||||
<properties>
|
||||
<tika.version>1.17</tika.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.tika</groupId>
|
||||
<artifactId>tika-parsers</artifactId>
|
||||
<version>${tika.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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.
|
@ -0,0 +1,23 @@
|
|||
<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>3.4.11</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.zookeeper.connection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
import org.apache.zookeeper.WatchedEvent;
|
||||
import org.apache.zookeeper.Watcher;
|
||||
import org.apache.zookeeper.Watcher.Event.KeeperState;
|
||||
import org.apache.zookeeper.ZooKeeper;
|
||||
|
||||
public class ZKConnection {
|
||||
private ZooKeeper zoo;
|
||||
final CountDownLatch connectionLatch = new CountDownLatch(1);
|
||||
|
||||
public ZKConnection() {
|
||||
}
|
||||
|
||||
public ZooKeeper connect(String host) throws IOException, InterruptedException {
|
||||
zoo = new ZooKeeper(host, 2000, new Watcher() {
|
||||
public void process(WatchedEvent we) {
|
||||
if (we.getState() == KeeperState.SyncConnected) {
|
||||
connectionLatch.countDown();
|
||||
}
|
||||
}
|
||||
});
|
||||
connectionLatch.await();
|
||||
return zoo;
|
||||
}
|
||||
|
||||
public void close() throws InterruptedException {
|
||||
zoo.close();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.zookeeper.manager;
|
||||
|
||||
import org.apache.zookeeper.KeeperException;
|
||||
|
||||
public interface ZKManager {
|
||||
/**
|
||||
* Create a Znode and save some data
|
||||
*
|
||||
* @param path
|
||||
* @param data
|
||||
* @throws KeeperException
|
||||
* @throws InterruptedException
|
||||
*/
|
||||
public void create(String path, byte[] data) throws KeeperException, InterruptedException;
|
||||
|
||||
/**
|
||||
* Get ZNode Data
|
||||
*
|
||||
* @param path
|
||||
* @param boolean watchFlag
|
||||
* @throws KeeperException
|
||||
* @throws InterruptedException
|
||||
*/
|
||||
public Object getZNodeData(String path, boolean watchFlag);
|
||||
|
||||
/**
|
||||
* Update the ZNode Data
|
||||
*
|
||||
* @param path
|
||||
* @param data
|
||||
* @throws KeeperException
|
||||
* @throws InterruptedException
|
||||
*/
|
||||
public void update(String path, byte[] data) throws KeeperException, InterruptedException, KeeperException;
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.zookeeper.manager;
|
||||
|
||||
import org.apache.zookeeper.CreateMode;
|
||||
import org.apache.zookeeper.KeeperException;
|
||||
import org.apache.zookeeper.ZooDefs;
|
||||
import org.apache.zookeeper.ZooKeeper;
|
||||
|
||||
import com.baeldung.zookeeper.connection.ZKConnection;
|
||||
|
||||
public class ZKManagerImpl implements ZKManager {
|
||||
private static ZooKeeper zkeeper;
|
||||
private static ZKConnection zkConnection;
|
||||
|
||||
public ZKManagerImpl() {
|
||||
initialize();
|
||||
}
|
||||
|
||||
/** * Initialize connection */
|
||||
private void initialize() {
|
||||
try {
|
||||
zkConnection = new ZKConnection();
|
||||
zkeeper = zkConnection.connect("localhost");
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void closeConnection() {
|
||||
try {
|
||||
zkConnection.close();
|
||||
} catch (InterruptedException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void create(String path, byte[] data) throws KeeperException, InterruptedException {
|
||||
zkeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
|
||||
}
|
||||
|
||||
public Object getZNodeData(String path, boolean watchFlag) {
|
||||
try {
|
||||
byte[] b = null;
|
||||
b = zkeeper.getData(path, null, null);
|
||||
String data = new String(b, "UTF-8");
|
||||
System.out.println(data);
|
||||
return data;
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void update(String path, byte[] data) throws KeeperException, InterruptedException {
|
||||
int version = zkeeper.exists(path, true)
|
||||
.getVersion();
|
||||
zkeeper.setData(path, data, version);
|
||||
}
|
||||
}
|
|
@ -3,4 +3,5 @@
|
|||
- [AWS Lambda Using DynamoDB With Java](http://www.baeldung.com/aws-lambda-dynamodb-java)
|
||||
- [AWS S3 with Java](http://www.baeldung.com/aws-s3-java)
|
||||
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
|
||||
- [Managing EC2 Instances in Java] (http://www.baeldung.com/ec2-java)
|
||||
|
||||
|
|
40
aws/pom.xml
40
aws/pom.xml
|
@ -18,10 +18,12 @@
|
|||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.0</gson.version>
|
||||
<aws-java-sdk.version>1.11.154</aws-java-sdk.version>
|
||||
<aws-java-sdk.version>1.11.290</aws-java-sdk.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito-core.version>2.8.9</mockito-core.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
<dynamodblocal.version>1.11.86</dynamodblocal.version>
|
||||
<dynamodblocal.repository.url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</dynamodblocal.repository.url>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
@ -88,6 +90,13 @@
|
|||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>DynamoDBLocal</artifactId>
|
||||
<version>${dynamodblocal.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -108,6 +117,35 @@
|
|||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>2.10</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includeScope>test</includeScope>
|
||||
<includeTypes>so,dll,dylib</includeTypes>
|
||||
<outputDirectory>${project.basedir}/native-libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>dynamodb-local</id>
|
||||
<name>DynamoDB Local Release Repository</name>
|
||||
<url>${dynamodblocal.repository.url}</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.dynamodb.entity;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
|
||||
|
||||
@DynamoDBTable(tableName = "ProductInfo")
|
||||
public class ProductInfo {
|
||||
|
||||
private String id;
|
||||
private String msrp;
|
||||
private String cost;
|
||||
|
||||
public ProductInfo() {
|
||||
}
|
||||
|
||||
public ProductInfo(String cost, String msrp) {
|
||||
this.msrp = msrp;
|
||||
this.cost = cost;
|
||||
}
|
||||
|
||||
@DynamoDBHashKey
|
||||
@DynamoDBAutoGeneratedKey
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@DynamoDBAttribute
|
||||
public String getMsrp() {
|
||||
return msrp;
|
||||
}
|
||||
|
||||
@DynamoDBAttribute
|
||||
public String getCost() {
|
||||
return cost;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setMsrp(String msrp) {
|
||||
this.msrp = msrp;
|
||||
}
|
||||
|
||||
public void setCost(String cost) {
|
||||
this.cost = cost;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.dynamodb.repository;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class AbstractRepository<T, ID extends Serializable> {
|
||||
|
||||
protected DynamoDBMapper mapper;
|
||||
protected Class<T> entityClass;
|
||||
|
||||
protected AbstractRepository() {
|
||||
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
|
||||
|
||||
// This entityClass refers to the actual entity class in the subclass declaration.
|
||||
|
||||
// For instance, ProductInfoDAO extends AbstractDAO<ProductInfo, String>
|
||||
// In this case entityClass = ProductInfo, and ID is String type
|
||||
// which refers to the ProductInfo's partition key string value
|
||||
this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
|
||||
}
|
||||
|
||||
public void save(T t) {
|
||||
mapper.save(t);
|
||||
}
|
||||
|
||||
public T findOne(ID id) {
|
||||
return mapper.load(entityClass, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* <strong>WARNING:</strong> It is not recommended to perform full table scan
|
||||
* targeting the real production environment.
|
||||
*
|
||||
* @return All items
|
||||
*/
|
||||
public List<T> findAll() {
|
||||
DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
|
||||
return mapper.scan(entityClass, scanExpression);
|
||||
}
|
||||
|
||||
public void setMapper(DynamoDBMapper dynamoDBMapper) {
|
||||
this.mapper = dynamoDBMapper;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package com.baeldung.dynamodb.repository;
|
||||
|
||||
import com.baeldung.dynamodb.entity.ProductInfo;
|
||||
|
||||
public class ProductInfoRepository extends AbstractRepository<ProductInfo, String> {
|
||||
}
|
|
@ -0,0 +1,137 @@
|
|||
package com.baeldung.ec2;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import com.amazonaws.auth.AWSCredentials;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.ec2.AmazonEC2;
|
||||
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
|
||||
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
|
||||
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
|
||||
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
|
||||
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
|
||||
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
|
||||
import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest;
|
||||
import com.amazonaws.services.ec2.model.DescribeKeyPairsResult;
|
||||
import com.amazonaws.services.ec2.model.IpPermission;
|
||||
import com.amazonaws.services.ec2.model.IpRange;
|
||||
import com.amazonaws.services.ec2.model.MonitorInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.RebootInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.RunInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.StartInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.StopInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest;
|
||||
|
||||
public class EC2Application {
|
||||
|
||||
private static final AWSCredentials credentials;
|
||||
|
||||
static {
|
||||
// put your accesskey and secretkey here
|
||||
credentials = new BasicAWSCredentials(
|
||||
"<AWS accesskey>",
|
||||
"<AWS secretkey>"
|
||||
);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Set up the client
|
||||
AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
|
||||
.withCredentials(new AWSStaticCredentialsProvider(credentials))
|
||||
.withRegion(Regions.US_EAST_1)
|
||||
.build();
|
||||
|
||||
// Create a security group
|
||||
CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
|
||||
.withDescription("Baeldung Security Group");
|
||||
ec2Client.createSecurityGroup(createSecurityGroupRequest);
|
||||
|
||||
// Allow HTTP and SSH traffic
|
||||
IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");
|
||||
|
||||
IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
|
||||
.withIpProtocol("tcp")
|
||||
.withFromPort(80)
|
||||
.withToPort(80);
|
||||
|
||||
IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
|
||||
.withIpProtocol("tcp")
|
||||
.withFromPort(22)
|
||||
.withToPort(22);
|
||||
|
||||
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
|
||||
.withGroupName("BaeldungSecurityGroup")
|
||||
.withIpPermissions(ipPermission1, ipPermission2);
|
||||
|
||||
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
|
||||
|
||||
// Create KeyPair
|
||||
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
|
||||
.withKeyName("baeldung-key-pair");
|
||||
CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
|
||||
String privateKey = createKeyPairResult
|
||||
.getKeyPair()
|
||||
.getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key
|
||||
|
||||
// See what key-pairs you've got
|
||||
DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
|
||||
DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);
|
||||
|
||||
// Launch an Amazon Instance
|
||||
RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
|
||||
.withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
|
||||
.withMinCount(1)
|
||||
.withMaxCount(1)
|
||||
.withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
|
||||
.withSecurityGroups("BaeldungSecurityGroup");
|
||||
|
||||
String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();
|
||||
|
||||
// Start an Instance
|
||||
StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.startInstances(startInstancesRequest);
|
||||
|
||||
// Monitor Instances
|
||||
MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.monitorInstances(monitorInstancesRequest);
|
||||
|
||||
UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.unmonitorInstances(unmonitorInstancesRequest);
|
||||
|
||||
// Reboot an Instance
|
||||
|
||||
RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.rebootInstances(rebootInstancesRequest);
|
||||
|
||||
// Stop an Instance
|
||||
StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.stopInstances(stopInstancesRequest)
|
||||
.getStoppingInstances()
|
||||
.get(0)
|
||||
.getPreviousState()
|
||||
.getName();
|
||||
|
||||
// Describe an Instance
|
||||
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
|
||||
DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
|
||||
System.out.println(response.getReservations()
|
||||
.get(0)
|
||||
.getInstances()
|
||||
.get(0)
|
||||
.getKernelId());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung.s3;
|
||||
|
||||
import com.amazonaws.AmazonClientException;
|
||||
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
|
||||
import com.amazonaws.event.ProgressListener;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
|
||||
import com.amazonaws.services.s3.model.PutObjectRequest;
|
||||
import com.amazonaws.services.s3.transfer.TransferManager;
|
||||
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
|
||||
import com.amazonaws.services.s3.transfer.Upload;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public class MultipartUpload {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String existingBucketName = "baeldung-bucket";
|
||||
String keyName = "my-picture.jpg";
|
||||
String filePath = "documents/my-picture.jpg";
|
||||
|
||||
AmazonS3 amazonS3 = AmazonS3ClientBuilder
|
||||
.standard()
|
||||
.withCredentials(new DefaultAWSCredentialsProviderChain())
|
||||
.withRegion(Regions.DEFAULT_REGION)
|
||||
.build();
|
||||
|
||||
int maxUploadThreads = 5;
|
||||
|
||||
TransferManager tm = TransferManagerBuilder
|
||||
.standard()
|
||||
.withS3Client(amazonS3)
|
||||
.withMultipartUploadThreshold((long) (5 * 1024 * 1024))
|
||||
.withExecutorFactory(() -> Executors.newFixedThreadPool(maxUploadThreads))
|
||||
.build();
|
||||
|
||||
ProgressListener progressListener =
|
||||
progressEvent -> System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred());
|
||||
|
||||
PutObjectRequest request = new PutObjectRequest(existingBucketName, keyName, new File(filePath));
|
||||
|
||||
request.setGeneralProgressListener(progressListener);
|
||||
|
||||
Upload upload = tm.upload(request);
|
||||
|
||||
try {
|
||||
upload.waitForCompletion();
|
||||
System.out.println("Upload complete.");
|
||||
} catch (AmazonClientException e) {
|
||||
System.out.println("Error occurred while uploading file");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,121 @@
|
|||
package com.baeldung.dynamodb;
|
||||
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
|
||||
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
|
||||
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
|
||||
import com.amazonaws.services.dynamodbv2.model.ResourceInUseException;
|
||||
import com.baeldung.dynamodb.entity.ProductInfo;
|
||||
import com.baeldung.dynamodb.repository.ProductInfoRepository;
|
||||
import com.baeldung.dynamodb.rule.LocalDbCreationRule;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class ProductInfoRepositoryIntegrationTest {
|
||||
|
||||
@ClassRule
|
||||
public static LocalDbCreationRule dynamoDB = new LocalDbCreationRule();
|
||||
|
||||
private static DynamoDBMapper dynamoDBMapper;
|
||||
private static AmazonDynamoDB amazonDynamoDB;
|
||||
|
||||
private ProductInfoRepository repository;
|
||||
|
||||
private static final String DYNAMODB_ENDPOINT = "amazon.dynamodb.endpoint";
|
||||
private static final String AWS_ACCESSKEY = "amazon.aws.accesskey";
|
||||
private static final String AWS_SECRETKEY = "amazon.aws.secretkey";
|
||||
|
||||
private static final String EXPECTED_COST = "20";
|
||||
private static final String EXPECTED_PRICE = "50";
|
||||
|
||||
@BeforeClass
|
||||
public static void setupClass() {
|
||||
Properties testProperties = loadFromFileInClasspath("test.properties")
|
||||
.filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY)))
|
||||
.filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY)))
|
||||
.filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT)))
|
||||
.orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values"));
|
||||
|
||||
String amazonAWSAccessKey = testProperties.getProperty(AWS_ACCESSKEY);
|
||||
String amazonAWSSecretKey = testProperties.getProperty(AWS_SECRETKEY);
|
||||
String amazonDynamoDBEndpoint = testProperties.getProperty(DYNAMODB_ENDPOINT);
|
||||
|
||||
amazonDynamoDB = new AmazonDynamoDBClient(new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey));
|
||||
amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint);
|
||||
dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
try {
|
||||
repository = new ProductInfoRepository();
|
||||
repository.setMapper(dynamoDBMapper);
|
||||
|
||||
CreateTableRequest tableRequest = dynamoDBMapper.generateCreateTableRequest(ProductInfo.class);
|
||||
|
||||
tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
|
||||
|
||||
amazonDynamoDB.createTable(tableRequest);
|
||||
} catch (ResourceInUseException e) {
|
||||
// Do nothing, table already created
|
||||
}
|
||||
|
||||
// TODO How to handle different environments. i.e. AVOID deleting all entries in ProductInfo on table
|
||||
dynamoDBMapper.batchDelete((List<ProductInfo>) repository.findAll());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenItemWithExpectedCost_whenRunFindAll_thenItemIsFound() {
|
||||
|
||||
ProductInfo productInfo = new ProductInfo(EXPECTED_COST, EXPECTED_PRICE);
|
||||
repository.save(productInfo);
|
||||
|
||||
List<ProductInfo> result = (List<ProductInfo>) repository.findAll();
|
||||
assertThat(result.size(), is(greaterThan(0)));
|
||||
assertThat(result.get(0).getCost(), is(equalTo(EXPECTED_COST)));
|
||||
}
|
||||
|
||||
private static boolean isEmpty(String inputString) {
|
||||
return inputString == null || "".equals(inputString);
|
||||
}
|
||||
|
||||
private static Optional<Properties> loadFromFileInClasspath(String fileName) {
|
||||
InputStream stream = null;
|
||||
try {
|
||||
Properties config = new Properties();
|
||||
Path configLocation = Paths.get(ClassLoader.getSystemResource(fileName).toURI());
|
||||
stream = Files.newInputStream(configLocation);
|
||||
config.load(stream);
|
||||
return Optional.of(config);
|
||||
} catch (Exception e) {
|
||||
return Optional.empty();
|
||||
} finally {
|
||||
if (stream != null) {
|
||||
try {
|
||||
stream.close();
|
||||
} catch (IOException e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.dynamodb.rule;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;
|
||||
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;
|
||||
import org.junit.rules.ExternalResource;
|
||||
|
||||
public class LocalDbCreationRule extends ExternalResource {
|
||||
|
||||
protected DynamoDBProxyServer server;
|
||||
|
||||
public LocalDbCreationRule() {
|
||||
System.setProperty("sqlite4java.library.path", "native-libs");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void before() throws Exception {
|
||||
String port = "8000";
|
||||
this.server = ServerRunner.createServerFromCommandLineArgs(new String[]{"-inMemory", "-port", port});
|
||||
server.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void after() {
|
||||
this.stopUnchecked(server);
|
||||
}
|
||||
|
||||
protected void stopUnchecked(DynamoDBProxyServer dynamoDbServer) {
|
||||
try {
|
||||
dynamoDbServer.stop();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.s3;
|
||||
|
||||
import com.amazonaws.event.ProgressListener;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.model.PutObjectRequest;
|
||||
import com.amazonaws.services.s3.model.PutObjectResult;
|
||||
import com.amazonaws.services.s3.transfer.TransferManager;
|
||||
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
|
||||
import com.amazonaws.services.s3.transfer.Upload;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class MultipartUploadTest {
|
||||
|
||||
private static final String BUCKET_NAME = "bucket_name";
|
||||
private static final String KEY_NAME = "picture.jpg";
|
||||
|
||||
private AmazonS3 amazonS3;
|
||||
private TransferManager tm;
|
||||
private ProgressListener progressListener;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
amazonS3 = mock(AmazonS3.class);
|
||||
tm = TransferManagerBuilder
|
||||
.standard()
|
||||
.withS3Client(amazonS3)
|
||||
.withMultipartUploadThreshold((long) (5 * 1024 * 1025))
|
||||
.withExecutorFactory(() -> Executors.newFixedThreadPool(5))
|
||||
.build();
|
||||
progressListener =
|
||||
progressEvent -> System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUploadingFileWithTransferManager_thenVerifyUploadRequested() {
|
||||
File file = mock(File.class);
|
||||
PutObjectResult s3Result = mock(PutObjectResult.class);
|
||||
|
||||
when(amazonS3.putObject(anyString(), anyString(), (File) any())).thenReturn(s3Result);
|
||||
when(file.getName()).thenReturn(KEY_NAME);
|
||||
|
||||
PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, KEY_NAME, file);
|
||||
request.setGeneralProgressListener(progressListener);
|
||||
|
||||
Upload upload = tm.upload(request);
|
||||
|
||||
assertThat(upload).isNotNull();
|
||||
verify(amazonS3).putObject(request);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
amazon.dynamodb.endpoint=http://localhost:8000/
|
||||
amazon.aws.accesskey=key
|
||||
amazon.aws.secretkey=key2
|
|
@ -0,0 +1,114 @@
|
|||
<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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>checker-plugin</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>checker-plugin</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<!-- https://checkerframework.org/manual/#maven -->
|
||||
|
||||
<properties>
|
||||
<!-- These properties will be set by the Maven Dependency plugin -->
|
||||
<annotatedJdk>${org.checkerframework:jdk8:jar}</annotatedJdk>
|
||||
<!-- Uncomment to use the Type Annotations compiler. -->
|
||||
<!--
|
||||
<typeAnnotationsJavac>${org.checkerframework:compiler:jar}</typeAnnotationsJavac>
|
||||
-->
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
|
||||
<!-- Annotations from the Checker Framework: nullness, interning, locking, ... -->
|
||||
<dependency>
|
||||
<groupId>org.checkerframework</groupId>
|
||||
<artifactId>checker-qual</artifactId>
|
||||
<version>2.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.checkerframework</groupId>
|
||||
<artifactId>checker</artifactId>
|
||||
<version>2.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.checkerframework</groupId>
|
||||
<artifactId>jdk8</artifactId>
|
||||
<version>2.3.1</version>
|
||||
</dependency>
|
||||
<!-- The Type Annotations compiler. Uncomment if using annotations in comments. -->
|
||||
<dependency>
|
||||
<groupId>org.checkerframework</groupId>
|
||||
<artifactId>compiler</artifactId>
|
||||
<version>2.3.1</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<!-- This plugin will set properties values using dependency information -->
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<!--
|
||||
Goal that sets a property pointing to the artifact file for each project dependency.
|
||||
For each dependency (direct and transitive) a project property will be set which
|
||||
follows the:
|
||||
|
||||
groupId:artifactId:type:[classifier]
|
||||
|
||||
form and contains the path to the resolved artifact. -->
|
||||
<goal>properties</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.6.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<!-- Uncomment the following line to use the type annotations compiler. -->
|
||||
<!-- <fork>true</fork> -->
|
||||
<compilerArguments>
|
||||
<Xmaxerrs>10000</Xmaxerrs>
|
||||
<Xmaxwarns>10000</Xmaxwarns>
|
||||
</compilerArguments>
|
||||
<annotationProcessors>
|
||||
<!-- Add all the checkers you want to enable here -->
|
||||
<annotationProcessor>org.checkerframework.checker.nullness.NullnessChecker</annotationProcessor>
|
||||
<annotationProcessor>org.checkerframework.checker.interning.InterningChecker</annotationProcessor>
|
||||
<annotationProcessor>org.checkerframework.checker.fenum.FenumChecker</annotationProcessor>
|
||||
<annotationProcessor>org.checkerframework.checker.formatter.FormatterChecker</annotationProcessor>
|
||||
<annotationProcessor>org.checkerframework.checker.regex.RegexChecker</annotationProcessor>
|
||||
</annotationProcessors>
|
||||
<compilerArgs>
|
||||
<arg>-AprintErrorStack</arg>
|
||||
|
||||
<!-- location of the annotated JDK, which comes from a Maven dependency -->
|
||||
<arg>-Xbootclasspath/p:${annotatedJdk}</arg>
|
||||
<!--
|
||||
-->
|
||||
|
||||
<!-- Uncomment the following line to use the type annotations compiler. -->
|
||||
<!--
|
||||
<arg>-J-Xbootclasspath/p:${typeAnnotationsJavac}</arg>
|
||||
-->
|
||||
<!-- Uncomment the following line to turn type-checking warnings into errors. -->
|
||||
<arg>-Awarns</arg>
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.typechecker;
|
||||
|
||||
import org.checkerframework.checker.fenum.qual.Fenum;
|
||||
|
||||
//@SuppressWarnings("fenum:assignment.type.incompatible")
|
||||
public class FakeNumExample {
|
||||
|
||||
// Here we use some String constants to represents countries.
|
||||
static final @Fenum("country") String ITALY = "IT";
|
||||
static final @Fenum("country") String US = "US";
|
||||
static final @Fenum("country") String UNITED_KINGDOM = "UK";
|
||||
|
||||
// Here we use other String constants to represent planets instead.
|
||||
static final @Fenum("planet") String MARS = "Mars";
|
||||
static final @Fenum("planet") String EARTH = "Earth";
|
||||
static final @Fenum("planet") String VENUS = "Venus";
|
||||
|
||||
// Now we write this method and we want to be sure that
|
||||
// the String parameter has a value of a country, not that is just a String.
|
||||
void greetCountries(@Fenum("country") String country) {
|
||||
System.out.println("Hello " + country);
|
||||
}
|
||||
|
||||
// Similarly we're enforcing here that the provided
|
||||
// parameter is a String that represent a planet.
|
||||
void greetPlanets(@Fenum("planet") String planet) {
|
||||
System.out.println("Hello " + planet);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
FakeNumExample obj = new FakeNumExample();
|
||||
|
||||
// This will fail because we pass a planet-String to a method that
|
||||
// accept a country-String.
|
||||
obj.greetCountries(MARS);
|
||||
|
||||
// Here the opposite happens.
|
||||
obj.greetPlanets(US);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.typechecker;
|
||||
|
||||
public class FormatExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Just enabling org.checkerframework.checker.formatter.FormatterChecker
|
||||
// we can be sure at compile time that the format strings we pass to format()
|
||||
// are correct. Normally we would have those errors raised just at runtime.
|
||||
// All those formats are in fact wrong.
|
||||
|
||||
String.format("%y", 7); // error: invalid format string
|
||||
|
||||
String.format("%d", "a string"); // error: invalid argument type for %d
|
||||
|
||||
String.format("%d %s", 7); // error: missing argument for %s
|
||||
|
||||
String.format("%d", 7, 3); // warning: unused argument 3
|
||||
|
||||
String.format("{0}", 7); // warning: unused argument 7, because {0} is wrong syntax
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.typechecker;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.KeyFor;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class KeyForExample {
|
||||
|
||||
private final Map<String, String> config = new HashMap<>();
|
||||
|
||||
KeyForExample() {
|
||||
|
||||
// Here we initialize a map to store
|
||||
// some config data.
|
||||
config.put("url", "http://1.2.3.4");
|
||||
config.put("name", "foobaz");
|
||||
}
|
||||
|
||||
public void dumpPort() {
|
||||
|
||||
// Here, we want to dump the port value stored in the
|
||||
// config, so we declare that this key has to be
|
||||
// present in the config map.
|
||||
// Obviously that will fail because such key is not present
|
||||
// in the map.
|
||||
@KeyFor("config") String key = "port";
|
||||
System.out.println( config.get(key) );
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.typechecker;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class MonotonicNotNullExample {
|
||||
|
||||
// The idea is we need this field to be to lazily initialized,
|
||||
// so it starts as null but once it becomes not null
|
||||
// it cannot return null.
|
||||
// In these cases, we can use @MonotonicNonNull
|
||||
@MonotonicNonNull private Date firstCall;
|
||||
|
||||
public Date getFirstCall() {
|
||||
if (firstCall == null) {
|
||||
firstCall = new Date();
|
||||
}
|
||||
return firstCall;
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
// This is reported as error because
|
||||
// we wrongly set the field back to null.
|
||||
firstCall = null;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.typechecker;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
public class NonNullExample {
|
||||
|
||||
// This method's parameter is annotated in order
|
||||
// to tell the pluggable type system that it can never be null.
|
||||
private static int countArgs(@NonNull String[] args) {
|
||||
return args.length;
|
||||
}
|
||||
|
||||
// This method's parameter is annotated in order
|
||||
// to tell the pluggable type system that it may be null.
|
||||
public static void main(@Nullable String[] args) {
|
||||
|
||||
// Here lies a potential error,
|
||||
// because we pass a potential null reference to a method
|
||||
// that does not accept nulls.
|
||||
// The Checker Framework will spot this problem at compile time
|
||||
// instead of runtime.
|
||||
System.out.println(countArgs(args));
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.typechecker;
|
||||
|
||||
import org.checkerframework.checker.regex.qual.Regex;
|
||||
|
||||
public class RegexExample {
|
||||
|
||||
// For some reason we want to be sure that this regex
|
||||
// contains at least one capturing group.
|
||||
// However, we do an error and we forgot to define such
|
||||
// capturing group in it.
|
||||
@Regex(1) private static String findNumbers = "\\d*";
|
||||
|
||||
public static void main(String[] args) {
|
||||
String message = "My phone number is +3911223344.";
|
||||
message.matches(findNumbers);
|
||||
}
|
||||
|
||||
}
|
|
@ -1 +1,4 @@
|
|||
# Groovy
|
||||
|
||||
## Relevant articles:
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
group 'com.baeldung'
|
||||
version '1.0-SNAPSHOT'
|
||||
|
||||
apply plugin: 'groovy'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile 'org.codehaus.groovy:groovy-all:2.4.13'
|
||||
testCompile 'org.spockframework:spock-core:1.1-groovy-2.4'
|
||||
}
|
|
@ -0,0 +1,128 @@
|
|||
<?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>core-groovy</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>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
<url>http://jcenter.bintray.com</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy</artifactId>
|
||||
<version>2.4.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>2.4.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-sql</artifactId>
|
||||
<version>2.4.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>2.4.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.spockframework</groupId>
|
||||
<artifactId>spock-core</artifactId>
|
||||
<version>1.1-groovy-2.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmavenplus</groupId>
|
||||
<artifactId>gmavenplus-plugin</artifactId>
|
||||
<version>1.6</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>addSources</goal>
|
||||
<goal>addTestSources</goal>
|
||||
<goal>compile</goal>
|
||||
<goal>compileTests</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>2.19.1</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>junit5</id>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*Test5.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<kotlin-maven-plugin.version>1.1.2</kotlin-maven-plugin.version>
|
||||
<kotlin-test-junit.version>1.1.2</kotlin-test-junit.version>
|
||||
<kotlin-stdlib.version>1.1.2</kotlin-stdlib.version>
|
||||
<kotlin-reflect.version>1.1.2</kotlin-reflect.version>
|
||||
<kotlinx.version>0.15</kotlinx.version>
|
||||
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
||||
|
||||
<junit.jupiter.version>5.0.0</junit.jupiter.version>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<junit.vintage.version>4.12.0</junit.vintage.version>
|
||||
<junit4.version>4.12</junit4.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.json
|
||||
|
||||
class Account {
|
||||
String id
|
||||
BigDecimal value
|
||||
Date createdAt
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.json
|
||||
|
||||
import groovy.json.JsonOutput
|
||||
import groovy.json.JsonParserType
|
||||
import groovy.json.JsonSlurper
|
||||
|
||||
class JsonParser {
|
||||
|
||||
Account toObject(String json) {
|
||||
JsonSlurper jsonSlurper = new JsonSlurper()
|
||||
jsonSlurper.parseText(json) as Account
|
||||
}
|
||||
|
||||
Account toObjectWithIndexOverlay(String json) {
|
||||
JsonSlurper jsonSlurper = new JsonSlurper(type: JsonParserType.INDEX_OVERLAY)
|
||||
jsonSlurper.parseText(json) as Account
|
||||
}
|
||||
|
||||
String toJson(Account account) {
|
||||
JsonOutput.toJson(account)
|
||||
}
|
||||
|
||||
String prettyfy(String json) {
|
||||
JsonOutput.prettyPrint(json)
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,229 @@
|
|||
package com.baeldung.groovy.sql
|
||||
|
||||
import groovy.sql.GroovyResultSet
|
||||
import groovy.sql.GroovyRowResult
|
||||
import groovy.sql.Sql
|
||||
import groovy.transform.CompileStatic
|
||||
import static org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class SqlTest {
|
||||
|
||||
final Map dbConnParams = [url: 'jdbc:hsqldb:mem:testDB', user: 'sa', password: '', driver: 'org.hsqldb.jdbc.JDBCDriver']
|
||||
|
||||
@Test
|
||||
void whenNewSqlInstance_thenDbIsAccessed() {
|
||||
def sql = Sql.newInstance(dbConnParams)
|
||||
sql.close()
|
||||
sql.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTableDoesNotExist_thenSelectFails() {
|
||||
try {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.eachRow('select * from PROJECT') {}
|
||||
}
|
||||
|
||||
fail("An exception should have been thrown")
|
||||
} catch (ignored) {
|
||||
//Ok
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTableCreated_thenSelectIsPossible() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
def result = sql.execute 'create table PROJECT_1 (id integer not null, name varchar(50), url varchar(100))'
|
||||
|
||||
assertEquals(0, sql.updateCount)
|
||||
assertFalse(result)
|
||||
|
||||
result = sql.execute('select * from PROJECT_1')
|
||||
|
||||
assertTrue(result)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIdentityColumn_thenInsertReturnsNewId() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
def ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
|
||||
assertEquals(0, ids[0][0])
|
||||
|
||||
ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
|
||||
assertEquals(1, ids[0][0])
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUpdate_thenNumberOfAffectedRows() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
def count = sql.executeUpdate("UPDATE PROJECT_3 SET URL = 'https://' + URL")
|
||||
|
||||
assertEquals(2, count)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenEachRow_thenResultSetHasProperties() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
|
||||
sql.eachRow("SELECT * FROM PROJECT_4") { GroovyResultSet rs ->
|
||||
assertNotNull(rs.name)
|
||||
assertNotNull(rs.url)
|
||||
assertNotNull(rs[0])
|
||||
assertNotNull(rs[1])
|
||||
assertNotNull(rs[2])
|
||||
assertEquals(rs.name, rs['name'])
|
||||
assertEquals(rs.url, rs['url'])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenPagination_thenSubsetIsReturned() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
def rows = sql.rows('SELECT * FROM PROJECT_5 ORDER BY NAME', 1, 1)
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
assertEquals('REST with Spring', rows[0].name)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenParameters_thenReplacement() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.execute('INSERT INTO PROJECT_6 (NAME, URL) VALUES (?, ?)', 'tutorials', 'github.com/eugenp/tutorials')
|
||||
sql.execute("INSERT INTO PROJECT_6 (NAME, URL) VALUES (:name, :url)", [name: 'REST with Spring', url: 'github.com/eugenp/REST-With-Spring'])
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'tutorials'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
|
||||
rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'REST with Spring'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenParametersInGString_thenReplacement() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${'tutorials'}, ${'github.com/eugenp/tutorials'})"
|
||||
def name = 'REST with Spring'
|
||||
def url = 'github.com/eugenp/REST-With-Spring'
|
||||
sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${name}, ${url})"
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_7 WHERE NAME = 'tutorials'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
|
||||
rows = sql.rows("SELECT * FROM PROJECT_7 WHERE NAME = 'REST with Spring'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTransactionRollback_thenNoDataInserted() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.withTransaction {
|
||||
sql.execute 'create table PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
sql.rollback()
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_8")
|
||||
|
||||
assertEquals(0, rows.size())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTransactionRollbackThenCommit_thenOnlyLastInserted() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.withTransaction {
|
||||
sql.execute 'create table PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.rollback()
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
sql.rollback()
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
}
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_9")
|
||||
|
||||
assertEquals(2, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenException_thenTransactionIsRolledBack() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
try {
|
||||
sql.withTransaction {
|
||||
sql.execute 'create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_10 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
throw new Exception('rollback')
|
||||
}
|
||||
} catch (ignored) {}
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_10")
|
||||
|
||||
assertEquals(0, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCachedConnection_whenException_thenDataIsPersisted() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
try {
|
||||
sql.cacheConnection {
|
||||
sql.execute 'create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_11 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
throw new Exception('This does not rollback')
|
||||
}
|
||||
} catch (ignored) {}
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_11")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
/*@Test
|
||||
void whenModifyResultSet_thenDataIsChanged() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
|
||||
sql.eachRow("SELECT * FROM PROJECT_5 FOR UPDATE ") { GroovyResultSet rs ->
|
||||
rs['name'] = "The great ${rs.name}!" as String
|
||||
rs.updateRow()
|
||||
}
|
||||
|
||||
sql.eachRow("SELECT * FROM PROJECT_5") { GroovyResultSet rs ->
|
||||
assertTrue(rs.name.startsWith('The great '))
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
package com.baeldung.json
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
import java.text.SimpleDateFormat
|
||||
|
||||
class JsonParserTest extends Specification {
|
||||
|
||||
JsonParser jsonParser
|
||||
|
||||
void setup () {
|
||||
jsonParser = new JsonParser()
|
||||
}
|
||||
|
||||
def 'Should parse to Account given Json String' () {
|
||||
given:
|
||||
def json = '{"id":"1234","value":15.6}'
|
||||
when:
|
||||
def account = jsonParser.toObject(json)
|
||||
then:
|
||||
account
|
||||
account instanceof Account
|
||||
account.id == '1234'
|
||||
account.value == 15.6
|
||||
}
|
||||
|
||||
def 'Should parse to Account given Json String with date property' () {
|
||||
given:
|
||||
def json = '{"id":"1234","value":15.6,"createdAt":"2018-01-01T00:00:00+0000"}'
|
||||
when:
|
||||
def account = jsonParser.toObjectWithIndexOverlay(json)
|
||||
then:
|
||||
account
|
||||
account instanceof Account
|
||||
account.id == '1234'
|
||||
account.value == 15.6
|
||||
println account.createdAt
|
||||
account.createdAt == Date.parse('yyyy-MM-dd', '2018-01-01')
|
||||
}
|
||||
|
||||
def 'Should parse to Json given an Account object' () {
|
||||
given:
|
||||
Account account = new Account(
|
||||
id: '123',
|
||||
value: 15.6,
|
||||
createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018')
|
||||
)
|
||||
when:
|
||||
def json = jsonParser.toJson(account)
|
||||
then:
|
||||
json
|
||||
json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}'
|
||||
}
|
||||
|
||||
def 'Should prettify given a json string' () {
|
||||
given:
|
||||
String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}'
|
||||
when:
|
||||
def jsonPretty = jsonParser.prettyfy(json)
|
||||
then:
|
||||
jsonPretty
|
||||
jsonPretty == '{\n "value": 15.6,\n "createdAt": "01/01/2018",\n "id": "123456"\n}'
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -40,3 +40,6 @@
|
|||
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
|
||||
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
|
||||
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
|
||||
|
|
|
@ -0,0 +1,71 @@
|
|||
package com.baeldung.findanelement;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
import org.apache.commons.collections4.IterableUtils;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.collect.Iterables;
|
||||
|
||||
public class FindElementInAList<T> {
|
||||
|
||||
public T findUsingIndexOf(T element, List<T> list) {
|
||||
int index = list.indexOf(element);
|
||||
if (index >= 0) {
|
||||
return element;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean findUsingListIterator(T element, List<T> list) {
|
||||
ListIterator<T> listIterator = list.listIterator();
|
||||
while (listIterator.hasNext()) {
|
||||
T elementFromList = listIterator.next();
|
||||
if (elementFromList.equals(element)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean findUsingEnhancedForLoop(T element, List<T> list) {
|
||||
for (T elementFromList : list) {
|
||||
if (element.equals(elementFromList)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public T findUsingStream(T element, List<T> list) {
|
||||
return list.stream()
|
||||
.filter(integer -> integer.equals(element))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public T findUsingParallelStream(T element, List<T> list) {
|
||||
return list.parallelStream()
|
||||
.filter(integer -> integer.equals(element))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public T findUsingGuava(T element, List<T> list) {
|
||||
T foundElement = Iterables.tryFind(list, new Predicate<T>() {
|
||||
public boolean apply(T input) {
|
||||
return element.equals(input);
|
||||
}
|
||||
}).orNull();
|
||||
return foundElement;
|
||||
}
|
||||
|
||||
public T findUsingApacheCommon(T element, List<T> list) {
|
||||
T foundElement = IterableUtils.find(list, new org.apache.commons.collections4.Predicate<T>() {
|
||||
public boolean evaluate(T input) {
|
||||
return element.equals(input);
|
||||
}
|
||||
});
|
||||
return foundElement;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,116 @@
|
|||
package com.baeldung.findanelement;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindAnElementTest {
|
||||
|
||||
private static List<Integer> scores = new ArrayList<>();
|
||||
static {
|
||||
scores.add(0);
|
||||
scores.add(1);
|
||||
scores.add(2);
|
||||
}
|
||||
|
||||
private static FindElementInAList<Integer> findElementInAList = new FindElementInAList<>();
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingIndexOf_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingIndexOf(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingListIterator_thenReturnNull() {
|
||||
boolean found = findElementInAList.findUsingListIterator(5, scores);
|
||||
assertTrue(!found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundListIterator_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
boolean found = findElementInAList.findUsingListIterator(scoreToFind, scores);
|
||||
assertTrue(found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingIndexOf_thenReturnNull() {
|
||||
Integer score = findElementInAList.findUsingIndexOf(5, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingEnhancedForLoop_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
boolean found = findElementInAList.findUsingEnhancedForLoop(scoreToFind, scores);
|
||||
assertTrue(found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingEnhancedForLoop_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
boolean found = findElementInAList.findUsingEnhancedForLoop(scoreToFind, scores);
|
||||
assertTrue(!found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingStream_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingStream(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingStream_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingStream(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingParallelStream_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingParallelStream(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingParallelStream_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingParallelStream(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingGuava_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingGuava(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingGuava_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingGuava(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingApacheCommons_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingApacheCommon(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingApacheCommons_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingApacheCommon(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
package com.baeldung.internationalization;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.DateFormatSymbols;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class DateFormatUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenLocaleSpecificDateInstance_givenLanguageSpecificMonths() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat itInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat usInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.US);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018", itInstance.format(date));
|
||||
Assert.assertEquals("Thursday, February 1, 2018", usInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenDateInstanceWithDifferentFormats_givenSpecificDateFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat fullInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat mediumInstance = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ITALY);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018", fullInstance.format(date));
|
||||
Assert.assertEquals("1-feb-2018", mediumInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenTimeInstanceWithDifferentFormats_givenSpecificTimeFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat fullInstance = DateFormat.getTimeInstance(DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat mediumInstance = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY);
|
||||
|
||||
Assert.assertEquals("10.15.20 CET", fullInstance.format(date));
|
||||
Assert.assertEquals("10.15.20" , mediumInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenDateTimeInstanceWithDifferentFormats_givenSpecificDateTimeFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat ffInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat smInstance = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.ITALY);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018 10.15.20 CET", ffInstance.format(date));
|
||||
Assert.assertEquals("01/02/18 10.15.20", smInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenLocaleSpecificDateTimeInstance_givenLocaleSpecificFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat itInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat jpInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.JAPAN);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018 10.15.20 CET", itInstance.format(date));
|
||||
Assert.assertEquals("2018年2月1日 10時15分20秒 CET", jpInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenCustomizedSimpleDateFormat_thenSpecificMonthRepresentations() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
Locale.setDefault(new Locale("pl", "PL"));
|
||||
|
||||
SimpleDateFormat fullMonthDateFormat = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss:SSS");
|
||||
SimpleDateFormat shortMonthsimpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:SSS");
|
||||
|
||||
Assert.assertEquals("01-lutego-2018 10:15:20:000", fullMonthDateFormat.format(date));
|
||||
Assert.assertEquals("01-02-2018 10:15:20:000" , shortMonthsimpleDateFormat.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenCustomizedDateFormatSymbols_thenChangedDayNames() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
Locale.setDefault(new Locale("pl", "PL"));
|
||||
|
||||
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols();
|
||||
dateFormatSymbols.setWeekdays(new String[]{"A", "B", "C", "D", "E", "F", "G", "H"});
|
||||
SimpleDateFormat standardDateFormat = new SimpleDateFormat("EEEE-MMMM-yyyy HH:mm:ss:SSS");
|
||||
SimpleDateFormat newDaysDateFormat = new SimpleDateFormat("EEEE-MMMM-yyyy HH:mm:ss:SSS", dateFormatSymbols);
|
||||
|
||||
Assert.assertEquals("czwartek-lutego-2018 10:15:20:000", standardDateFormat.format(date));
|
||||
Assert.assertEquals("F-lutego-2018 10:15:20:000", newDaysDateFormat.format(date));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.internationalization;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.FormatStyle;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class DateTimeFormatterUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDefaultUsLocaleAndDateTimeAndPattern_whenFormatWithDifferentLocales_thenGettingLocalizedDateTimes() {
|
||||
Locale.setDefault(Locale.US);
|
||||
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
|
||||
String pattern = "dd-MMMM-yyyy HH:mm:ss.SSS";
|
||||
|
||||
DateTimeFormatter defaultTimeFormatter = DateTimeFormatter.ofPattern(pattern);
|
||||
DateTimeFormatter plTimeFormatter = DateTimeFormatter.ofPattern(pattern, new Locale("pl", "PL"));
|
||||
DateTimeFormatter deTimeFormatter = DateTimeFormatter.ofPattern(pattern).withLocale(Locale.GERMANY);
|
||||
|
||||
Assert.assertEquals("01-January-2018 10:15:50.000", defaultTimeFormatter.format(localDateTime));
|
||||
Assert.assertEquals("01-stycznia-2018 10:15:50.000", plTimeFormatter.format(localDateTime));
|
||||
Assert.assertEquals("01-Januar-2018 10:15:50.000", deTimeFormatter.format(localDateTime));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateTimeAndTimeZone_whenFormatWithDifferentLocales_thenGettingLocalizedZonedDateTimes() {
|
||||
Locale.setDefault(Locale.US);
|
||||
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
|
||||
ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId();
|
||||
|
||||
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
|
||||
DateTimeFormatter frLocalizedFormatter =
|
||||
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE);
|
||||
String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
||||
String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
||||
|
||||
Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime);
|
||||
Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
package com.baeldung.internationalization;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.Currency;
|
||||
import java.util.Locale;
|
||||
|
||||
public class NumbersCurrenciesFormattingUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDifferentLocalesAndDoubleNumber_whenNumberInstance_thenDifferentOutput() {
|
||||
Locale usLocale = Locale.US;
|
||||
Locale plLocale = new Locale("pl", "PL");
|
||||
Locale deLocale = Locale.GERMANY;
|
||||
double number = 102_300.456d;
|
||||
|
||||
NumberFormat usNumberFormat = NumberFormat.getInstance(usLocale);
|
||||
NumberFormat plNumberFormat = NumberFormat.getInstance(plLocale);
|
||||
NumberFormat deNumberFormat = NumberFormat.getInstance(deLocale);
|
||||
|
||||
Assert.assertEquals(usNumberFormat.format(number), "102,300.456");
|
||||
Assert.assertEquals(plNumberFormat.format(number), "102 300,456");
|
||||
Assert.assertEquals(deNumberFormat.format(number), "102.300,456");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDifferentLocalesAndDoubleAmount_whenCurrencyInstance_thenDifferentOutput() {
|
||||
Locale usLocale = Locale.US;
|
||||
Locale plLocale = new Locale("pl", "PL");
|
||||
Locale deLocale = Locale.GERMANY;
|
||||
BigDecimal number = new BigDecimal(102_300.456d);
|
||||
|
||||
NumberFormat usNumberFormat = NumberFormat.getCurrencyInstance(usLocale);
|
||||
NumberFormat plNumberFormat = NumberFormat.getCurrencyInstance(plLocale);
|
||||
NumberFormat deNumberFormat = NumberFormat.getCurrencyInstance(deLocale);
|
||||
|
||||
Assert.assertEquals(usNumberFormat.format(number), "$102,300.46");
|
||||
Assert.assertEquals(plNumberFormat.format(number), "102 300,46 zł");
|
||||
Assert.assertEquals(deNumberFormat.format(number), "102.300,46 €");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleAndNumber_whenSpecificDecimalFormat_thenSpecificOutput() {
|
||||
Locale.setDefault(Locale.FRANCE);
|
||||
BigDecimal number = new BigDecimal(102_300.456d);
|
||||
|
||||
DecimalFormat zeroDecimalFormat = new DecimalFormat("000000000.0000");
|
||||
DecimalFormat hashDecimalFormat = new DecimalFormat("###,###.#");
|
||||
DecimalFormat dollarDecimalFormat = new DecimalFormat("$###,###.##");
|
||||
|
||||
Assert.assertEquals(zeroDecimalFormat.format(number), "000102300,4560");
|
||||
Assert.assertEquals(hashDecimalFormat.format(number), "102 300,5");
|
||||
Assert.assertEquals(dollarDecimalFormat.format(number), "$102 300,46");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleAndNumber_whenSpecificDecimalFormatSymbols_thenSpecificOutput() {
|
||||
Locale.setDefault(Locale.FRANCE);
|
||||
BigDecimal number = new BigDecimal(102_300.456d);
|
||||
|
||||
DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance();
|
||||
decimalFormatSymbols.setGroupingSeparator('^');
|
||||
decimalFormatSymbols.setDecimalSeparator('@');
|
||||
DecimalFormat separatorsDecimalFormat = new DecimalFormat("$###,###.##");
|
||||
separatorsDecimalFormat.setGroupingSize(4);
|
||||
separatorsDecimalFormat.setCurrency(Currency.getInstance(Locale.JAPAN));
|
||||
separatorsDecimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);
|
||||
|
||||
Assert.assertEquals(separatorsDecimalFormat.format(number), "$10^2300@46");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
package com.baeldung.math;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MathNewMethodsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAddExactToInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(150, Math.addExact(100, 50)); // Returns 150
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSubstractExactFromInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(50, Math.subtractExact(100, 50)); // Returns 50
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDecrementExactInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(99, Math.decrementExact(100)); // Returns 99
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIncrementExactToInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(101, Math.incrementExact(100)); // Returns 101
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultiplyExactTwoIntegers_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(500, Math.multiplyExact(100, 5)); // Returns 500
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNegateExactInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(-100, Math.negateExact(100)); // Returns -100
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenAddToMaxInteger_thenThrowsArithmeticException() {
|
||||
Math.addExact(Integer.MAX_VALUE, 1); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenDecrementMinInteger_thenThrowsArithmeticException() {
|
||||
Math.decrementExact(Integer.MIN_VALUE); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenIncrementMaxLong_thenThrowsArithmeticException() {
|
||||
Math.incrementExact(Long.MAX_VALUE); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenMultiplyMaxLong_thenThrowsArithmeticException() {
|
||||
Math.multiplyExact(Long.MAX_VALUE, 2); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenNegateMinInteger_thenThrowsArithmeticException() {
|
||||
Math.negateExact(Integer.MIN_VALUE); // MinInt value: −2.147.483.648, but MaxInt Value: 2.147.483.647 => Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenSubstractFromMinInteger_thenThrowsArithmeticException() {
|
||||
Math.subtractExact(Integer.MIN_VALUE, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFloorDivTwoIntegers_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(3, Math.floorDiv(7, 2)); // Exact quotient is 3.5 so floor(3.5) == 3
|
||||
assertEquals(-4, Math.floorDiv(-7, 2)); // Exact quotient is -3.5 so floor(-3.5) == -4
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModDivTwoIntegers_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(2, Math.floorMod(5, 3)); // Returns 2: floorMod for positive numbers returns the same as % operator
|
||||
assertEquals(1, Math.floorMod(-5, 3)); // Returns 1 and not 2 because floorDiv(-5, 3) is -2 and not -1 and (-2*3) + (1) = -5
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNextDownOfDouble_thenExpectCorrectNumber() {
|
||||
double number = 3.0;
|
||||
double expected = 2.999999999999;
|
||||
double delta = 0.00000001;
|
||||
assertEquals(expected, Math.nextDown(number), delta); // The delta defines the accepted error range
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
package com.baeldung.shufflingcollections;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ShufflingCollectionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenShufflingList_thenListIsShuffled() {
|
||||
List<String> students = Arrays.asList("Foo", "Bar", "Baz", "Qux");
|
||||
|
||||
System.out.println("List before shuffling:");
|
||||
System.out.println(students);
|
||||
|
||||
Collections.shuffle(students);
|
||||
System.out.println("List after shuffling:");
|
||||
System.out.println(students);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenShufflingMapEntries_thenValuesAreShuffled() {
|
||||
Map<Integer, String> studentsById = new HashMap<>();
|
||||
studentsById.put(1, "Foo");
|
||||
studentsById.put(2, "Bar");
|
||||
studentsById.put(3, "Baz");
|
||||
studentsById.put(4, "Qux");
|
||||
|
||||
System.out.println("Students before shuffling:");
|
||||
System.out.println(studentsById.values());
|
||||
|
||||
List<Map.Entry<Integer, String>> shuffledStudentEntries = new ArrayList<>(studentsById.entrySet());
|
||||
Collections.shuffle(shuffledStudentEntries);
|
||||
|
||||
List<String> shuffledStudents = shuffledStudentEntries.stream()
|
||||
.map(Map.Entry::getValue)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
System.out.println("Students after shuffling");
|
||||
System.out.println(shuffledStudents);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenShufflingSet_thenElementsAreShuffled() {
|
||||
Set<String> students = new HashSet<>(Arrays.asList("Foo", "Bar", "Baz", "Qux"));
|
||||
|
||||
System.out.println("Set before shuffling:");
|
||||
System.out.println(students);
|
||||
|
||||
List<String> studentList = new ArrayList<>(students);
|
||||
|
||||
Collections.shuffle(studentList);
|
||||
System.out.println("Shuffled set elements:");
|
||||
System.out.println(studentList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenShufflingWithSameRandomness_thenElementsAreShuffledDeterministically() {
|
||||
List<String> students_1 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
|
||||
List<String> students_2 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
|
||||
|
||||
Collections.shuffle(students_1, new Random(5));
|
||||
Collections.shuffle(students_2, new Random(5));
|
||||
|
||||
assertThat(students_1).isEqualTo(students_2);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.java9.methodhandles;
|
||||
|
||||
public class Book {
|
||||
|
||||
String id;
|
||||
String title;
|
||||
|
||||
public Book(String id, String title) {
|
||||
this.id = id;
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private String formatBook() {
|
||||
return id + " > " + title;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,152 @@
|
|||
package com.baeldung.java9.methodhandles;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.MethodType;
|
||||
import java.lang.invoke.WrongMethodTypeException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Test case for the {@link MethodHandles} API
|
||||
*/
|
||||
public class MethodHandlesTest {
|
||||
|
||||
@Test
|
||||
public void givenConcatMethodHandle_whenInvoked_thenCorrectlyConcatenated() throws Throwable {
|
||||
|
||||
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
|
||||
MethodType mt = MethodType.methodType(String.class, String.class);
|
||||
MethodHandle concatMH = publicLookup.findVirtual(String.class, "concat", mt);
|
||||
|
||||
String output = (String) concatMH.invoke("Effective ", "Java");
|
||||
|
||||
assertEquals("Effective Java", output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAsListMethodHandle_whenInvokingWithArguments_thenCorrectlyInvoked() throws Throwable {
|
||||
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
|
||||
MethodType mt = MethodType.methodType(List.class, Object[].class);
|
||||
MethodHandle asListMH = publicLookup.findStatic(Arrays.class, "asList", mt);
|
||||
|
||||
List<Integer> list = (List<Integer>) asListMH.invokeWithArguments(1, 2);
|
||||
|
||||
assertThat(Arrays.asList(1, 2), is(list));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConstructorMethodHandle_whenInvoked_thenObjectCreatedCorrectly() throws Throwable {
|
||||
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
|
||||
MethodType mt = MethodType.methodType(void.class, String.class);
|
||||
MethodHandle newIntegerMH = publicLookup.findConstructor(Integer.class, mt);
|
||||
|
||||
Integer integer = (Integer) newIntegerMH.invoke("1");
|
||||
|
||||
assertEquals(1, integer.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFieldWithoutGetter_whenCreatingAGetter_thenCorrectlyInvoked() throws Throwable {
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
MethodHandle getTitleMH = lookup.findGetter(Book.class, "title", String.class);
|
||||
|
||||
Book book = new Book("ISBN-1234", "Effective Java");
|
||||
|
||||
assertEquals("Effective Java", getTitleMH.invoke(book));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrivateMethod_whenCreatingItsMethodHandle_thenCorrectlyInvoked() throws Throwable {
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
Method formatBookMethod = Book.class.getDeclaredMethod("formatBook");
|
||||
formatBookMethod.setAccessible(true);
|
||||
|
||||
MethodHandle formatBookMH = lookup.unreflect(formatBookMethod);
|
||||
|
||||
Book book = new Book("ISBN-123", "Java in Action");
|
||||
|
||||
assertEquals("ISBN-123 > Java in Action", formatBookMH.invoke(book));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReplaceMethod_whenUsingReflectionAndInvoked_thenCorrectlyReplaced() throws Throwable {
|
||||
Method replaceMethod = String.class.getMethod("replace", char.class, char.class);
|
||||
|
||||
String string = (String) replaceMethod.invoke("jovo", 'o', 'a');
|
||||
|
||||
assertEquals("java", string);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReplaceMethodHandle_whenInvoked_thenCorrectlyReplaced() throws Throwable {
|
||||
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
|
||||
MethodType mt = MethodType.methodType(String.class, char.class, char.class);
|
||||
MethodHandle replaceMH = publicLookup.findVirtual(String.class, "replace", mt);
|
||||
|
||||
String replacedString = (String) replaceMH.invoke("jovo", Character.valueOf('o'), 'a');
|
||||
|
||||
assertEquals("java", replacedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReplaceMethodHandle_whenInvokingExact_thenCorrectlyReplaced() throws Throwable {
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
MethodType mt = MethodType.methodType(String.class, char.class, char.class);
|
||||
MethodHandle replaceMH = lookup.findVirtual(String.class, "replace", mt);
|
||||
|
||||
String s = (String) replaceMH.invokeExact("jovo", 'o', 'a');
|
||||
|
||||
assertEquals("java", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSumMethodHandle_whenInvokingExact_thenSumIsCorrect() throws Throwable {
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
MethodType mt = MethodType.methodType(int.class, int.class, int.class);
|
||||
MethodHandle sumMH = lookup.findStatic(Integer.class, "sum", mt);
|
||||
|
||||
int sum = (int) sumMH.invokeExact(1, 11);
|
||||
|
||||
assertEquals(12, sum);
|
||||
}
|
||||
|
||||
@Test(expected = WrongMethodTypeException.class)
|
||||
public void givenSumMethodHandleAndIncompatibleArguments_whenInvokingExact_thenException() throws Throwable {
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
MethodType mt = MethodType.methodType(int.class, int.class, int.class);
|
||||
MethodHandle sumMH = lookup.findStatic(Integer.class, "sum", mt);
|
||||
|
||||
sumMH.invokeExact(Integer.valueOf(1), 11);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSpreadedEqualsMethodHandle_whenInvokedOnArray_thenCorrectlyEvaluated() throws Throwable {
|
||||
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
|
||||
MethodType mt = MethodType.methodType(boolean.class, Object.class);
|
||||
MethodHandle equalsMH = publicLookup.findVirtual(String.class, "equals", mt);
|
||||
|
||||
MethodHandle methodHandle = equalsMH.asSpreader(Object[].class, 2);
|
||||
|
||||
assertTrue((boolean) methodHandle.invoke(new Object[] { "java", "java" }));
|
||||
assertFalse((boolean) methodHandle.invoke(new Object[] { "java", "jova" }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConcatMethodHandle_whenBindToAString_thenCorrectlyConcatenated() throws Throwable {
|
||||
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
|
||||
MethodType mt = MethodType.methodType(String.class, String.class);
|
||||
MethodHandle concatMH = publicLookup.findVirtual(String.class, "concat", mt);
|
||||
|
||||
MethodHandle bindedConcatMH = concatMH.bindTo("Hello ");
|
||||
|
||||
assertEquals("Hello World!", bindedConcatMH.invoke("World!"));
|
||||
}
|
||||
}
|
|
@ -10,7 +10,7 @@ import org.junit.Test;
|
|||
|
||||
import com.jayway.awaitility.Awaitility;
|
||||
|
||||
public class StopThreadTest {
|
||||
public class StopThreadManualTest {
|
||||
|
||||
@Test
|
||||
public void whenStoppedThreadIsStopped() throws InterruptedException {
|
|
@ -1,26 +1,5 @@
|
|||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
||||
# *.txt
|
||||
/temp
|
|
@ -1,5 +1,4 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-io</artifactId>
|
||||
|
@ -211,16 +210,6 @@
|
|||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>1.5.8.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
|
@ -264,99 +253,6 @@
|
|||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>one-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
|
@ -384,19 +280,19 @@
|
|||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath/>
|
||||
<classpath />
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>3.0.0-M1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
@ -442,7 +338,7 @@
|
|||
<executions>
|
||||
<execution>
|
||||
<id>run-benchmarks</id>
|
||||
<!-- <phase>integration-test</phase>-->
|
||||
<!-- <phase>integration-test</phase> -->
|
||||
<phase>none</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
|
@ -452,7 +348,7 @@
|
|||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath/>
|
||||
<classpath />
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
|
@ -490,7 +386,7 @@
|
|||
<protonpack.version>1.13</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
|
|
|
@ -10,7 +10,7 @@ import java.nio.file.WatchKey;
|
|||
import java.nio.file.WatchService;
|
||||
|
||||
public class DirectoryWatcherExample {
|
||||
|
||||
|
||||
public static void main(String[] args) throws IOException, InterruptedException {
|
||||
WatchService watchService = FileSystems.getDefault().newWatchService();
|
||||
Path path = Paths.get(System.getProperty("user.home"));
|
||||
|
@ -25,5 +25,5 @@ public class DirectoryWatcherExample {
|
|||
|
||||
watchService.close();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -1,2 +0,0 @@
|
|||
line 1
|
||||
a second line
|
|
@ -19,52 +19,51 @@ import org.junit.Test;
|
|||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class FileCopierTest {
|
||||
File original = new File("src/test/resources/original.txt");
|
||||
File original = new File("src/test/resources/original.txt");
|
||||
|
||||
@Before
|
||||
public void init() throws IOException {
|
||||
if (!original.exists())
|
||||
Files.createFile(original.toPath());
|
||||
}
|
||||
@Before
|
||||
public void init() throws IOException {
|
||||
if (!original.exists())
|
||||
Files.createFile(original.toPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
File copied = new File("src/test/resources/copiedWithIo.txt");
|
||||
try (InputStream in = new BufferedInputStream(new FileInputStream(original));
|
||||
OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int lengthRead;
|
||||
while ((lengthRead = in.read(buffer)) > 0) {
|
||||
out.write(buffer, 0, lengthRead);
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
|
||||
}
|
||||
@Test
|
||||
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
File copied = new File("src/test/resources/copiedWithIo.txt");
|
||||
try (InputStream in = new BufferedInputStream(new FileInputStream(original)); OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int lengthRead;
|
||||
while ((lengthRead = in.read(buffer)) > 0) {
|
||||
out.write(buffer, 0, lengthRead);
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
|
||||
FileUtils.copyFile(original, copied);
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
|
||||
}
|
||||
@Test
|
||||
public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
|
||||
FileUtils.copyFile(original, copied);
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
|
||||
Path originalPath = original.toPath();
|
||||
Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied)));
|
||||
}
|
||||
@Test
|
||||
public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
|
||||
Path originalPath = original.toPath();
|
||||
Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
|
||||
com.google.common.io.Files.copy(original, copied);
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
|
||||
}
|
||||
@Test
|
||||
public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
|
||||
com.google.common.io.Files.copy(original, copied);
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,7 +3,6 @@ package com.baeldung.file;
|
|||
import org.apache.commons.io.FileUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
|
|
|
@ -42,19 +42,14 @@ public class FilesTest {
|
|||
CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
|
||||
chs.write("Spain\r\n");
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingFiles_thenCorrect() throws IOException {
|
||||
Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND);
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -62,9 +57,7 @@ public class FilesTest {
|
|||
File file = new File(fileName);
|
||||
FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true);
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -73,9 +66,7 @@ public class FilesTest {
|
|||
fos.write("Spain\r\n".getBytes());
|
||||
fos.close();
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -86,9 +77,6 @@ public class FilesTest {
|
|||
bw.newLine();
|
||||
bw.close();
|
||||
|
||||
assertThat(
|
||||
StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
|
||||
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
|
||||
}
|
||||
}
|
|
@ -35,7 +35,7 @@ public class LookupFSJNDIIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void givenInitialContext_whenLokupFileExists_thenSuccess() {
|
||||
File file = fsjndi.getFile(FILENAME);
|
||||
assertNotNull("File exists", file);
|
||||
File file = fsjndi.getFile(FILENAME);
|
||||
assertNotNull("File exists", file);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,7 +9,6 @@ import java.net.URI;
|
|||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
|
|
|
@ -17,18 +17,19 @@ import java.util.concurrent.Future;
|
|||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AsyncFileIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||
Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
final Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
|
||||
operation.get();
|
||||
|
||||
String fileContent = new String(buffer.array()).trim();
|
||||
final String fileContent = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
|
||||
assertEquals(fileContent, "baeldung.com");
|
||||
|
@ -36,18 +37,16 @@ public class AsyncFileIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(URI.create(AsyncFileIntegrationTest.class.getResource("/file.txt").toString()));
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||
|
||||
@Override
|
||||
public void completed(Integer result, ByteBuffer attachment) {
|
||||
// result is number of bytes read
|
||||
// attachment is the buffer
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -59,42 +58,40 @@ public class AsyncFileIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||
String fileName = "temp";
|
||||
Path path = Paths.get(fileName);
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
|
||||
final String fileName = "temp";
|
||||
final Path path = Paths.get(fileName);
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
long position = 0;
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
final long position = 0;
|
||||
|
||||
buffer.put("hello world".getBytes());
|
||||
buffer.flip();
|
||||
|
||||
Future<Integer> operation = fileChannel.write(buffer, position);
|
||||
final Future<Integer> operation = fileChannel.write(buffer, position);
|
||||
buffer.clear();
|
||||
|
||||
operation.get();
|
||||
|
||||
String content = readContent(path);
|
||||
final String content = readContent(path);
|
||||
assertEquals("hello world", content);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException {
|
||||
String fileName = UUID.randomUUID().toString();
|
||||
Path path = Paths.get(fileName);
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
|
||||
final String fileName = UUID.randomUUID().toString();
|
||||
final Path path = Paths.get(fileName);
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
buffer.put("hello world".getBytes());
|
||||
buffer.flip();
|
||||
|
||||
fileChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||
|
||||
@Override
|
||||
public void completed(Integer result, ByteBuffer attachment) {
|
||||
// result is number of bytes written
|
||||
// attachment is the buffer
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -104,23 +101,25 @@ public class AsyncFileIntegrationTest {
|
|||
});
|
||||
}
|
||||
|
||||
public static String readContent(Path file) throws ExecutionException, InterruptedException {
|
||||
//
|
||||
|
||||
private String readContent(Path file) throws ExecutionException, InterruptedException {
|
||||
AsynchronousFileChannel fileChannel = null;
|
||||
try {
|
||||
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
final Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
|
||||
operation.get();
|
||||
|
||||
String fileContent = new String(buffer.array()).trim();
|
||||
final String fileContent = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
return fileContent;
|
||||
}
|
||||
|
||||
}
|
|
@ -20,7 +20,6 @@ public class BasicAttribsIntegrationTest {
|
|||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(BasicAttribsIntegrationTest.class);
|
||||
|
||||
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
private static BasicFileAttributes basicAttribs;
|
||||
|
||||
|
|
|
@ -55,12 +55,7 @@ public class JavaFolderSizeUnitTest {
|
|||
@Test
|
||||
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
|
||||
final Path folder = Paths.get(path);
|
||||
final long size = Files.walk(folder)
|
||||
.filter(p -> p.toFile()
|
||||
.isFile())
|
||||
.mapToLong(p -> p.toFile()
|
||||
.length())
|
||||
.sum();
|
||||
final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
|
@ -77,12 +72,8 @@ public class JavaFolderSizeUnitTest {
|
|||
public void whenGetFolderSizeUsingGuava_thenCorrect() {
|
||||
final File folder = new File(path);
|
||||
|
||||
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser()
|
||||
.breadthFirstTraversal(folder);
|
||||
final long size = StreamSupport.stream(files.spliterator(), false)
|
||||
.filter(File::isFile)
|
||||
.mapToLong(File::length)
|
||||
.sum();
|
||||
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
|
||||
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
|
|
|
@ -18,14 +18,13 @@ import static org.junit.Assert.assertNotNull;
|
|||
|
||||
public class MappedByteBufferUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception {
|
||||
//given
|
||||
// given
|
||||
CharBuffer charBuffer = null;
|
||||
Path pathToRead = getFileURIFromResources("fileToRead.txt");
|
||||
|
||||
//when
|
||||
// when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) {
|
||||
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
|
||||
|
||||
|
@ -34,20 +33,19 @@ public class MappedByteBufferUnitTest {
|
|||
}
|
||||
}
|
||||
|
||||
//then
|
||||
// then
|
||||
assertNotNull(charBuffer);
|
||||
assertEquals(charBuffer.toString(), "This is a content of the file");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception {
|
||||
//given
|
||||
CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
|
||||
Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
|
||||
// given
|
||||
final CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
|
||||
final Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
|
||||
|
||||
//when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite,
|
||||
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
|
||||
// when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
|
||||
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
|
||||
|
||||
if (mappedByteBuffer != null) {
|
||||
|
@ -55,14 +53,16 @@ public class MappedByteBufferUnitTest {
|
|||
}
|
||||
}
|
||||
|
||||
//then
|
||||
List<String> fileContent = Files.readAllLines(pathToWrite);
|
||||
// then
|
||||
final List<String> fileContent = Files.readAllLines(pathToWrite);
|
||||
assertEquals(fileContent.get(0), "This will be written to the file");
|
||||
|
||||
}
|
||||
|
||||
private Path getFileURIFromResources(String fileName) throws Exception {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
//
|
||||
|
||||
private final Path getFileURIFromResources(String fileName) throws Exception {
|
||||
final ClassLoader classLoader = getClass().getClassLoader();
|
||||
return Paths.get(classLoader.getResource(fileName).toURI());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,47 +0,0 @@
|
|||
package com.baeldung.stream;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileCopyTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingStream_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt");
|
||||
FileCopy.copyFileUsingStream(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFiles_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt");
|
||||
FileCopy.copyFileUsingJavaFiles(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingChannel_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt");
|
||||
FileCopy.copyFileUsingChannel(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingApache_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt");
|
||||
FileCopy.copyFileUsingApacheCommonsIO(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.stream;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileCopyUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingStream_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt");
|
||||
FileCopy.copyFileUsingStream(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFiles_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt");
|
||||
FileCopy.copyFileUsingJavaFiles(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingChannel_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt");
|
||||
FileCopy.copyFileUsingChannel(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingApache_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt");
|
||||
FileCopy.copyFileUsingApacheCommonsIO(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
}
|
|
@ -152,11 +152,11 @@ public class JavaInputStreamToXUnitTest {
|
|||
|
||||
@Test
|
||||
public final void whenConvertingToFile_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
|
||||
final byte[] buffer = new byte[initialStream.available()];
|
||||
initialStream.read(buffer);
|
||||
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final File targetFile = new File("src/test/resources/targetFile.tmp");
|
||||
final OutputStream outStream = new FileOutputStream(targetFile);
|
||||
outStream.write(buffer);
|
||||
|
||||
|
@ -166,8 +166,8 @@ public class JavaInputStreamToXUnitTest {
|
|||
|
||||
@Test
|
||||
public final void whenConvertingInProgressToFile_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
|
||||
final File targetFile = new File("src/test/resources/targetFile.tmp");
|
||||
final OutputStream outStream = new FileOutputStream(targetFile);
|
||||
|
||||
final byte[] buffer = new byte[8 * 1024];
|
||||
|
@ -182,8 +182,8 @@ public class JavaInputStreamToXUnitTest {
|
|||
|
||||
@Test
|
||||
public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
|
||||
final File targetFile = new File("src/test/resources/targetFile.tmp");
|
||||
|
||||
java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
|
||||
|
@ -192,11 +192,11 @@ public class JavaInputStreamToXUnitTest {
|
|||
|
||||
@Test
|
||||
public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
|
||||
final byte[] buffer = new byte[initialStream.available()];
|
||||
initialStream.read(buffer);
|
||||
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final File targetFile = new File("src/test/resources/targetFile.tmp");
|
||||
Files.write(buffer, targetFile);
|
||||
|
||||
IOUtils.closeQuietly(initialStream);
|
||||
|
@ -204,13 +204,13 @@ public class JavaInputStreamToXUnitTest {
|
|||
|
||||
@Test
|
||||
public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException {
|
||||
final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
|
||||
final InputStream initialStream = FileUtils.openInputStream(new File("src/test/resources/sample.txt"));
|
||||
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final File targetFile = new File("src/test/resources/targetFile.tmp");
|
||||
|
||||
FileUtils.copyInputStreamToFile(initialStream, targetFile);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingAnInputStreamToString_thenCorrect() throws IOException {
|
||||
String originalString = randomAlphabetic(8);
|
||||
|
@ -225,7 +225,7 @@ public class JavaInputStreamToXUnitTest {
|
|||
|
||||
buffer.flush();
|
||||
byte[] byteArray = buffer.toByteArray();
|
||||
|
||||
|
||||
String text = new String(byteArray, StandardCharsets.UTF_8);
|
||||
assertThat(text, equalTo(originalString));
|
||||
}
|
||||
|
|
|
@ -18,7 +18,6 @@ import static org.junit.Assert.assertTrue;
|
|||
|
||||
public class JavaReadFromFileUnitTest {
|
||||
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class);
|
||||
|
||||
@Test
|
||||
|
@ -107,11 +106,12 @@ public class JavaReadFromFileUnitTest {
|
|||
|
||||
@Test
|
||||
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
|
||||
final String expected_value = "青空";
|
||||
final String expected_value = "é<EFBFBD>’空";
|
||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
|
||||
final String currentLine = reader.readLine();
|
||||
reader.close();
|
||||
LOG.debug(currentLine);
|
||||
|
||||
assertEquals(expected_value, currentLine);
|
||||
}
|
||||
|
||||
|
|
|
@ -68,7 +68,7 @@ public class JavaXToInputStreamUnitTest {
|
|||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/main/resources/sample.txt");
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
final InputStream targetStream = new FileInputStream(initialFile);
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
|
@ -76,7 +76,7 @@ public class JavaXToInputStreamUnitTest {
|
|||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/main/resources/sample.txt");
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
final InputStream targetStream = Files.asByteSource(initialFile).openStream();
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
|
@ -84,7 +84,7 @@ public class JavaXToInputStreamUnitTest {
|
|||
|
||||
@Test
|
||||
public final void givenUsingCommonsIO_whenConvertingFileToInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/main/resources/sample.txt");
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
final InputStream targetStream = FileUtils.openInputStream(initialFile);
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
With Commons IO
|
|
@ -0,0 +1 @@
|
|||
Hello World
|
|
@ -0,0 +1 @@
|
|||
Hello World
|
|
@ -0,0 +1 @@
|
|||
Some textSome text
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue