resolved conflicts

This commit is contained in:
dhruba619 2017-03-19 22:39:05 +05:30
commit a652b5576a
310 changed files with 11128 additions and 1670 deletions

View File

@ -5,7 +5,6 @@ install: travis_wait 40 mvn -q clean install -Dgib.enabled=true
jdk:
- oraclejdk8
sudo: false
addons:
apt:
packages:
@ -14,4 +13,11 @@ addons:
cache:
directories:
- .autoconf
- $HOME/.m2
- $HOME/.m2
sudo: required
env:
global:
JAVA_OPTS="-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC"
MAVEN_OPTS="-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC"

3
Twitter4J/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [Introduction to Twitter4J](http://www.baeldung.com/twitter4j)

View File

@ -17,11 +17,6 @@
</properties>
<dependencies>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>4.0.6</version>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-stream</artifactId>

View File

@ -28,11 +28,10 @@ public class Application {
*/
// ConfigurationBuilder cb = new ConfigurationBuilder();
// cb.setDebugEnabled(true)
// .setOAuthConsumerKey("DPHTBsWWO42d8rzshxlK0OwSY")
// .setOAuthConsumerSecret("ACLXkeRY98NiaVCG1ai8fdYt0GoEGJbFeTuxjulSCO7sLKqls1")
// .setOAuthAccessToken("838080188214759428-9MSK1ddPTN5ZZHbddjFI7s75mYgmCFQ")
// .setOAuthAccessTokenSecret("1eXAADpHShAzQh5hGWLBUQHLysOuAKIOapmQQ8U0OVk2c");
//
// .setOAuthConsumerKey("//TODO")
// .setOAuthConsumerSecret("//TODO")
// .setOAuthAccessToken("//TODO")
// .setOAuthAccessTokenSecret("//TODO");
// TwitterFactory tf = new TwitterFactory(cb.build());
// Twitter twitter = tf.getSingleton();

View File

@ -2,3 +2,5 @@
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java)

View File

@ -9,6 +9,7 @@
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
<lombok.version>1.16.12</lombok.version>
</properties>
<dependencies>
@ -18,6 +19,12 @@
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>

View File

@ -9,13 +9,14 @@ import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm {
public static void main(String[] args) {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Scanner in = new Scanner(System.in);
System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One");
System.out.println("3 - Simple Genetic Algorithm");
System.out.println("4 - Ant Colony");
System.out.println("5 - Dijkstra");
int decision = in.nextInt();
switch (decision) {
case 1:
@ -33,6 +34,9 @@ public class RunAlgorithm {
AntColonyOptimization antColony = new AntColonyOptimization(21);
antColony.startAntOptimization();
break;
case 5:
System.out.println("Please run the DijkstraAlgorithmTest.");
break;
default:
System.out.println("Unknown option");
break;

View File

@ -0,0 +1,203 @@
package com.baeldung.algorithms.ga.ant_colony;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;
import java.util.Random;
import java.util.stream.IntStream;
public class AntColonyOptimization {
private double c = 1.0;
private double alpha = 1;
private double beta = 5;
private double evaporation = 0.5;
private double Q = 500;
private double antFactor = 0.8;
private double randomFactor = 0.01;
private int maxIterations = 1000;
private int numberOfCities;
private int numberOfAnts;
private double graph[][];
private double trails[][];
private List<Ant> ants = new ArrayList<>();
private Random random = new Random();
private double probabilities[];
private int currentIndex;
private int[] bestTourOrder;
private double bestTourLength;
public AntColonyOptimization(int noOfCities) {
graph = generateRandomMatrix(noOfCities);
numberOfCities = graph.length;
numberOfAnts = (int) (numberOfCities * antFactor);
trails = new double[numberOfCities][numberOfCities];
probabilities = new double[numberOfCities];
IntStream.range(0, numberOfAnts)
.forEach(i -> ants.add(new Ant(numberOfCities)));
}
/**
* Generate initial solution
*/
public double[][] generateRandomMatrix(int n) {
double[][] randomMatrix = new double[n][n];
IntStream.range(0, n)
.forEach(i -> IntStream.range(0, n)
.forEach(j -> randomMatrix[i][j] = Math.abs(random.nextInt(100) + 1)));
return randomMatrix;
}
/**
* Perform ant optimization
*/
public void startAntOptimization() {
IntStream.rangeClosed(1, 3)
.forEach(i -> {
System.out.println("Attempt #" + i);
solve();
});
}
/**
* Use this method to run the main logic
*/
public int[] solve() {
setupAnts();
clearTrails();
IntStream.range(0, maxIterations)
.forEach(i -> {
moveAnts();
updateTrails();
updateBest();
});
System.out.println("Best tour length: " + (bestTourLength - numberOfCities));
System.out.println("Best tour order: " + Arrays.toString(bestTourOrder));
return bestTourOrder.clone();
}
/**
* Prepare ants for the simulation
*/
private void setupAnts() {
IntStream.range(0, numberOfAnts)
.forEach(i -> {
ants.forEach(ant -> {
ant.clear();
ant.visitCity(-1, random.nextInt(numberOfCities));
});
});
currentIndex = 0;
}
/**
* At each iteration, move ants
*/
private void moveAnts() {
IntStream.range(currentIndex, numberOfCities - 1)
.forEach(i -> {
ants.forEach(ant -> ant.visitCity(currentIndex, selectNextCity(ant)));
currentIndex++;
});
}
/**
* Select next city for each ant
*/
private int selectNextCity(Ant ant) {
int t = random.nextInt(numberOfCities - currentIndex);
if (random.nextDouble() < randomFactor) {
OptionalInt cityIndex = IntStream.range(0, numberOfCities)
.filter(i -> i == t && !ant.visited(i))
.findFirst();
if (cityIndex.isPresent()) {
return cityIndex.getAsInt();
}
}
calculateProbabilities(ant);
double r = random.nextDouble();
double total = 0;
for (int i = 0; i < numberOfCities; i++) {
total += probabilities[i];
if (total >= r) {
return i;
}
}
throw new RuntimeException("There are no other cities");
}
/**
* Calculate the next city picks probabilites
*/
public void calculateProbabilities(Ant ant) {
int i = ant.trail[currentIndex];
double pheromone = 0.0;
for (int l = 0; l < numberOfCities; l++) {
if (!ant.visited(l)) {
pheromone += Math.pow(trails[i][l], alpha) * Math.pow(1.0 / graph[i][l], beta);
}
}
for (int j = 0; j < numberOfCities; j++) {
if (ant.visited(j)) {
probabilities[j] = 0.0;
} else {
double numerator = Math.pow(trails[i][j], alpha) * Math.pow(1.0 / graph[i][j], beta);
probabilities[j] = numerator / pheromone;
}
}
}
/**
* Update trails that ants used
*/
private void updateTrails() {
for (int i = 0; i < numberOfCities; i++) {
for (int j = 0; j < numberOfCities; j++) {
trails[i][j] *= evaporation;
}
}
for (Ant a : ants) {
double contribution = Q / a.trailLength(graph);
for (int i = 0; i < numberOfCities - 1; i++) {
trails[a.trail[i]][a.trail[i + 1]] += contribution;
}
trails[a.trail[numberOfCities - 1]][a.trail[0]] += contribution;
}
}
/**
* Update the best solution
*/
private void updateBest() {
if (bestTourOrder == null) {
bestTourOrder = ants.get(0).trail;
bestTourLength = ants.get(0)
.trailLength(graph);
}
for (Ant a : ants) {
if (a.trailLength(graph) < bestTourLength) {
bestTourLength = a.trailLength(graph);
bestTourOrder = a.trail.clone();
}
}
}
/**
* Clear trails after simulation
*/
private void clearTrails() {
IntStream.range(0, numberOfCities)
.forEach(i -> {
IntStream.range(0, numberOfCities)
.forEach(j -> trails[i][j] = c);
});
}
}

View File

@ -1,57 +1,57 @@
package com.baeldung.algorithms.dijkstra;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Set;
public class Dijkstra {
public static Graph calculateShortestPathFromSource(Graph graph, Node source) {
source.setDistance(0);
Set<Node> settledNodes = new HashSet<>();
Set<Node> unsettledNodes = new HashSet<>();
unsettledNodes.add(source);
while (unsettledNodes.size() != 0) {
Node currentNode = getLowestDistanceNode(unsettledNodes);
unsettledNodes.remove(currentNode);
for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
Node adjacentNode = adjacencyPair.getKey();
Integer edgeWeigh = adjacencyPair.getValue();
if (!settledNodes.contains(adjacentNode)) {
CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode);
unsettledNodes.add(adjacentNode);
}
}
settledNodes.add(currentNode);
}
return graph;
}
private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) {
Integer sourceDistance = sourceNode.getDistance();
if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) {
evaluationNode.setDistance(sourceDistance + edgeWeigh);
LinkedList<Node> shortestPath = new LinkedList<>(sourceNode.getShortestPath());
shortestPath.add(sourceNode);
evaluationNode.setShortestPath(shortestPath);
}
}
private static Node getLowestDistanceNode(Set<Node> unsettledNodes) {
Node lowestDistanceNode = null;
int lowestDistance = Integer.MAX_VALUE;
for (Node node : unsettledNodes) {
int nodeDistance = node.getDistance();
if (nodeDistance < lowestDistance) {
lowestDistance = nodeDistance;
lowestDistanceNode = node;
}
}
return lowestDistanceNode;
}
}
package com.baeldung.algorithms.ga.dijkstra;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Set;
public class Dijkstra {
public static Graph calculateShortestPathFromSource(Graph graph, Node source) {
source.setDistance(0);
Set<Node> settledNodes = new HashSet<>();
Set<Node> unsettledNodes = new HashSet<>();
unsettledNodes.add(source);
while (unsettledNodes.size() != 0) {
Node currentNode = getLowestDistanceNode(unsettledNodes);
unsettledNodes.remove(currentNode);
for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
Node adjacentNode = adjacencyPair.getKey();
Integer edgeWeigh = adjacencyPair.getValue();
if (!settledNodes.contains(adjacentNode)) {
CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode);
unsettledNodes.add(adjacentNode);
}
}
settledNodes.add(currentNode);
}
return graph;
}
private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) {
Integer sourceDistance = sourceNode.getDistance();
if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) {
evaluationNode.setDistance(sourceDistance + edgeWeigh);
LinkedList<Node> shortestPath = new LinkedList<>(sourceNode.getShortestPath());
shortestPath.add(sourceNode);
evaluationNode.setShortestPath(shortestPath);
}
}
private static Node getLowestDistanceNode(Set<Node> unsettledNodes) {
Node lowestDistanceNode = null;
int lowestDistance = Integer.MAX_VALUE;
for (Node node : unsettledNodes) {
int nodeDistance = node.getDistance();
if (nodeDistance < lowestDistance) {
lowestDistance = nodeDistance;
lowestDistanceNode = node;
}
}
return lowestDistanceNode;
}
}

