Merge remote-tracking branch 'refs/remotes/eugenp/master'
This commit is contained in:
commit
0b1bc56504
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,3 +1,5 @@
|
||||
*/bin/*
|
||||
|
||||
*.class
|
||||
|
||||
# Package Files #
|
||||
|
10
.travis.yml
10
.travis.yml
@ -1,11 +1,13 @@
|
||||
language: java
|
||||
|
||||
install: travis_wait 40 mvn -q clean install -Dgib.enabled=true
|
||||
install: travis_wait 60 mvn -q test
|
||||
|
||||
before_script:
|
||||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
jdk:
|
||||
- oraclejdk8
|
||||
|
||||
sudo: false
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
@ -14,4 +16,6 @@ addons:
|
||||
cache:
|
||||
directories:
|
||||
- .autoconf
|
||||
- $HOME/.m2
|
||||
- $HOME/.m2
|
||||
|
||||
|
||||
|
3
Twitter4J/README.md
Normal file
3
Twitter4J/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant articles
|
||||
|
||||
- [Introduction to Twitter4J](http://www.baeldung.com/twitter4j)
|
@ -3,3 +3,4 @@
|
||||
- [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)
|
||||
|
@ -10,9 +10,15 @@
|
||||
<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>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
|
@ -1,57 +1,57 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
@ -1,21 +1,21 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
@ -1,58 +1,58 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class BigIntegerPrimeChecker implements PrimeChecker{
|
||||
|
||||
@Override
|
||||
public boolean isPrime(int number) {
|
||||
BigInteger bigInt = BigInteger.valueOf(number);
|
||||
return bigInt.isProbablePrime(100);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class BruteForcePrimeChecker implements PrimeChecker{
|
||||
|
||||
@Override
|
||||
public boolean isPrime(int number) {
|
||||
return IntStream.range(2, number).noneMatch(n -> (number % n == 0));
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class OptimisedPrimeChecker implements PrimeChecker{
|
||||
|
||||
@Override
|
||||
public boolean isPrime(int number) {
|
||||
return IntStream.range(2, (int)Math.sqrt(number) + 1)
|
||||
.noneMatch(n -> (number % n == 0));
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
public interface PrimeChecker {
|
||||
|
||||
public boolean isPrime( int number );
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import org.apache.commons.math3.primes.Primes;
|
||||
|
||||
public class PrimesPrimeChecker implements PrimeChecker{
|
||||
|
||||
@Override
|
||||
public boolean isPrime(int number) {
|
||||
return Primes.isPrime(number);
|
||||
}
|
||||
|
||||
}
|
@ -5,12 +5,12 @@ package com.baeldung.automata;
|
||||
*/
|
||||
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);
|
||||
/**
|
||||
* 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?
|
||||
|
@ -6,25 +6,25 @@ package com.baeldung.automata;
|
||||
*/
|
||||
public final class RtFiniteStateMachine implements FiniteStateMachine {
|
||||
|
||||
/**
|
||||
* Current state.
|
||||
*/
|
||||
private State current;
|
||||
/**
|
||||
* Current state.
|
||||
*/
|
||||
private State current;
|
||||
|
||||
/**
|
||||
* Ctor.
|
||||
* @param initial Initial state of this machine.
|
||||
*/
|
||||
public RtFiniteStateMachine(final State initial) {
|
||||
this.current = initial;
|
||||
}
|
||||
/**
|
||||
* 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 FiniteStateMachine switchState(final CharSequence c) {
|
||||
return new RtFiniteStateMachine(this.current.transit(c));
|
||||
}
|
||||
|
||||
public boolean canStop() {
|
||||
return this.current.isFinal();
|
||||
}
|
||||
public boolean canStop() {
|
||||
return this.current.isFinal();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -21,22 +21,22 @@ public final class RtState implements State {
|
||||
}
|
||||
|
||||
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);
|
||||
return transitions
|
||||
.stream()
|
||||
.filter(t -> t.isPossible(c))
|
||||
.map(Transition::state)
|
||||
.findAny()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Input not accepted: " + c));
|
||||
}
|
||||
|
||||
public boolean isFinal() {
|
||||
return this.isFinal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public State with(Transition tr) {
|
||||
this.transitions.add(tr);
|
||||
return this;
|
||||
}
|
||||
@Override
|
||||
public State with(Transition tr) {
|
||||
this.transitions.add(tr);
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -6,26 +6,26 @@ package com.baeldung.automata;
|
||||
*/
|
||||
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;
|
||||
}
|
||||
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));
|
||||
}
|
||||
public boolean isPossible(CharSequence c) {
|
||||
return this.rule.equalsIgnoreCase(String.valueOf(c));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -5,12 +5,12 @@ package com.baeldung.automata;
|
||||
*/
|
||||
public interface State {
|
||||
|
||||
/**
|
||||
* Add a Transition to this state.
|
||||
* @param tr Given transition.
|
||||
* @return Modified State.
|
||||
*/
|
||||
State with(final Transition tr);
|
||||
/**
|
||||
* 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
|
||||
|
@ -5,16 +5,16 @@ package com.baeldung.automata;
|
||||
*/
|
||||
public interface Transition {
|
||||
|
||||
/**
|
||||
* Is the transition possible with the given character?
|
||||
* @param c char.
|
||||
* @return true or false.
|
||||
*/
|
||||
boolean isPossible(final CharSequence c);
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/**
|
||||
* The state to which this transition leads.
|
||||
* @return State.
|
||||
*/
|
||||
State state();
|
||||
}
|
||||
|
@ -9,74 +9,74 @@ import com.baeldung.automata.*;
|
||||
*/
|
||||
public final class RtFiniteStateMachineTest {
|
||||
|
||||
@Test
|
||||
@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());
|
||||
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
|
||||
@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());
|
||||
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)
|
||||
|
||||
@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)));
|
||||
}
|
||||
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);
|
||||
/**
|
||||
* 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)
|
||||
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)
|
||||
);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.primechecker.BigIntegerPrimeChecker;
|
||||
import com.baeldung.algorithms.primechecker.PrimeChecker;
|
||||
|
||||
public class BigIntegerPrimeCheckerTest {
|
||||
|
||||
PrimeChecker primeChecker = new BigIntegerPrimeChecker();
|
||||
|
||||
@Test
|
||||
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
|
||||
assertTrue(primeChecker.isPrime(13));
|
||||
assertTrue(primeChecker.isPrime(1009));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
|
||||
assertTrue(!primeChecker.isPrime(50));
|
||||
assertTrue(!primeChecker.isPrime(1001));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.primechecker.BruteForcePrimeChecker;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class BruteForcePrimeCheckerTest {
|
||||
|
||||
BruteForcePrimeChecker primeChecker = new BruteForcePrimeChecker();
|
||||
|
||||
@Test
|
||||
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
|
||||
assertTrue(primeChecker.isPrime(13));
|
||||
assertTrue(primeChecker.isPrime(1009));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
|
||||
assertTrue(!primeChecker.isPrime(50));
|
||||
assertTrue(!primeChecker.isPrime(1001));
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.primechecker.OptimisedPrimeChecker;
|
||||
import com.baeldung.algorithms.primechecker.PrimeChecker;
|
||||
|
||||
public class OptimisedPrimeCheckerTest {
|
||||
|
||||
PrimeChecker primeChecker = new OptimisedPrimeChecker();
|
||||
|
||||
@Test
|
||||
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
|
||||
assertTrue(primeChecker.isPrime(13));
|
||||
assertTrue(primeChecker.isPrime(1009));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
|
||||
assertTrue(!primeChecker.isPrime(50));
|
||||
assertTrue(!primeChecker.isPrime(1001));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.primechecker.PrimeChecker;
|
||||
import com.baeldung.algorithms.primechecker.PrimesPrimeChecker;
|
||||
|
||||
public class PrimesPrimeCheckerTest {
|
||||
PrimeChecker primeChecker = new PrimesPrimeChecker();
|
||||
|
||||
@Test
|
||||
public void givenPrimeNumber_whenCheckIsPrime_thenTrue() {
|
||||
assertTrue(primeChecker.isPrime(13));
|
||||
assertTrue(primeChecker.isPrime(1009));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse() {
|
||||
assertTrue(!primeChecker.isPrime(50));
|
||||
assertTrue(!primeChecker.isPrime(1001));
|
||||
}
|
||||
|
||||
}
|
2
apache-poi/.gitignore
vendored
2
apache-poi/.gitignore
vendored
@ -1 +1,3 @@
|
||||
*.docx
|
||||
temp.xls
|
||||
temp.xlsx
|
||||
|
Binary file not shown.
3
aws/README.md
Normal file
3
aws/README.md
Normal 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
3
axon/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant articles
|
||||
|
||||
- [A Guide to the Axon Framework](http://www.baeldung.com/axon-cqrs-event-sourcing)
|
@ -8,4 +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/)
|
||||
- [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)
|
||||
|
1
core-java-9/compile-modules.sh
Normal file
1
core-java-9/compile-modules.sh
Normal file
@ -0,0 +1 @@
|
||||
javac -d mods --module-source-path src/modules $(find src/modules -name "*.java")
|
3
core-java-9/compile-student-client.bat
Normal file
3
core-java-9/compile-student-client.bat
Normal 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
|
2
core-java-9/compile-student-model.bat
Normal file
2
core-java-9/compile-student-model.bat
Normal 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
|
3
core-java-9/compile-student-service-dbimpl.bat
Normal file
3
core-java-9/compile-student-service-dbimpl.bat
Normal 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
|
3
core-java-9/compile-student-service.bat
Normal file
3
core-java-9/compile-student-service.bat
Normal 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
|
1
core-java-9/run-student-client.bat
Normal file
1
core-java-9/run-student-client.bat
Normal file
@ -0,0 +1 @@
|
||||
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient
|
1
core-java-9/run-student-client.sh
Normal file
1
core-java-9/run-student-client.sh
Normal file
@ -0,0 +1 @@
|
||||
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient
|
@ -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");
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
module com.baeldung.student.client{
|
||||
requires com.baeldung.student.service.dbimpl;
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
module com.baeldung.student.model{
|
||||
exports com.baeldung.student.model;
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
@ -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);
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
module com.baeldung.student.service{
|
||||
requires transitive com.baeldung.student.model;
|
||||
exports com.baeldung.student.service;
|
||||
}
|
@ -79,3 +79,10 @@
|
||||
- [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)
|
||||
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
|
||||
|
||||
|
@ -198,7 +198,6 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
@ -250,6 +249,7 @@
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
|
@ -0,0 +1,61 @@
|
||||
package com.baeldung.arraycopy.model;
|
||||
|
||||
public class Address implements Cloneable {
|
||||
private String country;
|
||||
private String state;
|
||||
private String city;
|
||||
private String street;
|
||||
private String zipcode;
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
|
||||
public String getZipcode() {
|
||||
return zipcode;
|
||||
}
|
||||
|
||||
public void setZipcode(String zipcode) {
|
||||
this.zipcode = zipcode;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
super.clone();
|
||||
Address address = new Address();
|
||||
address.setCity(this.city);
|
||||
address.setCountry(this.country);
|
||||
address.setState(this.state);
|
||||
address.setStreet(this.street);
|
||||
address.setZipcode(this.zipcode);
|
||||
return address;
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.arraycopy.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class Employee implements Serializable {
|
||||
private static final long serialVersionUID = -2454619097207585825L;
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
package com.baeldung.list.flattennestedlist;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class FlattenNestedList {
|
||||
|
||||
public List<String> flattenListOfLists(List<List<String>> lol) {
|
||||
|
||||
// flatten the list
|
||||
List<String> ls = new ArrayList<>();
|
||||
lol.forEach((k) -> ls.addAll(k));
|
||||
|
||||
return ls;
|
||||
}
|
||||
|
||||
}
|
19
core-java/src/main/java/com/baeldung/pow/PowerExample.java
Normal file
19
core-java/src/main/java/com/baeldung/pow/PowerExample.java
Normal file
@ -0,0 +1,19 @@
|
||||
package com.baeldung.pow;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
|
||||
public class PowerExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
int intResult = (int) Math.pow(2, 3);
|
||||
System.out.println("Math.pow(2, 3) = " + intResult);
|
||||
|
||||
double dblResult = Math.pow(4.2, 3);
|
||||
System.out.println("Math.pow(4.2, 3) = " + Math.pow(4.2, 3));
|
||||
|
||||
DecimalFormat df = new DecimalFormat(".00");
|
||||
System.out.println("Math.pow(4.2, 3) rounded = " + df.format(dblResult));
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.stringtokenizer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
public class Application {
|
||||
|
||||
public List<String> getTokens(String str) {
|
||||
List<String> tokens = new ArrayList<String>();
|
||||
// StringTokenizer tokenizer = new StringTokenizer( str );
|
||||
StringTokenizer tokenizer = new StringTokenizer( str , "," );
|
||||
// StringTokenizer tokenizer = new StringTokenizer( str , "," , true );
|
||||
while (tokenizer.hasMoreElements()) {
|
||||
tokens.add( tokenizer.nextToken() );
|
||||
// tokens.add( tokenizer.nextToken( "," ) );
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,168 @@
|
||||
package com.baeldung.arraycopy;
|
||||
|
||||
import com.baeldung.arraycopy.model.Address;
|
||||
import com.baeldung.arraycopy.model.Employee;
|
||||
import org.apache.commons.lang3.SerializationUtils;
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class ArrayCopyUtilTest {
|
||||
private static Employee[] employees;
|
||||
private static final int MAX = 2;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup(){
|
||||
createEmployeesArray();
|
||||
}
|
||||
|
||||
private static void createEmployeesArray() {
|
||||
employees = new Employee[MAX];
|
||||
Employee employee;
|
||||
for(int i = 0; i < MAX; i++) {
|
||||
employee = new Employee();
|
||||
employee.setName("Emp"+i);
|
||||
employee.setId(i);
|
||||
employees[i] = employee;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfPrimitiveType_whenCopiedViaSystemsArrayCopy_thenSuccessful(){
|
||||
int[] array = {23, 43, 55};
|
||||
int[] copiedArray = new int[3];
|
||||
|
||||
System.arraycopy(array, 0, copiedArray, 0, 3);
|
||||
|
||||
Assert.assertArrayEquals(copiedArray, array);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaSystemsArrayCopy_thenSuccessful(){
|
||||
int[] array = {23, 43, 55, 12, 65, 88, 92};
|
||||
int[] copiedArray = new int[3];
|
||||
|
||||
System.arraycopy(array, 2, copiedArray, 0, 3);
|
||||
|
||||
Assert.assertTrue(3 == copiedArray.length);
|
||||
Assert.assertTrue(copiedArray[0] == array[2]);
|
||||
Assert.assertTrue(copiedArray[1] == array[3]);
|
||||
Assert.assertTrue(copiedArray[2] == array[4]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaArraysCopyOfRange_thenSuccessful(){
|
||||
int[] array = {23, 43, 55, 12, 65, 88, 92};
|
||||
|
||||
int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
|
||||
|
||||
Assert.assertTrue(3 == copiedArray.length);
|
||||
Assert.assertTrue(copiedArray[0] == array[1]);
|
||||
Assert.assertTrue(copiedArray[1] == array[2]);
|
||||
Assert.assertTrue(copiedArray[2] == array[3]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfPrimitiveType_whenCopiedViaArraysCopyOf_thenValueChangeIsSuccessful(){
|
||||
int[] array = {23, 43, 55, 12};
|
||||
int newLength = array.length;
|
||||
|
||||
int[] copiedArray = Arrays.copyOf(array, newLength);
|
||||
|
||||
Assert.assertArrayEquals(copiedArray, array);
|
||||
array[0] = 9;
|
||||
Assert.assertTrue(copiedArray[0] != array[0]);
|
||||
copiedArray[1] = 12;
|
||||
Assert.assertTrue(copiedArray[1] != array[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfNonPrimitiveType_whenCopiedViaArraysCopyOf_thenDoShallowCopy(){
|
||||
Employee[] copiedArray = Arrays.copyOf(employees, employees.length);
|
||||
|
||||
Assert.assertArrayEquals(copiedArray, employees);
|
||||
employees[0].setName(employees[0].getName()+"_Changed");
|
||||
//change in employees' element caused change in the copied array
|
||||
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfPrimitiveType_whenCopiedViaArrayClone_thenValueChangeIsSuccessful(){
|
||||
int[] array = {23, 43, 55, 12};
|
||||
|
||||
int[] copiedArray = array.clone();
|
||||
|
||||
Assert.assertArrayEquals(copiedArray, array);
|
||||
array[0] = 9;
|
||||
Assert.assertTrue(copiedArray[0] != array[0]);
|
||||
copiedArray[1] = 12;
|
||||
Assert.assertTrue(copiedArray[1] != array[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArraysOfNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
|
||||
Employee[] copiedArray = employees.clone();
|
||||
|
||||
Assert.assertArrayEquals(copiedArray, employees);;
|
||||
employees[0].setName(employees[0].getName()+"_Changed");
|
||||
//change in employees' element changed the copied array
|
||||
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArraysOfCloneableNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
|
||||
Address[] addresses = createAddressArray();
|
||||
|
||||
Address[] copiedArray = addresses.clone();
|
||||
|
||||
addresses[0].setCity(addresses[0].getCity()+"_Changed");
|
||||
Assert.assertArrayEquals(copiedArray, addresses);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArraysOfSerializableNonPrimitiveType_whenCopiedViaSerializationUtils_thenDoDeepCopy(){
|
||||
Employee[] copiedArray = SerializationUtils.clone(employees);
|
||||
|
||||
employees[0].setName(employees[0].getName()+"_Changed");
|
||||
//change in employees' element didn't change in the copied array
|
||||
Assert.assertFalse(
|
||||
copiedArray[0].getName().equals(employees[0].getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArraysOfNonPrimitiveType_whenCopiedViaStream_thenDoShallowCopy(){
|
||||
Employee[] copiedArray = Arrays.stream(employees).toArray(Employee[]::new);
|
||||
|
||||
Assert.assertArrayEquals(copiedArray, employees);
|
||||
employees[0].setName(employees[0].getName()+"_Changed");
|
||||
//change in employees' element didn't change in the copied array
|
||||
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArraysOfPrimitiveType_whenCopiedViaStream_thenSuccessful(){
|
||||
String[] strArray = {"orange", "red", "green'"};
|
||||
|
||||
String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new);
|
||||
|
||||
Assert.assertArrayEquals(copiedArray, strArray);
|
||||
}
|
||||
|
||||
private Address[] createAddressArray(){
|
||||
Address[] addresses = new Address[1];
|
||||
addresses[0] = createAddress();
|
||||
return addresses;
|
||||
}
|
||||
|
||||
private Address createAddress() {
|
||||
Address address = new Address();
|
||||
address.setCountry("USA");
|
||||
address.setState("CA");
|
||||
address.setCity("San Francisco");
|
||||
address.setStreet("Street 1");
|
||||
address.setZipcode("59999");
|
||||
return address;
|
||||
}
|
||||
}
|
@ -12,7 +12,7 @@ import java.util.stream.Stream;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class CountdownLatchExampleTest {
|
||||
public class CountdownLatchExampleIntegrationTest {
|
||||
@Test
|
||||
public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException {
|
||||
// Given
|
@ -1,5 +1,6 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
import com.baeldung.enums.Pizza.PizzaStatusEnum;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@ -69,11 +70,31 @@ public class PizzaUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
|
||||
public void whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
|
||||
Pizza pz = new Pizza();
|
||||
pz.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
pz.deliver();
|
||||
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {
|
||||
String pizzaEnumValue = "READY";
|
||||
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
|
||||
assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenConvertedIntoEnum_thenThrowsException() {
|
||||
String pizzaEnumValue = "rEAdY";
|
||||
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() {
|
||||
String pizzaEnumValue = "invalid";
|
||||
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -60,7 +60,7 @@ public class Java8ComparatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_whenUsingComparing_thenCheckingSort() {
|
||||
public void whenComparing_thenSortedByName() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Arrays.sort(employees, employeeNameComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
@ -68,7 +68,7 @@ public class Java8ComparatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_whenUsingComparingWithComparator_thenCheckingSort() {
|
||||
public void whenComparingWithComparator_thenSortedByNameDesc() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName, (s1, s2) -> {
|
||||
return s2.compareTo(s1);
|
||||
});
|
||||
@ -76,9 +76,18 @@ public class Java8ComparatorTest {
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReversed_thenSortedByNameDesc() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
|
||||
Arrays.sort(employees, employeeNameComparatorReversed);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_whenUsingComparingInt_thenCheckingSort() {
|
||||
public void whenComparingInt_thenSortedByAge() {
|
||||
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
|
||||
Arrays.sort(employees, employeeAgeComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
@ -86,7 +95,7 @@ public class Java8ComparatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_whenUsingComparingLong_thenCheckingSort() {
|
||||
public void whenComparingLong_thenSortedByMobile() {
|
||||
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
|
||||
Arrays.sort(employees, employeeMobileComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
@ -94,7 +103,7 @@ public class Java8ComparatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_whenUsingComparingDouble_thenCheckingSort() {
|
||||
public void whenComparingDouble_thenSortedBySalary() {
|
||||
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
|
||||
Arrays.sort(employees, employeeSalaryComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
@ -102,7 +111,7 @@ public class Java8ComparatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_whenUsingNaturalOrder_thenCheckingSort() {
|
||||
public void whenNaturalOrder_thenSortedByName() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
|
||||
Arrays.sort(employees, employeeNameComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
@ -110,7 +119,7 @@ public class Java8ComparatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_whenUsingReverseOrder_thenCheckingSort() {
|
||||
public void whenReverseOrder_thenSortedByNameDesc() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
|
||||
Arrays.sort(employees, employeeNameComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
@ -118,7 +127,7 @@ public class Java8ComparatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_whenUsingNullFirst_thenCheckingSort() {
|
||||
public void whenNullsFirst_thenSortedByNameWithNullsFirst() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
|
||||
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
|
||||
@ -127,7 +136,7 @@ public class Java8ComparatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_whenUsingNullLast_thenCheckingSort() {
|
||||
public void whenNullsLast_thenSortedByNameWithNullsLast() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
|
||||
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
|
||||
@ -136,7 +145,7 @@ public class Java8ComparatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_whenUsingThenComparing_thenCheckingSort() {
|
||||
public void whenThenComparing_thenSortedByAgeName() {
|
||||
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
|
||||
|
||||
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
|
||||
@ -145,7 +154,7 @@ public class Java8ComparatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_whenUsingThenComparingInt_thenCheckingSort() {
|
||||
public void whenThenComparing_thenSortedByNameAge() {
|
||||
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
|
||||
|
||||
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
|
||||
@ -153,40 +162,6 @@ public class Java8ComparatorTest {
|
||||
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));
|
||||
//
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
import org.junit.runners.MethodSorters;
|
||||
|
||||
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||
public class SortedTests {
|
||||
|
||||
@Test
|
||||
public void a_givenString_whenChangedtoInt_thenTrue() {
|
||||
assertTrue(Integer.valueOf("10") instanceof Integer);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void b_givenInt_whenChangedtoString_thenTrue() {
|
||||
assertTrue(String.valueOf(10) instanceof String);
|
||||
}
|
||||
|
||||
}
|
@ -1,52 +1,48 @@
|
||||
package com.baeldung.list.flattennestedlist;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.hamcrest.collection.IsIterableContainingInOrder;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class FlattenNestedListTest {
|
||||
List<List<String>> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FlattenNestedListTest.class);
|
||||
private FlattenNestedList flol;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
flol = new FlattenNestedList();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfListOfString_flattenNestedList() {
|
||||
|
||||
// create the list to flatten
|
||||
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>> lol = new ArrayList<>();
|
||||
lol.addAll(Arrays.asList(ls1, ls2, ls3));
|
||||
|
||||
// show nested list
|
||||
LOGGER.debug("\nNested list: ");
|
||||
lol.forEach((nl) -> LOGGER.debug(nl + ""));
|
||||
|
||||
// flatten it
|
||||
List<String> ls = flol.flattenListOfLists(lol);
|
||||
public void givenNestedList_thenFlattenNestedListImperative() {
|
||||
List<String> ls = flattenListOfListsImperatively(lol);
|
||||
|
||||
assertNotNull(ls);
|
||||
assertTrue(ls.size() == 9);
|
||||
|
||||
// show flattened list
|
||||
LOGGER.debug("\nFlattened list:");
|
||||
ls.forEach((l) -> LOGGER.debug(l));
|
||||
|
||||
assertTrue(ls.size() == 8);
|
||||
// assert content
|
||||
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNestedList_thenFlattenNestedListStream() {
|
||||
List<String> ls = flattenListOfListsStream(lol);
|
||||
|
||||
assertNotNull(ls);
|
||||
assertTrue(ls.size() == 8);
|
||||
// assert content
|
||||
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.stringtokenizer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ApplicationTest {
|
||||
|
||||
Application application = new Application();
|
||||
List<String> expectedTokens = new ArrayList<String>();
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
expectedTokens.add( "Welcome" );
|
||||
expectedTokens.add( "to" );
|
||||
expectedTokens.add( "baeldung.com" );
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfString() {
|
||||
String str = "Welcome,to,baeldung.com";
|
||||
List<String> actualTokens = application.getTokens(str);
|
||||
assertEquals(expectedTokens, actualTokens);
|
||||
}
|
||||
|
||||
}
|
@ -7,7 +7,7 @@ import java.io.*;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class JavaProcessUnitTest {
|
||||
public class JavaProcessUnitIntegrationTest {
|
||||
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
|
||||
|
||||
private static class StreamGobbler implements Runnable {
|
@ -1,38 +1,38 @@
|
||||
package org.baeldung.java.streams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ThreadPoolInParallelStreamTest {
|
||||
|
||||
@Test
|
||||
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
|
||||
long firstNum = 1;
|
||||
long lastNum = 1_000_000;
|
||||
|
||||
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
|
||||
|
||||
ForkJoinPool customThreadPool = new ForkJoinPool(4);
|
||||
long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
|
||||
|
||||
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenCallingParallelStream_shouldBeParallelStream() {
|
||||
List<Long> aList = new ArrayList<>();
|
||||
Stream<Long> parallelStream = aList.parallelStream();
|
||||
|
||||
assertTrue(parallelStream.isParallel());
|
||||
}
|
||||
}
|
||||
package org.baeldung.java.streams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ThreadPoolInParallelStreamIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
|
||||
long firstNum = 1;
|
||||
long lastNum = 1_000_000;
|
||||
|
||||
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
|
||||
|
||||
ForkJoinPool customThreadPool = new ForkJoinPool(4);
|
||||
long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
|
||||
|
||||
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenCallingParallelStream_shouldBeParallelStream() {
|
||||
List<Long> aList = new ArrayList<>();
|
||||
Stream<Long> parallelStream = aList.parallelStream();
|
||||
|
||||
assertTrue(parallelStream.isParallel());
|
||||
}
|
||||
}
|
@ -145,6 +145,7 @@
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
|
Binary file not shown.
Binary file not shown.
BIN
events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events
Normal file
BIN
events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events
Normal file
Binary file not shown.
BIN
events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events
Normal file
BIN
events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events
Normal file
Binary file not shown.
47
groovy-spock/pom.xml
Normal file
47
groovy-spock/pom.xml
Normal file
@ -0,0 +1,47 @@
|
||||
<?xml version="1.0"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.spockframework</groupId>
|
||||
<artifactId>groovy-spock</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Spock Framework - Example Project</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmavenplus</groupId>
|
||||
<artifactId>gmavenplus-plugin</artifactId>
|
||||
<version>1.5</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
<goal>testCompile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.spockframework</groupId>
|
||||
<artifactId>spock-core</artifactId>
|
||||
<version>1.0-groovy-2.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>2.4.7</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
89
groovy-spock/src/test/groovy/FirstSpecification.groovy
Normal file
89
groovy-spock/src/test/groovy/FirstSpecification.groovy
Normal file
@ -0,0 +1,89 @@
|
||||
import spock.lang.Specification
|
||||
|
||||
class FirstSpecification extends Specification {
|
||||
|
||||
def "one plus one should equal two"() {
|
||||
expect:
|
||||
1 + 1 == 2
|
||||
}
|
||||
|
||||
def "two plus two should equal four"() {
|
||||
given:
|
||||
int left = 2
|
||||
int right = 2
|
||||
|
||||
when:
|
||||
int result = left + right
|
||||
|
||||
then:
|
||||
result == 4
|
||||
}
|
||||
|
||||
def "Should be able to remove from list"() {
|
||||
given:
|
||||
def list = [1, 2, 3, 4]
|
||||
|
||||
when:
|
||||
list.remove(0)
|
||||
|
||||
then:
|
||||
list == [2, 3, 4]
|
||||
}
|
||||
|
||||
def "Should get an index out of bounds when removing a non-existent item"() {
|
||||
given:
|
||||
def list = [1, 2, 3, 4]
|
||||
|
||||
when:
|
||||
list.remove(20)
|
||||
|
||||
then:
|
||||
thrown(IndexOutOfBoundsException)
|
||||
list.size() == 4
|
||||
}
|
||||
|
||||
def "numbers to the power of two"(int a, int b, int c) {
|
||||
expect:
|
||||
Math.pow(a, b) == c
|
||||
|
||||
where:
|
||||
a | b | c
|
||||
1 | 2 | 1
|
||||
2 | 2 | 4
|
||||
3 | 2 | 9
|
||||
}
|
||||
|
||||
def "Should return default value for mock"() {
|
||||
given:
|
||||
def paymentGateway = Mock(PaymentGateway)
|
||||
|
||||
when:
|
||||
def result = paymentGateway.makePayment(12.99)
|
||||
|
||||
then:
|
||||
!result
|
||||
}
|
||||
|
||||
def "Should return true value for mock"() {
|
||||
given:
|
||||
def paymentGateway = Mock(PaymentGateway)
|
||||
paymentGateway.makePayment(20) >> true
|
||||
|
||||
when:
|
||||
def result = paymentGateway.makePayment(20)
|
||||
|
||||
then:
|
||||
result
|
||||
}
|
||||
|
||||
def "Should verify notify was called"() {
|
||||
given:
|
||||
def notifier = Mock(Notifier)
|
||||
|
||||
when:
|
||||
notifier.notify('foo')
|
||||
|
||||
then:
|
||||
1 * notifier.notify('foo')
|
||||
}
|
||||
}
|
3
groovy-spock/src/test/groovy/Notifier.groovy
Normal file
3
groovy-spock/src/test/groovy/Notifier.groovy
Normal file
@ -0,0 +1,3 @@
|
||||
interface Notifier {
|
||||
void notify(String message)
|
||||
}
|
3
groovy-spock/src/test/groovy/PaymentGateway.groovy
Normal file
3
groovy-spock/src/test/groovy/PaymentGateway.groovy
Normal file
@ -0,0 +1,3 @@
|
||||
interface PaymentGateway {
|
||||
boolean makePayment(BigDecimal amount)
|
||||
}
|
@ -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 Guava’s Reflection Utilities](http://www.baeldung.com/guava-reflection)
|
||||
|
192
guava/src/test/java/org/baeldung/guava/GuavaMathTest.java
Normal file
192
guava/src/test/java/org/baeldung/guava/GuavaMathTest.java
Normal file
@ -0,0 +1,192 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
import com.google.common.math.DoubleMath;
|
||||
import com.google.common.math.IntMath;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class GuavaMathTest {
|
||||
@Test
|
||||
public void testIntMathAdd() {
|
||||
try {
|
||||
IntMath.checkedAdd(Integer.MAX_VALUE, 1);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
IntMath.checkedAdd(Integer.MIN_VALUE, -1);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
int result1 = IntMath.checkedAdd(2, 1);
|
||||
assertThat(result1, equalTo(3));
|
||||
|
||||
int result2 = IntMath.saturatedAdd(Integer.MAX_VALUE, 100);
|
||||
assertThat(result2, equalTo(Integer.MAX_VALUE));
|
||||
|
||||
int result3 = IntMath.saturatedAdd(Integer.MIN_VALUE, -100);
|
||||
assertThat(result3, equalTo(Integer.MIN_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntMathSubtract() {
|
||||
try {
|
||||
IntMath.checkedSubtract(Integer.MIN_VALUE, 1);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
IntMath.checkedSubtract(Integer.MAX_VALUE, -1);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
};
|
||||
|
||||
int result1 = IntMath.checkedSubtract(200, 100);
|
||||
assertThat(result1, equalTo(100));
|
||||
|
||||
int result2 = IntMath.saturatedSubtract(Integer.MIN_VALUE, 1);
|
||||
assertThat(result2, equalTo(Integer.MIN_VALUE));
|
||||
|
||||
int result3 = IntMath.saturatedSubtract(Integer.MAX_VALUE, -1);
|
||||
assertThat(result3, equalTo(Integer.MAX_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntMathMultiply() {
|
||||
try {
|
||||
IntMath.checkedMultiply(Integer.MAX_VALUE, 2);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
IntMath.checkedMultiply(Integer.MIN_VALUE, 2);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
int result1 = IntMath.checkedMultiply(21, 3);
|
||||
assertThat(result1, equalTo(63));
|
||||
|
||||
int result2 = IntMath.saturatedMultiply(Integer.MAX_VALUE, 2);
|
||||
assertThat(result2, equalTo(Integer.MAX_VALUE));
|
||||
|
||||
int result3 = IntMath.saturatedMultiply(Integer.MIN_VALUE, 2);
|
||||
assertThat(result3, equalTo(Integer.MIN_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntMathPow() {
|
||||
try {
|
||||
IntMath.checkedPow(Integer.MAX_VALUE, 2);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
IntMath.checkedPow(Integer.MIN_VALUE, 3);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
int result1 = IntMath.saturatedPow(3, 3);
|
||||
assertThat(result1, equalTo(27));
|
||||
|
||||
int result2 = IntMath.saturatedPow(Integer.MAX_VALUE, 2);
|
||||
assertThat(result2, equalTo(Integer.MAX_VALUE));
|
||||
|
||||
int result3 = IntMath.saturatedPow(Integer.MIN_VALUE, 3);
|
||||
assertThat(result3, equalTo(Integer.MIN_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntMathRound() {
|
||||
int result1 = IntMath.divide(3, 2, RoundingMode.DOWN);
|
||||
assertThat(result1, equalTo(1));
|
||||
int result2 = IntMath.divide(3, 2, RoundingMode.UP);
|
||||
assertThat(result2, equalTo(2));
|
||||
|
||||
int result3 = IntMath.log2(5, RoundingMode.FLOOR);
|
||||
assertThat(result3, equalTo(2));
|
||||
int result4 = IntMath.log2(5, RoundingMode.CEILING);
|
||||
assertThat(result4, equalTo(3));
|
||||
|
||||
int result5 = IntMath.log10(11, RoundingMode.HALF_UP);
|
||||
assertThat(result5, equalTo(1));
|
||||
|
||||
int result6 = IntMath.sqrt(4, RoundingMode.UNNECESSARY);
|
||||
assertThat(result6, equalTo(2));
|
||||
try {
|
||||
IntMath.sqrt(5, RoundingMode.UNNECESSARY);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntMathAdditionalFunctions() {
|
||||
int result1 = IntMath.gcd(15, 20);
|
||||
assertThat(result1, equalTo(5));
|
||||
|
||||
int result2 = IntMath.mod(8, 3);
|
||||
assertThat(result2, equalTo(2));
|
||||
|
||||
boolean result3 = IntMath.isPowerOfTwo(8);
|
||||
assertTrue(result3);
|
||||
boolean result4 = IntMath.isPowerOfTwo(9);
|
||||
assertFalse(result4);
|
||||
|
||||
int result5 = IntMath.factorial(4);
|
||||
assertThat(result5, equalTo(24));
|
||||
|
||||
int result6 = IntMath.binomial(7, 3);
|
||||
assertThat(result6, equalTo(35));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_detect_integer() {
|
||||
boolean result1 = DoubleMath.isMathematicalInteger(2.0);
|
||||
assertThat(result1, equalTo(true));
|
||||
boolean result2 = DoubleMath.isMathematicalInteger(2.1);
|
||||
assertThat(result2, equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_round_to_integer_types() {
|
||||
int result3 = DoubleMath.roundToInt(2.5, RoundingMode.DOWN);
|
||||
assertThat(result3, equalTo(2));
|
||||
|
||||
long result4 = DoubleMath.roundToLong(2.5, RoundingMode.HALF_UP);
|
||||
assertThat(result4, equalTo(3L));
|
||||
|
||||
BigInteger result5 = DoubleMath.roundToBigInteger(2.5, RoundingMode.UP);
|
||||
assertThat(result5, equalTo(new BigInteger("3")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_calculate_log_2() {
|
||||
int result6 = DoubleMath.log2(10, RoundingMode.UP);
|
||||
assertThat(result6, equalTo(4));
|
||||
}
|
||||
}
|
1
guava21/README.md
Normal file
1
guava21/README.md
Normal file
@ -0,0 +1 @@
|
||||
## Relevant articles:
|
41
guava21/pom.xml
Normal file
41
guava21/pom.xml
Normal file
@ -0,0 +1,41 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung.guava</groupId>
|
||||
<artifactId>tutorial</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<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>
|
||||
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>21.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/junit/junit -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.11</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.util.concurrent.AtomicLongMap;
|
||||
|
||||
public class AtomicLongMapTutorials {
|
||||
|
||||
private AtomicLongMap<String> atomicLongMap;
|
||||
|
||||
public AtomicLongMapTutorials() {
|
||||
atomicLongMap = AtomicLongMap.create();
|
||||
}
|
||||
|
||||
public void addKeys() {
|
||||
atomicLongMap.addAndGet("apple", 250);
|
||||
atomicLongMap.addAndGet("bat", 350);
|
||||
atomicLongMap.addAndGet("cat", 450);
|
||||
atomicLongMap.addAndGet("dog", 550);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
AtomicLongMapTutorials atomicLongMapTutorials = new AtomicLongMapTutorials();
|
||||
atomicLongMapTutorials.addKeys();
|
||||
|
||||
System.out.println(atomicLongMapTutorials.atomicLongMap.get("2"));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.collect.Comparators;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
public class ComparatorsExamples {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 4, 6, 7, 8, 9, 10);
|
||||
boolean isInAscendingOrder = Comparators.isInOrder(integers, new AscedingOrderComparator());
|
||||
System.out.println(isInAscendingOrder);
|
||||
|
||||
}
|
||||
|
||||
private static class AscedingOrderComparator implements Comparator<Integer> {
|
||||
@Override
|
||||
public int compare(Integer o1, Integer o2) {
|
||||
return o1.compareTo(o2);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.collect.Streams;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class ConcatStreams {
|
||||
public static Stream concatStreams(Stream stream1, Stream stream2, Stream stream3) {
|
||||
return Streams.concat(stream1, stream2, stream3);
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.collect.Interner;
|
||||
import com.google.common.collect.Interners;
|
||||
|
||||
public class InternerBuilderExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Interner<Integer> interners = Interners.<Integer> newBuilder()
|
||||
.concurrencyLevel(2)
|
||||
.strong().<Integer> build();
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.util.concurrent.Monitor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class MonitorExample {
|
||||
private List<String> students = new ArrayList<String>();
|
||||
private static final int MAX_SIZE = 100;
|
||||
|
||||
private Monitor monitor = new Monitor();
|
||||
|
||||
public void addToCourse(String item) throws InterruptedException {
|
||||
Monitor.Guard studentsBelowCapacity = monitor.newGuard(this::isStudentsCapacityUptoLimit);
|
||||
monitor.enterWhen(studentsBelowCapacity);
|
||||
try {
|
||||
students.add(item);
|
||||
} finally {
|
||||
monitor.leave();
|
||||
}
|
||||
}
|
||||
|
||||
public Boolean isStudentsCapacityUptoLimit() {
|
||||
return students.size() > MAX_SIZE;
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.collect.MoreCollectors;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public class MoreCollectorsExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Integer> numbers = Arrays.asList(1);
|
||||
Optional<Integer> number = numbers
|
||||
.stream()
|
||||
.map(e -> e * 2)
|
||||
.collect(MoreCollectors.toOptional());
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.guava.tutorial;
|
||||
|
||||
import com.google.common.collect.Streams;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class StreamsUtility {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
|
||||
//Using Collection
|
||||
Stream<Integer> streamFromCollection = Streams.stream(numbers);
|
||||
//Using Iterator
|
||||
Stream<Integer> streamFromIterator = Streams.stream(numbers.iterator());
|
||||
//Using Iterable
|
||||
Stream<Integer> streamFromIterable = Streams.stream((Iterable<Integer>) numbers);
|
||||
//Using Optional
|
||||
Stream<Integer> streamFromOptional = Streams.stream(Optional.of(1));
|
||||
//Using OptionalLong to LongStream
|
||||
LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1));
|
||||
//Using OptionalInt to IntStream
|
||||
IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1));
|
||||
//Using OptionalDouble to DoubleStream
|
||||
DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0));
|
||||
|
||||
Stream<Integer> concatenatedStreams = Streams.concat(streamFromCollection, streamFromIterable, streamFromIterator);
|
||||
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
//This will return 10
|
||||
Optional<Integer> lastItem = Streams.findLast(integers.stream());
|
||||
|
||||
Streams.zip(Stream.of("candy", "chocolate", "bar"), Stream.of("$1", "$2", "$3"), (arg1, arg2) -> arg1 + ":" + arg2);
|
||||
}
|
||||
}
|
54
guava21/src/test/java/AtomicLongMapTests.java
Normal file
54
guava21/src/test/java/AtomicLongMapTests.java
Normal file
@ -0,0 +1,54 @@
|
||||
import com.google.common.util.concurrent.AtomicLongMap;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AtomicLongMapTests {
|
||||
|
||||
private static final String SPRING_COURSE_KEY = "Spring";
|
||||
private static final String HIBERNATE_COURSE_KEY = "hibernate";
|
||||
private static final String GUAVA_COURSE_KEY = "Guava";
|
||||
|
||||
AtomicLongMap<String> courses = AtomicLongMap.create();
|
||||
|
||||
public void setUp() {
|
||||
courses.put(SPRING_COURSE_KEY, 1056);
|
||||
courses.put(HIBERNATE_COURSE_KEY, 259);
|
||||
courses.put(GUAVA_COURSE_KEY, 78);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void accumulateAndGet_withLongBinaryOperator_thenSuccessful() {
|
||||
long noOfStudents = 56;
|
||||
long oldValue = courses.get(SPRING_COURSE_KEY);
|
||||
|
||||
long totalNotesRequired = courses.accumulateAndGet("Guava", noOfStudents, (x, y) -> (x * y));
|
||||
|
||||
assertEquals(totalNotesRequired, oldValue * noOfStudents);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAndAccumulate_withLongBinaryOperator_thenSuccessful() {
|
||||
long noOfStudents = 56;
|
||||
long beforeUpdate = courses.get(SPRING_COURSE_KEY);
|
||||
|
||||
long onUpdate = courses.accumulateAndGet("Guava", noOfStudents, (x, y) -> (x * y));
|
||||
|
||||
long afterUpdate = courses.get(SPRING_COURSE_KEY);
|
||||
|
||||
assertEquals(onUpdate, afterUpdate);
|
||||
assertEquals(afterUpdate, beforeUpdate * noOfStudents);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateAndGet_withLongUnaryOperator_thenSuccessful() {
|
||||
long beforeUpdate = courses.get(SPRING_COURSE_KEY);
|
||||
|
||||
long onUpdate = courses.updateAndGet("Guava", (x) -> (x / 2));
|
||||
|
||||
long afterUpdate = courses.get(SPRING_COURSE_KEY);
|
||||
|
||||
assertEquals(onUpdate, afterUpdate);
|
||||
assertEquals(afterUpdate, beforeUpdate / 2);
|
||||
}
|
||||
}
|
77
guava21/src/test/java/ComparatorsUnitTests.java
Normal file
77
guava21/src/test/java/ComparatorsUnitTests.java
Normal file
@ -0,0 +1,77 @@
|
||||
import com.google.common.collect.Comparators;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.ToDoubleFunction;
|
||||
import java.util.function.ToIntFunction;
|
||||
import java.util.function.ToLongFunction;
|
||||
|
||||
public class ComparatorsUnitTests {
|
||||
|
||||
@Test
|
||||
public void isInOrderTest() {
|
||||
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 4, 6, 7, 8, 9, 10);
|
||||
|
||||
boolean isInAscendingOrder = Comparators.isInOrder(numbers, new AscendingOrderComparator<Number>());
|
||||
|
||||
Assert.assertTrue(isInAscendingOrder);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isInStrictOrderTest() {
|
||||
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 3, 6, 7, 8, 9, 10);
|
||||
|
||||
boolean isInAscendingOrder = Comparators.isInOrder(numbers, new AscendingOrderComparator<Number>());
|
||||
|
||||
Assert.assertFalse(isInAscendingOrder);
|
||||
}
|
||||
|
||||
private class AscendingOrderComparator<I extends Number> implements Comparator<Integer> {
|
||||
|
||||
@Override
|
||||
public int compare(Integer o1, Integer o2) {
|
||||
return o1.compareTo(o2);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Comparator<Integer> reversed() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Comparator<Integer> thenComparing(Comparator<? super Integer> other) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <U> Comparator<Integer> thenComparing(Function<? super Integer, ? extends U> keyExtractor, Comparator<? super U> keyComparator) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <U extends Comparable<? super U>> Comparator<Integer> thenComparing(Function<? super Integer, ? extends U> keyExtractor) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Comparator<Integer> thenComparingInt(ToIntFunction<? super Integer> keyExtractor) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Comparator<Integer> thenComparingLong(ToLongFunction<? super Integer> keyExtractor) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Comparator<Integer> thenComparingDouble(ToDoubleFunction<? super Integer> keyExtractor) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
158
guava21/src/test/java/GauavaStreamsTests.java
Normal file
158
guava21/src/test/java/GauavaStreamsTests.java
Normal file
@ -0,0 +1,158 @@
|
||||
import com.google.common.collect.Streams;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class GauavaStreamsTests {
|
||||
|
||||
List<Integer> numbers;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStreamsWithCollection() {
|
||||
//Deprecated API to create stream from collection
|
||||
Stream streamFromCollection = Streams.stream(numbers);
|
||||
|
||||
//Assert.assertNotNull(streamFromCollection);
|
||||
StreamUtility.assertStreamEquals(streamFromCollection, numbers.stream());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStreamsWithIterable() {
|
||||
Iterable<Integer> numbersIterable = (Iterable<Integer>) numbers;
|
||||
|
||||
Stream streamFromIterable = Streams.stream(numbersIterable);
|
||||
|
||||
Assert.assertNotNull(streamFromIterable);
|
||||
StreamUtility.assertStreamEquals(streamFromIterable, numbers.stream());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStreamsWithIterator() {
|
||||
Iterator<Integer> numbersIterator = numbers.iterator();
|
||||
|
||||
Stream streamFromIterator = Streams.stream(numbersIterator);
|
||||
|
||||
Assert.assertNotNull(streamFromIterator);
|
||||
StreamUtility.assertStreamEquals(streamFromIterator, numbers.stream());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStreamsWithOptional() {
|
||||
|
||||
Stream streamFromOptional = Streams.stream(Optional.of(1));
|
||||
|
||||
Assert.assertNotNull(streamFromOptional);
|
||||
Assert.assertEquals(streamFromOptional.count(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStreamsWithOptionalLong() {
|
||||
|
||||
LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1));
|
||||
|
||||
Assert.assertNotNull(streamFromOptionalLong);
|
||||
Assert.assertEquals(streamFromOptionalLong.count(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStreamsWithOptionalInt() {
|
||||
|
||||
IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1));
|
||||
|
||||
//Assert.assertNotNull(streamFromOptionalInt);
|
||||
Assert.assertEquals(streamFromOptionalInt.count(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStreamsWithOptionalDouble() {
|
||||
|
||||
DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0));
|
||||
|
||||
//Assert.assertNotNull(streamFromOptionalDouble);
|
||||
Assert.assertEquals(streamFromOptionalDouble.count(), 1);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void concatStreamsOfSameType() {
|
||||
Stream oddNumbers = Arrays
|
||||
.asList(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
|
||||
.stream();
|
||||
Stream evenNumbers = Arrays
|
||||
.asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
|
||||
.stream();
|
||||
|
||||
Stream combinedStreams = Streams.concat(oddNumbers, evenNumbers);
|
||||
|
||||
//Assert.assertNotNull(combinedStreams);
|
||||
StreamUtility.assertStreamEquals(combinedStreams, Stream.concat(oddNumbers, evenNumbers));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void concatStreamsOfTypeLongStream() {
|
||||
LongStream firstTwenty = LongStream.range(1, 20);
|
||||
LongStream nextTwenty = LongStream.range(21, 40);
|
||||
|
||||
LongStream combinedStreams = Streams.concat(firstTwenty, nextTwenty);
|
||||
|
||||
Assert.assertNotNull(combinedStreams);
|
||||
StreamUtility.assertStreamEquals(combinedStreams, LongStream.concat(firstTwenty, nextTwenty));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void concatStreamsOfTypeIntStream() {
|
||||
IntStream firstTwenty = IntStream.range(1, 20);
|
||||
IntStream nextTwenty = IntStream.range(21, 40);
|
||||
|
||||
IntStream combinedStreams = Streams.concat(firstTwenty, nextTwenty);
|
||||
|
||||
Assert.assertNotNull(combinedStreams);
|
||||
StreamUtility.assertStreamEquals(combinedStreams, IntStream.concat(firstTwenty, nextTwenty));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findLastOfStream() {
|
||||
Optional<Integer> lastElement = Streams.findLast(numbers.stream());
|
||||
|
||||
Assert.assertNotNull(lastElement.get());
|
||||
Assert.assertEquals(lastElement.get(), numbers.get(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mapWithIndexTest() {
|
||||
Stream stringSream = Stream.of("a", "b", "c");
|
||||
|
||||
Stream<String> mappedStream = Streams.mapWithIndex(stringSream, (str, index) -> str + ":" + index);
|
||||
|
||||
//Assert.assertNotNull(mappedStream);
|
||||
Assert.assertEquals(mappedStream
|
||||
.findFirst()
|
||||
.get(), "a:0");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void streamsZipTest() {
|
||||
Stream stringSream = Stream.of("a", "b", "c");
|
||||
Stream intStream = Stream.of(1, 2, 3);
|
||||
Stream<String> mappedStream = Streams.zip(stringSream, intStream, (str, index) -> str + ":" + index);
|
||||
|
||||
//Assert.assertNotNull(mappedStream);
|
||||
Assert.assertEquals(mappedStream
|
||||
.findFirst()
|
||||
.get(), "a:1");
|
||||
|
||||
}
|
||||
|
||||
}
|
18
guava21/src/test/java/InternBuilderUnitTests.java
Normal file
18
guava21/src/test/java/InternBuilderUnitTests.java
Normal file
@ -0,0 +1,18 @@
|
||||
import com.google.common.collect.Interner;
|
||||
import com.google.common.collect.Interners;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class InternBuilderUnitTests {
|
||||
|
||||
@Test
|
||||
public void interBuilderTest() {
|
||||
|
||||
Interner<Integer> interners = Interners.<Integer> newBuilder()
|
||||
.concurrencyLevel(2)
|
||||
.strong().<Integer> build();
|
||||
|
||||
Assert.assertNotNull(interners);
|
||||
}
|
||||
|
||||
}
|
53
guava21/src/test/java/MonitorUnitTests.java
Normal file
53
guava21/src/test/java/MonitorUnitTests.java
Normal file
@ -0,0 +1,53 @@
|
||||
import com.google.common.util.concurrent.Monitor;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class MonitorUnitTests {
|
||||
|
||||
@Test
|
||||
public void whenGaurdConditionIsTrue_IsSuccessful() {
|
||||
Monitor monitor = new Monitor();
|
||||
boolean enteredInCriticalSection = false;
|
||||
|
||||
Monitor.Guard gaurdCondition = monitor.newGuard(this::returnTrue);
|
||||
|
||||
if (monitor.enterIf(gaurdCondition)) {
|
||||
try {
|
||||
System.out.println("Entered in critical section");
|
||||
enteredInCriticalSection = true;
|
||||
} finally {
|
||||
monitor.leave();
|
||||
}
|
||||
}
|
||||
|
||||
Assert.assertTrue(enteredInCriticalSection);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGaurdConditionIsFalse_IsSuccessful() {
|
||||
Monitor monitor = new Monitor();
|
||||
boolean enteredInCriticalSection = false;
|
||||
|
||||
Monitor.Guard gaurdCondition = monitor.newGuard(this::returnFalse);
|
||||
|
||||
if (monitor.enterIf(gaurdCondition)) {
|
||||
try {
|
||||
System.out.println("Entered in critical section");
|
||||
enteredInCriticalSection = true;
|
||||
} finally {
|
||||
monitor.leave();
|
||||
}
|
||||
}
|
||||
|
||||
Assert.assertFalse(enteredInCriticalSection);
|
||||
}
|
||||
|
||||
private boolean returnTrue() {
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean returnFalse() {
|
||||
return false;
|
||||
}
|
||||
}
|
36
guava21/src/test/java/MoreCollectorsUnitTests.java
Normal file
36
guava21/src/test/java/MoreCollectorsUnitTests.java
Normal file
@ -0,0 +1,36 @@
|
||||
import com.google.common.collect.MoreCollectors;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public class MoreCollectorsUnitTests {
|
||||
|
||||
@Test
|
||||
public void toOptionalTest() {
|
||||
|
||||
List<Integer> numbers = Arrays.asList(1);
|
||||
|
||||
Optional<Integer> number = numbers
|
||||
.stream()
|
||||
.map(e -> e * 2)
|
||||
.collect(MoreCollectors.toOptional());
|
||||
|
||||
Assert.assertEquals(number.get(), new Integer(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void onlyElementTest() {
|
||||
List<Integer> numbers = Arrays.asList(1);
|
||||
|
||||
Integer number = numbers
|
||||
.stream()
|
||||
.map(e -> e * 2)
|
||||
.collect(MoreCollectors.onlyElement());
|
||||
|
||||
Assert.assertEquals(number, new Integer(2));
|
||||
}
|
||||
|
||||
}
|
66
guava21/src/test/java/StreamUtility.java
Normal file
66
guava21/src/test/java/StreamUtility.java
Normal file
@ -0,0 +1,66 @@
|
||||
import org.junit.Assert;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class StreamUtility {
|
||||
|
||||
public static <T> boolean assertStreamEquals(Stream<T> stream1, Stream<T> stream2) {
|
||||
|
||||
Iterator<T> iterator1 = stream1.iterator();
|
||||
Iterator<T> iterator2 = stream2.iterator();
|
||||
|
||||
while (iterator1.hasNext()) {
|
||||
Assert.assertEquals(iterator1.next(), iterator2.next());
|
||||
}
|
||||
|
||||
Assert.assertFalse(iterator2.hasNext());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean assertStreamEquals(LongStream stream1, LongStream stream2) {
|
||||
|
||||
Iterator iterator1 = stream1.iterator();
|
||||
Iterator iterator2 = stream2.iterator();
|
||||
|
||||
while (iterator1.hasNext()) {
|
||||
Assert.assertEquals(iterator1.next(), iterator2.next());
|
||||
}
|
||||
|
||||
Assert.assertFalse(iterator2.hasNext());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean assertStreamEquals(DoubleStream stream1, DoubleStream stream2) {
|
||||
|
||||
Iterator iterator1 = stream1.iterator();
|
||||
Iterator iterator2 = stream2.iterator();
|
||||
|
||||
while (iterator1.hasNext()) {
|
||||
Assert.assertEquals(iterator1.next(), iterator2.next());
|
||||
}
|
||||
|
||||
Assert.assertFalse(iterator2.hasNext());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean assertStreamEquals(IntStream stream1, IntStream stream2) {
|
||||
|
||||
Iterator iterator1 = stream1.iterator();
|
||||
Iterator iterator2 = stream2.iterator();
|
||||
|
||||
while (iterator1.hasNext()) {
|
||||
Assert.assertEquals(iterator1.next(), iterator2.next());
|
||||
}
|
||||
|
||||
Assert.assertFalse(iterator2.hasNext());
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
4
guice/README.md
Normal file
4
guice/README.md
Normal file
@ -0,0 +1,4 @@
|
||||
## Google Guice Tutorials Project
|
||||
|
||||
### Relevant Articles
|
||||
- [Guide to Google Guice](http://www.baeldung.com/guice)
|
@ -1,32 +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);
|
||||
while (true) {
|
||||
String input = scanner.nextLine();
|
||||
if (input.equalsIgnoreCase("q")) {
|
||||
System.exit(0);
|
||||
} 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -1,40 +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;
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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);
|
||||
|
||||
}
|
||||
|
@ -1,51 +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;
|
||||
|
||||
/**
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,24 +1,24 @@
|
||||
|
||||
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.
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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.
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user