Merge branch 'master' of https://github.com/vikasrajput6035/tutorials into BAEL-3832
This commit is contained in:
commit
abd5eaf300
@ -10,7 +10,6 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
||||
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
|
||||
- [How to Determine if a Binary Tree is Balanced](https://www.baeldung.com/java-balanced-binary-tree)
|
||||
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
|
||||
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
|
||||
- [Prim’s Algorithm](https://www.baeldung.com/java-prim-algorithm)
|
||||
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
|
||||
|
@ -39,6 +39,16 @@
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-commons</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
@ -66,6 +76,8 @@
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<guava.version>28.1-jre</guava.version>
|
||||
<jackson.version>2.10.2</jackson.version>
|
||||
<junit.platform.version>1.6.0</junit.platform.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,61 @@
|
||||
package com.baeldung.algorithms.boruvka;
|
||||
|
||||
public class BoruvkaMST {
|
||||
|
||||
private static Tree mst = new Tree();
|
||||
private static int totalWeight;
|
||||
|
||||
public BoruvkaMST(Graph graph) {
|
||||
DisjointSet dSet = new DisjointSet(graph.getNodes());
|
||||
|
||||
// repeat at most log N times or until we have N-1 edges
|
||||
for (int t = 1; t < graph.getNodes() && mst.getEdgeCount() < graph.getNodes() - 1; t = t + t) {
|
||||
|
||||
// foreach tree in forest, find closest edge
|
||||
Edge[] closestEdgeArray = new Edge[graph.getNodes()];
|
||||
for (Edge edge : graph.getAllEdges()) {
|
||||
int first = edge.getFirst();
|
||||
int second = edge.getSecond();
|
||||
int firstParent = dSet.getParent(first);
|
||||
int secondParent = dSet.getParent(second);
|
||||
if (firstParent == secondParent) {
|
||||
continue; // same tree
|
||||
}
|
||||
if (closestEdgeArray[firstParent] == null || edge.getWeight() < closestEdgeArray[firstParent].getWeight()) {
|
||||
closestEdgeArray[firstParent] = edge;
|
||||
}
|
||||
if (closestEdgeArray[secondParent] == null || edge.getWeight() < closestEdgeArray[secondParent].getWeight()) {
|
||||
closestEdgeArray[secondParent] = edge;
|
||||
}
|
||||
}
|
||||
|
||||
// add newly discovered edges to MST
|
||||
for (int i = 0; i < graph.getNodes(); i++) {
|
||||
Edge edge = closestEdgeArray[i];
|
||||
if (edge != null) {
|
||||
int first = edge.getFirst();
|
||||
int second = edge.getSecond();
|
||||
// don't add the same edge twice
|
||||
if (dSet.getParent(first) != dSet.getParent(second)) {
|
||||
mst.addEdge(edge);
|
||||
totalWeight += edge.getWeight();
|
||||
dSet.union(first, second);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Iterable<Edge> getMST() {
|
||||
return mst;
|
||||
}
|
||||
|
||||
public int getTotalWeight() {
|
||||
return totalWeight;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "MST: " + mst.toString() + " | Total Weight: " + totalWeight;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.algorithms.boruvka;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class DisjointSet {
|
||||
|
||||
private int[] nodeParents;
|
||||
private int[] nodeRanks;
|
||||
|
||||
public DisjointSet(int n) {
|
||||
nodeParents = new int[n];
|
||||
nodeRanks = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
nodeParents[i] = i;
|
||||
nodeRanks[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getParent(int node) {
|
||||
while (node != nodeParents[node]) {
|
||||
node = nodeParents[node];
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
public void union(int node1, int node2) {
|
||||
int node1Parent = getParent(node1);
|
||||
int node2Parent = getParent(node2);
|
||||
if (node1Parent == node2Parent) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nodeRanks[node1Parent] < nodeRanks[node2Parent]) {
|
||||
nodeParents[node1Parent] = node2Parent;
|
||||
}
|
||||
else if (nodeRanks[node1Parent] > nodeRanks[node2Parent]) {
|
||||
nodeParents[node2Parent] = node1Parent;
|
||||
}
|
||||
else {
|
||||
nodeParents[node2Parent] = node1Parent;
|
||||
nodeRanks[node1Parent]++;
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "Parent: " + Arrays.toString(nodeParents) + "Rank: " + Arrays.toString(nodeRanks);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.baeldung.algorithms.boruvka;
|
||||
|
||||
public class Edge {
|
||||
|
||||
private final int first;
|
||||
private final int second;
|
||||
private final int weight;
|
||||
|
||||
public Edge(int first, int second, int weight) {
|
||||
this.first = first;
|
||||
this.second = second;
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public double getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public int getFirst() {
|
||||
return first;
|
||||
}
|
||||
|
||||
public int getSecond() {
|
||||
return second;
|
||||
}
|
||||
|
||||
public int getOtherNode(int firstNode) {
|
||||
int secondNode = 0;
|
||||
if (firstNode == first)
|
||||
secondNode = second;
|
||||
else if (firstNode == second)
|
||||
secondNode = first;
|
||||
return secondNode;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return String.format("%d-%d %d", first, second, weight);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
package com.baeldung.algorithms.boruvka;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
|
||||
public class Graph {
|
||||
|
||||
private int nodes;
|
||||
private int edges;
|
||||
private Tree[] trees;
|
||||
|
||||
public Graph(Input jsonGraph) throws JsonParseException, JsonMappingException, IOException {
|
||||
nodes = jsonGraph.getNodes();
|
||||
trees = (Tree[]) new Tree[nodes];
|
||||
for (int i = 0; i < nodes; i++) {
|
||||
trees[i] = new Tree();
|
||||
}
|
||||
|
||||
int edgesFromInput = jsonGraph.getEdges();
|
||||
for (int i = 0; i < edgesFromInput; i++) {
|
||||
int first = jsonGraph.getEdgeList()
|
||||
.get(i)
|
||||
.getFirst();
|
||||
int second = jsonGraph.getEdgeList()
|
||||
.get(i)
|
||||
.getSecond();
|
||||
int weight = jsonGraph.getEdgeList()
|
||||
.get(i)
|
||||
.getWeight();
|
||||
Edge edge = new Edge(first, second, weight);
|
||||
|
||||
trees[first].addEdge(edge);
|
||||
trees[second].addEdge(edge);
|
||||
edges++;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public int getNodes() {
|
||||
return nodes;
|
||||
}
|
||||
|
||||
public int getEdges() {
|
||||
return edges;
|
||||
}
|
||||
|
||||
public Iterable<Edge> iterableTree(int i) {
|
||||
return trees[i];
|
||||
}
|
||||
|
||||
public Iterable<Edge> getAllEdges() {
|
||||
Iterable<Edge> list = new Tree();
|
||||
for (int i = 0; i < nodes; i++) {
|
||||
for (Edge edge : iterableTree(i)) {
|
||||
if (edge.getOtherNode(i) > i) {
|
||||
((Tree) list).addEdge(edge);
|
||||
}
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package com.baeldung.algorithms.boruvka;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Input {
|
||||
private int nodes;
|
||||
private int edges;
|
||||
private List<E> edgeList;
|
||||
|
||||
public int getNodes() {
|
||||
return nodes;
|
||||
}
|
||||
|
||||
public void setNodes(int nodes) {
|
||||
this.nodes = nodes;
|
||||
}
|
||||
|
||||
public int getEdges() {
|
||||
return edges;
|
||||
}
|
||||
|
||||
public void setEdges(int edges) {
|
||||
this.edges = edges;
|
||||
}
|
||||
|
||||
public List<E> getEdgeList() {
|
||||
return edgeList;
|
||||
}
|
||||
|
||||
public void setEdgeList(List<E> edgeList) {
|
||||
this.edgeList = edgeList;
|
||||
}
|
||||
|
||||
static class E {
|
||||
private int first;
|
||||
private int second;
|
||||
private int weight;
|
||||
|
||||
public int getFirst() {
|
||||
return first;
|
||||
}
|
||||
|
||||
public void setFirst(int first) {
|
||||
this.first = first;
|
||||
}
|
||||
|
||||
public int getSecond() {
|
||||
return second;
|
||||
}
|
||||
|
||||
public void setSecond(int second) {
|
||||
this.second = second;
|
||||
}
|
||||
|
||||
public int getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public void setWeight(int weight) {
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
package com.baeldung.algorithms.boruvka;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
public class Tree implements Iterable<Edge> {
|
||||
private Node root;
|
||||
private int edgeCount;
|
||||
|
||||
private static class Node {
|
||||
private Edge edge;
|
||||
private Node next;
|
||||
|
||||
public String toString() {
|
||||
String nextStr = next != null ? next.toString() : "";
|
||||
return edge.toString() + " | " + nextStr;
|
||||
}
|
||||
}
|
||||
|
||||
public Tree() {
|
||||
root = null;
|
||||
edgeCount = 0;
|
||||
}
|
||||
|
||||
public int getEdgeCount() {
|
||||
return edgeCount;
|
||||
}
|
||||
|
||||
public void addEdge(Edge edge) {
|
||||
Node oldRoot = root;
|
||||
root = new Node();
|
||||
root.edge = edge;
|
||||
root.next = oldRoot;
|
||||
edgeCount++;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
String rootStr = root != null ? root.toString() : "";
|
||||
return "Tree: " + rootStr + "Size: " + edgeCount;
|
||||
}
|
||||
|
||||
public Iterator<Edge> iterator() {
|
||||
return new LinkedIterator(root);
|
||||
}
|
||||
|
||||
private class LinkedIterator implements Iterator<Edge> {
|
||||
private Node current;
|
||||
|
||||
public LinkedIterator(Node root) {
|
||||
current = root;
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
return current != null;
|
||||
}
|
||||
|
||||
public Edge next() {
|
||||
Edge edge = current.edge;
|
||||
current = current.next;
|
||||
return edge;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.baeldung.algorithms.boruvka;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class BoruvkaUnitTest {
|
||||
|
||||
private Input input;
|
||||
private static String INPUT_JSON = "/input.json";
|
||||
|
||||
@Before
|
||||
public void convertInputJsonToObject() throws JsonParseException, JsonMappingException, IOException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
StringBuilder jsonStr = new StringBuilder();
|
||||
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(BoruvkaMST.class.getResourceAsStream(INPUT_JSON)))) {
|
||||
String line;
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
jsonStr.append(line)
|
||||
.append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
input = mapper.readValue(jsonStr.toString(), Input.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputGraph_whenBoruvkaPerformed_thenMinimumSpanningTree() throws JsonParseException, JsonMappingException, IOException {
|
||||
Graph graph = new Graph(input);
|
||||
BoruvkaMST boruvkaMST = new BoruvkaMST(graph);
|
||||
|
||||
Tree mst = (Tree) boruvkaMST.getMST();
|
||||
|
||||
assertEquals(30, boruvkaMST.getTotalWeight());
|
||||
assertEquals(4, mst.getEdgeCount());
|
||||
}
|
||||
|
||||
}
|
41
algorithms-miscellaneous-5/src/test/resources/input.json
Normal file
41
algorithms-miscellaneous-5/src/test/resources/input.json
Normal file
@ -0,0 +1,41 @@
|
||||
{
|
||||
"nodes": 5,
|
||||
"edges": 7,
|
||||
"edgeList": [
|
||||
{
|
||||
"first": 0,
|
||||
"second": 1,
|
||||
"weight": 8
|
||||
},
|
||||
{
|
||||
"first": 0,
|
||||
"second": 2,
|
||||
"weight": 5
|
||||
},
|
||||
{
|
||||
"first": 1,
|
||||
"second": 2,
|
||||
"weight": 9
|
||||
},
|
||||
{
|
||||
"first": 1,
|
||||
"second": 3,
|
||||
"weight": 11
|
||||
},
|
||||
{
|
||||
"first": 2,
|
||||
"second": 3,
|
||||
"weight": 15
|
||||
},
|
||||
{
|
||||
"first": 2,
|
||||
"second": 4,
|
||||
"weight": 10
|
||||
},
|
||||
{
|
||||
"first": 3,
|
||||
"second": 4,
|
||||
"weight": 7
|
||||
}
|
||||
]
|
||||
}
|
43
apache-beam/pom.xml
Normal file
43
apache-beam/pom.xml
Normal file
@ -0,0 +1,43 @@
|
||||
<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>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<groupId>com.baeldung.apache</groupId>
|
||||
<artifactId>apache-beam</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.beam</groupId>
|
||||
<artifactId>beam-sdks-java-core</artifactId>
|
||||
<version>${beam.version}</version>
|
||||
</dependency>
|
||||
<!-- runtime scoped -->
|
||||
<dependency>
|
||||
<groupId>org.apache.beam</groupId>
|
||||
<artifactId>beam-runners-direct-java</artifactId>
|
||||
<version>${beam.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<beam.version>2.19.0</beam.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,71 @@
|
||||
package com.baeldung.apache.beam.intro;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.beam.sdk.Pipeline;
|
||||
import org.apache.beam.sdk.io.TextIO;
|
||||
import org.apache.beam.sdk.options.PipelineOptions;
|
||||
import org.apache.beam.sdk.options.PipelineOptionsFactory;
|
||||
import org.apache.beam.sdk.transforms.Count;
|
||||
import org.apache.beam.sdk.transforms.Filter;
|
||||
import org.apache.beam.sdk.transforms.FlatMapElements;
|
||||
import org.apache.beam.sdk.transforms.MapElements;
|
||||
import org.apache.beam.sdk.values.KV;
|
||||
import org.apache.beam.sdk.values.PCollection;
|
||||
import org.apache.beam.sdk.values.TypeDescriptors;
|
||||
|
||||
public class WordCount {
|
||||
|
||||
public static boolean wordCount(String inputFilePath, String outputFilePath) {
|
||||
// We use default options
|
||||
PipelineOptions options = PipelineOptionsFactory.create();
|
||||
// to create the pipeline
|
||||
Pipeline p = Pipeline.create(options);
|
||||
// Here is our workflow graph
|
||||
PCollection<KV<String, Long>> wordCount = p
|
||||
.apply("(1) Read all lines", TextIO.read().from(inputFilePath))
|
||||
.apply("(2) Flatmap to a list of words", FlatMapElements.into(TypeDescriptors.strings())
|
||||
.via(line -> Arrays.asList(line.split("\\s"))))
|
||||
.apply("(3) Lowercase all", MapElements.into(TypeDescriptors.strings())
|
||||
.via(word -> word.toLowerCase()))
|
||||
.apply("(4) Trim punctuations", MapElements.into(TypeDescriptors.strings())
|
||||
.via(word -> trim(word)))
|
||||
.apply("(5) Filter stopwords", Filter.by(word -> !isStopWord(word)))
|
||||
.apply("(6) Count words", Count.perElement());
|
||||
// We convert the PCollection to String so that we can write it to file
|
||||
wordCount.apply(MapElements.into(TypeDescriptors.strings())
|
||||
.via(count -> count.getKey() + " --> " + count.getValue()))
|
||||
.apply(TextIO.write().to(outputFilePath));
|
||||
// Finally we must run the pipeline, otherwise it's only a definition
|
||||
p.run().waitUntilFinish();
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isStopWord(String word) {
|
||||
String[] stopwords = {"am", "are", "is", "i", "you", "me",
|
||||
"he", "she", "they", "them", "was",
|
||||
"were", "from", "in", "of", "to", "be",
|
||||
"him", "her", "us", "and", "or"};
|
||||
for (String stopword : stopwords) {
|
||||
if (stopword.compareTo(word) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static String trim(String word) {
|
||||
return word.replace("(","")
|
||||
.replace(")", "")
|
||||
.replace(",", "")
|
||||
.replace(".", "")
|
||||
.replace("\"", "")
|
||||
.replace("'", "")
|
||||
.replace(":", "")
|
||||
.replace(";", "")
|
||||
.replace("-", "")
|
||||
.replace("?", "")
|
||||
.replace("!", "");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung.apache.beam.intro;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.apache.beam.intro.WordCount;
|
||||
|
||||
public class WordCountUnitTest {
|
||||
|
||||
@Test
|
||||
// @Ignore
|
||||
public void givenInputFile_whenWordCountRuns_thenJobFinishWithoutError() {
|
||||
boolean jobDone = WordCount.wordCount("src/test/resources/wordcount.txt", "target/output");
|
||||
assertTrue(jobDone);
|
||||
}
|
||||
|
||||
}
|
16
apache-beam/src/test/resources/wordcount.txt
Normal file
16
apache-beam/src/test/resources/wordcount.txt
Normal file
@ -0,0 +1,16 @@
|
||||
We've all heard the scare stories about North Korea: the homemade nuclear arsenal built while their people starve and then aimed imprecisely at the rest of the world, a
|
||||
leader so deluded he makes L Ron Hubbard look like a man excessively overburdened with self-doubt and their deep-seated belief that foreign capitalists will invade at any
|
||||
moment and steal all their bauxite.
|
||||
The popular portrayal of this Marxist nation is something like one of the more harrowing episodes of M*A*S*H, only with the cast of wacky characters replaced by twitchy,
|
||||
heavily armed Stalinist meth addicts
|
||||
Cracked would like to take a moment to celebrate the good things about North Korea though, the things that the country's enemies prefer to suppress as part of their politically
|
||||
motivated jealousy. Like how no different to you and me, there's nothing every North Korean likes more after an 18 hour shift at the phosphorus plant than a nice beer to go with
|
||||
his dried fish ration. Ever attentive to its people's needs and in the twinkling of a decade, North Korea's leadership bought, disassembled, transported and rebuilt a British
|
||||
brewery in order to discover and reproduce the secrets of beer and then brew the sweet nectar for its hardworking people, up to 18 bottles at a time. And with minimal fatalities.
|
||||
When was the last time YOUR leader got a beer for YOU, American? (NB do not answer this question if you are Henry Louis Gates).
|
||||
Or how about the fried chicken restaurant that downtown Pyongyang boasts? Yes real chicken, fried and then delivered to your sleeping cube, with optional beer if you like! You
|
||||
don't even have to remove the feathers or pull out the gizzard yourself. Mostly. Americans must eat their fried chicken from a bucket, like swine, sold by a company so secretive
|
||||
that even the very blend of seasoning used is intentionally kept from them. And they call North Korea paranoid?
|
||||
And how many nations would entertain the syphilitic, bourgeois ramblings of Bill Clinton let alone permit him anywhere near their proud womenfolk? Only wise Kim Jong Il could see
|
||||
past Bill's many, many imperfections and treat him with the pity and kindness he deserves, accepting his feeble pleas to pardon the American spies rightly convicted of photographing
|
||||
the nation's sensitive beetroot fields.
|
@ -1,3 +0,0 @@
|
||||
### Relevant Articles
|
||||
|
||||
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)
|
@ -1,5 +0,0 @@
|
||||
## Apache FOP
|
||||
|
||||
This module contains articles about Apache FOP
|
||||
|
||||
### Relevant Articles:
|
@ -1,4 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [OData Protocol Guide](https://www.baeldung.com/odata)
|
||||
- [Intro to OData with Olingo](https://www.baeldung.com/olingo)
|
||||
|
@ -8,4 +8,4 @@ This module contains articles about Apache POI
|
||||
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
|
||||
- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells)
|
||||
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
|
||||
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://github.com/eugenp/tutorials/tree/master/apache-poi)
|
||||
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
|
||||
|
@ -5,7 +5,7 @@ spring.jpa.hibernate.ddl-auto=create
|
||||
logging.file=azure.log
|
||||
logging.level.root=info
|
||||
|
||||
spring.datasource.url=jdbc:h2:file:~/test
|
||||
spring.datasource.url=jdbc:h2:mem:azure-test-db
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
|
||||
|
@ -26,8 +26,8 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<artifactId>hamcrest</artifactId>
|
||||
<version>${hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.java14.patternmatchingforinstanceof;
|
||||
|
||||
public class PatternMatchingForInstanceOf {
|
||||
|
||||
public void performAnimalOperations(Animal animal) {
|
||||
if (animal instanceof Cat cat) {
|
||||
cat.meow();
|
||||
} else if(animal instanceof Dog dog) {
|
||||
dog.woof();
|
||||
}
|
||||
}
|
||||
|
||||
abstract class Animal {
|
||||
}
|
||||
|
||||
final class Cat extends Animal {
|
||||
void meow() {
|
||||
}
|
||||
}
|
||||
|
||||
final class Dog extends Animal {
|
||||
void woof() {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.java14.patternmatchingforinstanceof;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.java14.patternmatchingforinstanceof.PatternMatchingForInstanceOf.Cat;
|
||||
import com.baeldung.java14.patternmatchingforinstanceof.PatternMatchingForInstanceOf.Dog;
|
||||
|
||||
class PatternMatchingForInstanceOfUnitTest {
|
||||
|
||||
@Test
|
||||
void givenAnAnimal_whenTypeIsCat_ThenCatGoesMeow() {
|
||||
Cat animal = mock(Cat.class);
|
||||
|
||||
PatternMatchingForInstanceOf instanceOf = new PatternMatchingForInstanceOf();
|
||||
instanceOf.performAnimalOperations(animal);
|
||||
|
||||
verify(animal).meow();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnAnimal_whenTypeIsDog_ThenDogGoesWoof() {
|
||||
Dog animal = mock(Dog.class);
|
||||
|
||||
PatternMatchingForInstanceOf instanceOf = new PatternMatchingForInstanceOf();
|
||||
instanceOf.performAnimalOperations(animal);
|
||||
|
||||
verify(animal).woof();
|
||||
}
|
||||
|
||||
}
|
@ -3,7 +3,7 @@
|
||||
This module contains articles about Java 8 core features
|
||||
|
||||
### Relevant Articles:
|
||||
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
|
||||
|
||||
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
|
||||
- [Run a Java Application from the Command Line](https://www.baeldung.com/java-run-jar-with-arguments)
|
||||
- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit)
|
||||
|
@ -48,25 +48,6 @@
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
@ -74,8 +55,6 @@
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<!-- plugins -->
|
||||
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -1,5 +0,0 @@
|
||||
## Core Java Arrays (Part 3)
|
||||
|
||||
This module contains articles about Java arrays
|
||||
|
||||
## Relevant Articles
|
@ -66,101 +66,7 @@
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>${maven-jar-plugin.version}</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${maven-shade-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<version>${onejar-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>one-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
@ -250,110 +156,6 @@
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<!-- java instrumentation profiles to build jars -->
|
||||
<profile>
|
||||
<id>buildAgentLoader</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>agentLoader</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/application/AgentLoader.class</include>
|
||||
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>buildApplication</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>application</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/application/MyAtm.class</include>
|
||||
<include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
|
||||
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>buildAgent</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>agent</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
|
||||
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
@ -368,10 +170,6 @@
|
||||
|
||||
<!-- maven and spring plugins -->
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
|
||||
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
||||
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
<source.version>1.8</source.version>
|
||||
<target.version>1.8</target.version>
|
||||
|
@ -15,7 +15,7 @@ import java.util.logging.Logger;
|
||||
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class PrimeNumbersUnitTest {
|
||||
public class PrimeNumbersUnitManualTest {
|
||||
|
||||
private static Logger logger = Logger.getAnonymousLogger();
|
||||
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.suppressed;
|
||||
|
||||
public class ExceptionalResource implements AutoCloseable {
|
||||
|
||||
public void processSomething() {
|
||||
throw new IllegalArgumentException("Thrown from processSomething()");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
throw new NullPointerException("Thrown from close()");
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.baeldung.suppressed;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
|
||||
public class SuppressedExceptionsDemo {
|
||||
|
||||
public static void demoSuppressedException(String filePath) throws IOException {
|
||||
FileInputStream fileIn = null;
|
||||
try {
|
||||
fileIn = new FileInputStream(filePath);
|
||||
} catch (FileNotFoundException e) {
|
||||
throw new IOException(e);
|
||||
} finally {
|
||||
fileIn.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void demoAddSuppressedException(String filePath) throws IOException {
|
||||
Throwable firstException = null;
|
||||
FileInputStream fileIn = null;
|
||||
try {
|
||||
fileIn = new FileInputStream(filePath);
|
||||
} catch (IOException e) {
|
||||
firstException = e;
|
||||
} finally {
|
||||
try {
|
||||
fileIn.close();
|
||||
} catch (NullPointerException npe) {
|
||||
if (firstException != null) {
|
||||
npe.addSuppressed(firstException);
|
||||
}
|
||||
throw npe;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void demoExceptionalResource() throws Exception {
|
||||
try (ExceptionalResource exceptionalResource = new ExceptionalResource()) {
|
||||
exceptionalResource.processSomething();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.suppressed;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.hamcrest.CoreMatchers.instanceOf;
|
||||
|
||||
public class SuppressedExceptionsUnitTest {
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenNonExistentFileName_whenAttemptFileOpen_thenNullPointerException() throws IOException {
|
||||
SuppressedExceptionsDemo.demoSuppressedException("/non-existent-path/non-existent-file.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonExistentFileName_whenAttemptFileOpenStoreSuppressed_thenSuppressedExceptionAvailable() {
|
||||
try {
|
||||
SuppressedExceptionsDemo.demoAddSuppressedException("/non-existent-path/non-existent-file.txt");
|
||||
} catch (Exception e) {
|
||||
assertThat(e, instanceOf(NullPointerException.class));
|
||||
assertEquals(1, e.getSuppressed().length);
|
||||
assertThat(e.getSuppressed()[0], instanceOf(FileNotFoundException.class));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingExceptionalResource_thenSuppressedExceptionAvailable() {
|
||||
try {
|
||||
SuppressedExceptionsDemo.demoExceptionalResource();
|
||||
} catch (Exception e) {
|
||||
assertThat(e, instanceOf(IllegalArgumentException.class));
|
||||
assertEquals("Thrown from processSomething()", e.getMessage());
|
||||
assertEquals(1, e.getSuppressed().length);
|
||||
assertThat(e.getSuppressed()[0], instanceOf(NullPointerException.class));
|
||||
assertEquals("Thrown from close()", e.getSuppressed()[0].getMessage());
|
||||
}
|
||||
}
|
||||
}
|
@ -11,5 +11,4 @@ This module contains articles about Java operators
|
||||
- [Java Compound Operators](https://www.baeldung.com/java-compound-operators)
|
||||
- [The XOR Operator in Java](https://www.baeldung.com/java-xor-operator)
|
||||
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
|
||||
- [Bitwise & vs Logical && Operators](https://www.baeldung.com/bitwise-vs-logical-operators/)
|
||||
|
||||
- [Bitwise & vs Logical && Operators](https://www.baeldung.com/java-bitwise-vs-logical-and)
|
||||
|
@ -0,0 +1,28 @@
|
||||
package com.baeldung.threaddump;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.ThreadInfo;
|
||||
import java.lang.management.ThreadMXBean;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
public class ThreadDump {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
threadDump(true, true);
|
||||
}
|
||||
|
||||
private static void threadDump(boolean lockedMonitors, boolean lockedSynchronizers) throws IOException {
|
||||
Path threadDumpFile = Paths.get("ThreadDump.txt");
|
||||
|
||||
StringBuffer threadDump = new StringBuffer(System.lineSeparator());
|
||||
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
|
||||
for(ThreadInfo threadInfo : threadMXBean.dumpAllThreads(lockedMonitors, lockedSynchronizers)) {
|
||||
threadDump.append(threadInfo.toString());
|
||||
}
|
||||
Files.write(threadDumpFile, threadDump.toString().getBytes());
|
||||
}
|
||||
|
||||
}
|
@ -25,6 +25,12 @@
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.15.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -0,0 +1,63 @@
|
||||
package com.baeldung.replacetokens;
|
||||
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class ReplacingTokens {
|
||||
public static final Pattern TITLE_CASE_PATTERN = Pattern.compile("(?<=^|[^A-Za-z])([A-Z][a-z]*)(?=[^A-Za-z]|$)");
|
||||
|
||||
/**
|
||||
* Iterate over the title case tokens in the input and replace them with lowercase
|
||||
* @param original the original string
|
||||
* @return a string with words replaced with their lowercase equivalents
|
||||
*/
|
||||
public static String replaceTitleCaseWithLowerCase(String original) {
|
||||
int lastIndex = 0;
|
||||
StringBuilder output = new StringBuilder();
|
||||
Matcher matcher = TITLE_CASE_PATTERN.matcher(original);
|
||||
while (matcher.find()) {
|
||||
output.append(original, lastIndex, matcher.start())
|
||||
.append(convert(matcher.group(1)));
|
||||
|
||||
lastIndex = matcher.end();
|
||||
}
|
||||
if (lastIndex < original.length()) {
|
||||
output.append(original, lastIndex, original.length());
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a token found into its desired lowercase
|
||||
* @param token the token to convert
|
||||
* @return the converted token
|
||||
*/
|
||||
private static String convert(String token) {
|
||||
return token.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace all the tokens in an input using the algorithm provided for each
|
||||
* @param original original string
|
||||
* @param tokenPattern the pattern to match with
|
||||
* @param converter the conversion to apply
|
||||
* @return the substituted string
|
||||
*/
|
||||
public static String replaceTokens(String original, Pattern tokenPattern,
|
||||
Function<Matcher, String> converter) {
|
||||
int lastIndex = 0;
|
||||
StringBuilder output = new StringBuilder();
|
||||
Matcher matcher = tokenPattern.matcher(original);
|
||||
while (matcher.find()) {
|
||||
output.append(original, lastIndex, matcher.start())
|
||||
.append(converter.apply(matcher));
|
||||
|
||||
lastIndex = matcher.end();
|
||||
}
|
||||
if (lastIndex < original.length()) {
|
||||
output.append(original, lastIndex, original.length());
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,79 @@
|
||||
package com.baeldung.replacetokens;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static com.baeldung.replacetokens.ReplacingTokens.TITLE_CASE_PATTERN;
|
||||
import static com.baeldung.replacetokens.ReplacingTokens.replaceTokens;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ReplacingTokensUnitTest {
|
||||
private static final String EXAMPLE_INPUT = "First 3 Capital Words! then 10 TLAs, I Found";
|
||||
private static final String EXAMPLE_INPUT_PROCESSED = "first 3 capital words! then 10 TLAs, i found";
|
||||
|
||||
@Test
|
||||
public void whenFindMatches_thenTitleWordsFound() {
|
||||
Matcher matcher = TITLE_CASE_PATTERN.matcher(EXAMPLE_INPUT);
|
||||
List<String> matches = new ArrayList<>();
|
||||
while (matcher.find()) {
|
||||
matches.add(matcher.group(1));
|
||||
}
|
||||
|
||||
assertThat(matches)
|
||||
.containsExactly("First", "Capital", "Words", "I", "Found");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exploreMatches() {
|
||||
Matcher matcher = TITLE_CASE_PATTERN.matcher(EXAMPLE_INPUT);
|
||||
while (matcher.find()) {
|
||||
System.out.println("Match: " + matcher.group(0));
|
||||
System.out.println("Start: " + matcher.start());
|
||||
System.out.println("End: " + matcher.end());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceTokensWithLowerCase() {
|
||||
assertThat(ReplacingTokens.replaceTitleCaseWithLowerCase(EXAMPLE_INPUT))
|
||||
.isEqualTo(EXAMPLE_INPUT_PROCESSED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceTokensWithLowerCaseUsingGeneralPurpose() {
|
||||
assertThat(replaceTokens("First 3 Capital Words! then 10 TLAs, I Found",
|
||||
TITLE_CASE_PATTERN,
|
||||
match -> match.group(1).toLowerCase()))
|
||||
.isEqualTo("first 3 capital words! then 10 TLAs, i found");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void escapeRegexCharacters() {
|
||||
Pattern regexCharacters = Pattern.compile("[<(\\[{\\\\^\\-=$!|\\]})?*+.>]");
|
||||
|
||||
assertThat(replaceTokens("A regex character like [",
|
||||
regexCharacters,
|
||||
match -> "\\" + match.group()))
|
||||
.isEqualTo("A regex character like \\[");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void replacePlaceholders() {
|
||||
Pattern placeholderPattern = Pattern.compile("\\$\\{(?<placeholder>[A-Za-z0-9-_]+)}");
|
||||
|
||||
Map<String, String> placeholderValues = new HashMap<>();
|
||||
placeholderValues.put("name", "Bill");
|
||||
placeholderValues.put("company", "Baeldung");
|
||||
|
||||
assertThat(replaceTokens("Hi ${name} at ${company}",
|
||||
placeholderPattern,
|
||||
match -> placeholderValues.get(match.group("placeholder"))))
|
||||
.isEqualTo("Hi Bill at Baeldung");
|
||||
}
|
||||
}
|
17
core-java-modules/core-java-security-2/pom.xml
Normal file
17
core-java-modules/core-java-security-2/pom.xml
Normal file
@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-security-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-security-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
</project>
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.jaas;
|
||||
|
||||
import javax.security.auth.callback.*;
|
||||
import java.io.Console;
|
||||
import java.io.IOException;
|
||||
|
||||
public class ConsoleCallbackHandler implements CallbackHandler {
|
||||
|
||||
@Override
|
||||
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
|
||||
Console console = System.console();
|
||||
for (Callback callback : callbacks) {
|
||||
if (callback instanceof NameCallback) {
|
||||
NameCallback nameCallback = (NameCallback) callback;
|
||||
nameCallback.setName(console.readLine(nameCallback.getPrompt()));
|
||||
} else if (callback instanceof PasswordCallback) {
|
||||
PasswordCallback passwordCallback = (PasswordCallback) callback;
|
||||
passwordCallback.setPassword(console.readPassword(passwordCallback.getPrompt()));
|
||||
} else {
|
||||
throw new UnsupportedCallbackException(callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.jaas;
|
||||
|
||||
import javax.security.auth.Subject;
|
||||
import javax.security.auth.login.LoginException;
|
||||
|
||||
public class JaasAuthentication {
|
||||
|
||||
public static void main(String[] args) throws LoginException {
|
||||
LoginService loginService = new LoginService();
|
||||
Subject subject = loginService.login();
|
||||
System.out.println(subject.getPrincipals().iterator().next() + " sucessfully logeed in");
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.jaas;
|
||||
|
||||
import javax.security.auth.Subject;
|
||||
import javax.security.auth.login.LoginException;
|
||||
import java.security.PrivilegedAction;
|
||||
|
||||
public class JaasAuthorization {
|
||||
|
||||
public static void main(String[] args) throws LoginException {
|
||||
|
||||
LoginService loginService = new LoginService();
|
||||
Subject subject = loginService.login();
|
||||
|
||||
PrivilegedAction privilegedAction = new ResourceAction();
|
||||
Subject.doAsPrivileged(subject, privilegedAction, null);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.jaas;
|
||||
|
||||
import javax.security.auth.Subject;
|
||||
import javax.security.auth.login.LoginContext;
|
||||
import javax.security.auth.login.LoginException;
|
||||
|
||||
public class LoginService {
|
||||
|
||||
public Subject login() throws LoginException {
|
||||
LoginContext loginContext = new LoginContext("jaasApplication", new ConsoleCallbackHandler());
|
||||
loginContext.login();
|
||||
return loginContext.getSubject();
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.jaas;
|
||||
|
||||
import java.security.PrivilegedAction;
|
||||
|
||||
public class ResourceAction implements PrivilegedAction {
|
||||
@Override
|
||||
public Object run() {
|
||||
SecurityManager sm = System.getSecurityManager();
|
||||
if (sm != null) {
|
||||
sm.checkPermission(new ResourcePermission("test_resource"));
|
||||
}
|
||||
System.out.println("I have access to test_resource !");
|
||||
return null;
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.jaas;
|
||||
|
||||
import java.security.BasicPermission;
|
||||
|
||||
public class ResourcePermission extends BasicPermission {
|
||||
public ResourcePermission(String name) {
|
||||
super(name);
|
||||
}
|
||||
}
|
@ -0,0 +1,74 @@
|
||||
package com.baeldung.jaas.loginmodule;
|
||||
|
||||
import com.sun.security.auth.UserPrincipal;
|
||||
|
||||
import javax.security.auth.Subject;
|
||||
import javax.security.auth.callback.*;
|
||||
import javax.security.auth.login.LoginException;
|
||||
import javax.security.auth.spi.LoginModule;
|
||||
import java.io.IOException;
|
||||
import java.security.Principal;
|
||||
import java.util.Map;
|
||||
|
||||
public class InMemoryLoginModule implements LoginModule {
|
||||
|
||||
private static final String USERNAME = "testuser";
|
||||
private static final String PASSWORD = "testpassword";
|
||||
|
||||
private Subject subject;
|
||||
private CallbackHandler callbackHandler;
|
||||
private Map<String, ?> sharedState;
|
||||
private Map<String, ?> options;
|
||||
|
||||
private String username;
|
||||
private boolean loginSucceeded = false;
|
||||
private Principal userPrincipal;
|
||||
|
||||
@Override
|
||||
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
|
||||
Map<String, ?> options) {
|
||||
this.subject = subject;
|
||||
this.callbackHandler = callbackHandler;
|
||||
this.sharedState = sharedState;
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean login() throws LoginException {
|
||||
NameCallback nameCallback = new NameCallback("username: ");
|
||||
PasswordCallback passwordCallback = new PasswordCallback("password: ", false);
|
||||
try {
|
||||
callbackHandler.handle(new Callback[]{nameCallback, passwordCallback});
|
||||
username = nameCallback.getName();
|
||||
String password = new String(passwordCallback.getPassword());
|
||||
if (USERNAME.equals(username) && PASSWORD.equals(password)) {
|
||||
loginSucceeded = true;
|
||||
}
|
||||
} catch (IOException | UnsupportedCallbackException e) {
|
||||
throw new LoginException("Can't login");
|
||||
}
|
||||
return loginSucceeded;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean commit() throws LoginException {
|
||||
if (!loginSucceeded) {
|
||||
return false;
|
||||
}
|
||||
userPrincipal = new UserPrincipal(username);
|
||||
subject.getPrincipals().add(userPrincipal);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean abort() throws LoginException {
|
||||
logout();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean logout() throws LoginException {
|
||||
subject.getPrincipals().remove(userPrincipal);
|
||||
return false;
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
jaasApplication {
|
||||
com.baeldung.jaas.loginmodule.InMemoryLoginModule required debug=true;
|
||||
};
|
@ -0,0 +1,14 @@
|
||||
grant codebase "file:./target/core-java-security-2-0.1.0-SNAPSHOT.jar" {
|
||||
permission javax.security.auth.AuthPermission "createLoginContext.jaasApplication";
|
||||
permission javax.security.auth.AuthPermission "doAsPrivileged";
|
||||
permission java.lang.RuntimePermission "readFileDescriptor";
|
||||
permission java.lang.RuntimePermission "writeFileDescriptor";
|
||||
};
|
||||
|
||||
grant codebase "file:./target/core-java-security-2-0.1.0-SNAPSHOT.jar" {
|
||||
permission javax.security.auth.AuthPermission "modifyPrincipals";
|
||||
};
|
||||
|
||||
grant principal com.sun.security.auth.UserPrincipal "testuser" {
|
||||
permission com.baeldung.jaas.ResourcePermission "test_resource";
|
||||
};
|
@ -28,8 +28,8 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<artifactId>hamcrest</artifactId>
|
||||
<version>${hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
@ -44,8 +44,8 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<artifactId>hamcrest</artifactId>
|
||||
<version>${hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
@ -48,8 +48,8 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<artifactId>hamcrest</artifactId>
|
||||
<version>${hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -40,20 +40,6 @@
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>${maven-jar-plugin.version}</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
@ -115,7 +101,6 @@
|
||||
|
||||
<!-- maven plugins -->
|
||||
<sun-tools.version>1.8.0</sun-tools.version>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -11,7 +11,7 @@
|
||||
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
||||
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
||||
- [Quick Guide to the Java Stack](http://www.baeldung.com/java-stack)
|
||||
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
|
||||
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||
- [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
|
||||
|
@ -90,101 +90,6 @@
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>${maven-jar-plugin.version}</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${maven-shade-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<version>${onejar-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>one-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
@ -273,111 +178,6 @@
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<!-- java instrumentation profiles to build jars -->
|
||||
<profile>
|
||||
<id>buildAgentLoader</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>agentLoader</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/application/AgentLoader.class</include>
|
||||
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>buildApplication</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>application</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/application/MyAtm.class</include>
|
||||
<include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
|
||||
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>buildAgent</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>agent</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
|
||||
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
@ -392,10 +192,6 @@
|
||||
<javamoney.moneta.version>1.1</javamoney.moneta.version>
|
||||
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
|
||||
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
||||
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
<source.version>1.8</source.version>
|
||||
<target.version>1.8</target.version>
|
||||
|
@ -1,123 +1,153 @@
|
||||
package com.baeldung.stack;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
import java.util.Stack;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
public class StackUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenStackIsCreated_thenItHasSize0() {
|
||||
Stack intStack = new Stack();
|
||||
public void whenStackIsCreated_thenItHasSizeZero() {
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
|
||||
assertEquals(0, intStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStack_whenElementIsPushed_thenStackSizeisIncreased() {
|
||||
Stack intStack = new Stack();
|
||||
public void whenElementIsPushed_thenStackSizeIsIncreased() {
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
intStack.push(1);
|
||||
|
||||
assertEquals(1, intStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStack_whenMultipleElementsArePushed_thenStackSizeisIncreased() {
|
||||
Stack intStack = new Stack();
|
||||
public void whenMultipleElementsArePushed_thenStackSizeIsIncreased() {
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
|
||||
|
||||
boolean result = intStack.addAll(intList);
|
||||
|
||||
assertTrue(result);
|
||||
assertEquals(7, intList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
intStack.push(5);
|
||||
intStack.pop();
|
||||
|
||||
Integer element = intStack.pop();
|
||||
|
||||
assertEquals(Integer.valueOf(5), element);
|
||||
assertTrue(intStack.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
intStack.push(5);
|
||||
intStack.peek();
|
||||
|
||||
Integer element = intStack.peek();
|
||||
|
||||
assertEquals(Integer.valueOf(5), element);
|
||||
assertEquals(1, intStack.search(5));
|
||||
assertEquals(1, intStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenElementIsOnStack_thenSearchReturnsItsDistanceFromTheTop() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
intStack.push(5);
|
||||
assertEquals(1, intStack.search(5));
|
||||
intStack.push(8);
|
||||
|
||||
assertEquals(2, intStack.search(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenElementIsOnStack_thenIndexOfReturnsItsIndex() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
intStack.push(5);
|
||||
|
||||
int indexOf = intStack.indexOf(5);
|
||||
|
||||
assertEquals(0, indexOf);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultipleElementsAreOnStack_thenIndexOfReturnsLastElementIndex() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
intStack.push(5);
|
||||
intStack.push(5);
|
||||
intStack.push(5);
|
||||
|
||||
int lastIndexOf = intStack.lastIndexOf(5);
|
||||
|
||||
assertEquals(2, lastIndexOf);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElementOnStack_whenRemoveElementIsInvoked_thenElementIsRemoved() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
public void whenRemoveElementIsInvoked_thenElementIsRemoved() {
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
intStack.push(5);
|
||||
intStack.push(5);
|
||||
|
||||
intStack.removeElement(5);
|
||||
|
||||
assertEquals(1, intStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElementOnStack_whenRemoveElementAtIsInvoked_thenElementIsRemoved() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
public void whenRemoveElementAtIsInvoked_thenElementIsRemoved() {
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
intStack.push(5);
|
||||
intStack.push(7);
|
||||
|
||||
intStack.removeElementAt(1);
|
||||
|
||||
assertEquals(-1, intStack.search(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElementsOnStack_whenRemoveAllElementsIsInvoked_thenAllElementsAreRemoved() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
public void whenRemoveAllElementsIsInvoked_thenAllElementsAreRemoved() {
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
intStack.push(5);
|
||||
intStack.push(7);
|
||||
|
||||
intStack.removeAllElements();
|
||||
|
||||
assertTrue(intStack.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElementsOnStack_whenRemoveAllIsInvoked_thenAllElementsFromCollectionAreRemoved() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
|
||||
intStack.addAll(intList);
|
||||
intStack.add(500);
|
||||
|
||||
intStack.removeAll(intList);
|
||||
|
||||
assertEquals(1, intStack.size());
|
||||
assertEquals(1, intStack.search(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElementsOnStack_whenRemoveIfIsInvoked_thenAllElementsSatysfyingConditionAreRemoved() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
public void whenRemoveIfIsInvoked_thenAllElementsSatysfyingConditionAreRemoved() {
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
|
||||
intStack.addAll(intList);
|
||||
|
||||
intStack.removeIf(element -> element < 6);
|
||||
|
||||
assertEquals(2, intStack.size());
|
||||
}
|
||||
|
||||
@ -126,12 +156,28 @@ public class StackUnitTest {
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
|
||||
intStack.addAll(intList);
|
||||
|
||||
ListIterator<Integer> it = intStack.listIterator();
|
||||
Stack<Integer> result = new Stack();
|
||||
|
||||
Stack<Integer> result = new Stack<>();
|
||||
while(it.hasNext()) {
|
||||
result.push(it.next());
|
||||
}
|
||||
|
||||
assertThat(result, equalTo(intStack));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStackIsFiltered_allElementsNotSatisfyingFilterConditionAreDiscarded() {
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
List<Integer> inputIntList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 9, 10);
|
||||
intStack.addAll(inputIntList);
|
||||
|
||||
List<Integer> filtered = intStack
|
||||
.stream()
|
||||
.filter(element -> element <= 3)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(3, filtered.size());
|
||||
}
|
||||
}
|
||||
|
@ -100,6 +100,7 @@
|
||||
<module>core-java-reflection</module>
|
||||
|
||||
<module>core-java-security</module>
|
||||
<module>core-java-security-2</module>
|
||||
<module>core-java-streams</module>
|
||||
<module>core-java-streams-2</module>
|
||||
<module>core-java-streams-3</module>
|
||||
|
@ -1,5 +0,0 @@
|
||||
## Core Kotlin
|
||||
|
||||
This module contains articles about core Kotlin.
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.algorithms.balancedbinarytree;
|
||||
package com.baeldung.avltree;
|
||||
|
||||
public class AVLTree {
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.algorithms.balancedbinarytree;
|
||||
package com.baeldung.avltree;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
@ -159,8 +159,8 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<artifactId>hamcrest</artifactId>
|
||||
<version>${hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -0,0 +1,95 @@
|
||||
package com.baeldung.gson.jsoncompare;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class JsonCompareUnitTest {
|
||||
@Test
|
||||
public void givenJsonStrings_whenCompared_thenNotEqual() {
|
||||
String string1 = "{\"fullName\": \"Emily Jenkins\", \"age\": 27 }";
|
||||
String string2 = "{\"fullName\": \"Emily Jenkins\", \"age\": 27}";
|
||||
|
||||
assertNotEquals(string1, string2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdenticalSimpleObjects_whenCompared_thenEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27 }}";
|
||||
String string2 = "{\"customer\": {\"id\": \"44521\", \"fullName\": \"Emily Jenkins\",\"age\": 27}}";
|
||||
|
||||
assertTrue(parser.parse(string1)
|
||||
.isJsonObject());
|
||||
assertEquals(parser.parse(string1), parser.parse(string2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameObjectsInDifferentOrder_whenCompared_thenEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27 }}";
|
||||
String string2 = "{\"customer\": {\"id\": \"44521\",\"age\": 27, \"fullName\": \"Emily Jenkins\" }}";
|
||||
|
||||
JsonElement json1 = parser.parse(string1);
|
||||
JsonElement json2 = parser.parse(string2);
|
||||
|
||||
assertEquals(json1, json2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdenticalArrays_whenCompared_thenEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "[10, 20, 30]";
|
||||
String string2 = "[10, 20, 30]";
|
||||
|
||||
assertTrue(parser.parse(string1)
|
||||
.isJsonArray());
|
||||
assertEquals(parser.parse(string1), parser.parse(string2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArraysInDifferentOrder_whenCompared_thenNotEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "[20, 10, 30]";
|
||||
String string2 = "[10, 20, 30]";
|
||||
|
||||
assertNotEquals(parser.parse(string1), parser.parse(string2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdenticalNestedObjects_whenCompared_thenEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"fav_product\": \"Coke\", \"last_buy\": \"2012-04-23\"}}}";
|
||||
String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"fav_product\": \"Coke\"}}}";
|
||||
|
||||
JsonElement json1 = parser.parse(string1);
|
||||
JsonElement json2 = parser.parse(string2);
|
||||
|
||||
assertEquals(json1, json2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdenticalNestedObjectsWithArray_whenCompared_thenEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}";
|
||||
String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}";
|
||||
|
||||
JsonElement json1 = parser.parse(string1);
|
||||
JsonElement json2 = parser.parse(string2);
|
||||
|
||||
assertEquals(json1, json2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNestedObjectsDifferentArrayOrder_whenCompared_thenNotEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}";
|
||||
String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"eggs\", \"banana\"]}}}";
|
||||
|
||||
JsonElement json1 = parser.parse(string1);
|
||||
JsonElement json2 = parser.parse(string2);
|
||||
|
||||
assertNotEquals(json1, json2);
|
||||
}
|
||||
}
|
@ -13,7 +13,7 @@ This module contains articles about numbers in Java.
|
||||
- [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers)
|
||||
- [Finding the Least Common Multiple in Java](https://www.baeldung.com/java-least-common-multiple)
|
||||
- [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers)
|
||||
- [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers)
|
||||
- [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers-in-range)
|
||||
- [Listing Numbers Within a Range in Java](https://www.baeldung.com/java-listing-numbers-within-a-range)
|
||||
- [Fibonacci Series in Java](https://www.baeldung.com/java-fibonacci)
|
||||
- More articles: [[<-- prev]](/../java-numbers)
|
||||
|
1
jhipster-5/bookstore-monolith/.gitignore
vendored
1
jhipster-5/bookstore-monolith/.gitignore
vendored
@ -14,6 +14,7 @@ node_modules/
|
||||
npm-debug.log.*
|
||||
/.awcache/*
|
||||
/.cache-loader/*
|
||||
package-lock.json
|
||||
|
||||
######################
|
||||
# SASS
|
||||
|
18244
jhipster-5/bookstore-monolith/package-lock.json
generated
18244
jhipster-5/bookstore-monolith/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -20,11 +20,11 @@ import static java.lang.String.format;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Unit tests for the UTC Hibernate configuration.
|
||||
* Tests for the UTC Hibernate configuration.
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = BookstoreApp.class)
|
||||
public class HibernateTimeZoneTest {
|
||||
public class HibernateTimeZoneIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private DateTimeWrapperRepository dateTimeWrapperRepository;
|
@ -83,7 +83,6 @@
|
||||
<artifactId>moshi-adapters</artifactId>
|
||||
<version>${moshi.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.jcabi</groupId>
|
||||
<artifactId>jcabi-aspects</artifactId>
|
||||
@ -95,6 +94,16 @@
|
||||
<version>${aspectjrt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.takes</groupId>
|
||||
<artifactId>takes</artifactId>
|
||||
<version>${takes.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.velocity</groupId>
|
||||
<artifactId>velocity-engine-core</artifactId>
|
||||
<version>${velocity-engine-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
@ -132,8 +141,55 @@
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/webapp</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>reload</id>
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>src/main/webapp</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-server</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>java</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.takes.TakesApp</mainClass>
|
||||
<cleanupDaemonThreads>false</cleanupDaemonThreads>
|
||||
<arguments>
|
||||
<argument>--port=${port}</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<jcommander.version>1.78</jcommander.version>
|
||||
<lombok.version>1.18.6</lombok.version>
|
||||
@ -151,5 +207,9 @@
|
||||
<jcabi-maven-plugin.version>0.14.1</jcabi-maven-plugin.version>
|
||||
<aspectjtools.version>1.9.2</aspectjtools.version>
|
||||
<aspectjweaver.version>1.9.2</aspectjweaver.version>
|
||||
|
||||
<takes.version>1.19</takes.version>
|
||||
<velocity-engine-core.version>2.2</velocity-engine-core.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
42
libraries-3/src/main/java/com/baeldung/takes/TakesApp.java
Normal file
42
libraries-3/src/main/java/com/baeldung/takes/TakesApp.java
Normal file
@ -0,0 +1,42 @@
|
||||
package com.baeldung.takes;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.takes.Response;
|
||||
import org.takes.facets.fallback.Fallback;
|
||||
import org.takes.facets.fallback.FbChain;
|
||||
import org.takes.facets.fallback.FbStatus;
|
||||
import org.takes.facets.fallback.RqFallback;
|
||||
import org.takes.facets.fallback.TkFallback;
|
||||
import org.takes.facets.fork.FkRegex;
|
||||
import org.takes.facets.fork.TkFork;
|
||||
import org.takes.http.Exit;
|
||||
import org.takes.http.FtBasic;
|
||||
import org.takes.misc.Opt;
|
||||
import org.takes.rs.RsText;
|
||||
|
||||
public final class TakesApp {
|
||||
|
||||
public static void main(final String... args) throws IOException, SQLException {
|
||||
new FtBasic(
|
||||
new TkFallback(
|
||||
new TkFork(
|
||||
new FkRegex("/", new TakesHelloWorld()),
|
||||
new FkRegex("/index", new TakesIndex()),
|
||||
new FkRegex("/contact", new TakesContact())
|
||||
),
|
||||
new FbChain(
|
||||
new FbStatus(404, new RsText("Page Not Found")),
|
||||
new FbStatus(405, new RsText("Method Not Allowed")),
|
||||
new Fallback() {
|
||||
@Override
|
||||
public Opt<Response> route(final RqFallback req) {
|
||||
return new Opt.Single<Response>(new RsText(req.throwable().getMessage()));
|
||||
}
|
||||
})
|
||||
), 6060
|
||||
).start(Exit.NEVER);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.takes;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.takes.Request;
|
||||
import org.takes.Response;
|
||||
import org.takes.Take;
|
||||
import org.takes.rs.RsWithBody;
|
||||
import org.takes.rs.RsWithStatus;
|
||||
import org.takes.rs.RsWithType;
|
||||
|
||||
public final class TakesContact implements Take {
|
||||
|
||||
@Override
|
||||
public Response act(Request req) throws IOException {
|
||||
return new RsWithStatus(
|
||||
new RsWithType(
|
||||
new RsWithBody("Contact us at https://www.baeldung.com"),
|
||||
"text/html"), 200);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.takes;
|
||||
|
||||
import org.takes.Request;
|
||||
import org.takes.Response;
|
||||
import org.takes.Take;
|
||||
import org.takes.rs.RsText;
|
||||
|
||||
public class TakesHelloWorld implements Take {
|
||||
|
||||
@Override
|
||||
public Response act(final Request request) {
|
||||
return new RsText("Hello, world!");
|
||||
}
|
||||
|
||||
}
|
24
libraries-3/src/main/java/com/baeldung/takes/TakesIndex.java
Normal file
24
libraries-3/src/main/java/com/baeldung/takes/TakesIndex.java
Normal file
@ -0,0 +1,24 @@
|
||||
package com.baeldung.takes;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.takes.Request;
|
||||
import org.takes.Response;
|
||||
import org.takes.Take;
|
||||
import org.takes.rq.form.RqFormSmart;
|
||||
import org.takes.rs.RsHtml;
|
||||
import org.takes.rs.RsVelocity;
|
||||
|
||||
public final class TakesIndex implements Take {
|
||||
|
||||
@Override
|
||||
public Response act(final Request req) throws IOException {
|
||||
RqFormSmart form = new RqFormSmart(req);
|
||||
String username = form.single("username");
|
||||
return new RsHtml(
|
||||
new RsVelocity(this.getClass().getResource("/templates/index.vm"),
|
||||
new RsVelocity.Pair("username", username))
|
||||
);
|
||||
}
|
||||
|
||||
}
|
9
libraries-3/src/main/webapp/templates/index.vm
Normal file
9
libraries-3/src/main/webapp/templates/index.vm
Normal file
@ -0,0 +1,9 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Index</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Takes Web Application</h1>
|
||||
<h2>Welcome, ${username}</h2>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.takes;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.junit.Test;
|
||||
import org.takes.http.FtRemote;
|
||||
|
||||
public class TakesAppIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenTake_whenRunRemoteServer_thenRespond() throws Exception {
|
||||
new FtRemote(new TakesContact()).exec(
|
||||
new FtRemote.Script() {
|
||||
@Override
|
||||
public void exec(final URI home) throws IOException {
|
||||
HttpClient client = HttpClientBuilder.create().build();
|
||||
HttpResponse response = client.execute(new HttpGet(home));
|
||||
int statusCode = response.getStatusLine().getStatusCode();
|
||||
HttpEntity entity = response.getEntity();
|
||||
String result = EntityUtils.toString(entity);
|
||||
|
||||
assertEquals(200, statusCode);
|
||||
assertEquals("Contact us at https://www.baeldung.com", result);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.takes;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.takes.rq.RqFake;
|
||||
import org.takes.rs.RsPrint;
|
||||
|
||||
public class TakesContactUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTake_whenInvokeActMethod_thenRespond() throws Exception {
|
||||
final String resp = new RsPrint(new TakesContact().act(new RqFake())).printBody();
|
||||
assertEquals("Contact us at https://www.baeldung.com", resp);
|
||||
}
|
||||
|
||||
}
|
@ -435,7 +435,23 @@
|
||||
<artifactId>reflections</artifactId>
|
||||
<version>${reflections.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.uber.nullaway</groupId>
|
||||
<artifactId>nullaway</artifactId>
|
||||
<version>0.3.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.plexus</groupId>
|
||||
<artifactId>plexus-compiler-javac-errorprone</artifactId>
|
||||
<version>2.8</version>
|
||||
</dependency>
|
||||
<!-- override plexus-compiler-javac-errorprone's dependency on
|
||||
Error Prone with the latest version -->
|
||||
<dependency>
|
||||
<groupId>com.google.errorprone</groupId>
|
||||
<artifactId>error_prone_core</artifactId>
|
||||
<version>2.1.3</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
@ -552,6 +568,47 @@
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5</version>
|
||||
<configuration>
|
||||
<compilerId>javac-with-errorprone</compilerId>
|
||||
<forceJavacCompilerUse>true</forceJavacCompilerUse>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<showWarnings>true</showWarnings>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>com.uber.nullaway</groupId>
|
||||
<artifactId>nullaway</artifactId>
|
||||
<version>0.3.0</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
<compilerArgs>
|
||||
<!-- NullAway will warn by default, uncomment the next line to make the build fail -->
|
||||
<!-- <arg>-Xep:NullAway:ERROR</arg> -->
|
||||
<arg>-XepExcludedPaths:(.*)/test/.*|(.*)/streamex/.*</arg>
|
||||
<arg>-XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway</arg>
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.plexus</groupId>
|
||||
<artifactId>plexus-compiler-javac-errorprone</artifactId>
|
||||
<version>2.8</version>
|
||||
</dependency>
|
||||
<!-- override plexus-compiler-javac-errorprone's dependency on
|
||||
Error Prone with the latest version -->
|
||||
<dependency>
|
||||
<groupId>com.google.errorprone</groupId>
|
||||
<artifactId>error_prone_core</artifactId>
|
||||
<version>2.1.3</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.nullaway;
|
||||
|
||||
import com.baeldung.distinct.Person;
|
||||
|
||||
public class NullAwayExample {
|
||||
|
||||
/*
|
||||
* 1- NullAway will warn about yearsToRetirement method
|
||||
* 2- Uncomment @Nullable in printAge and NullAway will warn about this method
|
||||
* 3- Add a standard null check to be NullAway compliant
|
||||
* 4- Build will be SUCCESS
|
||||
*/
|
||||
|
||||
static Integer getAge(/*@Nullable*/ Person person) {
|
||||
return person.getAge();
|
||||
}
|
||||
|
||||
Integer yearsToRetirement() {
|
||||
Person p = null;
|
||||
// ... p never gets set correctly...
|
||||
return 65 - getAge(p);
|
||||
}
|
||||
|
||||
}
|
@ -1,3 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/remove-text-after-x-in-file)
|
||||
- [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/tr-manipulate-strings)
|
||||
|
@ -53,24 +53,6 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>mac-profile</id>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
<file>
|
||||
<exists>${java.home}/../Classes/classes.jar</exists>
|
||||
</file>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.sun</groupId>
|
||||
<artifactId>tools</artifactId>
|
||||
<version>${java.version}</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${java.home}/../Classes/classes.jar</systemPath>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
|
@ -1,3 +1,3 @@
|
||||
### Relevant Articles
|
||||
|
||||
- [Maven Compiler Plugin](http://www.baeldung.com/maven-compiler-plugin)
|
||||
- [Maven Compiler Plugin](https://www.baeldung.com/maven-compiler-plugin)
|
||||
|
@ -4,4 +4,3 @@ This module contains articles about Maven with Java 11+.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
|
||||
|
@ -83,7 +83,7 @@
|
||||
<dependency>
|
||||
<groupId>com.mulesoft.munit</groupId>
|
||||
<artifactId>mule-munit-support</artifactId>
|
||||
<version>${mule.munit.support.version}</version>
|
||||
<version>${mule.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -106,18 +106,19 @@
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.mule.tools</groupId>
|
||||
<artifactId>muleesb-maven-plugin</artifactId>
|
||||
<version>${muleesb-maven-plugin.version}</version>
|
||||
<groupId>org.mule.tools.maven</groupId>
|
||||
<artifactId>mule-maven-plugin</artifactId>
|
||||
<version>2.2.1</version>
|
||||
<configuration>
|
||||
<deploymentType>standalone</deploymentType>
|
||||
<muleVersion>${mule.version}</muleVersion>
|
||||
<applications>/home/abir/AnypointStudio/workspace/variablescopetest</applications>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>deploy</id>
|
||||
<phase>deploy</phase>
|
||||
<goals>
|
||||
<goal>start</goal>
|
||||
<goal>deploy</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
@ -210,11 +211,9 @@
|
||||
</pluginRepositories>
|
||||
|
||||
<properties>
|
||||
<mule.version>3.8.1</mule.version>
|
||||
<mule.version>3.9.0</mule.version>
|
||||
<mule.tools.version>1.2</mule.tools.version>
|
||||
<munit.version>1.3.6</munit.version>
|
||||
<mule.munit.support.version>3.9.0</mule.munit.support.version>
|
||||
<muleesb-maven-plugin.version>1.0</muleesb-maven-plugin.version>
|
||||
<build-helper-maven-plugin.version>1.7</build-helper-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
@ -4,4 +4,4 @@ This module contains articles about Netflix.
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [Introduction to Netflix Genie](https://github.com/eugenp/tutorials/tree/master/netflix/genie)
|
||||
- [Introduction to Netflix Genie](https://www.baeldung.com/netflix-genie-intro)
|
||||
|
@ -1,3 +0,0 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Implementing The OAuth 2.0 Authorization Framework Using Jakarta EE](https://www.baeldung.com/java-ee-oauth2-implementation)
|
@ -5,7 +5,7 @@ This module contains articles about the Java Persistence API (JPA) in Java.
|
||||
### Relevant Articles
|
||||
|
||||
- [JPA Query Parameters Usage](https://www.baeldung.com/jpa-query-parameters)
|
||||
- [Mapping Entitiy Class Names to SQL Table Names with JPA](https://www.baeldung.com/jpa-entity-table-names)
|
||||
- [Mapping Entity Class Names to SQL Table Names with JPA](https://www.baeldung.com/jpa-entity-table-names)
|
||||
- [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values)
|
||||
- [Types of JPA Queries](https://www.baeldung.com/jpa-queries)
|
||||
- [JPA/Hibernate Projections](https://www.baeldung.com/jpa-hibernate-projections)
|
||||
|
@ -3,7 +3,7 @@ server.port=8082
|
||||
|
||||
#spring boot mongodb
|
||||
spring.data.mongodb.host=localhost
|
||||
spring.data.mongodb.port=27017
|
||||
spring.data.mongodb.port=0
|
||||
spring.data.mongodb.database=springboot-mongo
|
||||
|
||||
spring.thymeleaf.cache=false
|
||||
|
@ -1,5 +1,5 @@
|
||||
spring.jpa.show-sql=true
|
||||
#MySql
|
||||
spring.datasource.url=jdbc:mysql://localhost:3306/baeldung
|
||||
spring.datasource.username=baeldung
|
||||
spring.datasource.password=baeldung
|
||||
#spring.datasource.url=jdbc:mysql://localhost:3306/baeldung
|
||||
#spring.datasource.username=baeldung
|
||||
#spring.datasource.password=baeldung
|
@ -1,13 +1,11 @@
|
||||
package com.baeldung.spring.data.redis.config;
|
||||
|
||||
import com.baeldung.spring.data.redis.queue.MessagePublisher;
|
||||
import com.baeldung.spring.data.redis.queue.RedisMessagePublisher;
|
||||
import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
|
||||
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.listener.ChannelTopic;
|
||||
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
|
||||
@ -15,6 +13,10 @@ import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
|
||||
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
|
||||
import org.springframework.data.redis.serializer.GenericToStringSerializer;
|
||||
|
||||
import com.baeldung.spring.data.redis.queue.MessagePublisher;
|
||||
import com.baeldung.spring.data.redis.queue.RedisMessagePublisher;
|
||||
import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.baeldung.spring.data.redis")
|
||||
@EnableRedisRepositories(basePackages = "com.baeldung.spring.data.redis.repo")
|
||||
@ -33,6 +35,18 @@ public class RedisConfig {
|
||||
template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
|
||||
return template;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LettuceConnectionFactory lettuceConnectionFactory() {
|
||||
return new LettuceConnectionFactory();
|
||||
}
|
||||
|
||||
@Bean(name = "flushRedisTemplate")
|
||||
public RedisTemplate<String, String> flushRedisTemplate() {
|
||||
RedisTemplate<String, String> template = new RedisTemplate<>();
|
||||
template.setConnectionFactory(lettuceConnectionFactory());
|
||||
return template;
|
||||
}
|
||||
|
||||
@Bean
|
||||
MessageListenerAdapter messageListener() {
|
||||
|
@ -0,0 +1,92 @@
|
||||
package com.baeldung.spring.data.redis.delete;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.data.redis.connection.RedisConnection;
|
||||
import org.springframework.data.redis.core.RedisCallback;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.annotation.DirtiesContext.ClassMode;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.baeldung.spring.data.redis.config.RedisConfig;
|
||||
|
||||
import redis.embedded.RedisServer;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { RedisConfig.class })
|
||||
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
|
||||
public class RedisFlushDatabaseIntegrationTest {
|
||||
|
||||
private RedisServer redisServer;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("flushRedisTemplate")
|
||||
private RedisTemplate<String, String> flushRedisTemplate;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException {
|
||||
redisServer = new RedisServer(6390);
|
||||
redisServer.start();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
redisServer.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFlushDB_thenAllKeysInDatabaseAreCleared() {
|
||||
|
||||
ValueOperations<String, String> simpleValues = flushRedisTemplate.opsForValue();
|
||||
String key = "key";
|
||||
String value = "value";
|
||||
simpleValues.set(key, value);
|
||||
assertThat(simpleValues.get(key)).isEqualTo(value);
|
||||
|
||||
flushRedisTemplate.execute(new RedisCallback<Void>() {
|
||||
|
||||
@Override
|
||||
public Void doInRedis(RedisConnection connection) throws DataAccessException {
|
||||
connection.flushDb();
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
assertThat(simpleValues.get(key)).isNull();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFlushAll_thenAllKeysInDatabasesAreCleared() {
|
||||
|
||||
ValueOperations<String, String> simpleValues = flushRedisTemplate.opsForValue();
|
||||
String key = "key";
|
||||
String value = "value";
|
||||
simpleValues.set(key, value);
|
||||
assertThat(simpleValues.get(key)).isEqualTo(value);
|
||||
|
||||
flushRedisTemplate.execute(new RedisCallback<Void>() {
|
||||
|
||||
@Override
|
||||
public Void doInRedis(RedisConnection connection) throws DataAccessException {
|
||||
connection.flushAll();
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
assertThat(simpleValues.get(key)).isNull();
|
||||
|
||||
}
|
||||
}
|
@ -6,7 +6,7 @@
|
||||
### Relevant Articles:
|
||||
- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
|
||||
- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
|
||||
- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
|
||||
- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
|
||||
- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
|
||||
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
|
||||
- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
|
||||
|
27
pom.xml
27
pom.xml
@ -59,20 +59,14 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<artifactId>hamcrest</artifactId>
|
||||
<version>${hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<version>${hamcrest-all.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -862,6 +856,7 @@
|
||||
<module>antlr</module>
|
||||
|
||||
<module>apache-avro</module>
|
||||
<module>apache-beam</module>
|
||||
<module>apache-bval</module>
|
||||
<module>apache-curator</module>
|
||||
<module>apache-cxf</module>
|
||||
@ -1333,17 +1328,18 @@
|
||||
<gib.enabled>false</gib.enabled>
|
||||
|
||||
<junit.version>4.12</junit.version>
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<hamcrest.version>2.2</hamcrest.version>
|
||||
<hamcrest-all.version>1.3</hamcrest-all.version>
|
||||
<mockito.version>2.21.0</mockito.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.30</org.slf4j.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
<logback.version>1.2.3</logback.version>
|
||||
|
||||
<!-- plugins -->
|
||||
<!-- can't upgrade the plugin yet; as there is an issue with 2.22 no longer running all the tests-->
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
<java.version>1.8</java.version>
|
||||
<log4j.version>1.2.17</log4j.version>
|
||||
@ -1351,7 +1347,6 @@
|
||||
<esapi.version>2.1.0.1</esapi.version>
|
||||
<jmh-core.version>1.19</jmh-core.version>
|
||||
<jmh-generator.version>1.19</jmh-generator.version>
|
||||
<hamcrest-all.version>1.3</hamcrest-all.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
<maven-failsafe-plugin.version>2.21.0</maven-failsafe-plugin.version>
|
||||
<commons-io.version>2.5</commons-io.version>
|
||||
@ -1369,12 +1364,12 @@
|
||||
<junit-platform.version>1.2.0</junit-platform.version>
|
||||
<junit-jupiter.version>5.2.0</junit-jupiter.version>
|
||||
<directory-maven-plugin.version>0.3.1</directory-maven-plugin.version>
|
||||
<maven-install-plugin.version>2.5.1</maven-install-plugin.version>
|
||||
<maven-install-plugin.version>2.5.2</maven-install-plugin.version>
|
||||
<custom-pmd.version>0.0.1</custom-pmd.version>
|
||||
<gitflow-incremental-builder.version>3.8</gitflow-incremental-builder.version>
|
||||
<maven-jxr-plugin.version>2.3</maven-jxr-plugin.version>
|
||||
<maven-jxr-plugin.version>3.0.0</maven-jxr-plugin.version>
|
||||
<!-- <maven-pmd-plugin.version>3.9.0</maven-pmd-plugin.version> -->
|
||||
<maven-pmd-plugin.version>3.8</maven-pmd-plugin.version>
|
||||
<maven-pmd-plugin.version>3.13.0</maven-pmd-plugin.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
<h2.version>1.4.197</h2.version>
|
||||
</properties>
|
||||
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.spring.serverconfig;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/timeout")
|
||||
public class TimeoutController {
|
||||
|
||||
@GetMapping("/{timeout}")
|
||||
private Mono<String> timeout(@PathVariable int timeout) {
|
||||
try {
|
||||
Thread.sleep(timeout * 1000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return Mono.just("OK");
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.spring.serverconfig;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.net.ssl.SSLException;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
import io.netty.handler.ssl.SslContextBuilder;
|
||||
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
|
||||
import io.netty.handler.timeout.ReadTimeoutException;
|
||||
import io.netty.handler.timeout.ReadTimeoutHandler;
|
||||
import io.netty.handler.timeout.WriteTimeoutHandler;
|
||||
import reactor.netty.http.client.HttpClient;
|
||||
import reactor.netty.tcp.TcpClient;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
|
||||
@DirtiesContext
|
||||
public class TimeoutLiveTest {
|
||||
|
||||
private static final String BASE_URL = "https://localhost:8443";
|
||||
private static final int TIMEOUT_MILLIS = 2000;
|
||||
|
||||
private WebTestClient webTestClient;
|
||||
|
||||
@Rule
|
||||
public ExpectedException exception = ExpectedException.none();
|
||||
|
||||
@Before
|
||||
public void setup() throws SSLException {
|
||||
webTestClient = WebTestClient.bindToServer(getConnector())
|
||||
.baseUrl(BASE_URL)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldTimeout() {
|
||||
exception.expect(ReadTimeoutException.class);
|
||||
webTestClient.get()
|
||||
.uri("/timeout/{timeout}", 3)
|
||||
.exchange();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotTimeout() {
|
||||
WebTestClient.ResponseSpec response = webTestClient.get()
|
||||
.uri("/timeout/{timeout}", 1)
|
||||
.exchange();
|
||||
response.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("OK");
|
||||
}
|
||||
|
||||
private ReactorClientHttpConnector getConnector() throws SSLException {
|
||||
SslContext sslContext = SslContextBuilder
|
||||
.forClient()
|
||||
.trustManager(InsecureTrustManagerFactory.INSTANCE)
|
||||
.build();
|
||||
|
||||
TcpClient tcpClient = TcpClient
|
||||
.create()
|
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT_MILLIS)
|
||||
.doOnConnected(connection -> {
|
||||
connection.addHandlerLast(new ReadTimeoutHandler(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
|
||||
connection.addHandlerLast(new WriteTimeoutHandler(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
|
||||
});
|
||||
|
||||
HttpClient httpClient = HttpClient.from(tcpClient).secure(t -> t.sslContext(sslContext));
|
||||
return new ReactorClientHttpConnector(httpClient);
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.version;
|
||||
|
||||
import org.springframework.boot.system.JavaVersion;
|
||||
import org.springframework.boot.system.SystemProperties;
|
||||
import org.springframework.core.SpringVersion;
|
||||
|
||||
public class VersionObtainer {
|
||||
|
||||
public String getSpringVersion() {
|
||||
return SpringVersion.getVersion();
|
||||
}
|
||||
|
||||
public String getJavaVersion() {
|
||||
return JavaVersion.getJavaVersion().toString();
|
||||
}
|
||||
|
||||
public String getJdkVersion() {
|
||||
return SystemProperties.get("java.version");
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.version;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest(classes = VersionObtainer.class)
|
||||
public class VersionObtainerUnitTest {
|
||||
|
||||
public VersionObtainer version = new VersionObtainer();
|
||||
|
||||
@Test
|
||||
public void testGetSpringVersion() {
|
||||
String res = version.getSpringVersion();
|
||||
assertThat(res).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetJdkVersion() {
|
||||
String res = version.getJdkVersion();
|
||||
assertThat(res).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetJavaVersion() {
|
||||
String res = version.getJavaVersion();
|
||||
assertThat(res).isNotEmpty();
|
||||
}
|
||||
}
|
@ -1,8 +1,10 @@
|
||||
package org.baeldung.batch.model;
|
||||
|
||||
import java.util.Date;
|
||||
import org.baeldung.batch.service.adapter.LocalDateTimeAdapter;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@SuppressWarnings("restriction")
|
||||
@XmlRootElement(name = "transactionRecord")
|
||||
@ -11,7 +13,7 @@ public class Transaction {
|
||||
private int userId;
|
||||
private int age;
|
||||
private String postCode;
|
||||
private Date transactionDate;
|
||||
private LocalDateTime transactionDate;
|
||||
private double amount;
|
||||
|
||||
/* getters and setters for the attributes */
|
||||
@ -32,11 +34,12 @@ public class Transaction {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Date getTransactionDate() {
|
||||
@XmlJavaTypeAdapter(LocalDateTimeAdapter.class)
|
||||
public LocalDateTime getTransactionDate() {
|
||||
return transactionDate;
|
||||
}
|
||||
|
||||
public void setTransactionDate(Date transactionDate) {
|
||||
public void setTransactionDate(LocalDateTime transactionDate) {
|
||||
this.transactionDate = transactionDate;
|
||||
}
|
||||
|
||||
|
@ -1,18 +1,19 @@
|
||||
package org.baeldung.batch.service;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import org.baeldung.batch.model.Transaction;
|
||||
import org.springframework.batch.item.file.mapping.FieldSetMapper;
|
||||
import org.springframework.batch.item.file.transform.FieldSet;
|
||||
import org.springframework.validation.BindException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class RecordFieldSetMapper implements FieldSetMapper<Transaction> {
|
||||
|
||||
public Transaction mapFieldSet(FieldSet fieldSet) throws BindException {
|
||||
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyy");
|
||||
|
||||
Transaction transaction = new Transaction();
|
||||
// you can either use the indices or custom names
|
||||
// I personally prefer the custom names easy for debugging and
|
||||
@ -20,13 +21,10 @@ public class RecordFieldSetMapper implements FieldSetMapper<Transaction> {
|
||||
transaction.setUsername(fieldSet.readString("username"));
|
||||
transaction.setUserId(fieldSet.readInt("userid"));
|
||||
transaction.setAmount(fieldSet.readDouble(3));
|
||||
|
||||
// Converting the date
|
||||
String dateString = fieldSet.readString(2);
|
||||
try {
|
||||
transaction.setTransactionDate(dateFormat.parse(dateString));
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
transaction.setTransactionDate(LocalDate.parse(dateString, formatter).atStartOfDay());
|
||||
|
||||
return transaction;
|
||||
|
||||
|
@ -0,0 +1,19 @@
|
||||
package org.baeldung.batch.service.adapter;
|
||||
|
||||
import javax.xml.bind.annotation.adapters.XmlAdapter;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {
|
||||
|
||||
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
|
||||
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT);
|
||||
|
||||
public LocalDateTime unmarshal(String v) throws Exception {
|
||||
return LocalDateTime.parse(v, DATE_TIME_FORMATTER);
|
||||
}
|
||||
|
||||
public String marshal(LocalDateTime v) throws Exception {
|
||||
return DATE_TIME_FORMATTER.format(v);
|
||||
}
|
||||
}
|
@ -2,19 +2,19 @@
|
||||
<transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>10000.0</amount>
|
||||
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-10-31 00:00:00</transactionDate>
|
||||
<userId>1234</userId>
|
||||
<username>devendra</username>
|
||||
</transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>12321.0</amount>
|
||||
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-12-03 00:00:00</transactionDate>
|
||||
<userId>2134</userId>
|
||||
<username>john</username>
|
||||
</transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>23411.0</amount>
|
||||
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-02-02 00:00:00</transactionDate>
|
||||
<userId>2134</userId>
|
||||
<username>robin</username>
|
||||
</transactionRecord>
|
||||
|
@ -2,19 +2,19 @@
|
||||
<transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>10000.0</amount>
|
||||
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-10-31 00:00:00</transactionDate>
|
||||
<userId>1234</userId>
|
||||
<username>devendra</username>
|
||||
</transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>12321.0</amount>
|
||||
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-12-03 00:00:00</transactionDate>
|
||||
<userId>2134</userId>
|
||||
<username>john</username>
|
||||
</transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>23411.0</amount>
|
||||
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-02-02 00:00:00</transactionDate>
|
||||
<userId>2134</userId>
|
||||
<username>robin</username>
|
||||
</transactionRecord>
|
||||
|
@ -2,19 +2,19 @@
|
||||
<transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>10000.0</amount>
|
||||
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-10-31 00:00:00</transactionDate>
|
||||
<userId>1234</userId>
|
||||
<username>devendra</username>
|
||||
</transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>12321.0</amount>
|
||||
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-12-03 00:00:00</transactionDate>
|
||||
<userId>2134</userId>
|
||||
<username>john</username>
|
||||
</transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>23411.0</amount>
|
||||
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-02-02 00:00:00</transactionDate>
|
||||
<userId>2134</userId>
|
||||
<username>robin</username>
|
||||
</transactionRecord>
|
||||
|
@ -2,19 +2,19 @@
|
||||
<transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>10000.0</amount>
|
||||
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-10-31 00:00:00</transactionDate>
|
||||
<userId>1234</userId>
|
||||
<username>devendra</username>
|
||||
</transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>12321.0</amount>
|
||||
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-12-03 00:00:00</transactionDate>
|
||||
<userId>2134</userId>
|
||||
<username>john</username>
|
||||
</transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>23411.0</amount>
|
||||
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-02-02 00:00:00</transactionDate>
|
||||
<userId>2134</userId>
|
||||
<username>robin</username>
|
||||
</transactionRecord>
|
||||
|
@ -2,19 +2,19 @@
|
||||
<transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>10000.0</amount>
|
||||
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-10-31 00:00:00</transactionDate>
|
||||
<userId>1234</userId>
|
||||
<username>devendra</username>
|
||||
</transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>12321.0</amount>
|
||||
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-12-03 00:00:00</transactionDate>
|
||||
<userId>2134</userId>
|
||||
<username>john</username>
|
||||
</transactionRecord>
|
||||
<transactionRecord>
|
||||
<amount>23411.0</amount>
|
||||
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
|
||||
<transactionDate>2015-02-02 00:00:00</transactionDate>
|
||||
<userId>2134</userId>
|
||||
<username>robin</username>
|
||||
</transactionRecord>
|
||||
|
@ -1 +1 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><transactionRecord><transactionRecord><age>10</age><amount>10000.0</amount><postCode>430222</postCode><transactionDate>2015-10-31T00:00:00+05:30</transactionDate><userId>1234</userId><username>sammy</username></transactionRecord><transactionRecord><age>10</age><amount>12321.0</amount><postCode>430222</postCode><transactionDate>2015-12-03T00:00:00+05:30</transactionDate><userId>9999</userId><username>john</username></transactionRecord></transactionRecord>
|
||||
<?xml version="1.0" encoding="UTF-8"?><transactionRecord><transactionRecord><age>10</age><amount>10000.0</amount><postCode>430222</postCode><transactionDate>2015-10-31 00:00:00</transactionDate><userId>1234</userId><username>sammy</username></transactionRecord><transactionRecord><age>10</age><amount>12321.0</amount><postCode>430222</postCode><transactionDate>2015-12-03 00:00:00</transactionDate><userId>9999</userId><username>john</username></transactionRecord></transactionRecord>
|
||||
|
@ -1 +1 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><transactionRecord><transactionRecord><amount>10000.0</amount><transactionDate>2015-10-31T00:00:00+05:30</transactionDate><userId>1234</userId><username>devendra</username></transactionRecord><transactionRecord><amount>12321.0</amount><transactionDate>2015-12-03T00:00:00+05:30</transactionDate><userId>2134</userId><username>john</username></transactionRecord><transactionRecord><amount>23411.0</amount><transactionDate>2015-02-02T00:00:00+05:30</transactionDate><userId>2134</userId><username>robin</username></transactionRecord></transactionRecord>
|
||||
<?xml version="1.0" encoding="UTF-8"?><transactionRecord><transactionRecord><amount>10000.0</amount><transactionDate>2015-10-31 00:00:00</transactionDate><userId>1234</userId><username>devendra</username></transactionRecord><transactionRecord><amount>12321.0</amount><transactionDate>2015-12-03 00:00:00</transactionDate><userId>2134</userId><username>john</username></transactionRecord><transactionRecord><amount>23411.0</amount><transactionDate>2015-02-02 00:00:00</transactionDate><userId>2134</userId><username>robin</username></transactionRecord></transactionRecord>
|
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