View File

@ -1,21 +1,21 @@
package com.baeldung.algorithms.dijkstra;
import java.util.HashSet;
import java.util.Set;
public class Graph {
private Set<Node> nodes = new HashSet<>();
public void addNode(Node nodeA) {
nodes.add(nodeA);
}
public Set<Node> getNodes() {
return nodes;
}
public void setNodes(Set<Node> nodes) {
this.nodes = nodes;
}
}
package com.baeldung.algorithms.ga.dijkstra;
import java.util.HashSet;
import java.util.Set;
public class Graph {
private Set<Node> nodes = new HashSet<>();
public void addNode(Node nodeA) {
nodes.add(nodeA);
}
public Set<Node> getNodes() {
return nodes;
}
public void setNodes(Set<Node> nodes) {
this.nodes = nodes;
}
}

View File

@ -1,58 +1,58 @@
package com.baeldung.algorithms.dijkstra;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Node {
private String name;
private LinkedList<Node> shortestPath = new LinkedList<>();
private Integer distance = Integer.MAX_VALUE;
private Map<Node, Integer> adjacentNodes = new HashMap<>();
public Node(String name) {
this.name = name;
}
public void addDestination(Node destination, int distance) {
adjacentNodes.put(destination, distance);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<Node, Integer> getAdjacentNodes() {
return adjacentNodes;
}
public void setAdjacentNodes(Map<Node, Integer> adjacentNodes) {
this.adjacentNodes = adjacentNodes;
}
public Integer getDistance() {
return distance;
}
public void setDistance(Integer distance) {
this.distance = distance;
}
public List<Node> getShortestPath() {
return shortestPath;
}
public void setShortestPath(LinkedList<Node> shortestPath) {
this.shortestPath = shortestPath;
}
}
package com.baeldung.algorithms.ga.dijkstra;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Node {
private String name;
private LinkedList<Node> shortestPath = new LinkedList<>();
private Integer distance = Integer.MAX_VALUE;
private Map<Node, Integer> adjacentNodes = new HashMap<>();
public Node(String name) {
this.name = name;
}
public void addDestination(Node destination, int distance) {
adjacentNodes.put(destination, distance);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<Node, Integer> getAdjacentNodes() {
return adjacentNodes;
}
public void setAdjacentNodes(Map<Node, Integer> adjacentNodes) {
this.adjacentNodes = adjacentNodes;
}
public Integer getDistance() {
return distance;
}
public void setDistance(Integer distance) {
this.distance = distance;
}
public List<Node> getShortestPath() {
return shortestPath;
}
public void setShortestPath(LinkedList<Node> shortestPath) {
this.shortestPath = shortestPath;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.automata;
/**
* Finite state machine.
*/
public interface FiniteStateMachine {
/**
* Follow a transition, switch the state of the machine.
* @param c Char.
* @return A new finite state machine with the new state.
*/
FiniteStateMachine switchState(final CharSequence c);
/**
* Is the current state a final one?
* @return true or false.
*/
boolean canStop();
}

View File

@ -0,0 +1,30 @@
package com.baeldung.automata;
/**
* Default implementation of a finite state machine.
* This class is immutable and thread-safe.
*/
public final class RtFiniteStateMachine implements FiniteStateMachine {
/**
* Current state.
*/
private State current;
/**
* Ctor.
* @param initial Initial state of this machine.
*/
public RtFiniteStateMachine(final State initial) {
this.current = initial;
}
public FiniteStateMachine switchState(final CharSequence c) {
return new RtFiniteStateMachine(this.current.transit(c));
}
public boolean canStop() {
return this.current.isFinal();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.automata;
import java.util.ArrayList;
import java.util.List;
/**
* State in a finite state machine.
*/
public final class RtState implements State {
private List<Transition> transitions;
private boolean isFinal;
public RtState() {
this(false);
}
public RtState(final boolean isFinal) {
this.transitions = new ArrayList<>();
this.isFinal = isFinal;
}
public State transit(final CharSequence c) {
for(final Transition t : this.transitions) {
if(t.isPossible(c)) {
return t.state();
}
}
throw new IllegalArgumentException("Input not accepted: " + c);
}
public boolean isFinal() {
return this.isFinal;
}
@Override
public State with(Transition tr) {
this.transitions.add(tr);
return this;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.automata;
/**
* Transition in finite state machine.
*/
public final class RtTransition implements Transition {
private String rule;
private State next;
/**
* Ctor.
* @param rule Rule that a character has to meet
* in order to get to the next state.
* @param next Next state.
*/
public RtTransition (String rule, State next) {
this.rule = rule;
this.next = next;
}
public State state() {
return this.next;
}
public boolean isPossible(CharSequence c) {
return this.rule.equalsIgnoreCase(String.valueOf(c));
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.automata;
/**
* State. Part of a finite state machine.
*/
public interface State {
/**
* Add a Transition to this state.
* @param tr Given transition.
* @return Modified State.
*/
State with(final Transition tr);
/**
* Follow one of the transitions, to get
* to the next state.
* @param c Character.
* @return State.
* @throws IllegalStateException if the char is not accepted.
*/
State transit(final CharSequence c);
/**
* Can the automaton stop on this state?
* @return true or false
*/
boolean isFinal();
}

View File

@ -0,0 +1,20 @@
package com.baeldung.automata;
/**
* Transition in a finite State machine.
*/
public interface Transition {
/**
* Is the transition possible with the given character?
* @param c char.
* @return true or false.
*/
boolean isPossible(final CharSequence c);
/**
* The state to which this transition leads.
* @return State.
*/
State state();
}

View File

@ -1,4 +1,4 @@
package com.baeldung.algorithms;
package algorithms;
import org.junit.Assert;
import org.junit.Test;

View File

@ -1,4 +1,4 @@
package com.baeldung.algorithms;
package algorithms;
import org.junit.Assert;
import org.junit.Test;

View File

@ -1,10 +1,11 @@
package algorithms;
import com.baeldung.algorithms.dijkstra.Dijkstra;
import com.baeldung.algorithms.dijkstra.Graph;
import com.baeldung.algorithms.dijkstra.Node;
import org.junit.Test;
import com.baeldung.algorithms.ga.dijkstra.Dijkstra;
import com.baeldung.algorithms.ga.dijkstra.Graph;
import com.baeldung.algorithms.ga.dijkstra.Node;
import java.util.Arrays;
import java.util.List;

View File

@ -0,0 +1,82 @@
package algorithms;
import static org.junit.Assert.*;
import org.junit.Test;
import com.baeldung.automata.*;
/**
* Tests for {@link RtFiniteStateMachine}
*/
public final class RtFiniteStateMachineTest {
@Test
public void acceptsSimplePair() {
String json = "{\"key\":\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i=0;i<json.length();i++) {
machine = machine.switchState(String.valueOf(json.charAt(i)));
}
assertTrue(machine.canStop());
}
@Test
public void acceptsMorePairs() {
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i=0;i<json.length();i++) {
machine = machine.switchState(String.valueOf(json.charAt(i)));
}
assertTrue(machine.canStop());
}
@Test(expected = IllegalArgumentException.class)
public void missingColon() {
String json = "{\"key\"\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i=0;i<json.length();i++) {
machine = machine.switchState(String.valueOf(json.charAt(i)));
}
}
/**
* Builds a finite state machine to validate a simple
* Json object.
* @return
*/
private FiniteStateMachine buildJsonStateMachine() {
State first = new RtState();
State second = new RtState();
State third = new RtState();
State fourth = new RtState();
State fifth = new RtState();
State sixth = new RtState();
State seventh = new RtState();
State eighth = new RtState(true);
first.with(new RtTransition("{", second));
second.with(new RtTransition("\"", third));
//Add transitions with chars 0-9 and a-z
for (int i = 0; i < 26; i++) {
if(i<10) {
third = third.with(
new RtTransition(String.valueOf(i), third)
);
sixth = sixth.with(
new RtTransition(String.valueOf(i), sixth)
);
}
third = third.with(
new RtTransition(String.valueOf((char) ('a' + i)), third)
);
sixth = sixth.with(
new RtTransition(String.valueOf((char) ('a' + i)), sixth)
);
}
third.with(new RtTransition("\"", fourth));
fourth.with(new RtTransition(":", fifth));
fifth.with(new RtTransition("\"", sixth));
sixth.with(new RtTransition("\"", seventh));
seventh.with(new RtTransition(",", second));
seventh.with(new RtTransition("}", eighth));
return new RtFiniteStateMachine(first);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.algorithms;
package algorithms;
import org.junit.Assert;
import org.junit.Test;

View File

@ -1,36 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-commons</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<junit.version>4.12</junit.version>
<compiler.version>3.6.0</compiler.version>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

Binary file not shown.

3
aws/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [AWS Lambda Using DynamoDB With Java](http://www.baeldung.com/aws-lambda-dynamodb-java)

3
axon/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [A Guide to the Axon Framework](http://www.baeldung.com/axon-cqrs-event-sourcing)

52
axon/pom.xml Normal file
View File

@ -0,0 +1,52 @@
<?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">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>axon</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-test</artifactId>
<version>${axon.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-core</artifactId>
<version>${axon.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<axon.version>3.0.2</axon.version>
<junit.version>4.12</junit.version>
</properties>
</project>

View File

@ -0,0 +1,54 @@
package com.baeldung.axon;
import com.baeldung.axon.aggregates.MessagesAggregate;
import com.baeldung.axon.commands.CreateMessageCommand;
import com.baeldung.axon.commands.MarkReadMessageCommand;
import com.baeldung.axon.eventhandlers.MessagesEventHandler;
import org.axonframework.commandhandling.AggregateAnnotationCommandHandler;
import org.axonframework.commandhandling.CommandBus;
import org.axonframework.commandhandling.SimpleCommandBus;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.commandhandling.gateway.DefaultCommandGateway;
import org.axonframework.eventhandling.AnnotationEventListenerAdapter;
import org.axonframework.eventsourcing.EventSourcingRepository;
import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore;
import org.axonframework.eventsourcing.eventstore.EventStore;
import org.axonframework.eventsourcing.eventstore.inmemory.InMemoryEventStorageEngine;
import java.util.UUID;
public class MessagesRunner {
public static void main(String[] args) {
CommandBus commandBus = new SimpleCommandBus();
CommandGateway commandGateway = new DefaultCommandGateway(commandBus);
EventStore eventStore = new EmbeddedEventStore(new InMemoryEventStorageEngine());
EventSourcingRepository<MessagesAggregate> repository =
new EventSourcingRepository<>(MessagesAggregate.class, eventStore);
AggregateAnnotationCommandHandler<MessagesAggregate> messagesAggregateAggregateAnnotationCommandHandler =
new AggregateAnnotationCommandHandler<MessagesAggregate>(MessagesAggregate.class, repository);
messagesAggregateAggregateAnnotationCommandHandler.subscribe(commandBus);
final AnnotationEventListenerAdapter annotationEventListenerAdapter =
new AnnotationEventListenerAdapter(new MessagesEventHandler());
eventStore.subscribe(eventMessages -> eventMessages.forEach(e -> {
try {
annotationEventListenerAdapter.handle(e);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
));
final String itemId = UUID.randomUUID().toString();
commandGateway.send(new CreateMessageCommand(itemId, "Hello, how is your day? :-)"));
commandGateway.send(new MarkReadMessageCommand(itemId));
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.axon.aggregates;
import com.baeldung.axon.commands.CreateMessageCommand;
import com.baeldung.axon.commands.MarkReadMessageCommand;
import com.baeldung.axon.events.MessageCreatedEvent;
import com.baeldung.axon.events.MessageReadEvent;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.AggregateIdentifier;
import org.axonframework.eventhandling.EventHandler;
import static org.axonframework.commandhandling.model.AggregateLifecycle.apply;
public class MessagesAggregate {
@AggregateIdentifier
private String id;
public MessagesAggregate() {
}
@CommandHandler
public MessagesAggregate(CreateMessageCommand command) {
apply(new MessageCreatedEvent(command.getId(), command.getText()));
}
@EventHandler
public void on(MessageCreatedEvent event) {
this.id = event.getId();
}
@CommandHandler
public void markRead(MarkReadMessageCommand command) {
apply(new MessageReadEvent(id));
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.axon.commands;
import org.axonframework.commandhandling.TargetAggregateIdentifier;
public class CreateMessageCommand {
@TargetAggregateIdentifier
private final String id;
private final String text;
public CreateMessageCommand(String id, String text) {
this.id = id;
this.text = text;
}
public String getId() {
return id;
}
public String getText() {
return text;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.axon.commands;
import org.axonframework.commandhandling.TargetAggregateIdentifier;
public class MarkReadMessageCommand {
@TargetAggregateIdentifier
private final String id;
public MarkReadMessageCommand(String id) {
this.id = id;
}
public String getId() {
return id;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.axon.eventhandlers;
import com.baeldung.axon.events.MessageReadEvent;
import com.baeldung.axon.events.MessageCreatedEvent;
import org.axonframework.eventhandling.EventHandler;
public class MessagesEventHandler {
@EventHandler
public void handle(MessageCreatedEvent event) {
System.out.println("Message received: " + event.getText() + " (" + event.getId() + ")");
}
@EventHandler
public void handle(MessageReadEvent event) {
System.out.println("Message read: " + event.getId());
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.axon.events;
public class MessageCreatedEvent {
private final String id;
private final String text;
public MessageCreatedEvent(String id, String text) {
this.id = id;
this.text = text;
}
public String getId() {
return id;
}
public String getText() {
return text;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.axon.events;
public class MessageReadEvent {
private final String id;
public MessageReadEvent(String id) {
this.id = id;
}
public String getId() {
return id;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.axon;
import com.baeldung.axon.aggregates.MessagesAggregate;
import com.baeldung.axon.commands.CreateMessageCommand;
import com.baeldung.axon.commands.MarkReadMessageCommand;
import com.baeldung.axon.events.MessageCreatedEvent;
import com.baeldung.axon.events.MessageReadEvent;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.Before;
import org.junit.Test;
import java.util.UUID;
public class MessagesAggregateTest {
private FixtureConfiguration<MessagesAggregate> fixture;
@Before
public void setUp() throws Exception {
fixture = new AggregateTestFixture<MessagesAggregate>(MessagesAggregate.class);
}
@Test
public void giveAggregateRoot_whenCreateMessageCommand_thenShouldProduceMessageCreatedEvent() throws Exception {
String eventText = "Hello, how is your day?";
String id = UUID.randomUUID().toString();
fixture.given()
.when(new CreateMessageCommand(id, eventText))
.expectEvents(new MessageCreatedEvent(id, eventText));
}
@Test
public void givenMessageCreatedEvent_whenReadMessageCommand_thenShouldProduceMessageReadEvent() throws Exception {
String id = UUID.randomUUID().toString();
fixture.given(new MessageCreatedEvent(id, "Hello :-)"))
.when(new MarkReadMessageCommand(id))
.expectEvents(new MessageReadEvent(id));
}
}

View File

@ -8,3 +8,7 @@
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java9-completablefuture-api-improvements/)
- [Spring Security Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login)
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)

View File

@ -0,0 +1 @@
javac -d mods --module-source-path src/modules $(find src/modules -name "*.java")

View File

@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.client^
src/modules/com.baeldung.student.client/module-info.java^
src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java

View File

@ -0,0 +1,2 @@
javac -d mods/com.baeldung.student.model src/modules/com.baeldung.student.model/module-info.java^
src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java

View File

@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.service.dbimpl^
src/modules/com.baeldung.student.service.dbimpl/module-info.java^
src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java

View File

@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.service^
src/modules/com.baeldung.student.service/module-info.java^
src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java

View File

@ -0,0 +1 @@
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient

View File

@ -0,0 +1 @@
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient

View File

@ -0,0 +1,84 @@
package com.baeldung.java9.stackwalker;
import java.lang.StackWalker.StackFrame;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StackWalkerDemo {
public void methodOne() {
this.methodTwo();
}
public void methodTwo() {
this.methodThree();
}
public void methodThree() {
List<StackFrame> stackTrace = StackWalker.getInstance()
.walk(this::walkExample);
printStackTrace(stackTrace);
System.out.println("---------------------------------------------");
stackTrace = StackWalker.getInstance()
.walk(this::walkExample2);
printStackTrace(stackTrace);
System.out.println("---------------------------------------------");
String line = StackWalker.getInstance().walk(this::walkExample3);
System.out.println(line);
System.out.println("---------------------------------------------");
stackTrace = StackWalker.getInstance(StackWalker.Option.SHOW_REFLECT_FRAMES)
.walk(this::walkExample);
printStackTrace(stackTrace);
System.out.println("---------------------------------------------");
Runnable r = () -> {
List<StackFrame> stackTrace2 = StackWalker.getInstance(StackWalker.Option.SHOW_HIDDEN_FRAMES)
.walk(this::walkExample);
printStackTrace(stackTrace2);
};
r.run();
}
public List<StackFrame> walkExample(Stream<StackFrame> stackFrameStream) {
return stackFrameStream.collect(Collectors.toList());
}
public List<StackFrame> walkExample2(Stream<StackFrame> stackFrameStream) {
return stackFrameStream.filter(frame -> frame.getClassName()
.contains("com.baeldung"))
.collect(Collectors.toList());
}
public String walkExample3(Stream<StackFrame> stackFrameStream) {
return stackFrameStream.filter(frame -> frame.getClassName()
.contains("com.baeldung")
&& frame.getClassName()
.endsWith("Test"))
.findFirst()
.map(frame -> frame.getClassName() + "#" + frame.getMethodName() + ", Line " + frame.getLineNumber())
.orElse("Unknown caller");
}
public void findCaller() {
Class<?> caller = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass();
System.out.println(caller.getCanonicalName());
}
public void printStackTrace(List<StackFrame> stackTrace) {
for (StackFrame stackFrame : stackTrace) {
System.out.println(stackFrame.getClassName()
.toString() + "#" + stackFrame.getMethodName() + ", Line " + stackFrame.getLineNumber());
}
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.student.client;
import com.baeldung.student.service.StudentService;
import com.baeldung.student.service.dbimpl.StudentDbService;
import com.baeldung.student.model.Student;
public class StudentClient {
public static void main(String[] args) {
StudentService service = new StudentDbService();
service.create(new Student());
service.read("17SS0001");
service.update(new Student());
service.delete("17SS0001");
}
}

View File

@ -0,0 +1,3 @@
module com.baeldung.student.client{
requires com.baeldung.student.service.dbimpl;
}

View File

@ -0,0 +1,15 @@
package com.baeldung.student.model;
import java.util.Date;
public class Student {
private String registrationId;
public String getRegistrationId() {
return registrationId;
}
public void setRegistrationId(String registrationId) {
this.registrationId = registrationId;
}
}

View File

@ -0,0 +1,3 @@
module com.baeldung.student.model{
exports com.baeldung.student.model;
}

View File

@ -0,0 +1,30 @@
package com.baeldung.student.service.dbimpl;
import com.baeldung.student.service.StudentService;
import com.baeldung.student.model.Student;
import java.util.logging.*;
public class StudentDbService implements StudentService {
private static Logger logger = Logger.getLogger("StudentDbService");
public String create(Student student) {
logger.log(Level.INFO, "Creating student in DB...");
return student.getRegistrationId();
}
public Student read(String registrationId) {
logger.log(Level.INFO, "Reading student from DB...");
return new Student();
}
public Student update(Student student) {
logger.log(Level.INFO, "Updating sutdent in DB...");
return student;
}
public String delete(String registrationId) {
logger.log(Level.INFO, "Deleteing sutdent in DB...");
return registrationId;
}
}

View File

@ -0,0 +1,5 @@
module com.baeldung.student.service.dbimpl{
requires transitive com.baeldung.student.service;
exports com.baeldung.student.service.dbimpl;
requires java.logging;
}

View File

@ -0,0 +1,14 @@
package com.baeldung.student.service;
import com.baeldung.student.model.Student;
public interface StudentService {
public String create(Student student);
public Student read(String registrationId);
public Student update(Student student);
public String delete(String registrationId);
}

View File

@ -0,0 +1,4 @@
module com.baeldung.student.service{
requires transitive com.baeldung.student.model;
exports com.baeldung.student.service;
}

View File

@ -0,0 +1,74 @@
package com.baeldung.java9.concurrent.future;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CompletableFutureTest {
@Test
public void testDelay () throws Exception {
Object input = new Object();
CompletableFuture<Object> future = new CompletableFuture<>();
future.completeAsync(() -> input, CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
Thread.sleep(100);
assertFalse(future.isDone());
Thread.sleep(1000);
assertTrue(future.isDone());
assertSame(input, future.get());
}
@Test
public void testTimeoutTriggered () throws Exception {
CompletableFuture<Object> future = new CompletableFuture<>();
future.orTimeout(1, TimeUnit.SECONDS);
Thread.sleep(1100);
assertTrue(future.isDone());
try {
future.get();
} catch (ExecutionException e) {
assertTrue(e.getCause() instanceof TimeoutException);
}
}
@Test
public void testTimeoutNotTriggered () throws Exception {
Object input = new Object();
CompletableFuture<Object> future = new CompletableFuture<>();
future.orTimeout(1, TimeUnit.SECONDS);
Thread.sleep(100);
future.complete(input);
Thread.sleep(1000);
assertTrue(future.isDone());
assertSame(input, future.get());
}
@Test
public void completeOnTimeout () throws Exception {
Object input = new Object();
CompletableFuture<Object> future = new CompletableFuture<>();
future.completeOnTimeout(input, 1, TimeUnit.SECONDS);
Thread.sleep(1100);
assertTrue(future.isDone());
assertSame(input, future.get());
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.java9.stackwalker;
import org.junit.Test;
public class StackWalkerDemoTest {
@Test
public void giveStalkWalker_whenWalkingTheStack_thenShowStackFrames() {
new StackWalkerDemo().methodOne();
}
@Test
public void giveStalkWalker_whenInvokingFindCaller_thenFindCallingClass() {
new StackWalkerDemo().findCaller();
}
}

View File

@ -79,3 +79,9 @@
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)
- [A Guide to LinkedHashMap in Java](http://www.baeldung.com/java-linked-hashmap)
- [A Guide to TreeMap in Java](http://www.baeldung.com/java-treemap)
- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks)
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)

View File

@ -1,207 +0,0 @@
package com.baeldung.algorithms.ga.ant_colony;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;
public class AntColonyOptimization {
private double c = 1.0;
private double alpha = 1;
private double beta = 5;
private double evaporation = 0.5;
private double Q = 500;
private double antFactor = 0.8;
private double randomFactor = 0.01;
private int maxIterations = 1000;
public int numberOfCities;
public int numberOfAnts;
private double graph[][];
private double trails[][];
private List<Ant> ants = new ArrayList<>();
private Random random = new Random();
private double probabilities[];
private int currentIndex;
public int[] bestTourOrder;
public double bestTourLength;
public AntColonyOptimization(int noOfCities) {
graph = generateRandomMatrix(noOfCities);
numberOfCities = graph.length;
numberOfAnts = (int) (numberOfCities * antFactor);
trails = new double[numberOfCities][numberOfCities];
probabilities = new double[numberOfCities];
IntStream.range(0, numberOfAnts).forEach(i -> ants.add(new Ant(numberOfCities)));
}
/**
* Generate initial solution
*
* @param n
* @return
*/
public double[][] generateRandomMatrix(int n) {
double[][] randomMatrix = new double[n][n];
random.setSeed(System.currentTimeMillis());
IntStream.range(0, n).forEach(i -> {
IntStream.range(0, n).forEach(j -> {
Integer r = random.nextInt(100) + 1;
randomMatrix[i][j] = Math.abs(r);
});
});
return randomMatrix;
}
/**
* Perform ant optimization
*
* @return
*/
public void startAntOptimization() {
IntStream.rangeClosed(1, 3).forEach(i -> {
System.out.println("Attempt #" + i);
solve();
});
}
/**
* Use this method to run the main logic
*
* @return
*/
public int[] solve() {
setupAnts();
clearTrails();
IntStream.range(0, maxIterations).forEach(i -> {
moveAnts();
updateTrails();
updateBest();
});
System.out.println("Best tour length: " + (bestTourLength - numberOfCities));
System.out.println("Best tour order: " + Arrays.toString(bestTourOrder));
return bestTourOrder.clone();
}
/**
* Prepare ants for the simulation
*/
private void setupAnts() {
IntStream.range(0, numberOfAnts).forEach(i -> {
ants.stream().forEach(ant -> {
ant.clear();
ant.visitCity(-1, random.nextInt(numberOfCities));
});
});
currentIndex = 0;
}
/**
* At each iteration, move ants
*/
private void moveAnts() {
IntStream.range(currentIndex, numberOfCities - 1).forEach(i -> {
ants.stream().forEach(ant -> {
ant.visitCity(currentIndex, selectNextCity(ant));
});
currentIndex++;
});
}
/**
* Select next city for each ant
*
* @param ant
* @return
*/
private int selectNextCity(Ant ant) {
int t = random.nextInt(numberOfCities - currentIndex);
if (random.nextDouble() < randomFactor) {
IntStream.range(0, numberOfCities).filter(i -> i == t && !ant.visited(i)).findFirst();
}
calculateProbabilities(ant);
double r = random.nextDouble();
double total = 0;
for (int i = 0; i < numberOfCities; i++) {
total += probabilities[i];
if (total >= r) {
return i;
}
}
throw new RuntimeException("There are no other cities");
}
/**
* Calculate the next city picks probabilites
*
* @param ant
*/
public void calculateProbabilities(Ant ant) {
int i = ant.trail[currentIndex];
double pheromone = 0.0;
for (int l = 0; l < numberOfCities; l++) {
if (!ant.visited(l)) {
pheromone += Math.pow(trails[i][l], alpha) * Math.pow(1.0 / graph[i][l], beta);
}
}
for (int j = 0; j < numberOfCities; j++) {
if (ant.visited(j)) {
probabilities[j] = 0.0;
} else {
double numerator = Math.pow(trails[i][j], alpha) * Math.pow(1.0 / graph[i][j], beta);
probabilities[j] = numerator / pheromone;
}
}
}
/**
* Update trails that ants used
*/
private void updateTrails() {
for (int i = 0; i < numberOfCities; i++) {
for (int j = 0; j < numberOfCities; j++) {
trails[i][j] *= evaporation;
}
}
for (Ant a : ants) {
double contribution = Q / a.trailLength(graph);
for (int i = 0; i < numberOfCities - 1; i++) {
trails[a.trail[i]][a.trail[i + 1]] += contribution;
}
trails[a.trail[numberOfCities - 1]][a.trail[0]] += contribution;
}
}
/**
* Update the best solution
*/
private void updateBest() {
if (bestTourOrder == null) {
bestTourOrder = ants.get(0).trail;
bestTourLength = ants.get(0).trailLength(graph);
}
for (Ant a : ants) {
if (a.trailLength(graph) < bestTourLength) {
bestTourLength = a.trailLength(graph);
bestTourOrder = a.trail.clone();
}
}
}
/**
* Clear trails after simulation
*/
private void clearTrails() {
IntStream.range(0, numberOfCities).forEach(i -> {
IntStream.range(0, numberOfCities).forEach(j -> trails[i][j] = c);
});
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.primitiveconversions;
package com.baeldung;
import org.junit.Test;
import static org.junit.Assert.*;

View File

@ -0,0 +1,23 @@
package com.baeldung.java8.comparator;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@Data
@AllArgsConstructor
@ToString
@EqualsAndHashCode
public class Employee implements Comparable<Employee>{
String name;
int age;
double salary;
long mobile;
@Override
public int compareTo(Employee argEmployee) {
return name.compareTo(argEmployee.getName());
}
}

View File

@ -0,0 +1,192 @@
package com.baeldung.java8.comparator;
import java.util.Arrays;
import java.util.Comparator;
import org.junit.Before;
import org.junit.Test;
import lombok.Data;
import static org.junit.Assert.assertTrue;
public class Java8ComparatorTest {
private Employee[] employees;
private Employee[] employeesArrayWithNulls;
private Employee[] sortedEmployeesByName;
private Employee[] sortedEmployeesByNameDesc;
private Employee[] sortedEmployeesByAge;
private Employee[] sortedEmployeesByMobile;
private Employee[] sortedEmployeesBySalary;
private Employee[] sortedEmployeesArray_WithNullsFirst;
private Employee[] sortedEmployeesArray_WithNullsLast;
private Employee[] sortedEmployeesByNameAge;
private Employee[] someMoreEmployees;
private Employee[] sortedEmployeesByAgeName;;
@Before
public void initData() {
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001),
new Employee("Keith", 35, 4000, 3924401) };
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001),
null, new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001),
new Employee("Ace", 22, 2000, 5924001) };
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), };
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001),
new Employee("Keith", 35, 4000, 3924401), };
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001),
new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
}
@Test
public void givenEmployeeArray_whenUsingComparing_thenCheckingSort() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
}
@Test
public void givenEmployeeArray_whenUsingComparingWithComparator_thenCheckingSort() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName, (s1, s2) -> {
return s2.compareTo(s1);
});
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@Test
public void givenEmployeeArray_whenUsingComparingInt_thenCheckingSort() {
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
Arrays.sort(employees, employeeAgeComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByAge));
}
@Test
public void givenEmployeeArray_whenUsingComparingLong_thenCheckingSort() {
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
Arrays.sort(employees, employeeMobileComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByMobile));
}
@Test
public void givenEmployeeArray_whenUsingComparingDouble_thenCheckingSort() {
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
Arrays.sort(employees, employeeSalaryComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesBySalary));
}
@Test
public void givenEmployeeArray_whenUsingNaturalOrder_thenCheckingSort() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
}
@Test
public void givenEmployeeArray_whenUsingReverseOrder_thenCheckingSort() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@Test
public void givenEmployeeArray_whenUsingNullFirst_thenCheckingSort() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
// System.out.println(Arrays.toString(employeesArrayWithNulls));
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst));
}
@Test
public void givenEmployeeArray_whenUsingNullLast_thenCheckingSort() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
// System.out.println(Arrays.toString(employeesArrayWithNulls));
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast));
}
@Test
public void givenEmployeeArray_whenUsingThenComparing_thenCheckingSort() {
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
// System.out.println(Arrays.toString(someMoreEmployees));
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName));
}
@Test
public void givenEmployeeArray_whenUsingThenComparingInt_thenCheckingSort() {
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
// System.out.println(Arrays.toString(someMoreEmployees));
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
}
@Before
public void printData() {
// System.out.println("employees");
// System.out.println(Arrays.toString(employees));
//
// System.out.println("employeesArrayWithNulls");
// System.out.println(Arrays.toString(employeesArrayWithNulls));
//
// System.out.println("sortedEmployeesByName");
// System.out.println(Arrays.toString(sortedEmployeesByName));
//
// System.out.println("sortedEmployeesByNameDesc");
// System.out.println(Arrays.toString(sortedEmployeesByNameDesc));
//
// System.out.println("sortedEmployeesByAge");
// System.out.println(Arrays.toString(sortedEmployeesByAge));
//
// System.out.println("sortedEmployeesByMobile");
// System.out.println(Arrays.toString(sortedEmployeesByMobile));
//
// System.out.println("sortedEmployeesBySalary");
// System.out.println(Arrays.toString(sortedEmployeesBySalary));
//
// System.out.println("sortedEmployeesArray_WithNullsFirst");
// System.out.println(Arrays.toString(sortedEmployeesArray_WithNullsFirst));
//
// System.out.println("sortedEmployeesArray_WithNullsLast");
// System.out.println(Arrays.toString(sortedEmployeesArray_WithNullsLast));
//
// System.out.println("sortedEmployeesByNameAge");
// System.out.println(Arrays.toString(sortedEmployeesByNameAge));
//
// System.out.println("someMoreEmployees");
// System.out.println(Arrays.toString(someMoreEmployees));
//
}
}

View File

@ -0,0 +1,64 @@
package com.baeldung.list.flattennestedlist;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class FlattenNestedListTest {
@Test
public void givenListOfListOfString_flattenNestedList1() {
// given
List<String> ls1 = Arrays.asList("one:one", "one:two", "one:three");
List<String> ls2 = Arrays.asList("two:one", "two:two", "two:three");
List<String> ls3 = Arrays.asList("three:one", "three:two", "three:three");
List<List<String>> list = Arrays.asList(ls1, ls2, ls3);
// when
List<String> ls = flattenListOfListsImperatively(list);
// then
assertNotNull(ls);
assertTrue(ls.size() == 9);
//TODO content assertion
}
@Test
public void givenListOfListOfString_flattenNestedList2() {
// given
List<String> ls1 = Arrays.asList("one:one", "one:two", "one:three");
List<String> ls2 = Arrays.asList("two:one", "two:two", "two:three");
List<String> ls3 = Arrays.asList("three:one", "three:two", "three:three");
List<List<String>> list = Arrays.asList(ls1, ls2, ls3);
// when
List<String> ls = flattenListOfListsStream(list);
// then
assertNotNull(ls);
assertTrue(ls.size() == 9);
//TODO content assertion
}
public <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
List<T> ls = new ArrayList<>();
list.forEach(ls::addAll);
return ls;
}
public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
}

View File

@ -15,6 +15,8 @@ import javax.money.convert.MonetaryConversions;
import javax.money.format.AmountFormatQueryBuilder;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import static org.junit.Assert.*;
@ -40,7 +42,11 @@ public class JavaMoneyTest {
@Test
public void givenAmounts_whenStringified_thanEquals() {
CurrencyUnit usd = Monetary.getCurrency("USD");
MonetaryAmount fstAmtUSD = Monetary.getDefaultAmountFactory().setCurrency(usd).setNumber(200).create();
MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200)
.create();
Money moneyof = Money.of(12, usd);
FastMoney fastmoneyof = FastMoney.of(2, usd);
@ -52,7 +58,11 @@ public class JavaMoneyTest {
@Test
public void givenCurrencies_whenCompared_thanNotequal() {
MonetaryAmount oneDolar = Monetary.getDefaultAmountFactory().setCurrency("USD").setNumber(1).create();
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
Money oneEuro = Money.of(1, "EUR");
assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
@ -61,20 +71,22 @@ public class JavaMoneyTest {
@Test(expected = ArithmeticException.class)
public void givenAmount_whenDivided_thanThrowsException() {
MonetaryAmount oneDolar = Monetary.getDefaultAmountFactory().setCurrency("USD").setNumber(1).create();
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
oneDolar.divide(3);
fail(); // if no exception
}
@Test
public void givenAmounts_whenSummed_thanCorrect() {
MonetaryAmount[] monetaryAmounts = new MonetaryAmount[]{
Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF")};
List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
Money sumAmtCHF = Money.of(0, "CHF");
for (MonetaryAmount monetaryAmount : monetaryAmounts) {
sumAmtCHF = sumAmtCHF.add(monetaryAmount);
}
Money sumAmtCHF = (Money) monetaryAmounts
.stream()
.reduce(Money.of(0, "CHF"), MonetaryAmount::add);
assertEquals("CHF 111.35", sumAmtCHF.toString());
}
@ -84,9 +96,19 @@ public class JavaMoneyTest {
CurrencyUnit usd = Monetary.getCurrency("USD");
Money moneyof = Money.of(12, usd);
MonetaryAmount fstAmtUSD = Monetary.getDefaultAmountFactory().setCurrency(usd).setNumber(200.50).create();
MonetaryAmount oneDolar = Monetary.getDefaultAmountFactory().setCurrency("USD").setNumber(1).create();
Money subtractedAmount = Money.of(1, "USD").subtract(fstAmtUSD);
MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200.50)
.create();
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
Money subtractedAmount = Money
.of(1, "USD")
.subtract(fstAmtUSD);
MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
MonetaryAmount divideAmount = oneDolar.divide(0.25);
@ -101,53 +123,64 @@ public class JavaMoneyTest {
@Test
public void givenAmount_whenRounded_thanEquals() {
MonetaryAmount fstAmtEUR = Monetary.getDefaultAmountFactory().setCurrency("EUR").setNumber(1.30473908).create();
MonetaryAmount fstAmtEUR = Monetary
.getDefaultAmountFactory()
.setCurrency("EUR")
.setNumber(1.30473908)
.create();
MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
assertEquals("EUR 1.30473908", fstAmtEUR.toString());
assertEquals("EUR 1.3", roundEUR.toString());
}
@Test
public void givenAmount_whenCustomFormat_thanEquals() {
MonetaryAmount oneDolar = Monetary.getDefaultAmountFactory().setCurrency("USD").setNumber(1).create();
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
String usFormatted = formatUSD.format(oneDolar);
public void givenAmount_whenConversion_thenNotNull() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder.of(Locale.US).set(CurrencyStyle.NAME).set("pattern", "00000.00 ¤").build());
String customFormatted = customFormat.format(oneDolar);
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
assertEquals("USD 1", oneDolar.toString());
assertNotNull(formatUSD);
assertNotNull(customFormat);
assertEquals("USD1.00", usFormatted);
assertEquals("00001.00 US Dollar", customFormatted);
MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR);
assertEquals("USD 1", oneDollar.toString());
assertNotNull(convertedAmountUSDtoEUR);
}
@Test
public void givenAmount_whenConversion_thenNotNull() {
CurrencyUnit USD = Monetary.getCurrency("USD");
MonetaryAmount oneDolar = Monetary.getDefaultAmountFactory().setCurrency("USD").setNumber(1).create();
MonetaryAmount fstAmtEUR = Monetary.getDefaultAmountFactory().setCurrency("EUR").setNumber(1.30473908).create();
public void givenLocale_whenFormatted_thanEquals() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
String usFormatted = formatUSD.format(oneDollar);
CurrencyConversion convEUR = MonetaryConversions.getConversion(ConversionQueryBuilder.of().setTermCurrency("EUR").build());
CurrencyConversion convUSD = MonetaryConversions.getConversion(ConversionQueryBuilder.of().setTermCurrency(USD).build());
assertEquals("USD 1", oneDollar.toString());
assertNotNull(formatUSD);
assertEquals("USD1.00", usFormatted);
}
CurrencyConversion conversionUSD = MonetaryConversions.getConversion("USD");
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
@Test
public void givenAmount_whenCustomFormat_thanEquals() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
MonetaryAmount convertedAmountEURtoUSD = fstAmtEUR.with(conversionUSD);
MonetaryAmount convertedAmountEURtoUSD2 = fstAmtEUR.with(convUSD);
MonetaryAmount convertedAmountUSDtoEUR = oneDolar.with(conversionEUR);
MonetaryAmount convertedAmountUSDtoEUR2 = oneDolar.with(convEUR);
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
.of(Locale.US)
.set(CurrencyStyle.NAME)
.set("pattern", "00000.00 ¤")
.build());
String customFormatted = customFormat.format(oneDollar);
assertEquals("USD", USD.toString());
assertEquals("USD 1", oneDolar.toString());
assertEquals("EUR 1.30473908", fstAmtEUR.toString());
assertNotNull(convEUR);
assertNotNull(convUSD);
assertNotNull(convertedAmountEURtoUSD);
assertNotNull(convertedAmountEURtoUSD2);
assertNotNull(convertedAmountUSDtoEUR);
assertNotNull(convertedAmountUSDtoEUR2);
assertNotNull(customFormat);
assertEquals("USD 1", oneDollar.toString());
assertEquals("00001.00 US Dollar", customFormatted);
}
}

View File

@ -24,3 +24,4 @@
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
- [Guide to Guavas Reflection Utilities](http://www.baeldung.com/guava-reflection)

View File

@ -1,11 +0,0 @@
package com.baeldung.examples.guice.marker;
/**
*
* @author Baeldung
*/
public interface Communicator {
public boolean sendMessage(String message);
}

4
guice/README.md Normal file
View File

@ -0,0 +1,4 @@
## Google Guice Tutorials Project
### Relevant Articles
- [Guide to Google Guice](http://www.baeldung.com/guice)

View File

@ -2,7 +2,7 @@
<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.examples.guice</groupId>
<artifactId>guice-intro</artifactId>
<artifactId>guice</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
@ -30,5 +30,5 @@
<maven.compiler.target>1.8</maven.compiler.target>
<guice.version>4.1.0</guice.version>
</properties>
<name>guice-intro</name>
<name>guice</name>
</project>

View File

@ -1,36 +1,32 @@
package com.baeldung.examples;
import com.baeldung.examples.guice.Communication;
import com.baeldung.examples.guice.binding.AOPModule;
import com.baeldung.examples.guice.modules.BasicModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.Scanner;
/**
*
* @author Baeldung
*/
public class RunGuice {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new BasicModule(), new AOPModule());
Communication comms = injector.getInstance(Communication.class);
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your message to be sent; press Q to quit and P to print the message log");
while (true) {
String input = scanner.nextLine();
if (input.equalsIgnoreCase("q")) {
System.exit(0);
}
if (input.equalsIgnoreCase("p")) {
comms.print();
} else {
comms.sendMessage(input);
}
}
}
}
package com.baeldung.examples;
import com.baeldung.examples.guice.Communication;
import com.baeldung.examples.guice.binding.AOPModule;
import com.baeldung.examples.guice.modules.BasicModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.Scanner;
/**
*
* @author baeldung
*/
public class RunGuice {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new BasicModule(), new AOPModule());
Communication comms = injector.getInstance(Communication.class);
Scanner scanner = new Scanner(System.in);
while (true) {
String input = scanner.nextLine();
if (input.equalsIgnoreCase("q")) {
System.exit(0);
} else {
comms.sendMessage(input);
}
}
}
}

View File

@ -1,57 +1,40 @@
package com.baeldung.examples.guice;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Logger;
/**
*
* @author Baeldung
*/
public class Communication {
final Date start = new Date();
@Inject
private Logger logger;
private Queue<String> messageLog;
@Named("CommsUUID")
private String commsID;
@Inject
private DefaultCommunicator communicator;
public Communication(Boolean keepRecords) {
if (keepRecords) {
messageLog = new LinkedList();
}
}
public boolean sendMessage(String message) {
if (!message.isEmpty() && messageLog != null) {
messageLog.add(message);
}
return communicator.sendMessage(message);
}
public void print() {
if (messageLog != null) {
for (String message : messageLog) {
logger.info(message);
}
} else {
logger.info("Message logging wasn't enabled");
}
}
public DefaultCommunicator getCommunicator() {
return this.communicator;
}
}
package com.baeldung.examples.guice;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Logger;
/**
*
* @author baeldung
*/
public class Communication {
final Date start = new Date();
@Inject
private Logger logger;
@Inject
private DefaultCommunicator communicator;
public Communication(Boolean keepRecords) {
if (keepRecords) {
System.out.println("keeping records");
}
}
public boolean sendMessage(String message) {
return communicator.sendMessage(message);
}
public DefaultCommunicator getCommunicator() {
return this.communicator;
}
}

View File

@ -1,12 +1,12 @@
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.constant.CommunicationModel;
public interface CommunicationMode {
public CommunicationModel getMode();
public boolean sendMessage(String message);
}
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.constant.CommunicationModel;
public interface CommunicationMode {
public CommunicationModel getMode();
public boolean sendMessage(String message);
}

View File

@ -1,48 +1,51 @@
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.marker.Communicator;
import com.google.inject.Inject;
import com.google.inject.name.Named;
public class DefaultCommunicator implements Communicator {
private CommunicationMode defaultCommsMode;
@Inject
@Named("SMSComms")
CommunicationMode smsCommsMode;
@Inject
@Named("EmailComms")
CommunicationMode emailCommsMode;
@Inject
@Named("IMComms")
CommunicationMode imCommsMode;
protected DefaultCommunicator(CommunicationMode defaultComms) {
this.defaultCommsMode = defaultComms;
}
public DefaultCommunicator() {
}
public boolean sendMessage(String message) {
boolean sent = false;
if (defaultCommsMode != null) {
sent = sendMessageByDefault(message);
} else {
sent = smsCommsMode.sendMessage(message);
}
return sent;
}
private boolean sendMessageByDefault(String message) {
boolean sent = false;
if (message != null && !message.trim().equals("")) {
return defaultCommsMode.sendMessage(message);
}
return sent;
}
}
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.marker.Communicator;
import com.google.inject.Inject;
import com.google.inject.name.Named;
/**
*
* @author baeldung
*/
public class DefaultCommunicator implements Communicator {
private CommunicationMode defaultCommsMode;
@Inject
@Named("SMSComms")
CommunicationMode smsCommsMode;
@Inject
@Named("EmailComms")
CommunicationMode emailCommsMode;
@Inject
@Named("IMComms")
CommunicationMode imCommsMode;
protected DefaultCommunicator(CommunicationMode defaultComms) {
this.defaultCommsMode = defaultComms;
}
public DefaultCommunicator() {
}
public boolean sendMessage(String message) {
boolean sent = false;
if (defaultCommsMode != null) {
sent = sendMessageByDefault(message);
} else {
sent = smsCommsMode.sendMessage(message);
}
return sent;
}
private boolean sendMessageByDefault(String message) {
boolean sent = false;
if (message != null && !message.trim().equals("")) {
return defaultCommsMode.sendMessage(message);
}
return sent;
}
}

View File

@ -1,23 +1,24 @@
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.baeldung.examples.guice.constant.CommunicationModel;
/**
*
* @author Baekdung
*/
public class EmailCommunicationMode implements CommunicationMode {
@Override
public CommunicationModel getMode() {
return CommunicationModel.EMAIL;
}
@Override
@MessageSentLoggable
public boolean sendMessage(String Message) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.baeldung.examples.guice.constant.CommunicationModel;
/**
*
* @author baeldung
*/
public class EmailCommunicationMode implements CommunicationMode {
@Override
public CommunicationModel getMode() {
return CommunicationModel.EMAIL;
}
@Override
@MessageSentLoggable
public boolean sendMessage(String Message) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}

View File

@ -1,30 +1,30 @@
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.baeldung.examples.guice.constant.CommunicationModel;
import com.google.inject.Inject;
import java.util.logging.Logger;
/**
*
* @author Baeldung
*/
public class IMCommunicationMode implements CommunicationMode {
@Inject
private Logger logger;
@Override
public CommunicationModel getMode() {
return CommunicationModel.IM;
}
@Override
@MessageSentLoggable
public boolean sendMessage(String message) {
logger.info("IM Message Sent");
return true;
}
}
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.baeldung.examples.guice.constant.CommunicationModel;
import com.google.inject.Inject;
import java.util.logging.Logger;
/**
*
* @author baeldung
*/
public class IMCommunicationMode implements CommunicationMode {
@Inject
private Logger logger;
@Override
public CommunicationModel getMode() {
return CommunicationModel.IM;
}
@Override
@MessageSentLoggable
public boolean sendMessage(String message) {
logger.info("IM Message Sent");
return true;
}
}

View File

@ -1,29 +1,30 @@
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.baeldung.examples.guice.constant.CommunicationModel;
import com.google.inject.Inject;
import java.util.logging.Logger;
/**
*
* @author Baeldung
*/
public class SMSCommunicationMode implements CommunicationMode {
@Inject
private Logger logger;
@Override
public CommunicationModel getMode() {
return CommunicationModel.SMS;
}
@Override
@MessageSentLoggable
public boolean sendMessage(String message) {
logger.info("SMS message sent");
return true;
}
}
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.baeldung.examples.guice.constant.CommunicationModel;
import com.google.inject.Inject;
import java.util.logging.Logger;
/**
*
* @author baeldung
*/
public class SMSCommunicationMode implements CommunicationMode {
@Inject
private Logger logger;
@Override
public CommunicationModel getMode() {
return CommunicationModel.SMS;
}
@Override
@MessageSentLoggable
public boolean sendMessage(String message) {
logger.info("SMS message sent");
return true;
}
}

View File

@ -1,22 +1,24 @@
package com.baeldung.examples.guice.aop;
import java.util.logging.Logger;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
*
* @author Baeldung
*/
public class MessageLogger implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object[] objectArray = invocation.getArguments();
int i = 0;
for (Object object : objectArray) {
Logger.getAnonymousLogger().info("Sending message: " + object.toString());
}
return invocation.proceed();
}
}
package com.baeldung.examples.guice.aop;
import com.google.inject.Inject;
import java.util.logging.Logger;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
*
* @author baeldung
*/
public class MessageLogger implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object[] objectArray = invocation.getArguments();
int i = 0;
for (Object object : objectArray) {
Logger.getAnonymousLogger().info("Sending message: " + object.toString());
}
return invocation.proceed();
}
}

View File

@ -1,16 +1,17 @@
package com.baeldung.examples.guice.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author Baeldung
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MessageSentLoggable {
}
package com.baeldung.examples.guice.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author baeldung
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MessageSentLoggable {
}

View File

@ -1,22 +1,23 @@
package com.baeldung.examples.guice.binding;
import com.baeldung.examples.guice.aop.MessageLogger;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.google.inject.AbstractModule;
import com.google.inject.matcher.Matchers;
/**
*
* @author Baeldung
*/
public class AOPModule extends AbstractModule {
@Override
protected void configure() {
bindInterceptor(Matchers.any(),
Matchers.annotatedWith(MessageSentLoggable.class),
new MessageLogger()
);
}
}
package com.baeldung.examples.guice.binding;
import com.baeldung.examples.guice.aop.MessageLogger;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.google.inject.AbstractModule;
import com.google.inject.matcher.Matchers;
/**
*
* @author baeldung
*/
public class AOPModule extends AbstractModule {
@Override
protected void configure() {
bindInterceptor(Matchers.any(),
Matchers.annotatedWith(MessageSentLoggable.class),
new MessageLogger()
);
}
}

View File

@ -1,36 +1,37 @@
package com.baeldung.examples.guice.binding;
import com.baeldung.examples.guice.Communication;
import com.baeldung.examples.guice.CommunicationMode;
import com.baeldung.examples.guice.DefaultCommunicator;
import com.baeldung.examples.guice.EmailCommunicationMode;
import com.baeldung.examples.guice.IMCommunicationMode;
import com.baeldung.examples.guice.SMSCommunicationMode;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Baeldung
*/
public class BasicModule extends AbstractModule {
@Override
protected void configure() {
try {
bind(Communication.class).toConstructor(Communication.class.getConstructor(Boolean.TYPE));
} catch (NoSuchMethodException ex) {
Logger.getLogger(BasicModule.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(BasicModule.class.getName()).log(Level.SEVERE, null, ex);
}
bind(DefaultCommunicator.class).annotatedWith(Names.named("AnotherCommunicator")).to(DefaultCommunicator.class).asEagerSingleton();
bind(CommunicationMode.class).annotatedWith(Names.named("IMComms")).to(IMCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("EmailComms")).to(EmailCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("SMSComms")).to(SMSCommunicationMode.class);
}
}
package com.baeldung.examples.guice.binding;
import com.baeldung.examples.guice.Communication;
import com.baeldung.examples.guice.CommunicationMode;
import com.baeldung.examples.guice.DefaultCommunicator;
import com.baeldung.examples.guice.EmailCommunicationMode;
import com.baeldung.examples.guice.IMCommunicationMode;
import com.baeldung.examples.guice.SMSCommunicationMode;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author baeldung
*/
public class BasicModule extends AbstractModule {
@Override
protected void configure() {
try {
bind(Communication.class).toConstructor(Communication.class.getConstructor(Boolean.TYPE));
} catch (NoSuchMethodException ex) {
Logger.getLogger(BasicModule.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(BasicModule.class.getName()).log(Level.SEVERE, null, ex);
}
bind(DefaultCommunicator.class).annotatedWith(Names.named("AnotherCommunicator")).to(DefaultCommunicator.class).asEagerSingleton();
bind(CommunicationMode.class).annotatedWith(Names.named("IMComms")).to(IMCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("EmailComms")).to(EmailCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("SMSComms")).to(SMSCommunicationMode.class);
}
}

View File

@ -1,16 +1,17 @@
package com.baeldung.examples.guice.constant;
/**
*
* @author Baeldung
*/
public enum CommunicationModel {
EMAIL("Email"), SMS("SMS"), IM("IM"), PHONE("Phone");
final String name;
CommunicationModel(String name) {
this.name = name;
}
}
package com.baeldung.examples.guice.constant;
/**
*
* @author baeldung
*/
public enum CommunicationModel {
EMAIL("Email"), SMS("SMS"), IM("IM"), PHONE("Phone");
final String name;
CommunicationModel(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,14 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.examples.guice.marker;
/**
*
* @author Tayo
*/
public interface Communicator {
}

View File

@ -1,37 +1,38 @@
package com.baeldung.examples.guice.modules;
import com.baeldung.examples.guice.Communication;
import com.baeldung.examples.guice.CommunicationMode;
import com.baeldung.examples.guice.DefaultCommunicator;
import com.baeldung.examples.guice.EmailCommunicationMode;
import com.baeldung.examples.guice.IMCommunicationMode;
import com.baeldung.examples.guice.SMSCommunicationMode;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Baeldung
*/
public class BasicModule extends AbstractModule {
@Override
protected void configure() {
try {
bind(Communication.class).toConstructor(Communication.class.getConstructor(Boolean.class));
bind(Boolean.class).toInstance(true);
} catch (NoSuchMethodException ex) {
Logger.getLogger(com.baeldung.examples.guice.binding.BasicModule.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(com.baeldung.examples.guice.binding.BasicModule.class.getName()).log(Level.SEVERE, null, ex);
}
bind(DefaultCommunicator.class).annotatedWith(Names.named("AnotherCommunicator")).to(DefaultCommunicator.class).asEagerSingleton();
bind(CommunicationMode.class).annotatedWith(Names.named("IMComms")).to(IMCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("EmailComms")).to(EmailCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("SMSComms")).to(SMSCommunicationMode.class);
}
}
package com.baeldung.examples.guice.modules;
import com.baeldung.examples.guice.Communication;
import com.baeldung.examples.guice.CommunicationMode;
import com.baeldung.examples.guice.DefaultCommunicator;
import com.baeldung.examples.guice.EmailCommunicationMode;
import com.baeldung.examples.guice.IMCommunicationMode;
import com.baeldung.examples.guice.SMSCommunicationMode;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author baeldung
*/
public class BasicModule extends AbstractModule {
@Override
protected void configure() {
try {
bind(Communication.class).toConstructor(Communication.class.getConstructor(Boolean.class));
bind(Boolean.class).toInstance(true);
} catch (NoSuchMethodException ex) {
Logger.getLogger(com.baeldung.examples.guice.binding.BasicModule.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(com.baeldung.examples.guice.binding.BasicModule.class.getName()).log(Level.SEVERE, null, ex);
}
bind(DefaultCommunicator.class).annotatedWith(Names.named("AnotherCommunicator")).to(DefaultCommunicator.class).asEagerSingleton();
bind(CommunicationMode.class).annotatedWith(Names.named("IMComms")).to(IMCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("EmailComms")).to(EmailCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("SMSComms")).to(SMSCommunicationMode.class);
}
}

3
hbase/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [HBase with Java](http://www.baeldung.com/hbase)

3
java-websocket/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [A Guide to the Java API for WebSocket](http://www.baeldung.com/java-websockets)

View File

@ -17,6 +17,7 @@
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>

View File

@ -8,9 +8,11 @@ import com.baeldung.model.Message;
import com.google.gson.Gson;
public class MessageDecoder implements Decoder.Text<Message> {
private static Gson gson = new Gson();
@Override
public Message decode(String s) throws DecodeException {
Gson gson = new Gson();
Message message = gson.fromJson(s, Message.class);
return message;
}

View File

@ -8,9 +8,11 @@ import com.baeldung.model.Message;
import com.google.gson.Gson;
public class MessageEncoder implements Encoder.Text<Message> {
private static Gson gson = new Gson();
@Override
public String encode(Message message) throws EncodeException {
Gson gson = new Gson();
String json = gson.toJson(message);
return json;
}

View File

@ -2,8 +2,11 @@ var ws;
function connect() {
var username = document.getElementById("username").value;
ws = new WebSocket("ws://" + document.location.host + "/java-websocket/chat/" + username);
var host = document.location.host;
var pathname = document.location.pathname;
ws = new WebSocket("ws://" +host + pathname + "chat/" + username);
ws.onmessage = function(event) {
var log = document.getElementById("log");

View File

@ -1,36 +1,36 @@
package com.baeldung.javaeeannotations;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter(
urlPatterns = "/bankAccount/*",
filterName = "LoggingFilter",
description = "Filter all account transaction URLs"
)
public class LoggingFilter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect(req.getContextPath() + "/login.jsp");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
package com.baeldung.javaeeannotations;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter(
urlPatterns = "/bankAccount/*",
filterName = "LogInFilter",
description = "Filter all account transaction URLs"
)
public class LogInFilter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect(req.getContextPath() + "/login.jsp");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}

3
jooq/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [Introduction to jOOL](http://www.baeldung.com/jool)

7
jws/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
/target/
.classpath
.project
.settings
/.settings/
/settings/
.tern-project

Binary file not shown.

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