Merge branch 'master' into master
This commit is contained in:
commit
81502c54b5
8
.gitignore
vendored
8
.gitignore
vendored
@ -33,3 +33,11 @@ spring-openid/src/main/resources/application.properties
|
|||||||
spring-security-openid/src/main/resources/application.properties
|
spring-security-openid/src/main/resources/application.properties
|
||||||
|
|
||||||
spring-all/*.log
|
spring-all/*.log
|
||||||
|
|
||||||
|
*.jar
|
||||||
|
|
||||||
|
SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties
|
||||||
|
|
||||||
|
spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
|
||||||
|
|
||||||
|
spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties
|
||||||
|
3
akka-streams/README.md
Normal file
3
akka-streams/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
### Relevant articles
|
||||||
|
|
||||||
|
- [Guide to Akka Streams](http://www.baeldung.com/akka-streams)
|
30
akka-streams/pom.xml
Normal file
30
akka-streams/pom.xml
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>akka-streams</artifactId>
|
||||||
|
<name>akka-streams</name>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.typesafe.akka</groupId>
|
||||||
|
<artifactId>akka-stream_2.11</artifactId>
|
||||||
|
<version>${akkastreams.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.typesafe.akka</groupId>
|
||||||
|
<artifactId>akka-stream-testkit_2.11</artifactId>
|
||||||
|
<version>${akkastreams.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<properties>
|
||||||
|
<akkastreams.version>2.5.2</akkastreams.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.akkastreams;
|
||||||
|
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.CompletionStage;
|
||||||
|
|
||||||
|
public class AverageRepository {
|
||||||
|
CompletionStage<Double> save(Double average) {
|
||||||
|
return CompletableFuture.supplyAsync(() -> {
|
||||||
|
System.out.println("saving average: " + average);
|
||||||
|
return average;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,74 @@
|
|||||||
|
package com.baeldung.akkastreams;
|
||||||
|
|
||||||
|
|
||||||
|
import akka.Done;
|
||||||
|
import akka.NotUsed;
|
||||||
|
import akka.actor.ActorSystem;
|
||||||
|
import akka.stream.ActorMaterializer;
|
||||||
|
import akka.stream.javadsl.Flow;
|
||||||
|
import akka.stream.javadsl.Keep;
|
||||||
|
import akka.stream.javadsl.Sink;
|
||||||
|
import akka.stream.javadsl.Source;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.CompletionStage;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
public class DataImporter {
|
||||||
|
private final ActorSystem actorSystem;
|
||||||
|
private final AverageRepository averageRepository = new AverageRepository();
|
||||||
|
|
||||||
|
public DataImporter(ActorSystem actorSystem) {
|
||||||
|
this.actorSystem = actorSystem;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Integer> parseLine(String line) {
|
||||||
|
String[] fields = line.split(";");
|
||||||
|
return Arrays.stream(fields)
|
||||||
|
.map(Integer::parseInt)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Flow<String, Integer, NotUsed> parseContent() {
|
||||||
|
return Flow.of(String.class).mapConcat(this::parseLine);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Flow<Integer, Double, NotUsed> computeAverage() {
|
||||||
|
return Flow.of(Integer.class).grouped(2).mapAsyncUnordered(8, integers ->
|
||||||
|
CompletableFuture.supplyAsync(() -> integers
|
||||||
|
.stream()
|
||||||
|
.mapToDouble(v -> v)
|
||||||
|
.average()
|
||||||
|
.orElse(-1.0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
Flow<String, Double, NotUsed> calculateAverage() {
|
||||||
|
return Flow.of(String.class)
|
||||||
|
.via(parseContent())
|
||||||
|
.via(computeAverage());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Sink<Double, CompletionStage<Done>> storeAverages() {
|
||||||
|
return Flow.of(Double.class)
|
||||||
|
.mapAsyncUnordered(4, averageRepository::save)
|
||||||
|
.toMat(Sink.ignore(), Keep.right());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
CompletionStage<Done> calculateAverageForContent(String content) {
|
||||||
|
return Source.single(content)
|
||||||
|
.via(calculateAverage())
|
||||||
|
.runWith(storeAverages(), ActorMaterializer.create(actorSystem))
|
||||||
|
.whenComplete((d, e) -> {
|
||||||
|
if (d != null) {
|
||||||
|
System.out.println("Import finished ");
|
||||||
|
} else {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.akkastreams;
|
||||||
|
|
||||||
|
import akka.NotUsed;
|
||||||
|
import akka.actor.ActorSystem;
|
||||||
|
import akka.stream.ActorMaterializer;
|
||||||
|
import akka.stream.javadsl.Flow;
|
||||||
|
import akka.stream.javadsl.Source;
|
||||||
|
import akka.stream.testkit.javadsl.TestSink;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
|
||||||
|
public class DataImporterUnitTest {
|
||||||
|
private final ActorSystem actorSystem = ActorSystem.create();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStreamOfIntegers_whenCalculateAverageOfPairs_thenShouldReturnProperResults() {
|
||||||
|
//given
|
||||||
|
Flow<String, Double, NotUsed> tested = new DataImporter(actorSystem).calculateAverage();
|
||||||
|
String input = "1;9;11;0";
|
||||||
|
|
||||||
|
//when
|
||||||
|
Source<Double, NotUsed> flow = Source.single(input).via(tested);
|
||||||
|
|
||||||
|
//then
|
||||||
|
flow
|
||||||
|
.runWith(TestSink.probe(actorSystem), ActorMaterializer.create(actorSystem))
|
||||||
|
.request(4)
|
||||||
|
.expectNextUnordered(5d, 5.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStreamOfIntegers_whenCalculateAverageAndSaveToSink_thenShouldFinishSuccessfully() {
|
||||||
|
//given
|
||||||
|
DataImporter dataImporter = new DataImporter(actorSystem);
|
||||||
|
String input = "10;90;110;10";
|
||||||
|
|
||||||
|
//when
|
||||||
|
dataImporter.calculateAverageForContent(input)
|
||||||
|
.thenAccept(d -> actorSystem.terminate());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Finite state machine.
|
* Finite state machine.
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Default implementation of a finite state machine.
|
* Default implementation of a finite state machine.
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* State. Part of a finite state machine.
|
* State. Part of a finite state machine.
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.automata;
|
package com.baeldung.algorithms.automata;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Transition in a finite State machine.
|
* Transition in a finite State machine.
|
@ -0,0 +1,189 @@
|
|||||||
|
package com.baeldung.algorithms.hillclimbing;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Stack;
|
||||||
|
|
||||||
|
public class HillClimbing {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
HillClimbing hillClimbing = new HillClimbing();
|
||||||
|
String blockArr[] = { "B", "C", "D", "A" };
|
||||||
|
Stack<String> startState = hillClimbing.getStackWithValues(blockArr);
|
||||||
|
String goalBlockArr[] = { "A", "B", "C", "D" };
|
||||||
|
Stack<String> goalState = hillClimbing.getStackWithValues(goalBlockArr);
|
||||||
|
try {
|
||||||
|
List<State> solutionSequence = hillClimbing.getRouteWithHillClimbing(startState, goalState);
|
||||||
|
solutionSequence.forEach(HillClimbing::printEachStep);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void printEachStep(State state) {
|
||||||
|
List<Stack<String>> stackList = state.getState();
|
||||||
|
System.out.println("----------------");
|
||||||
|
stackList.forEach(stack -> {
|
||||||
|
while (!stack.isEmpty()) {
|
||||||
|
System.out.println(stack.pop());
|
||||||
|
}
|
||||||
|
System.out.println(" ");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Stack<String> getStackWithValues(String[] blocks) {
|
||||||
|
Stack<String> stack = new Stack<>();
|
||||||
|
for (String block : blocks)
|
||||||
|
stack.push(block);
|
||||||
|
return stack;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method prepares path from init state to goal state
|
||||||
|
*/
|
||||||
|
public List<State> getRouteWithHillClimbing(Stack<String> initStateStack, Stack<String> goalStateStack) throws Exception {
|
||||||
|
List<Stack<String>> initStateStackList = new ArrayList<>();
|
||||||
|
initStateStackList.add(initStateStack);
|
||||||
|
int initStateHeuristics = getHeuristicsValue(initStateStackList, goalStateStack);
|
||||||
|
State initState = new State(initStateStackList, initStateHeuristics);
|
||||||
|
|
||||||
|
List<State> resultPath = new ArrayList<>();
|
||||||
|
resultPath.add(new State(initState));
|
||||||
|
|
||||||
|
State currentState = initState;
|
||||||
|
boolean noStateFound = false;
|
||||||
|
while (!currentState.getState()
|
||||||
|
.get(0)
|
||||||
|
.equals(goalStateStack) || noStateFound) {
|
||||||
|
noStateFound = true;
|
||||||
|
State nextState = findNextState(currentState, goalStateStack);
|
||||||
|
if (nextState != null) {
|
||||||
|
noStateFound = false;
|
||||||
|
currentState = nextState;
|
||||||
|
resultPath.add(new State(nextState));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return resultPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method finds new state from current state based on goal and
|
||||||
|
* heuristics
|
||||||
|
*/
|
||||||
|
public State findNextState(State currentState, Stack<String> goalStateStack) {
|
||||||
|
List<Stack<String>> listOfStacks = currentState.getState();
|
||||||
|
int currentStateHeuristics = currentState.getHeuristics();
|
||||||
|
|
||||||
|
return listOfStacks.stream()
|
||||||
|
.map(stack -> {
|
||||||
|
return applyOperationsOnState(listOfStacks, stack, currentStateHeuristics, goalStateStack);
|
||||||
|
})
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method applies operations on the current state to get a new state
|
||||||
|
*/
|
||||||
|
public State applyOperationsOnState(List<Stack<String>> listOfStacks, Stack<String> stack, int currentStateHeuristics, Stack<String> goalStateStack) {
|
||||||
|
State tempState;
|
||||||
|
List<Stack<String>> tempStackList = new ArrayList<>(listOfStacks);
|
||||||
|
String block = stack.pop();
|
||||||
|
if (stack.size() == 0)
|
||||||
|
tempStackList.remove(stack);
|
||||||
|
tempState = pushElementToNewStack(tempStackList, block, currentStateHeuristics, goalStateStack);
|
||||||
|
if (tempState == null) {
|
||||||
|
tempState = pushElementToExistingStacks(stack, tempStackList, block, currentStateHeuristics, goalStateStack);
|
||||||
|
}
|
||||||
|
if (tempState == null)
|
||||||
|
stack.push(block);
|
||||||
|
return tempState;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Operation to be applied on a state in order to find new states. This
|
||||||
|
* operation pushes an element into a new stack
|
||||||
|
*/
|
||||||
|
private State pushElementToNewStack(List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
|
||||||
|
State newState = null;
|
||||||
|
Stack<String> newStack = new Stack<>();
|
||||||
|
newStack.push(block);
|
||||||
|
|
||||||
|
currentStackList.add(newStack);
|
||||||
|
int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
|
||||||
|
if (newStateHeuristics > currentStateHeuristics) {
|
||||||
|
newState = new State(currentStackList, newStateHeuristics);
|
||||||
|
} else {
|
||||||
|
currentStackList.remove(newStack);
|
||||||
|
}
|
||||||
|
return newState;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Operation to be applied on a state in order to find new states. This
|
||||||
|
* operation pushes an element into one of the other stacks to explore new
|
||||||
|
* states
|
||||||
|
*/
|
||||||
|
private State pushElementToExistingStacks(Stack currentStack, List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
|
||||||
|
|
||||||
|
Optional<State> newState = currentStackList.stream()
|
||||||
|
.filter(stack -> stack != currentStack)
|
||||||
|
.map(stack -> {
|
||||||
|
return pushElementToStack(stack, block, currentStackList, currentStateHeuristics, goalStateStack);
|
||||||
|
})
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.findFirst();
|
||||||
|
|
||||||
|
return newState.orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method pushes a block to the stack and returns new state if its closer to goal
|
||||||
|
*/
|
||||||
|
private State pushElementToStack(Stack stack, String block, List<Stack<String>> currentStackList, int currentStateHeuristics, Stack<String> goalStateStack) {
|
||||||
|
stack.push(block);
|
||||||
|
int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
|
||||||
|
if (newStateHeuristics > currentStateHeuristics) {
|
||||||
|
return new State(currentStackList, newStateHeuristics);
|
||||||
|
}
|
||||||
|
stack.pop();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method returns heuristics value for given state with respect to goal
|
||||||
|
* state
|
||||||
|
*/
|
||||||
|
public int getHeuristicsValue(List<Stack<String>> currentState, Stack<String> goalStateStack) {
|
||||||
|
Integer heuristicValue;
|
||||||
|
heuristicValue = currentState.stream()
|
||||||
|
.mapToInt(stack -> {
|
||||||
|
return getHeuristicsValueForStack(stack, currentState, goalStateStack);
|
||||||
|
})
|
||||||
|
.sum();
|
||||||
|
return heuristicValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method returns heuristics value for a particular stack
|
||||||
|
*/
|
||||||
|
public int getHeuristicsValueForStack(Stack<String> stack, List<Stack<String>> currentState, Stack<String> goalStateStack) {
|
||||||
|
int stackHeuristics = 0;
|
||||||
|
boolean isPositioneCorrect = true;
|
||||||
|
int goalStartIndex = 0;
|
||||||
|
for (String currentBlock : stack) {
|
||||||
|
if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) {
|
||||||
|
stackHeuristics += goalStartIndex;
|
||||||
|
} else {
|
||||||
|
stackHeuristics -= goalStartIndex;
|
||||||
|
isPositioneCorrect = false;
|
||||||
|
}
|
||||||
|
goalStartIndex++;
|
||||||
|
}
|
||||||
|
return stackHeuristics;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.algorithms.hillclimbing;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Stack;
|
||||||
|
|
||||||
|
public class State {
|
||||||
|
private List<Stack<String>> state;
|
||||||
|
private int heuristics;
|
||||||
|
|
||||||
|
public State(List<Stack<String>> state) {
|
||||||
|
this.state = state;
|
||||||
|
}
|
||||||
|
|
||||||
|
State(List<Stack<String>> state, int heuristics) {
|
||||||
|
this.state = state;
|
||||||
|
this.heuristics = heuristics;
|
||||||
|
}
|
||||||
|
|
||||||
|
State(State state) {
|
||||||
|
if (state != null) {
|
||||||
|
this.state = new ArrayList<>();
|
||||||
|
for (Stack s : state.getState()) {
|
||||||
|
Stack s1;
|
||||||
|
s1 = (Stack) s.clone();
|
||||||
|
this.state.add(s1);
|
||||||
|
}
|
||||||
|
this.heuristics = state.getHeuristics();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Stack<String>> getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getHeuristics() {
|
||||||
|
return heuristics;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setHeuristics(int heuristics) {
|
||||||
|
this.heuristics = heuristics;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,109 @@
|
|||||||
|
package com.baeldung.algorithms.mcts.montecarlo;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.mcts.tictactoe.Board;
|
||||||
|
import com.baeldung.algorithms.mcts.tree.Node;
|
||||||
|
import com.baeldung.algorithms.mcts.tree.Tree;
|
||||||
|
|
||||||
|
public class MonteCarloTreeSearch {
|
||||||
|
|
||||||
|
private static final int WIN_SCORE = 10;
|
||||||
|
private int level;
|
||||||
|
private int oponent;
|
||||||
|
|
||||||
|
public MonteCarloTreeSearch() {
|
||||||
|
this.level = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getLevel() {
|
||||||
|
return level;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLevel(int level) {
|
||||||
|
this.level = level;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getMillisForCurrentLevel() {
|
||||||
|
return 2 * (this.level - 1) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Board findNextMove(Board board, int playerNo) {
|
||||||
|
long start = System.currentTimeMillis();
|
||||||
|
long end = start + 60 * getMillisForCurrentLevel();
|
||||||
|
|
||||||
|
oponent = 3 - playerNo;
|
||||||
|
Tree tree = new Tree();
|
||||||
|
Node rootNode = tree.getRoot();
|
||||||
|
rootNode.getState().setBoard(board);
|
||||||
|
rootNode.getState().setPlayerNo(oponent);
|
||||||
|
|
||||||
|
while (System.currentTimeMillis() < end) {
|
||||||
|
// Phase 1 - Selection
|
||||||
|
Node promisingNode = selectPromisingNode(rootNode);
|
||||||
|
// Phase 2 - Expansion
|
||||||
|
if (promisingNode.getState().getBoard().checkStatus() == Board.IN_PROGRESS)
|
||||||
|
expandNode(promisingNode);
|
||||||
|
|
||||||
|
// Phase 3 - Simulation
|
||||||
|
Node nodeToExplore = promisingNode;
|
||||||
|
if (promisingNode.getChildArray().size() > 0) {
|
||||||
|
nodeToExplore = promisingNode.getRandomChildNode();
|
||||||
|
}
|
||||||
|
int playoutResult = simulateRandomPlayout(nodeToExplore);
|
||||||
|
// Phase 4 - Update
|
||||||
|
backPropogation(nodeToExplore, playoutResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
Node winnerNode = rootNode.getChildWithMaxScore();
|
||||||
|
tree.setRoot(winnerNode);
|
||||||
|
return winnerNode.getState().getBoard();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Node selectPromisingNode(Node rootNode) {
|
||||||
|
Node node = rootNode;
|
||||||
|
while (node.getChildArray().size() != 0) {
|
||||||
|
node = UCT.findBestNodeWithUCT(node);
|
||||||
|
}
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void expandNode(Node node) {
|
||||||
|
List<State> possibleStates = node.getState().getAllPossibleStates();
|
||||||
|
possibleStates.forEach(state -> {
|
||||||
|
Node newNode = new Node(state);
|
||||||
|
newNode.setParent(node);
|
||||||
|
newNode.getState().setPlayerNo(node.getState().getOpponent());
|
||||||
|
node.getChildArray().add(newNode);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void backPropogation(Node nodeToExplore, int playerNo) {
|
||||||
|
Node tempNode = nodeToExplore;
|
||||||
|
while (tempNode != null) {
|
||||||
|
tempNode.getState().incrementVisit();
|
||||||
|
if (tempNode.getState().getPlayerNo() == playerNo)
|
||||||
|
tempNode.getState().addScore(WIN_SCORE);
|
||||||
|
tempNode = tempNode.getParent();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int simulateRandomPlayout(Node node) {
|
||||||
|
Node tempNode = new Node(node);
|
||||||
|
State tempState = tempNode.getState();
|
||||||
|
int boardStatus = tempState.getBoard().checkStatus();
|
||||||
|
|
||||||
|
if (boardStatus == oponent) {
|
||||||
|
tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE);
|
||||||
|
return boardStatus;
|
||||||
|
}
|
||||||
|
while (boardStatus == Board.IN_PROGRESS) {
|
||||||
|
tempState.togglePlayer();
|
||||||
|
tempState.randomPlay();
|
||||||
|
boardStatus = tempState.getBoard().checkStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
return boardStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,97 @@
|
|||||||
|
package com.baeldung.algorithms.mcts.montecarlo;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.mcts.tictactoe.Board;
|
||||||
|
import com.baeldung.algorithms.mcts.tictactoe.Position;
|
||||||
|
|
||||||
|
public class State {
|
||||||
|
private Board board;
|
||||||
|
private int playerNo;
|
||||||
|
private int visitCount;
|
||||||
|
private double winScore;
|
||||||
|
|
||||||
|
public State() {
|
||||||
|
board = new Board();
|
||||||
|
}
|
||||||
|
|
||||||
|
public State(State state) {
|
||||||
|
this.board = new Board(state.getBoard());
|
||||||
|
this.playerNo = state.getPlayerNo();
|
||||||
|
this.visitCount = state.getVisitCount();
|
||||||
|
this.winScore = state.getWinScore();
|
||||||
|
}
|
||||||
|
|
||||||
|
public State(Board board) {
|
||||||
|
this.board = new Board(board);
|
||||||
|
}
|
||||||
|
|
||||||
|
Board getBoard() {
|
||||||
|
return board;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setBoard(Board board) {
|
||||||
|
this.board = board;
|
||||||
|
}
|
||||||
|
|
||||||
|
int getPlayerNo() {
|
||||||
|
return playerNo;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setPlayerNo(int playerNo) {
|
||||||
|
this.playerNo = playerNo;
|
||||||
|
}
|
||||||
|
|
||||||
|
int getOpponent() {
|
||||||
|
return 3 - playerNo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getVisitCount() {
|
||||||
|
return visitCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setVisitCount(int visitCount) {
|
||||||
|
this.visitCount = visitCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
double getWinScore() {
|
||||||
|
return winScore;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setWinScore(double winScore) {
|
||||||
|
this.winScore = winScore;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<State> getAllPossibleStates() {
|
||||||
|
List<State> possibleStates = new ArrayList<>();
|
||||||
|
List<Position> availablePositions = this.board.getEmptyPositions();
|
||||||
|
availablePositions.forEach(p -> {
|
||||||
|
State newState = new State(this.board);
|
||||||
|
newState.setPlayerNo(3 - this.playerNo);
|
||||||
|
newState.getBoard().performMove(newState.getPlayerNo(), p);
|
||||||
|
possibleStates.add(newState);
|
||||||
|
});
|
||||||
|
return possibleStates;
|
||||||
|
}
|
||||||
|
|
||||||
|
void incrementVisit() {
|
||||||
|
this.visitCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void addScore(double score) {
|
||||||
|
if (this.winScore != Integer.MIN_VALUE)
|
||||||
|
this.winScore += score;
|
||||||
|
}
|
||||||
|
|
||||||
|
void randomPlay() {
|
||||||
|
List<Position> availablePositions = this.board.getEmptyPositions();
|
||||||
|
int totalPossibilities = availablePositions.size();
|
||||||
|
int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1));
|
||||||
|
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
|
||||||
|
}
|
||||||
|
|
||||||
|
void togglePlayer() {
|
||||||
|
this.playerNo = 3 - this.playerNo;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.algorithms.mcts.montecarlo;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.mcts.tree.Node;
|
||||||
|
|
||||||
|
public class UCT {
|
||||||
|
|
||||||
|
public static double uctValue(int totalVisit, double nodeWinScore, int nodeVisit) {
|
||||||
|
if (nodeVisit == 0) {
|
||||||
|
return Integer.MAX_VALUE;
|
||||||
|
}
|
||||||
|
return (nodeWinScore / (double) nodeVisit) + 1.41 * Math.sqrt(Math.log(totalVisit) / (double) nodeVisit);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Node findBestNodeWithUCT(Node node) {
|
||||||
|
int parentVisit = node.getState().getVisitCount();
|
||||||
|
return Collections.max(
|
||||||
|
node.getChildArray(),
|
||||||
|
Comparator.comparing(c -> uctValue(parentVisit, c.getState().getWinScore(), c.getState().getVisitCount())));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,155 @@
|
|||||||
|
package com.baeldung.algorithms.mcts.tictactoe;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Board {
|
||||||
|
int[][] boardValues;
|
||||||
|
int totalMoves;
|
||||||
|
|
||||||
|
public static final int DEFAULT_BOARD_SIZE = 3;
|
||||||
|
|
||||||
|
public static final int IN_PROGRESS = -1;
|
||||||
|
public static final int DRAW = 0;
|
||||||
|
public static final int P1 = 1;
|
||||||
|
public static final int P2 = 2;
|
||||||
|
|
||||||
|
public Board() {
|
||||||
|
boardValues = new int[DEFAULT_BOARD_SIZE][DEFAULT_BOARD_SIZE];
|
||||||
|
}
|
||||||
|
|
||||||
|
public Board(int boardSize) {
|
||||||
|
boardValues = new int[boardSize][boardSize];
|
||||||
|
}
|
||||||
|
|
||||||
|
public Board(int[][] boardValues) {
|
||||||
|
this.boardValues = boardValues;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Board(int[][] boardValues, int totalMoves) {
|
||||||
|
this.boardValues = boardValues;
|
||||||
|
this.totalMoves = totalMoves;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Board(Board board) {
|
||||||
|
int boardLength = board.getBoardValues().length;
|
||||||
|
this.boardValues = new int[boardLength][boardLength];
|
||||||
|
int[][] boardValues = board.getBoardValues();
|
||||||
|
int n = boardValues.length;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
int m = boardValues[i].length;
|
||||||
|
for (int j = 0; j < m; j++) {
|
||||||
|
this.boardValues[i][j] = boardValues[i][j];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void performMove(int player, Position p) {
|
||||||
|
this.totalMoves++;
|
||||||
|
boardValues[p.getX()][p.getY()] = player;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[][] getBoardValues() {
|
||||||
|
return boardValues;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBoardValues(int[][] boardValues) {
|
||||||
|
this.boardValues = boardValues;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int checkStatus() {
|
||||||
|
int boardSize = boardValues.length;
|
||||||
|
int maxIndex = boardSize - 1;
|
||||||
|
int[] diag1 = new int[boardSize];
|
||||||
|
int[] diag2 = new int[boardSize];
|
||||||
|
|
||||||
|
for (int i = 0; i < boardSize; i++) {
|
||||||
|
int[] row = boardValues[i];
|
||||||
|
int[] col = new int[boardSize];
|
||||||
|
for (int j = 0; j < boardSize; j++) {
|
||||||
|
col[j] = boardValues[j][i];
|
||||||
|
}
|
||||||
|
|
||||||
|
int checkRowForWin = checkForWin(row);
|
||||||
|
if(checkRowForWin!=0)
|
||||||
|
return checkRowForWin;
|
||||||
|
|
||||||
|
int checkColForWin = checkForWin(col);
|
||||||
|
if(checkColForWin!=0)
|
||||||
|
return checkColForWin;
|
||||||
|
|
||||||
|
diag1[i] = boardValues[i][i];
|
||||||
|
diag2[i] = boardValues[maxIndex - i][i];
|
||||||
|
}
|
||||||
|
|
||||||
|
int checkDia1gForWin = checkForWin(diag1);
|
||||||
|
if(checkDia1gForWin!=0)
|
||||||
|
return checkDia1gForWin;
|
||||||
|
|
||||||
|
int checkDiag2ForWin = checkForWin(diag2);
|
||||||
|
if(checkDiag2ForWin!=0)
|
||||||
|
return checkDiag2ForWin;
|
||||||
|
|
||||||
|
if (getEmptyPositions().size() > 0)
|
||||||
|
return IN_PROGRESS;
|
||||||
|
else
|
||||||
|
return DRAW;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int checkForWin(int[] row) {
|
||||||
|
boolean isEqual = true;
|
||||||
|
int size = row.length;
|
||||||
|
int previous = row[0];
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
if (previous != row[i]) {
|
||||||
|
isEqual = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
previous = row[i];
|
||||||
|
}
|
||||||
|
if(isEqual)
|
||||||
|
return previous;
|
||||||
|
else
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void printBoard() {
|
||||||
|
int size = this.boardValues.length;
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
for (int j = 0; j < size; j++) {
|
||||||
|
System.out.print(boardValues[i][j] + " ");
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Position> getEmptyPositions() {
|
||||||
|
int size = this.boardValues.length;
|
||||||
|
List<Position> emptyPositions = new ArrayList<>();
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
for (int j = 0; j < size; j++) {
|
||||||
|
if (boardValues[i][j] == 0)
|
||||||
|
emptyPositions.add(new Position(i, j));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return emptyPositions;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void printStatus() {
|
||||||
|
switch (this.checkStatus()) {
|
||||||
|
case P1:
|
||||||
|
System.out.println("Player 1 wins");
|
||||||
|
break;
|
||||||
|
case P2:
|
||||||
|
System.out.println("Player 2 wins");
|
||||||
|
break;
|
||||||
|
case DRAW:
|
||||||
|
System.out.println("Game Draw");
|
||||||
|
break;
|
||||||
|
case IN_PROGRESS:
|
||||||
|
System.out.println("Game In rogress");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.algorithms.mcts.tictactoe;
|
||||||
|
|
||||||
|
public class Position {
|
||||||
|
int x;
|
||||||
|
int y;
|
||||||
|
|
||||||
|
public Position() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Position(int x, int y) {
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getX() {
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setX(int x) {
|
||||||
|
this.x = x;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getY() {
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setY(int y) {
|
||||||
|
this.y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,78 @@
|
|||||||
|
package com.baeldung.algorithms.mcts.tree;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.mcts.montecarlo.State;
|
||||||
|
|
||||||
|
public class Node {
|
||||||
|
State state;
|
||||||
|
Node parent;
|
||||||
|
List<Node> childArray;
|
||||||
|
|
||||||
|
public Node() {
|
||||||
|
this.state = new State();
|
||||||
|
childArray = new ArrayList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node(State state) {
|
||||||
|
this.state = state;
|
||||||
|
childArray = new ArrayList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node(State state, Node parent, List<Node> childArray) {
|
||||||
|
this.state = state;
|
||||||
|
this.parent = parent;
|
||||||
|
this.childArray = childArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node(Node node) {
|
||||||
|
this.childArray = new ArrayList<>();
|
||||||
|
this.state = new State(node.getState());
|
||||||
|
if (node.getParent() != null)
|
||||||
|
this.parent = node.getParent();
|
||||||
|
List<Node> childArray = node.getChildArray();
|
||||||
|
for (Node child : childArray) {
|
||||||
|
this.childArray.add(new Node(child));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public State getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setState(State state) {
|
||||||
|
this.state = state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node getParent() {
|
||||||
|
return parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setParent(Node parent) {
|
||||||
|
this.parent = parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Node> getChildArray() {
|
||||||
|
return childArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setChildArray(List<Node> childArray) {
|
||||||
|
this.childArray = childArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node getRandomChildNode() {
|
||||||
|
int noOfPossibleMoves = this.childArray.size();
|
||||||
|
int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1));
|
||||||
|
return this.childArray.get(selectRandom);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node getChildWithMaxScore() {
|
||||||
|
return Collections.max(this.childArray, Comparator.comparing(c -> {
|
||||||
|
return c.getState().getVisitCount();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.algorithms.mcts.tree;
|
||||||
|
|
||||||
|
public class Tree {
|
||||||
|
Node root;
|
||||||
|
|
||||||
|
public Tree() {
|
||||||
|
root = new Node();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Tree(Node root) {
|
||||||
|
this.root = root;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node getRoot() {
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRoot(Node root) {
|
||||||
|
this.root = root;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addChild(Node parent, Node child) {
|
||||||
|
parent.getChildArray().add(child);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.algorithms.minimax;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
class GameOfBones {
|
||||||
|
static List<Integer> getPossibleStates(int noOfBonesInHeap) {
|
||||||
|
return IntStream.rangeClosed(1, 3).boxed()
|
||||||
|
.map(i -> noOfBonesInHeap - i)
|
||||||
|
.filter(newHeapCount -> newHeapCount >= 0)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,60 @@
|
|||||||
|
package com.baeldung.algorithms.minimax;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
|
||||||
|
public class MiniMax {
|
||||||
|
private Tree tree;
|
||||||
|
|
||||||
|
public Tree getTree() {
|
||||||
|
return tree;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void constructTree(int noOfBones) {
|
||||||
|
tree = new Tree();
|
||||||
|
Node root = new Node(noOfBones, true);
|
||||||
|
tree.setRoot(root);
|
||||||
|
constructTree(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void constructTree(Node node) {
|
||||||
|
List<Integer> listofPossibleHeaps = GameOfBones.getPossibleStates(node.getNoOfBones());
|
||||||
|
boolean isMaxPlayer = !node.isMaxPlayer();
|
||||||
|
listofPossibleHeaps.forEach(n -> {
|
||||||
|
Node newNode = new Node(n, isMaxPlayer);
|
||||||
|
node.addChild(newNode);
|
||||||
|
if (newNode.getNoOfBones() > 0) {
|
||||||
|
constructTree(newNode);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean checkWin() {
|
||||||
|
Node root = tree.getRoot();
|
||||||
|
checkWin(root);
|
||||||
|
return root.getScore() == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void checkWin(Node node) {
|
||||||
|
List<Node> children = node.getChildren();
|
||||||
|
boolean isMaxPlayer = node.isMaxPlayer();
|
||||||
|
children.forEach(child -> {
|
||||||
|
if (child.getNoOfBones() == 0) {
|
||||||
|
child.setScore(isMaxPlayer ? 1 : -1);
|
||||||
|
} else {
|
||||||
|
checkWin(child);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Node bestChild = findBestChild(isMaxPlayer, children);
|
||||||
|
node.setScore(bestChild.getScore());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Node findBestChild(boolean isMaxPlayer, List<Node> children) {
|
||||||
|
Comparator<Node> byScoreComparator = Comparator.comparing(Node::getScore);
|
||||||
|
|
||||||
|
return children.stream()
|
||||||
|
.max(isMaxPlayer ? byScoreComparator : byScoreComparator.reversed())
|
||||||
|
.orElseThrow(NoSuchElementException::new);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,42 @@
|
|||||||
|
package com.baeldung.algorithms.minimax;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Node {
|
||||||
|
private int noOfBones;
|
||||||
|
private boolean isMaxPlayer;
|
||||||
|
private int score;
|
||||||
|
private List<Node> children;
|
||||||
|
|
||||||
|
public Node(int noOfBones, boolean isMaxPlayer) {
|
||||||
|
this.noOfBones = noOfBones;
|
||||||
|
this.isMaxPlayer = isMaxPlayer;
|
||||||
|
children = new ArrayList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
int getNoOfBones() {
|
||||||
|
return noOfBones;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isMaxPlayer() {
|
||||||
|
return isMaxPlayer;
|
||||||
|
}
|
||||||
|
|
||||||
|
int getScore() {
|
||||||
|
return score;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setScore(int score) {
|
||||||
|
this.score = score;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Node> getChildren() {
|
||||||
|
return children;
|
||||||
|
}
|
||||||
|
|
||||||
|
void addChild(Node newNode) {
|
||||||
|
children.add(newNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.algorithms.minimax;
|
||||||
|
|
||||||
|
public class Tree {
|
||||||
|
private Node root;
|
||||||
|
|
||||||
|
Tree() {
|
||||||
|
}
|
||||||
|
|
||||||
|
Node getRoot() {
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setRoot(Node root) {
|
||||||
|
this.root = root;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package algorithms;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.hillclimbing.HillClimbing;
|
||||||
|
import com.baeldung.algorithms.hillclimbing.State;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Stack;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class HillClimbingAlgorithmTest {
|
||||||
|
private Stack<String> initStack;
|
||||||
|
private Stack<String> goalStack;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void initStacks() {
|
||||||
|
String blockArr[] = { "B", "C", "D", "A" };
|
||||||
|
String goalBlockArr[] = { "A", "B", "C", "D" };
|
||||||
|
initStack = new Stack<>();
|
||||||
|
for (String block : blockArr)
|
||||||
|
initStack.push(block);
|
||||||
|
goalStack = new Stack<>();
|
||||||
|
for (String block : goalBlockArr)
|
||||||
|
goalStack.push(block);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() {
|
||||||
|
HillClimbing hillClimbing = new HillClimbing();
|
||||||
|
|
||||||
|
List<State> path;
|
||||||
|
try {
|
||||||
|
path = hillClimbing.getRouteWithHillClimbing(initStack, goalStack);
|
||||||
|
assertNotNull(path);
|
||||||
|
assertEquals(path.get(path.size() - 1)
|
||||||
|
.getState()
|
||||||
|
.get(0), goalStack);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
|
||||||
|
HillClimbing hillClimbing = new HillClimbing();
|
||||||
|
List<Stack<String>> initList = new ArrayList<>();
|
||||||
|
initList.add(initStack);
|
||||||
|
State currentState = new State(initList);
|
||||||
|
currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack));
|
||||||
|
State nextState = hillClimbing.findNextState(currentState, goalStack);
|
||||||
|
assertTrue(nextState.getHeuristics() > currentState.getHeuristics());
|
||||||
|
}
|
||||||
|
}
|
92
algorithms/src/test/java/algorithms/MCTSTest.java
Normal file
92
algorithms/src/test/java/algorithms/MCTSTest.java
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
package algorithms;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
|
||||||
|
import com.baeldung.algorithms.mcts.montecarlo.State;
|
||||||
|
import com.baeldung.algorithms.mcts.montecarlo.UCT;
|
||||||
|
import com.baeldung.algorithms.mcts.tictactoe.Board;
|
||||||
|
import com.baeldung.algorithms.mcts.tictactoe.Position;
|
||||||
|
import com.baeldung.algorithms.mcts.tree.Tree;
|
||||||
|
|
||||||
|
public class MCTSTest {
|
||||||
|
Tree gameTree;
|
||||||
|
MonteCarloTreeSearch mcts;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void initGameTree() {
|
||||||
|
gameTree = new Tree();
|
||||||
|
mcts = new MonteCarloTreeSearch();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
|
||||||
|
double uctValue = 15.79;
|
||||||
|
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
|
||||||
|
State initState = gameTree.getRoot().getState();
|
||||||
|
List<State> possibleStates = initState.getAllPossibleStates();
|
||||||
|
assertTrue(possibleStates.size() > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
|
||||||
|
Board board = new Board();
|
||||||
|
int initAvailablePositions = board.getEmptyPositions().size();
|
||||||
|
board.performMove(Board.P1, new Position(1, 1));
|
||||||
|
int availablePositions = board.getEmptyPositions().size();
|
||||||
|
assertTrue(initAvailablePositions > availablePositions);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
|
||||||
|
Board board = new Board();
|
||||||
|
|
||||||
|
int player = Board.P1;
|
||||||
|
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
|
||||||
|
for (int i = 0; i < totalMoves; i++) {
|
||||||
|
board = mcts.findNextMove(board, player);
|
||||||
|
if (board.checkStatus() != -1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
player = 3 - player;
|
||||||
|
}
|
||||||
|
int winStatus = board.checkStatus();
|
||||||
|
assertEquals(winStatus, Board.DRAW);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
|
||||||
|
Board board = new Board();
|
||||||
|
MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
|
||||||
|
mcts1.setLevel(1);
|
||||||
|
MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch();
|
||||||
|
mcts3.setLevel(3);
|
||||||
|
|
||||||
|
int player = Board.P1;
|
||||||
|
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
|
||||||
|
for (int i = 0; i < totalMoves; i++) {
|
||||||
|
if (player == Board.P1)
|
||||||
|
board = mcts3.findNextMove(board, player);
|
||||||
|
else
|
||||||
|
board = mcts1.findNextMove(board, player);
|
||||||
|
|
||||||
|
if (board.checkStatus() != -1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
player = 3 - player;
|
||||||
|
}
|
||||||
|
int winStatus = board.checkStatus();
|
||||||
|
assertTrue(winStatus == Board.DRAW || winStatus == Board.P1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,6 +1,6 @@
|
|||||||
package algorithms;
|
package algorithms;
|
||||||
|
|
||||||
import com.baeldung.automata.*;
|
import com.baeldung.algorithms.automata.*;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
92
algorithms/src/test/java/algorithms/mcts/MCTSTest.java
Normal file
92
algorithms/src/test/java/algorithms/mcts/MCTSTest.java
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
package algorithms.mcts;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
|
||||||
|
import com.baeldung.algorithms.mcts.montecarlo.State;
|
||||||
|
import com.baeldung.algorithms.mcts.montecarlo.UCT;
|
||||||
|
import com.baeldung.algorithms.mcts.tictactoe.Board;
|
||||||
|
import com.baeldung.algorithms.mcts.tictactoe.Position;
|
||||||
|
import com.baeldung.algorithms.mcts.tree.Tree;
|
||||||
|
|
||||||
|
public class MCTSTest {
|
||||||
|
private Tree gameTree;
|
||||||
|
private MonteCarloTreeSearch mcts;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void initGameTree() {
|
||||||
|
gameTree = new Tree();
|
||||||
|
mcts = new MonteCarloTreeSearch();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
|
||||||
|
double uctValue = 15.79;
|
||||||
|
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
|
||||||
|
State initState = gameTree.getRoot().getState();
|
||||||
|
List<State> possibleStates = initState.getAllPossibleStates();
|
||||||
|
assertTrue(possibleStates.size() > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
|
||||||
|
Board board = new Board();
|
||||||
|
int initAvailablePositions = board.getEmptyPositions().size();
|
||||||
|
board.performMove(Board.P1, new Position(1, 1));
|
||||||
|
int availablePositions = board.getEmptyPositions().size();
|
||||||
|
assertTrue(initAvailablePositions > availablePositions);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
|
||||||
|
Board board = new Board();
|
||||||
|
|
||||||
|
int player = Board.P1;
|
||||||
|
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
|
||||||
|
for (int i = 0; i < totalMoves; i++) {
|
||||||
|
board = mcts.findNextMove(board, player);
|
||||||
|
if (board.checkStatus() != -1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
player = 3 - player;
|
||||||
|
}
|
||||||
|
int winStatus = board.checkStatus();
|
||||||
|
assertEquals(winStatus, Board.DRAW);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
|
||||||
|
Board board = new Board();
|
||||||
|
MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
|
||||||
|
mcts1.setLevel(1);
|
||||||
|
MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch();
|
||||||
|
mcts3.setLevel(3);
|
||||||
|
|
||||||
|
int player = Board.P1;
|
||||||
|
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
|
||||||
|
for (int i = 0; i < totalMoves; i++) {
|
||||||
|
if (player == Board.P1)
|
||||||
|
board = mcts3.findNextMove(board, player);
|
||||||
|
else
|
||||||
|
board = mcts1.findNextMove(board, player);
|
||||||
|
|
||||||
|
if (board.checkStatus() != -1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
player = 3 - player;
|
||||||
|
}
|
||||||
|
int winStatus = board.checkStatus();
|
||||||
|
assertTrue(winStatus == Board.DRAW || winStatus == Board.P1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
36
algorithms/src/test/java/algorithms/minimax/MinimaxTest.java
Normal file
36
algorithms/src/test/java/algorithms/minimax/MinimaxTest.java
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package algorithms.minimax;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import com.baeldung.algorithms.minimax.MiniMax;
|
||||||
|
import com.baeldung.algorithms.minimax.Tree;
|
||||||
|
|
||||||
|
public class MinimaxTest {
|
||||||
|
private Tree gameTree;
|
||||||
|
private MiniMax miniMax;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void initMiniMaxUtility() {
|
||||||
|
miniMax = new MiniMax();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMiniMax_whenConstructTree_thenNotNullTree() {
|
||||||
|
assertNull(gameTree);
|
||||||
|
miniMax.constructTree(6);
|
||||||
|
gameTree = miniMax.getTree();
|
||||||
|
assertNotNull(gameTree);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMiniMax_whenCheckWin_thenComputeOptimal() {
|
||||||
|
miniMax.constructTree(6);
|
||||||
|
boolean result = miniMax.checkWin();
|
||||||
|
assertTrue(result);
|
||||||
|
miniMax.constructTree(8);
|
||||||
|
result = miniMax.checkWin();
|
||||||
|
assertFalse(result);
|
||||||
|
}
|
||||||
|
}
|
3
asciidoctor/README.md
Normal file
3
asciidoctor/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
### Relevant articles
|
||||||
|
|
||||||
|
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
|
56
asciidoctor/pom.xml
Normal file
56
asciidoctor/pom.xml
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<artifactId>asciidoctor</artifactId>
|
||||||
|
<name>asciidoctor</name>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctor-maven-plugin</artifactId>
|
||||||
|
<version>1.5.5</version>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctorj-pdf</artifactId>
|
||||||
|
<version>1.5.0-alpha.15</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>output-pdf</id>
|
||||||
|
<phase>generate-resources</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>process-asciidoc</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<sourceDirectory>src/docs/asciidoc</sourceDirectory>
|
||||||
|
<outputDirectory>target/docs/asciidoc</outputDirectory>
|
||||||
|
<backend>pdf</backend>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctorj</artifactId>
|
||||||
|
<version>1.5.4</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.asciidoctor</groupId>
|
||||||
|
<artifactId>asciidoctorj-pdf</artifactId>
|
||||||
|
<version>1.5.0-alpha.11</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
3
asciidoctor/src/docs/asciidoc/test.adoc
Normal file
3
asciidoctor/src/docs/asciidoc/test.adoc
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
== Introduction Section
|
||||||
|
|
||||||
|
Hi. I'm a simple test to see if this Maven build is working. If you see me in a nice PDF, then it means everything is [red]#working#.
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.asciidoctor;
|
||||||
|
|
||||||
|
import static org.asciidoctor.Asciidoctor.Factory.create;
|
||||||
|
import static org.asciidoctor.OptionsBuilder.options;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.asciidoctor.Asciidoctor;
|
||||||
|
|
||||||
|
public class AsciidoctorDemo {
|
||||||
|
|
||||||
|
private final Asciidoctor asciidoctor;
|
||||||
|
|
||||||
|
AsciidoctorDemo() {
|
||||||
|
asciidoctor = create();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void generatePDFFromString(final String input) {
|
||||||
|
|
||||||
|
final Map<String, Object> options = options().inPlace(true)
|
||||||
|
.backend("pdf")
|
||||||
|
.asMap();
|
||||||
|
|
||||||
|
|
||||||
|
final String outfile = asciidoctor.convertFile(new File("sample.adoc"), options);
|
||||||
|
}
|
||||||
|
|
||||||
|
String generateHTMLFromString(final String input) {
|
||||||
|
return asciidoctor.convert("Hello _Baeldung_!", new HashMap<String, Object>());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.asciidoctor;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class AsciidoctorDemoTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenString_whenConverting_thenResultingHTMLCode() {
|
||||||
|
final AsciidoctorDemo asciidoctorDemo = new AsciidoctorDemo();
|
||||||
|
Assert.assertEquals(asciidoctorDemo.generateHTMLFromString("Hello _Baeldung_!"), "<div class=\"paragraph\">\n<p>Hello <em>Baeldung</em>!</p>\n</div>");
|
||||||
|
}
|
||||||
|
}
|
15
camel-api/README.md
Normal file
15
camel-api/README.md
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
Example for the Article on Camel API with SpringBoot
|
||||||
|
|
||||||
|
to start up, run:
|
||||||
|
mvn spring-boot:run
|
||||||
|
|
||||||
|
them, do a POST http request to:
|
||||||
|
http://localhost:8080/camel/api/bean
|
||||||
|
|
||||||
|
with the HEADER: Content-Type: application/json,
|
||||||
|
|
||||||
|
and a BODY Payload like {"id": 1,"name": "World"}
|
||||||
|
|
||||||
|
and we will get a return code of 201 and the response: Hello, World - if the transform() method from Application class is uncommented and the process() method is commented
|
||||||
|
|
||||||
|
or return code of 201 and the response: {"id": 10,"name": "Hello, World"} - if the transform() method from Application class is commented and the process() method is uncommented
|
80
camel-api/pom.xml
Normal file
80
camel-api/pom.xml
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
<?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.example</groupId>
|
||||||
|
<artifactId>spring-boot-camel</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<name>Spring-Boot - Camel API</name>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
<camel.version>2.19.1</camel.version>
|
||||||
|
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.camel</groupId>
|
||||||
|
<artifactId>camel-servlet-starter</artifactId>
|
||||||
|
<version>${camel.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.camel</groupId>
|
||||||
|
<artifactId>camel-jackson-starter</artifactId>
|
||||||
|
<version>${camel.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.camel</groupId>
|
||||||
|
<artifactId>camel-swagger-java-starter</artifactId>
|
||||||
|
<version>${camel.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.camel</groupId>
|
||||||
|
<artifactId>camel-spring-boot-starter</artifactId>
|
||||||
|
<version>${camel.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
<version>${spring-boot-starter.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<defaultGoal>spring-boot:run</defaultGoal>
|
||||||
|
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>${maven-surefire-plugin.version}</version>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
<version>${spring-boot-starter.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>repackage</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
104
camel-api/src/main/java/com/baeldung/camel/Application.java
Normal file
104
camel-api/src/main/java/com/baeldung/camel/Application.java
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
package com.baeldung.camel;
|
||||||
|
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
|
||||||
|
import org.apache.camel.CamelContext;
|
||||||
|
import org.apache.camel.Exchange;
|
||||||
|
import org.apache.camel.Processor;
|
||||||
|
import org.apache.camel.builder.RouteBuilder;
|
||||||
|
import org.apache.camel.component.servlet.CamelHttpTransportServlet;
|
||||||
|
import org.apache.camel.impl.DefaultCamelContext;
|
||||||
|
import org.apache.camel.model.rest.RestBindingMode;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||||
|
import org.springframework.boot.web.support.SpringBootServletInitializer;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@ComponentScan(basePackages="com.baeldung.camel")
|
||||||
|
public class Application extends SpringBootServletInitializer {
|
||||||
|
|
||||||
|
@Value("${server.port}")
|
||||||
|
String serverPort;
|
||||||
|
|
||||||
|
@Value("${baeldung.api.path}")
|
||||||
|
String contextPath;
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(Application.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
ServletRegistrationBean servletRegistrationBean() {
|
||||||
|
ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath+"/*");
|
||||||
|
servlet.setName("CamelServlet");
|
||||||
|
return servlet;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Component
|
||||||
|
class RestApi extends RouteBuilder {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configure() {
|
||||||
|
|
||||||
|
CamelContext context = new DefaultCamelContext();
|
||||||
|
|
||||||
|
|
||||||
|
// http://localhost:8080/camel/api-doc
|
||||||
|
restConfiguration().contextPath(contextPath) //
|
||||||
|
.port(serverPort)
|
||||||
|
.enableCORS(true)
|
||||||
|
.apiContextPath("/api-doc")
|
||||||
|
.apiProperty("api.title", "Test REST API")
|
||||||
|
.apiProperty("api.version", "v1")
|
||||||
|
.apiProperty("cors", "true") // cross-site
|
||||||
|
.apiContextRouteId("doc-api")
|
||||||
|
.component("servlet")
|
||||||
|
.bindingMode(RestBindingMode.json)
|
||||||
|
.dataFormatProperty("prettyPrint", "true");
|
||||||
|
/**
|
||||||
|
The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format.
|
||||||
|
By default the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages.
|
||||||
|
You may want to use binding if you develop POJOs that maps to your REST services request and response types.
|
||||||
|
This allows you, as a developer, to work with the POJOs in Java code.
|
||||||
|
*/
|
||||||
|
|
||||||
|
rest("/api/").description("Teste REST Service")
|
||||||
|
.id("api-route")
|
||||||
|
.post("/bean")
|
||||||
|
.produces(MediaType.APPLICATION_JSON)
|
||||||
|
.consumes(MediaType.APPLICATION_JSON)
|
||||||
|
// .get("/hello/{place}")
|
||||||
|
.bindingMode(RestBindingMode.auto)
|
||||||
|
.type(MyBean.class)
|
||||||
|
.enableCORS(true)
|
||||||
|
// .outType(OutBean.class)
|
||||||
|
|
||||||
|
.to("direct:remoteService");
|
||||||
|
|
||||||
|
|
||||||
|
from("direct:remoteService")
|
||||||
|
.routeId("direct-route")
|
||||||
|
.tracing()
|
||||||
|
.log(">>> ${body.id}")
|
||||||
|
.log(">>> ${body.name}")
|
||||||
|
// .transform().simple("blue ${in.body.name}")
|
||||||
|
.process(new Processor() {
|
||||||
|
@Override
|
||||||
|
public void process(Exchange exchange) throws Exception {
|
||||||
|
MyBean bodyIn = (MyBean) exchange.getIn().getBody();
|
||||||
|
|
||||||
|
ExampleServices.example(bodyIn);
|
||||||
|
|
||||||
|
exchange.getIn().setBody(bodyIn);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.camel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* a Mock class to show how some other layer
|
||||||
|
* (a persistence layer, for instance)
|
||||||
|
* could be used insida a Camel
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class ExampleServices {
|
||||||
|
|
||||||
|
public static void example(MyBean bodyIn) {
|
||||||
|
bodyIn.setName( "Hello, " + bodyIn.getName() );
|
||||||
|
bodyIn.setId(bodyIn.getId()*10);
|
||||||
|
}
|
||||||
|
}
|
18
camel-api/src/main/java/com/baeldung/camel/MyBean.java
Normal file
18
camel-api/src/main/java/com/baeldung/camel/MyBean.java
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.camel;
|
||||||
|
|
||||||
|
public class MyBean {
|
||||||
|
private Integer id;
|
||||||
|
private String name;
|
||||||
|
public Integer getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
public void setId(Integer id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
15
camel-api/src/main/resources/application.properties
Normal file
15
camel-api/src/main/resources/application.properties
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
logging.config=classpath:logback.xml
|
||||||
|
|
||||||
|
# the options from org.apache.camel.spring.boot.CamelConfigurationProperties can be configured here
|
||||||
|
camel.springboot.name=MyCamel
|
||||||
|
|
||||||
|
# lets listen on all ports to ensure we can be invoked from the pod IP
|
||||||
|
server.address=0.0.0.0
|
||||||
|
management.address=0.0.0.0
|
||||||
|
|
||||||
|
# lets use a different management port in case you need to listen to HTTP requests on 8080
|
||||||
|
management.port=8081
|
||||||
|
|
||||||
|
# disable all management enpoints except health
|
||||||
|
endpoints.enabled = true
|
||||||
|
endpoints.health.enabled = true
|
27
camel-api/src/main/resources/application.yml
Normal file
27
camel-api/src/main/resources/application.yml
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
server:
|
||||||
|
port: 8080
|
||||||
|
|
||||||
|
# for example purposes of Camel version 2.18 and below
|
||||||
|
baeldung:
|
||||||
|
api:
|
||||||
|
path: '/camel'
|
||||||
|
|
||||||
|
camel:
|
||||||
|
springboot:
|
||||||
|
# The Camel context name
|
||||||
|
name: ServicesRest
|
||||||
|
|
||||||
|
# Binding health checks to a different port
|
||||||
|
management:
|
||||||
|
port: 8081
|
||||||
|
|
||||||
|
# disable all management enpoints except health
|
||||||
|
endpoints:
|
||||||
|
enabled: false
|
||||||
|
health:
|
||||||
|
enabled: true
|
||||||
|
|
||||||
|
# The application configuration properties
|
||||||
|
quickstart:
|
||||||
|
generateOrderPeriod: 10s
|
||||||
|
processOrderPeriod: 30s
|
17
camel-api/src/main/resources/logback.xml
Normal file
17
camel-api/src/main/resources/logback.xml
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE xml>
|
||||||
|
<configuration>
|
||||||
|
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<!-- encoders are assigned the type
|
||||||
|
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="info">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
|
||||||
|
</configuration>
|
@ -47,6 +47,13 @@
|
|||||||
<version>${mockito.version}</version>
|
<version>${mockito.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.jayway.awaitility</groupId>
|
||||||
|
<artifactId>awaitility</artifactId>
|
||||||
|
<version>${awaitility.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
@ -90,6 +97,7 @@
|
|||||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
<mockito.version>1.10.19</mockito.version>
|
<mockito.version>1.10.19</mockito.version>
|
||||||
|
<awaitility.version>1.7.0</awaitility.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.java9.streams.reactive;
|
||||||
|
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.Flow.Subscriber;
|
||||||
|
import java.util.concurrent.Flow.Subscription;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
public class EndSubscriber<T> implements Subscriber<T> {
|
||||||
|
private final AtomicInteger howMuchMessagesToConsume;
|
||||||
|
private Subscription subscription;
|
||||||
|
public List<T> consumedElements = new LinkedList<>();
|
||||||
|
|
||||||
|
public EndSubscriber(Integer howMuchMessagesToConsume) {
|
||||||
|
this.howMuchMessagesToConsume = new AtomicInteger(howMuchMessagesToConsume);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onSubscribe(Subscription subscription) {
|
||||||
|
this.subscription = subscription;
|
||||||
|
subscription.request(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onNext(T item) {
|
||||||
|
howMuchMessagesToConsume.decrementAndGet();
|
||||||
|
System.out.println("Got : " + item);
|
||||||
|
consumedElements.add(item);
|
||||||
|
if (howMuchMessagesToConsume.get() > 0) {
|
||||||
|
subscription.request(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onError(Throwable t) {
|
||||||
|
t.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onComplete() {
|
||||||
|
System.out.println("Done");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.java9.streams.reactive;
|
||||||
|
|
||||||
|
import java.util.concurrent.Flow;
|
||||||
|
import java.util.concurrent.SubmissionPublisher;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
public class TransformProcessor<T, R> extends SubmissionPublisher<R> implements Flow.Processor<T, R> {
|
||||||
|
|
||||||
|
private Function<T, R> function;
|
||||||
|
private Flow.Subscription subscription;
|
||||||
|
|
||||||
|
public TransformProcessor(Function<T, R> function) {
|
||||||
|
super();
|
||||||
|
this.function = function;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onSubscribe(Flow.Subscription subscription) {
|
||||||
|
this.subscription = subscription;
|
||||||
|
subscription.request(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onNext(T item) {
|
||||||
|
submit(function.apply(item));
|
||||||
|
subscription.request(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onError(Throwable t) {
|
||||||
|
t.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onComplete() {
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.java9.time;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.GregorianCalendar;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
public class TimeApi {
|
||||||
|
|
||||||
|
public static List<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate) {
|
||||||
|
List<Date> datesInRange = new ArrayList<Date>();
|
||||||
|
Calendar calendar = new GregorianCalendar();
|
||||||
|
calendar.setTime(startDate);
|
||||||
|
|
||||||
|
Calendar endCalendar = new GregorianCalendar();
|
||||||
|
endCalendar.setTime(endDate);
|
||||||
|
|
||||||
|
while (calendar.before(endCalendar)) {
|
||||||
|
Date result = calendar.getTime();
|
||||||
|
datesInRange.add(result);
|
||||||
|
calendar.add(Calendar.DATE, 1);
|
||||||
|
}
|
||||||
|
return datesInRange;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<LocalDate> getDatesBetweenUsingJava8(LocalDate startDate, LocalDate endDate) {
|
||||||
|
long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
|
||||||
|
return IntStream.iterate(0, i -> i + 1)
|
||||||
|
.limit(numOfDaysBetween)
|
||||||
|
.mapToObj(i -> startDate.plusDays(i))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<LocalDate> getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate) {
|
||||||
|
return startDate.datesUntil(endDate).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,73 @@
|
|||||||
|
package com.baeldung.java9.streams.reactive;
|
||||||
|
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.SubmissionPublisher;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Java6Assertions.assertThat;
|
||||||
|
|
||||||
|
public class ReactiveStreamsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPublisher_whenSubscribeToIt_thenShouldConsumeAllElements() throws InterruptedException {
|
||||||
|
//given
|
||||||
|
SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
|
||||||
|
EndSubscriber<String> subscriber = new EndSubscriber<>(6);
|
||||||
|
publisher.subscribe(subscriber);
|
||||||
|
List<String> items = List.of("1", "x", "2", "x", "3", "x");
|
||||||
|
|
||||||
|
//when
|
||||||
|
assertThat(publisher.getNumberOfSubscribers()).isEqualTo(1);
|
||||||
|
items.forEach(publisher::submit);
|
||||||
|
publisher.close();
|
||||||
|
|
||||||
|
//then
|
||||||
|
|
||||||
|
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
||||||
|
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(items)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPublisher_whenSubscribeAndTransformElements_thenShouldConsumeAllElements() throws InterruptedException {
|
||||||
|
//given
|
||||||
|
SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
|
||||||
|
TransformProcessor<String, Integer> transformProcessor = new TransformProcessor<>(Integer::parseInt);
|
||||||
|
EndSubscriber<Integer> subscriber = new EndSubscriber<>(3);
|
||||||
|
List<String> items = List.of("1", "2", "3");
|
||||||
|
List<Integer> expectedResult = List.of(1, 2, 3);
|
||||||
|
|
||||||
|
//when
|
||||||
|
publisher.subscribe(transformProcessor);
|
||||||
|
transformProcessor.subscribe(subscriber);
|
||||||
|
items.forEach(publisher::submit);
|
||||||
|
publisher.close();
|
||||||
|
|
||||||
|
//then
|
||||||
|
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
||||||
|
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expectedResult)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPublisher_whenRequestForOnlyOneElement_thenShouldConsumeOnlyThatOne() throws InterruptedException {
|
||||||
|
//given
|
||||||
|
SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
|
||||||
|
EndSubscriber<String> subscriber = new EndSubscriber<>(1);
|
||||||
|
publisher.subscribe(subscriber);
|
||||||
|
List<String> items = List.of("1", "x", "2", "x", "3", "x");
|
||||||
|
List<String> expected = List.of("1");
|
||||||
|
|
||||||
|
//when
|
||||||
|
assertThat(publisher.getNumberOfSubscribers()).isEqualTo(1);
|
||||||
|
items.forEach(publisher::submit);
|
||||||
|
publisher.close();
|
||||||
|
|
||||||
|
//then
|
||||||
|
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
||||||
|
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expected)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package com.baeldung.java9.time;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class TimeApiTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGetDatesBetweenWithUsingJava7_WhenStartEndDate_thenDatesList() {
|
||||||
|
Date startDate = Calendar.getInstance().getTime();
|
||||||
|
Calendar endCalendar = Calendar.getInstance();
|
||||||
|
endCalendar.add(Calendar.DATE, 2);
|
||||||
|
Date endDate = endCalendar.getTime();
|
||||||
|
|
||||||
|
List<Date> dates = TimeApi.getDatesBetweenUsingJava7(startDate, endDate);
|
||||||
|
assertEquals(dates.size(), 2);
|
||||||
|
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
Date date1 = calendar.getTime();
|
||||||
|
assertEquals(dates.get(0).getDay(), date1.getDay());
|
||||||
|
assertEquals(dates.get(0).getMonth(), date1.getMonth());
|
||||||
|
assertEquals(dates.get(0).getYear(), date1.getYear());
|
||||||
|
|
||||||
|
calendar.add(Calendar.DATE, 1);
|
||||||
|
Date date2 = calendar.getTime();
|
||||||
|
assertEquals(dates.get(1).getDay(), date2.getDay());
|
||||||
|
assertEquals(dates.get(1).getMonth(), date2.getMonth());
|
||||||
|
assertEquals(dates.get(1).getYear(), date2.getYear());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGetDatesBetweenWithUsingJava8_WhenStartEndDate_thenDatesList() {
|
||||||
|
LocalDate startDate = LocalDate.now();
|
||||||
|
LocalDate endDate = LocalDate.now().plusDays(2);
|
||||||
|
|
||||||
|
List<LocalDate> dates = TimeApi.getDatesBetweenUsingJava8(startDate, endDate);
|
||||||
|
assertEquals(dates.size(), 2);
|
||||||
|
assertEquals(dates.get(0), LocalDate.now());
|
||||||
|
assertEquals(dates.get(1), LocalDate.now().plusDays(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGetDatesBetweenWithUsingJava9_WhenStartEndDate_thenDatesList() {
|
||||||
|
LocalDate startDate = LocalDate.now();
|
||||||
|
LocalDate endDate = LocalDate.now().plusDays(2);
|
||||||
|
|
||||||
|
List<LocalDate> dates = TimeApi.getDatesBetweenUsingJava9(startDate, endDate);
|
||||||
|
assertEquals(dates.size(), 2);
|
||||||
|
assertEquals(dates.get(0), LocalDate.now());
|
||||||
|
assertEquals(dates.get(1), LocalDate.now().plusDays(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
3
core-java/.gitignore
vendored
3
core-java/.gitignore
vendored
@ -17,9 +17,10 @@
|
|||||||
|
|
||||||
# Files generated by integration tests
|
# Files generated by integration tests
|
||||||
*.txt
|
*.txt
|
||||||
|
backup-pom.xml
|
||||||
/bin/
|
/bin/
|
||||||
/temp
|
/temp
|
||||||
|
|
||||||
#IntelliJ specific
|
#IntelliJ specific
|
||||||
.idea
|
.idea/
|
||||||
*.iml
|
*.iml
|
@ -113,4 +113,21 @@
|
|||||||
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
|
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
|
||||||
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
|
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
|
||||||
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
|
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
|
||||||
|
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
|
||||||
|
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
|
||||||
|
- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
|
||||||
|
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
|
||||||
|
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
|
||||||
|
- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string)
|
||||||
|
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
|
||||||
|
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
|
||||||
|
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
|
||||||
|
- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
|
||||||
|
- [Split a String in Java](http://www.baeldung.com/java-split-string)
|
||||||
|
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||||
|
- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
|
||||||
|
- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
|
||||||
|
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
|
||||||
|
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
||||||
|
- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
|
||||||
|
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
|
||||||
|
@ -177,6 +177,11 @@
|
|||||||
<version>2.1.0.1</version>
|
<version>2.1.0.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.sun.messaging.mq</groupId>
|
||||||
|
<artifactId>fscontext</artifactId>
|
||||||
|
<version>${fscontext.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -322,6 +327,22 @@
|
|||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
|
<version>1.6.0</version>
|
||||||
|
<configuration>
|
||||||
|
<executable>java</executable>
|
||||||
|
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||||
|
<arguments>
|
||||||
|
<argument>-Xmx300m</argument>
|
||||||
|
<argument>-XX:+UseParallelGC</argument>
|
||||||
|
<argument>-classpath</argument>
|
||||||
|
<classpath/>
|
||||||
|
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||||
|
</arguments>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
|
|
||||||
</build>
|
</build>
|
||||||
@ -382,6 +403,7 @@
|
|||||||
<unix4j.version>0.4</unix4j.version>
|
<unix4j.version>0.4</unix4j.version>
|
||||||
<grep4j.version>1.8.7</grep4j.version>
|
<grep4j.version>1.8.7</grep4j.version>
|
||||||
<lombok.version>1.16.12</lombok.version>
|
<lombok.version>1.16.12</lombok.version>
|
||||||
|
<fscontext.version>4.6-b01</fscontext.version>
|
||||||
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||||
@ -395,5 +417,4 @@
|
|||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -6,7 +6,7 @@ public class NumbersConsumer implements Runnable {
|
|||||||
private final BlockingQueue<Integer> queue;
|
private final BlockingQueue<Integer> queue;
|
||||||
private final int poisonPill;
|
private final int poisonPill;
|
||||||
|
|
||||||
public NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
||||||
this.queue = queue;
|
this.queue = queue;
|
||||||
this.poisonPill = poisonPill;
|
this.poisonPill = poisonPill;
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,7 @@ public class NumbersProducer implements Runnable {
|
|||||||
private final int poisonPill;
|
private final int poisonPill;
|
||||||
private final int poisonPillPerProducer;
|
private final int poisonPillPerProducer;
|
||||||
|
|
||||||
public NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
|
NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
|
||||||
this.numbersQueue = numbersQueue;
|
this.numbersQueue = numbersQueue;
|
||||||
this.poisonPill = poisonPill;
|
this.poisonPill = poisonPill;
|
||||||
this.poisonPillPerProducer = poisonPillPerProducer;
|
this.poisonPillPerProducer = poisonPillPerProducer;
|
||||||
|
@ -7,7 +7,7 @@ public class BrokenWorker implements Runnable {
|
|||||||
private final List<String> outputScraper;
|
private final List<String> outputScraper;
|
||||||
private final CountDownLatch countDownLatch;
|
private final CountDownLatch countDownLatch;
|
||||||
|
|
||||||
public BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||||
this.outputScraper = outputScraper;
|
this.outputScraper = outputScraper;
|
||||||
this.countDownLatch = countDownLatch;
|
this.countDownLatch = countDownLatch;
|
||||||
}
|
}
|
||||||
|
@ -10,7 +10,7 @@ public class WaitingWorker implements Runnable {
|
|||||||
private final CountDownLatch callingThreadBlocker;
|
private final CountDownLatch callingThreadBlocker;
|
||||||
private final CountDownLatch completedThreadCounter;
|
private final CountDownLatch completedThreadCounter;
|
||||||
|
|
||||||
public WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
||||||
|
|
||||||
this.outputScraper = outputScraper;
|
this.outputScraper = outputScraper;
|
||||||
this.readyThreadCounter = readyThreadCounter;
|
this.readyThreadCounter = readyThreadCounter;
|
||||||
|
@ -7,7 +7,7 @@ public class Worker implements Runnable {
|
|||||||
private final List<String> outputScraper;
|
private final List<String> outputScraper;
|
||||||
private final CountDownLatch countDownLatch;
|
private final CountDownLatch countDownLatch;
|
||||||
|
|
||||||
public Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||||
this.outputScraper = outputScraper;
|
this.outputScraper = outputScraper;
|
||||||
this.countDownLatch = countDownLatch;
|
this.countDownLatch = countDownLatch;
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,81 @@
|
|||||||
|
package com.baeldung.concurrent.cyclicbarrier;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.concurrent.BrokenBarrierException;
|
||||||
|
import java.util.concurrent.CyclicBarrier;
|
||||||
|
|
||||||
|
public class CyclicBarrierDemo {
|
||||||
|
|
||||||
|
private CyclicBarrier cyclicBarrier;
|
||||||
|
private List<List<Integer>> partialResults = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
private Random random = new Random();
|
||||||
|
private int NUM_PARTIAL_RESULTS;
|
||||||
|
private int NUM_WORKERS;
|
||||||
|
|
||||||
|
|
||||||
|
private void runSimulation(int numWorkers, int numberOfPartialResults) {
|
||||||
|
NUM_PARTIAL_RESULTS = numberOfPartialResults;
|
||||||
|
NUM_WORKERS = numWorkers;
|
||||||
|
|
||||||
|
cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
|
||||||
|
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute "
|
||||||
|
+ NUM_PARTIAL_RESULTS + " partial results each");
|
||||||
|
for (int i = 0; i < NUM_WORKERS; i++) {
|
||||||
|
Thread worker = new Thread(new NumberCruncherThread());
|
||||||
|
worker.setName("Thread " + i);
|
||||||
|
worker.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class NumberCruncherThread implements Runnable {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
String thisThreadName = Thread.currentThread().getName();
|
||||||
|
List<Integer> partialResult = new ArrayList<>();
|
||||||
|
for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
|
||||||
|
Integer num = random.nextInt(10);
|
||||||
|
System.out.println(thisThreadName
|
||||||
|
+ ": Crunching some numbers! Final result - " + num);
|
||||||
|
partialResult.add(num);
|
||||||
|
}
|
||||||
|
partialResults.add(partialResult);
|
||||||
|
try {
|
||||||
|
System.out.println(thisThreadName + " waiting for others to reach barrier.");
|
||||||
|
cyclicBarrier.await();
|
||||||
|
} catch (InterruptedException | BrokenBarrierException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class AggregatorThread implements Runnable {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
String thisThreadName = Thread.currentThread().getName();
|
||||||
|
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS
|
||||||
|
+ " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
|
||||||
|
int sum = 0;
|
||||||
|
for (List<Integer> threadResult : partialResults) {
|
||||||
|
System.out.print("Adding ");
|
||||||
|
for (Integer partialResult : threadResult) {
|
||||||
|
System.out.print(partialResult+" ");
|
||||||
|
sum += partialResult;
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
System.out.println(Thread.currentThread().getName() + ": Final result = " + sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
CyclicBarrierDemo play = new CyclicBarrierDemo();
|
||||||
|
play.runSimulation(5, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -9,7 +9,7 @@ public class DelayObject implements Delayed {
|
|||||||
private String data;
|
private String data;
|
||||||
private long startTime;
|
private long startTime;
|
||||||
|
|
||||||
public DelayObject(String data, long delayInMilliseconds) {
|
DelayObject(String data, long delayInMilliseconds) {
|
||||||
this.data = data;
|
this.data = data;
|
||||||
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
|
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
|
||||||
}
|
}
|
||||||
|
@ -7,9 +7,9 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||||||
public class DelayQueueConsumer implements Runnable {
|
public class DelayQueueConsumer implements Runnable {
|
||||||
private BlockingQueue<DelayObject> queue;
|
private BlockingQueue<DelayObject> queue;
|
||||||
private final Integer numberOfElementsToTake;
|
private final Integer numberOfElementsToTake;
|
||||||
public final AtomicInteger numberOfConsumedElements = new AtomicInteger();
|
final AtomicInteger numberOfConsumedElements = new AtomicInteger();
|
||||||
|
|
||||||
public DelayQueueConsumer(BlockingQueue<DelayObject> queue, Integer numberOfElementsToTake) {
|
DelayQueueConsumer(BlockingQueue<DelayObject> queue, Integer numberOfElementsToTake) {
|
||||||
this.queue = queue;
|
this.queue = queue;
|
||||||
this.numberOfElementsToTake = numberOfElementsToTake;
|
this.numberOfElementsToTake = numberOfElementsToTake;
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,7 @@ public class DelayQueueProducer implements Runnable {
|
|||||||
private final Integer numberOfElementsToProduce;
|
private final Integer numberOfElementsToProduce;
|
||||||
private final Integer delayOfEachProducedMessageMilliseconds;
|
private final Integer delayOfEachProducedMessageMilliseconds;
|
||||||
|
|
||||||
public DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
||||||
Integer numberOfElementsToProduce,
|
Integer numberOfElementsToProduce,
|
||||||
Integer delayOfEachProducedMessageMilliseconds) {
|
Integer delayOfEachProducedMessageMilliseconds) {
|
||||||
this.queue = queue;
|
this.queue = queue;
|
||||||
|
@ -5,7 +5,7 @@ public class Philosopher implements Runnable {
|
|||||||
private final Object leftFork;
|
private final Object leftFork;
|
||||||
private final Object rightFork;
|
private final Object rightFork;
|
||||||
|
|
||||||
public Philosopher(Object left, Object right) {
|
Philosopher(Object left, Object right) {
|
||||||
this.leftFork = left;
|
this.leftFork = left;
|
||||||
this.rightFork = right;
|
this.rightFork = right;
|
||||||
}
|
}
|
||||||
@ -30,7 +30,6 @@ public class Philosopher implements Runnable {
|
|||||||
}
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -7,7 +7,7 @@ public class FactorialSquareCalculator extends RecursiveTask<Integer> {
|
|||||||
|
|
||||||
final private Integer n;
|
final private Integer n;
|
||||||
|
|
||||||
public FactorialSquareCalculator(Integer n) {
|
FactorialSquareCalculator(Integer n) {
|
||||||
this.n = n;
|
this.n = n;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,15 +3,15 @@ package com.baeldung.concurrent.future;
|
|||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Future;
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
public class SquareCalculator {
|
class SquareCalculator {
|
||||||
|
|
||||||
private final ExecutorService executor;
|
private final ExecutorService executor;
|
||||||
|
|
||||||
public SquareCalculator(ExecutorService executor) {
|
SquareCalculator(ExecutorService executor) {
|
||||||
this.executor = executor;
|
this.executor = executor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Future<Integer> calculate(Integer input) {
|
Future<Integer> calculate(Integer input) {
|
||||||
return executor.submit(() -> {
|
return executor.submit(() -> {
|
||||||
Thread.sleep(1000);
|
Thread.sleep(1000);
|
||||||
return input * input;
|
return input * input;
|
||||||
|
@ -13,23 +13,23 @@ import static java.lang.Thread.sleep;
|
|||||||
|
|
||||||
public class ReentrantLockWithCondition {
|
public class ReentrantLockWithCondition {
|
||||||
|
|
||||||
static Logger logger = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
private static Logger LOG = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
|
||||||
|
|
||||||
Stack<String> stack = new Stack<>();
|
private Stack<String> stack = new Stack<>();
|
||||||
int CAPACITY = 5;
|
private static final int CAPACITY = 5;
|
||||||
|
|
||||||
ReentrantLock lock = new ReentrantLock();
|
private ReentrantLock lock = new ReentrantLock();
|
||||||
Condition stackEmptyCondition = lock.newCondition();
|
private Condition stackEmptyCondition = lock.newCondition();
|
||||||
Condition stackFullCondition = lock.newCondition();
|
private Condition stackFullCondition = lock.newCondition();
|
||||||
|
|
||||||
public void pushToStack(String item) throws InterruptedException {
|
private void pushToStack(String item) throws InterruptedException {
|
||||||
try {
|
try {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
if (stack.size() == CAPACITY) {
|
if (stack.size() == CAPACITY) {
|
||||||
logger.info(Thread.currentThread().getName() + " wait on stack full");
|
LOG.info(Thread.currentThread().getName() + " wait on stack full");
|
||||||
stackFullCondition.await();
|
stackFullCondition.await();
|
||||||
}
|
}
|
||||||
logger.info("Pushing the item " + item);
|
LOG.info("Pushing the item " + item);
|
||||||
stack.push(item);
|
stack.push(item);
|
||||||
stackEmptyCondition.signalAll();
|
stackEmptyCondition.signalAll();
|
||||||
} finally {
|
} finally {
|
||||||
@ -38,11 +38,11 @@ public class ReentrantLockWithCondition {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String popFromStack() throws InterruptedException {
|
private String popFromStack() throws InterruptedException {
|
||||||
try {
|
try {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
if (stack.size() == 0) {
|
if (stack.size() == 0) {
|
||||||
logger.info(Thread.currentThread().getName() + " wait on stack empty");
|
LOG.info(Thread.currentThread().getName() + " wait on stack empty");
|
||||||
stackEmptyCondition.await();
|
stackEmptyCondition.await();
|
||||||
}
|
}
|
||||||
return stack.pop();
|
return stack.pop();
|
||||||
@ -70,7 +70,7 @@ public class ReentrantLockWithCondition {
|
|||||||
service.execute(() -> {
|
service.execute(() -> {
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
try {
|
try {
|
||||||
logger.info("Item popped " + object.popFromStack());
|
LOG.info("Item popped " + object.popFromStack());
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
@ -12,48 +12,48 @@ import static java.lang.Thread.sleep;
|
|||||||
|
|
||||||
public class SharedObjectWithLock {
|
public class SharedObjectWithLock {
|
||||||
|
|
||||||
Logger logger = LoggerFactory.getLogger(SharedObjectWithLock.class);
|
private static final Logger LOG = LoggerFactory.getLogger(SharedObjectWithLock.class);
|
||||||
|
|
||||||
ReentrantLock lock = new ReentrantLock(true);
|
private ReentrantLock lock = new ReentrantLock(true);
|
||||||
|
|
||||||
int counter = 0;
|
private int counter = 0;
|
||||||
|
|
||||||
public void perform() {
|
void perform() {
|
||||||
|
|
||||||
lock.lock();
|
lock.lock();
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||||
try {
|
try {
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||||
counter++;
|
counter++;
|
||||||
} catch (Exception exception) {
|
} catch (Exception exception) {
|
||||||
logger.error(" Interrupted Exception ", exception);
|
LOG.error(" Interrupted Exception ", exception);
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void performTryLock() {
|
private void performTryLock() {
|
||||||
|
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
|
||||||
try {
|
try {
|
||||||
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
|
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
|
||||||
if (isLockAcquired) {
|
if (isLockAcquired) {
|
||||||
try {
|
try {
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
|
||||||
|
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " processing");
|
||||||
sleep(1000);
|
sleep(1000);
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock");
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (InterruptedException exception) {
|
} catch (InterruptedException exception) {
|
||||||
logger.error(" Interrupted Exception ", exception);
|
LOG.error(" Interrupted Exception ", exception);
|
||||||
}
|
}
|
||||||
logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
|
LOG.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
|
||||||
}
|
}
|
||||||
|
|
||||||
public ReentrantLock getLock() {
|
public ReentrantLock getLock() {
|
||||||
@ -78,12 +78,8 @@ public class SharedObjectWithLock {
|
|||||||
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
|
||||||
final SharedObjectWithLock object = new SharedObjectWithLock();
|
final SharedObjectWithLock object = new SharedObjectWithLock();
|
||||||
|
|
||||||
service.execute(() -> {
|
service.execute(object::perform);
|
||||||
object.perform();
|
service.execute(object::performTryLock);
|
||||||
});
|
|
||||||
service.execute(() -> {
|
|
||||||
object.performTryLock();
|
|
||||||
});
|
|
||||||
|
|
||||||
service.shutdown();
|
service.shutdown();
|
||||||
|
|
||||||
|
@ -12,8 +12,8 @@ import java.util.concurrent.locks.StampedLock;
|
|||||||
import static java.lang.Thread.sleep;
|
import static java.lang.Thread.sleep;
|
||||||
|
|
||||||
public class StampedLockDemo {
|
public class StampedLockDemo {
|
||||||
Map<String, String> map = new HashMap<>();
|
private Map<String, String> map = new HashMap<>();
|
||||||
Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
private Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
||||||
|
|
||||||
private final StampedLock lock = new StampedLock();
|
private final StampedLock lock = new StampedLock();
|
||||||
|
|
||||||
@ -44,7 +44,7 @@ public class StampedLockDemo {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String readWithOptimisticLock(String key) throws InterruptedException {
|
private String readWithOptimisticLock(String key) throws InterruptedException {
|
||||||
long stamp = lock.tryOptimisticRead();
|
long stamp = lock.tryOptimisticRead();
|
||||||
String value = map.get(key);
|
String value = map.get(key);
|
||||||
|
|
||||||
|
@ -15,8 +15,8 @@ import static java.lang.Thread.sleep;
|
|||||||
|
|
||||||
public class SynchronizedHashMapWithRWLock {
|
public class SynchronizedHashMapWithRWLock {
|
||||||
|
|
||||||
static Map<String, String> syncHashMap = new HashMap<>();
|
private static Map<String, String> syncHashMap = new HashMap<>();
|
||||||
Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
private Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
||||||
|
|
||||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||||
private final Lock readLock = lock.readLock();
|
private final Lock readLock = lock.readLock();
|
||||||
@ -84,7 +84,7 @@ public class SynchronizedHashMapWithRWLock {
|
|||||||
|
|
||||||
SynchronizedHashMapWithRWLock object;
|
SynchronizedHashMapWithRWLock object;
|
||||||
|
|
||||||
public Reader(SynchronizedHashMapWithRWLock object) {
|
Reader(SynchronizedHashMapWithRWLock object) {
|
||||||
this.object = object;
|
this.object = object;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.concurrent.semaphores;
|
||||||
|
|
||||||
|
import java.util.concurrent.Semaphore;
|
||||||
|
|
||||||
|
class CounterUsingMutex {
|
||||||
|
|
||||||
|
private final Semaphore mutex;
|
||||||
|
private int count;
|
||||||
|
|
||||||
|
CounterUsingMutex() {
|
||||||
|
mutex = new Semaphore(1);
|
||||||
|
count = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void increase() throws InterruptedException {
|
||||||
|
mutex.acquire();
|
||||||
|
this.count = this.count + 1;
|
||||||
|
Thread.sleep(1000);
|
||||||
|
mutex.release();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
int getCount() {
|
||||||
|
return this.count;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean hasQueuedThreads() {
|
||||||
|
return mutex.hasQueuedThreads();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.concurrent.semaphores;
|
||||||
|
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.concurrent.TimedSemaphore;
|
||||||
|
|
||||||
|
class DelayQueueUsingTimedSemaphore {
|
||||||
|
|
||||||
|
private final TimedSemaphore semaphore;
|
||||||
|
|
||||||
|
DelayQueueUsingTimedSemaphore(long period, int slotLimit) {
|
||||||
|
semaphore = new TimedSemaphore(period, TimeUnit.SECONDS, slotLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean tryAdd() {
|
||||||
|
return semaphore.tryAcquire();
|
||||||
|
}
|
||||||
|
|
||||||
|
int availableSlots() {
|
||||||
|
return semaphore.getAvailablePermits();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.concurrent.semaphores;
|
||||||
|
|
||||||
|
import java.util.concurrent.Semaphore;
|
||||||
|
|
||||||
|
class LoginQueueUsingSemaphore {
|
||||||
|
|
||||||
|
private final Semaphore semaphore;
|
||||||
|
|
||||||
|
LoginQueueUsingSemaphore(int slotLimit) {
|
||||||
|
semaphore = new Semaphore(slotLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean tryLogin() {
|
||||||
|
return semaphore.tryAcquire();
|
||||||
|
}
|
||||||
|
|
||||||
|
void logout() {
|
||||||
|
semaphore.release();
|
||||||
|
}
|
||||||
|
|
||||||
|
int availableSlots() {
|
||||||
|
return semaphore.availablePermits();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -2,20 +2,20 @@ package com.baeldung.concurrent.skiplist;
|
|||||||
|
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
|
||||||
public class Event {
|
class Event {
|
||||||
private final ZonedDateTime eventTime;
|
private final ZonedDateTime eventTime;
|
||||||
private final String content;
|
private final String content;
|
||||||
|
|
||||||
public Event(ZonedDateTime eventTime, String content) {
|
Event(ZonedDateTime eventTime, String content) {
|
||||||
this.eventTime = eventTime;
|
this.eventTime = eventTime;
|
||||||
this.content = content;
|
this.content = content;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ZonedDateTime getEventTime() {
|
ZonedDateTime getEventTime() {
|
||||||
return eventTime;
|
return eventTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getContent() {
|
String getContent() {
|
||||||
return content;
|
return content;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,21 +5,21 @@ import java.util.Comparator;
|
|||||||
import java.util.concurrent.ConcurrentNavigableMap;
|
import java.util.concurrent.ConcurrentNavigableMap;
|
||||||
import java.util.concurrent.ConcurrentSkipListMap;
|
import java.util.concurrent.ConcurrentSkipListMap;
|
||||||
|
|
||||||
public class EventWindowSort {
|
class EventWindowSort {
|
||||||
private final ConcurrentSkipListMap<ZonedDateTime, String> events
|
private final ConcurrentSkipListMap<ZonedDateTime, String> events
|
||||||
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
|
= new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli()));
|
||||||
|
|
||||||
public void acceptEvent(Event event) {
|
void acceptEvent(Event event) {
|
||||||
events.put(event.getEventTime(), event.getContent());
|
events.put(event.getEventTime(), event.getContent());
|
||||||
}
|
}
|
||||||
|
|
||||||
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
||||||
return events.tailMap(ZonedDateTime
|
return events.tailMap(ZonedDateTime
|
||||||
.now()
|
.now()
|
||||||
.minusMinutes(1));
|
.minusMinutes(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
||||||
return events.headMap(ZonedDateTime
|
return events.headMap(ZonedDateTime
|
||||||
.now()
|
.now()
|
||||||
.minusMinutes(1));
|
.minusMinutes(1));
|
||||||
|
@ -13,10 +13,10 @@ public class WaitSleepExample {
|
|||||||
private static final Object LOCK = new Object();
|
private static final Object LOCK = new Object();
|
||||||
|
|
||||||
public static void main(String... args) throws InterruptedException {
|
public static void main(String... args) throws InterruptedException {
|
||||||
sleepWaitInSyncronizedBlocks();
|
sleepWaitInSynchronizedBlocks();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void sleepWaitInSyncronizedBlocks() throws InterruptedException {
|
private static void sleepWaitInSynchronizedBlocks() throws InterruptedException {
|
||||||
Thread.sleep(1000); // called on the thread
|
Thread.sleep(1000); // called on the thread
|
||||||
LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
|
LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
|
||||||
|
|
||||||
|
@ -5,13 +5,13 @@ public class BaeldungSynchronizedBlocks {
|
|||||||
private int count = 0;
|
private int count = 0;
|
||||||
private static int staticCount = 0;
|
private static int staticCount = 0;
|
||||||
|
|
||||||
public void performSynchronisedTask() {
|
void performSynchronisedTask() {
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
setCount(getCount() + 1);
|
setCount(getCount() + 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void performStaticSyncTask() {
|
static void performStaticSyncTask() {
|
||||||
synchronized (BaeldungSynchronizedBlocks.class) {
|
synchronized (BaeldungSynchronizedBlocks.class) {
|
||||||
setStaticCount(getStaticCount() + 1);
|
setStaticCount(getStaticCount() + 1);
|
||||||
}
|
}
|
||||||
@ -25,11 +25,11 @@ public class BaeldungSynchronizedBlocks {
|
|||||||
this.count = count;
|
this.count = count;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int getStaticCount() {
|
static int getStaticCount() {
|
||||||
return staticCount;
|
return staticCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void setStaticCount(int staticCount) {
|
private static void setStaticCount(int staticCount) {
|
||||||
BaeldungSynchronizedBlocks.staticCount = staticCount;
|
BaeldungSynchronizedBlocks.staticCount = staticCount;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,17 +5,17 @@ public class BaeldungSynchronizedMethods {
|
|||||||
private int sum = 0;
|
private int sum = 0;
|
||||||
private int syncSum = 0;
|
private int syncSum = 0;
|
||||||
|
|
||||||
public static int staticSum = 0;
|
static int staticSum = 0;
|
||||||
|
|
||||||
public void calculate() {
|
void calculate() {
|
||||||
setSum(getSum() + 1);
|
setSum(getSum() + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void synchronisedCalculate() {
|
synchronized void synchronisedCalculate() {
|
||||||
setSyncSum(getSyncSum() + 1);
|
setSyncSum(getSyncSum() + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static synchronized void syncStaticCalculate() {
|
static synchronized void syncStaticCalculate() {
|
||||||
staticSum = staticSum + 1;
|
staticSum = staticSum + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,11 +27,11 @@ public class BaeldungSynchronizedMethods {
|
|||||||
this.sum = sum;
|
this.sum = sum;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getSyncSum() {
|
int getSyncSum() {
|
||||||
return syncSum;
|
return syncSum;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setSyncSum(int syncSum) {
|
private void setSyncSum(int syncSum) {
|
||||||
this.syncSum = syncSum;
|
this.syncSum = syncSum;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,40 +6,40 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
import java.time.temporal.TemporalAdjusters;
|
import java.time.temporal.TemporalAdjusters;
|
||||||
|
|
||||||
public class UseLocalDate {
|
class UseLocalDate {
|
||||||
|
|
||||||
public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
|
LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
|
||||||
return LocalDate.of(year, month, dayOfMonth);
|
return LocalDate.of(year, month, dayOfMonth);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getLocalDateUsingParseMethod(String representation) {
|
LocalDate getLocalDateUsingParseMethod(String representation) {
|
||||||
return LocalDate.parse(representation);
|
return LocalDate.parse(representation);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getLocalDateFromClock() {
|
LocalDate getLocalDateFromClock() {
|
||||||
LocalDate localDate = LocalDate.now();
|
LocalDate localDate = LocalDate.now();
|
||||||
return localDate;
|
return localDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getNextDay(LocalDate localDate) {
|
LocalDate getNextDay(LocalDate localDate) {
|
||||||
return localDate.plusDays(1);
|
return localDate.plusDays(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getPreviousDay(LocalDate localDate) {
|
LocalDate getPreviousDay(LocalDate localDate) {
|
||||||
return localDate.minus(1, ChronoUnit.DAYS);
|
return localDate.minus(1, ChronoUnit.DAYS);
|
||||||
}
|
}
|
||||||
|
|
||||||
public DayOfWeek getDayOfWeek(LocalDate localDate) {
|
DayOfWeek getDayOfWeek(LocalDate localDate) {
|
||||||
DayOfWeek day = localDate.getDayOfWeek();
|
DayOfWeek day = localDate.getDayOfWeek();
|
||||||
return day;
|
return day;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDate getFirstDayOfMonth() {
|
LocalDate getFirstDayOfMonth() {
|
||||||
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
||||||
return firstDayOfMonth;
|
return firstDayOfMonth;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDateTime getStartOfDay(LocalDate localDate) {
|
LocalDateTime getStartOfDay(LocalDate localDate) {
|
||||||
LocalDateTime startofDay = localDate.atStartOfDay();
|
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||||
return startofDay;
|
return startofDay;
|
||||||
}
|
}
|
||||||
|
@ -5,31 +5,27 @@ import java.time.temporal.ChronoUnit;
|
|||||||
|
|
||||||
public class UseLocalTime {
|
public class UseLocalTime {
|
||||||
|
|
||||||
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
|
||||||
LocalTime localTime = LocalTime.of(hour, min, seconds);
|
return LocalTime.of(hour, min, seconds);
|
||||||
return localTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
||||||
LocalTime localTime = LocalTime.parse(timeRepresentation);
|
return LocalTime.parse(timeRepresentation);
|
||||||
return localTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeFromClock() {
|
private LocalTime getLocalTimeFromClock() {
|
||||||
LocalTime localTime = LocalTime.now();
|
return LocalTime.now();
|
||||||
return localTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime addAnHour(LocalTime localTime) {
|
LocalTime addAnHour(LocalTime localTime) {
|
||||||
LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS);
|
return localTime.plus(1, ChronoUnit.HOURS);
|
||||||
return newTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getHourFromLocalTime(LocalTime localTime) {
|
int getHourFromLocalTime(LocalTime localTime) {
|
||||||
return localTime.getHour();
|
return localTime.getHour();
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
|
||||||
return localTime.withMinute(minute);
|
return localTime.withMinute(minute);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,13 +3,13 @@ package com.baeldung.datetime;
|
|||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.Period;
|
import java.time.Period;
|
||||||
|
|
||||||
public class UsePeriod {
|
class UsePeriod {
|
||||||
|
|
||||||
public LocalDate modifyDates(LocalDate localDate, Period period) {
|
LocalDate modifyDates(LocalDate localDate, Period period) {
|
||||||
return localDate.plus(period);
|
return localDate.plus(period);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) {
|
||||||
return Period.between(localDate1, localDate2);
|
return Period.between(localDate1, localDate2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,12 +8,10 @@ import java.util.Date;
|
|||||||
public class UseToInstant {
|
public class UseToInstant {
|
||||||
|
|
||||||
public LocalDateTime convertDateToLocalDate(Date date) {
|
public LocalDateTime convertDateToLocalDate(Date date) {
|
||||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||||
return localDateTime;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
public LocalDateTime convertDateToLocalDate(Calendar calendar) {
|
||||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||||
return localDateTime;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,10 +4,9 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
|
||||||
public class UseZonedDateTime {
|
class UseZonedDateTime {
|
||||||
|
|
||||||
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
|
||||||
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
|
return ZonedDateTime.of(localDateTime, zoneId);
|
||||||
return zonedDateTime;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.deserialization;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
public class AppleProduct implements Serializable {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated)
|
||||||
|
// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated)
|
||||||
|
|
||||||
|
public String headphonePort;
|
||||||
|
public String thunderboltPort;
|
||||||
|
public String lighteningPort;
|
||||||
|
|
||||||
|
public String getHeadphonePort() {
|
||||||
|
return headphonePort;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getThunderboltPort() {
|
||||||
|
return thunderboltPort;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long getSerialVersionUID() {
|
||||||
|
return serialVersionUID;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.deserialization;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
public class DeserializationUtility {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws ClassNotFoundException, IOException {
|
||||||
|
|
||||||
|
String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA==";
|
||||||
|
System.out.println("Deserializing AppleProduct...");
|
||||||
|
AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj);
|
||||||
|
System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort());
|
||||||
|
System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException {
|
||||||
|
byte[] data = Base64.getDecoder().decode(s);
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
|
||||||
|
Object o = ois.readObject();
|
||||||
|
ois.close();
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.deserialization;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.ObjectOutputStream;
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
public class SerializationUtility {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws ClassNotFoundException, IOException {
|
||||||
|
|
||||||
|
AppleProduct macBook = new AppleProduct();
|
||||||
|
macBook.headphonePort = "headphonePort2020";
|
||||||
|
macBook.thunderboltPort = "thunderboltPort2020";
|
||||||
|
|
||||||
|
String serializedObj = serializeObjectToString(macBook);
|
||||||
|
System.out.println("Serialized AppleProduct object to string:");
|
||||||
|
System.out.println(serializedObj);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String serializeObjectToString(Serializable o) throws IOException {
|
||||||
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
|
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||||
|
oos.writeObject(o);
|
||||||
|
oos.close();
|
||||||
|
return Base64.getEncoder().encodeToString(baos.toByteArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -13,8 +13,7 @@ public class DirectoryMonitoringExample {
|
|||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
|
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
|
||||||
|
|
||||||
|
private static final int POLL_INTERVAL = 500;
|
||||||
public static final int POLL_INTERVAL = 500;
|
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
|
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
|
||||||
|
@ -6,12 +6,12 @@ public class Computer {
|
|||||||
private String color;
|
private String color;
|
||||||
private Integer healty;
|
private Integer healty;
|
||||||
|
|
||||||
public Computer(final int age, final String color) {
|
Computer(final int age, final String color) {
|
||||||
this.age = age;
|
this.age = age;
|
||||||
this.color = color;
|
this.color = color;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Computer(final Integer age, final String color, final Integer healty) {
|
Computer(final Integer age, final String color, final Integer healty) {
|
||||||
this.age = age;
|
this.age = age;
|
||||||
this.color = color;
|
this.color = color;
|
||||||
this.healty = healty;
|
this.healty = healty;
|
||||||
@ -28,7 +28,7 @@ public class Computer {
|
|||||||
this.age = age;
|
this.age = age;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getColor() {
|
String getColor() {
|
||||||
return color;
|
return color;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,11 +36,11 @@ public class Computer {
|
|||||||
this.color = color;
|
this.color = color;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getHealty() {
|
Integer getHealty() {
|
||||||
return healty;
|
return healty;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setHealty(final Integer healty) {
|
void setHealty(final Integer healty) {
|
||||||
this.healty = healty;
|
this.healty = healty;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -72,10 +72,7 @@ public class Computer {
|
|||||||
|
|
||||||
final Computer computer = (Computer) o;
|
final Computer computer = (Computer) o;
|
||||||
|
|
||||||
if (age != null ? !age.equals(computer.age) : computer.age != null) {
|
return (age != null ? age.equals(computer.age) : computer.age == null) && (color != null ? color.equals(computer.color) : computer.color == null);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return color != null ? color.equals(computer.color) : computer.color == null;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,8 +7,8 @@ import java.util.List;
|
|||||||
|
|
||||||
public class ComputerUtils {
|
public class ComputerUtils {
|
||||||
|
|
||||||
public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||||
public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||||
|
|
||||||
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
||||||
|
|
||||||
@ -18,7 +18,7 @@ public class ComputerUtils {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void repair(final Computer computer) {
|
static void repair(final Computer computer) {
|
||||||
if (computer.getHealty() < 50) {
|
if (computer.getHealty() < 50) {
|
||||||
computer.setHealty(100);
|
computer.setHealty(100);
|
||||||
}
|
}
|
||||||
|
@ -13,7 +13,7 @@ public class MacbookPro extends Computer {
|
|||||||
super(age, color);
|
super(age, color);
|
||||||
}
|
}
|
||||||
|
|
||||||
public MacbookPro(Integer age, String color, Integer healty) {
|
MacbookPro(Integer age, String color, Integer healty) {
|
||||||
super(age, color, healty);
|
super(age, color, healty);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -15,7 +15,7 @@ public class TimingDynamicInvocationHandler implements InvocationHandler {
|
|||||||
|
|
||||||
private Object target;
|
private Object target;
|
||||||
|
|
||||||
public TimingDynamicInvocationHandler(Object target) {
|
TimingDynamicInvocationHandler(Object target) {
|
||||||
this.target = target;
|
this.target = target;
|
||||||
|
|
||||||
for(Method method: target.getClass().getDeclaredMethods()) {
|
for(Method method: target.getClass().getDeclaredMethods()) {
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
package com.baeldung.equalshashcode.entities;
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
import java.awt.Color;
|
import java.awt.*;
|
||||||
|
|
||||||
public class Square extends Rectangle {
|
public class Square extends Rectangle {
|
||||||
|
|
||||||
Color color;
|
private Color color;
|
||||||
|
|
||||||
public Square(double width, Color color) {
|
public Square(double width, Color color) {
|
||||||
super(width, width);
|
super(width, width);
|
||||||
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.filesystem.jndi;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.util.Hashtable;
|
||||||
|
|
||||||
|
import javax.naming.Context;
|
||||||
|
import javax.naming.InitialContext;
|
||||||
|
import javax.naming.NamingException;
|
||||||
|
|
||||||
|
public class LookupFSJNDI {
|
||||||
|
private InitialContext ctx = null;
|
||||||
|
|
||||||
|
public LookupFSJNDI() throws NamingException {
|
||||||
|
super();
|
||||||
|
init();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void init() throws NamingException {
|
||||||
|
Hashtable<String, String> env = new Hashtable<String, String>();
|
||||||
|
|
||||||
|
env.put (Context.INITIAL_CONTEXT_FACTORY,
|
||||||
|
"com.sun.jndi.fscontext.RefFSContextFactory");
|
||||||
|
// URI to namespace (actual directory)
|
||||||
|
env.put(Context.PROVIDER_URL, "file:./src/test/resources");
|
||||||
|
|
||||||
|
ctx = new InitialContext(env);
|
||||||
|
}
|
||||||
|
|
||||||
|
public InitialContext getCtx() {
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
public File getFile(String fileName) {
|
||||||
|
File file;
|
||||||
|
try {
|
||||||
|
file = (File)getCtx().lookup(fileName);
|
||||||
|
} catch (NamingException e) {
|
||||||
|
file = null;
|
||||||
|
}
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
import java.lang.annotation.Annotation;
|
||||||
|
|
||||||
|
public class DynamicGreeter implements Greeter {
|
||||||
|
|
||||||
|
private String greet;
|
||||||
|
|
||||||
|
public DynamicGreeter(String greet) {
|
||||||
|
this.greet = greet;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Class<? extends Annotation> annotationType() {
|
||||||
|
return DynamicGreeter.class;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String greet() {
|
||||||
|
return greet;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
public @interface Greeter {
|
||||||
|
|
||||||
|
public String greet() default "";
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
import java.lang.annotation.Annotation;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class GreetingAnnotation {
|
||||||
|
|
||||||
|
private static final String ANNOTATION_METHOD = "annotationData";
|
||||||
|
private static final String ANNOTATION_FIELDS = "declaredAnnotations";
|
||||||
|
private static final String ANNOTATIONS = "annotations";
|
||||||
|
|
||||||
|
public static void main(String ...args) {
|
||||||
|
Greeter greetings = Greetings.class.getAnnotation(Greeter.class);
|
||||||
|
System.err.println("Hello there, " + greetings.greet() + " !!");
|
||||||
|
|
||||||
|
Greeter targetValue = new DynamicGreeter("Good evening");
|
||||||
|
//alterAnnotationValueJDK8(Greetings.class, Greeter.class, targetValue);
|
||||||
|
alterAnnotationValueJDK7(Greetings.class, Greeter.class, targetValue);
|
||||||
|
|
||||||
|
greetings = Greetings.class.getAnnotation(Greeter.class);
|
||||||
|
System.err.println("Hello there, " + greetings.greet() + " !!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static void alterAnnotationValueJDK8(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
|
||||||
|
try {
|
||||||
|
Method method = Class.class.getDeclaredMethod(ANNOTATION_METHOD, null);
|
||||||
|
method.setAccessible(true);
|
||||||
|
|
||||||
|
Object annotationData = method.invoke(targetClass);
|
||||||
|
|
||||||
|
Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS);
|
||||||
|
annotations.setAccessible(true);
|
||||||
|
|
||||||
|
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData);
|
||||||
|
map.put(targetAnnotation, targetValue);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static void alterAnnotationValueJDK7(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
|
||||||
|
try {
|
||||||
|
Field annotations = Class.class.getDeclaredField(ANNOTATIONS);
|
||||||
|
annotations.setAccessible(true);
|
||||||
|
|
||||||
|
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(targetClass);
|
||||||
|
System.out.println(map);
|
||||||
|
map.put(targetAnnotation, targetValue);
|
||||||
|
System.out.println(map);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
package com.baeldung.java.reflection;
|
||||||
|
|
||||||
|
@Greeter(greet="Good morning")
|
||||||
|
public class Greetings {
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,69 @@
|
|||||||
|
package com.baeldung.javanetworking.url;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.net.URLConnection;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class URLDemo {
|
||||||
|
private final Logger log = LoggerFactory.getLogger(URLDemo.class);
|
||||||
|
|
||||||
|
String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||||
|
// parsed locator
|
||||||
|
String URLPROTOCOL = "https";
|
||||||
|
// final static String URLAUTHORITY = "wordpress.org:443";
|
||||||
|
String URLHOST = "wordpress.org";
|
||||||
|
String URLPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||||
|
// final static String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
|
||||||
|
// final static int URLPORT = 443;
|
||||||
|
int URLDEFAULTPORT = 443;
|
||||||
|
String URLQUERY = "replies=3";
|
||||||
|
String URLREFERENCE = "post-2278484";
|
||||||
|
String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
|
||||||
|
|
||||||
|
URL url;
|
||||||
|
URLConnection urlConnection = null;
|
||||||
|
HttpURLConnection connection = null;
|
||||||
|
BufferedReader in = null;
|
||||||
|
String urlContent = "";
|
||||||
|
|
||||||
|
public String testURL(String urlString) throws IOException, IllegalArgumentException {
|
||||||
|
String urlStringCont = "";
|
||||||
|
// comment the if clause if experiment with URL
|
||||||
|
/*if (!URLSTRING.equals(urlString)) {
|
||||||
|
throw new IllegalArgumentException("URL String argument is not proper: " + urlString);
|
||||||
|
}*/
|
||||||
|
// creating URL object
|
||||||
|
url = new URL(urlString);
|
||||||
|
// get URL connection
|
||||||
|
urlConnection = url.openConnection();
|
||||||
|
connection = null;
|
||||||
|
// we can check, if connection is proper type
|
||||||
|
if (urlConnection instanceof HttpURLConnection) {
|
||||||
|
connection = (HttpURLConnection) urlConnection;
|
||||||
|
} else {
|
||||||
|
log.info("Please enter an HTTP URL");
|
||||||
|
throw new IOException("HTTP URL is not correct");
|
||||||
|
}
|
||||||
|
// we can check response code (200 OK is expected)
|
||||||
|
log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
|
||||||
|
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||||
|
String current;
|
||||||
|
|
||||||
|
while ((current = in.readLine()) != null) {
|
||||||
|
urlStringCont += current;
|
||||||
|
}
|
||||||
|
return urlStringCont;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
URLDemo demo = new URLDemo();
|
||||||
|
String content = demo.testURL(demo.URLCOMPOUND);
|
||||||
|
demo.log.info(content);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,71 @@
|
|||||||
|
package com.baeldung.map.iteration;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class MapIteration {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
MapIteration mapIteration = new MapIteration();
|
||||||
|
Map<String, Integer> map = new HashMap<>();
|
||||||
|
|
||||||
|
map.put("One", 1);
|
||||||
|
map.put("Three", 3);
|
||||||
|
map.put("Two", 2);
|
||||||
|
|
||||||
|
System.out.println("Iterating Keys of Map Using KeySet");
|
||||||
|
mapIteration.iterateKeys(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Map Using Entry Set");
|
||||||
|
mapIteration.iterateUsingEntrySet(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Using Iterator and Map Entry");
|
||||||
|
mapIteration.iterateUsingIteratorAndEntry(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Using KeySet and For Each");
|
||||||
|
mapIteration.iterateUsingKeySetAndForeach(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Map Using Lambda Expression");
|
||||||
|
mapIteration.iterateUsingLambda(map);
|
||||||
|
|
||||||
|
System.out.println("Iterating Using Stream API");
|
||||||
|
mapIteration.iterateUsingStreamAPI(map);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateUsingEntrySet(Map<String, Integer> map) {
|
||||||
|
for (Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||||
|
System.out.println(entry.getKey() + ":" + entry.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateUsingLambda(Map<String, Integer> map) {
|
||||||
|
map.forEach((k, v) -> System.out.println((k + ":" + v)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
|
||||||
|
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
Map.Entry<String, Integer> pair = iterator.next();
|
||||||
|
System.out.println(pair.getKey() + ":" + pair.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateUsingKeySetAndForeach(Map<String, Integer> map) {
|
||||||
|
for (String key : map.keySet()) {
|
||||||
|
System.out.println(key + ":" + map.get(key));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateUsingStreamAPI(Map<String, Integer> map) {
|
||||||
|
map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateKeys(Map<String, Integer> map) {
|
||||||
|
for (String key : map.keySet()) {
|
||||||
|
System.out.println(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.maths;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
|
||||||
|
public class BigDecimalImpl {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
BigDecimal serviceTax = new BigDecimal("56.0084578639");
|
||||||
|
serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
|
||||||
|
|
||||||
|
BigDecimal entertainmentTax = new BigDecimal("23.00689");
|
||||||
|
entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
|
||||||
|
|
||||||
|
BigDecimal totalTax = serviceTax.add(entertainmentTax);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.maths;
|
||||||
|
|
||||||
|
import java.math.BigInteger;
|
||||||
|
|
||||||
|
public class BigIntegerImpl {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
|
||||||
|
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
|
||||||
|
|
||||||
|
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
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