Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Ankur Gupta 2020-07-26 01:53:40 +05:30
commit 0c032b90bb
1092 changed files with 32755 additions and 2711 deletions

6
.gitignore vendored
View File

@ -85,7 +85,5 @@ transaction.log
*-shell.log *-shell.log
apache-cxf/cxf-aegis/baeldung.xml apache-cxf/cxf-aegis/baeldung.xml
apache-fop/src/test/resources/input.xml
apache-fop/src/test/resources/output_herold.pdf libraries-2/*.db
apache-fop/src/test/resources/output_html2fo.pdf
apache-fop/src/test/resources/output_jtidy.pdf

View File

@ -1,16 +1,21 @@
package com.baeldung.jgrapht; package com.baeldung.jgrapht;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.awt.Color; import java.awt.Color;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import org.jgrapht.ext.JGraphXAdapter; import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultDirectedGraph; import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.DefaultEdge;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.mxgraph.layout.mxCircleLayout; import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxIGraphLayout; import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.util.mxCellRenderer; import com.mxgraph.util.mxCellRenderer;
@ -20,7 +25,7 @@ public class GraphImageGenerationUnitTest {
@Before @Before
public void createGraph() throws IOException { public void createGraph() throws IOException {
File imgFile = new File("src/test/resources/graph.png"); File imgFile = new File("src/test/resources/graph1.png");
imgFile.createNewFile(); imgFile.createNewFile();
g = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class); g = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
String x1 = "x1"; String x1 = "x1";
@ -34,12 +39,18 @@ public class GraphImageGenerationUnitTest {
g.addEdge(x3, x1); g.addEdge(x3, x1);
} }
@After
public void cleanup() {
File imgFile = new File("src/test/resources/graph1.png");
imgFile.deleteOnExit();
}
@Test @Test
public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException { public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g); JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g);
mxIGraphLayout layout = new mxCircleLayout(graphAdapter); mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent()); layout.execute(graphAdapter.getDefaultParent());
File imgFile = new File("src/test/resources/graph.png"); File imgFile = new File("src/test/resources/graph1.png");
BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null); BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null);
ImageIO.write(image, "PNG", imgFile); ImageIO.write(image, "PNG", imgFile);
assertTrue(imgFile.exists()); assertTrue(imgFile.exists());

View File

@ -7,4 +7,6 @@
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences) - [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms) - [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher) - [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5) - More articles: [[<-- prev]](/../algorithms-miscellaneous-5)

View File

@ -1,7 +1,7 @@
package com.baeldung.algorithms.play2048; package com.baeldung.algorithms.play2048;
public class Play2048 { public class Play2048 {
private static final int SIZE = 3; private static final int SIZE = 4;
private static final int INITIAL_NUMBERS = 2; private static final int INITIAL_NUMBERS = 2;
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.topkelements;
import java.util.ArrayList;
import java.util.List;
public class BruteForceTopKElementsFinder implements TopKElementsFinder<Integer> {
public List<Integer> findTopK(List<Integer> input, int k) {
List<Integer> array = new ArrayList<>(input);
List<Integer> topKList = new ArrayList<>();
for (int i = 0; i < k; i++) {
int maxIndex = 0;
for (int j = 1; j < array.size(); j++) {
if (array.get(j) > array.get(maxIndex)) {
maxIndex = j;
}
}
topKList.add(array.remove(maxIndex));
}
return topKList;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.topkelements;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
public class MaxHeapTopKElementsFinder implements TopKElementsFinder<Integer> {
public List<Integer> findTopK(List<Integer> input, int k) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
input.forEach(number -> {
maxHeap.add(number);
if (maxHeap.size() > k) {
maxHeap.poll();
}
});
List<Integer> topKList = new ArrayList<>(maxHeap);
Collections.reverse(topKList);
return topKList;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.algorithms.topkelements;
import java.util.List;
public interface TopKElementsFinder<T extends Comparable<T>> {
List<T> findTopK(List<T> input, int k);
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.topkelements;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class TreeSetTopKElementsFinder implements TopKElementsFinder<Integer> {
public List<Integer> findTopK(List<Integer> input, int k) {
Set<Integer> sortedSet = new TreeSet<>(Comparator.reverseOrder());
sortedSet.addAll(input);
return sortedSet.stream().limit(k).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.algorithms.topkelements;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class TopKElementsFinderUnitTest {
private final TopKElementsFinder<Integer> bruteForceFinder = new BruteForceTopKElementsFinder();
private final TopKElementsFinder<Integer> maxHeapFinder = new MaxHeapTopKElementsFinder();
private final TopKElementsFinder<Integer> treeSetFinder = new TreeSetTopKElementsFinder();
private final int k = 4;
private final List<Integer> distinctIntegers = Arrays.asList(1, 2, 3, 9, 7, 6, 12);
private final List<Integer> distinctIntegersTopK = Arrays.asList(9, 7, 6, 12);
private final List<Integer> nonDistinctIntegers = Arrays.asList(1, 2, 3, 3, 9, 9, 7, 6, 12);
private final List<Integer> nonDistinctIntegersTopK = Arrays.asList(9, 9, 7, 12);
@Test
public void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
assertThat(bruteForceFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
assertThat(maxHeapFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() {
assertThat(treeSetFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
assertThat(bruteForceFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
}
@Test
public void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
assertThat(maxHeapFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
}
}

View File

@ -1,6 +0,0 @@
## Apache Avro
This module contains articles about Apache Avro
### Relevant Articles:
- [Guide to Apache Avro](https://www.baeldung.com/java-apache-avro)

View File

@ -1,72 +0,0 @@
<?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>apache-avro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-avro</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>${avro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro-compiler</artifactId>
<version>${avro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>${avro.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>${avro.version}</version>
<executions>
<execution>
<id>schemas</id>
<phase>generate-sources</phase>
<goals>
<goal>schema</goal>
<goal>protocol</goal>
<goal>idl-protocol</goal>
</goals>
<configuration>
<sourceDirectory>${project.basedir}/src/main/resources/</sourceDirectory>
<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<avro.version>1.8.2</avro.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>
</project>

View File

@ -1,3 +0,0 @@
### Relevant Articles:
- [Introduction to Apache Beam](https://www.baeldung.com/apache-beam)

View File

@ -1,43 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<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>

View File

@ -1,7 +0,0 @@
## Apache BVal
This module contains articles about Apache BVal
### Relevant Articles:
- [Intro to Apache BVal](https://www.baeldung.com/apache-bval)

View File

@ -1,40 +0,0 @@
<?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>apache-bval</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-bval</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-jsr</artifactId>
<version>${bval.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation.validation-api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-extras</artifactId>
<version>${bval.version}</version>
</dependency>
</dependencies>
<properties>
<bval.version>1.1.2</bval.version>
<javax.validation.validation-api.version>1.1.0.Final</javax.validation.validation-api.version>
</properties>
</project>

View File

@ -1,7 +0,0 @@
## Apache Curator
This module contains articles about Apache Curator
### Relevant Articles:
- [Introduction to Apache Curator](https://www.baeldung.com/apache-curator)

View File

@ -1,70 +0,0 @@
<?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>apache-curator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-curator</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- curator -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-x-async</artifactId>
<version>${curator.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>${curator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<curator.version>4.0.1</curator.version>
<zookeeper.version>3.4.11</zookeeper.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
</properties>
</project>

View File

@ -1,7 +0,0 @@
## Apache Geode
This module contains articles about Apache Geode
### Relevant Articles:
- [A Quick Guide to Apache Geode](https://www.baeldung.com/apache-geode)

View File

@ -1,29 +0,0 @@
<?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>apache-geode</artifactId>
<version>1.0-SNAPSHOT</version>
<name>apache-geode</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.geode</groupId>
<artifactId>geode-core</artifactId>
<version>${geode.core}</version>
</dependency>
</dependencies>
<properties>
<geode.core>1.6.0</geode.core>
</properties>
</project>

View File

@ -0,0 +1,15 @@
## Apache Libraries
This module contains articles about various Apache libraries and utilities
### Relevant Articles:
- [Guide to Apache Avro](https://www.baeldung.com/java-apache-avro)
- [Introduction to Apache Beam](https://www.baeldung.com/apache-beam)
- [Intro to Apache BVal](https://www.baeldung.com/apache-bval)
- [Building a Microservice with Apache Meecrowave](https://www.baeldung.com/apache-meecrowave)
- [Intro to Apache OpenNLP](https://www.baeldung.com/apache-open-nlp)
- [Introduction to Apache Pulsar](https://www.baeldung.com/apache-pulsar)
- [Getting Started with Java and Zookeeper](https://www.baeldung.com/java-zookeeper)
- [Introduction to Apache Curator](https://www.baeldung.com/apache-curator)
- [A Quick Guide to Apache Geode](https://www.baeldung.com/apache-geode)
- [Guide to Solr in Java with Apache Solrj](https://www.baeldung.com/apache-solrj)

223
apache-libraries/pom.xml Normal file
View File

@ -0,0 +1,223 @@
<?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>apache-libraries</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-libraries</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- avro -->
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>${avro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro-compiler</artifactId>
<version>${avro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>${avro.version}</version>
</dependency>
<!-- beam -->
<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>
<!-- bval -->
<dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-jsr</artifactId>
<version>${bval.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation.validation-api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-extras</artifactId>
<version>${bval.version}</version>
</dependency>
<!-- meecrowave -->
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-core</artifactId>
<version>${meecrowave-core.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-jpa -->
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-jpa</artifactId>
<version>${meecrowave-jpa.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-junit</artifactId>
<version>${meecrowave-junit.version}</version>
<scope>test</scope>
</dependency>
<!-- opennlp -->
<dependency>
<groupId>org.apache.opennlp</groupId>
<artifactId>opennlp-tools</artifactId>
<version>${opennlp.opennlp-tools.version}</version>
</dependency>
<!-- pulsar -->
<dependency>
<groupId>org.apache.pulsar</groupId>
<artifactId>pulsar-client</artifactId>
<version>${pulsar-client.version}</version>
<scope>compile</scope>
</dependency>
<!-- zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<!-- curator -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-x-async</artifactId>
<version>${curator.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>${curator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<!-- geode -->
<dependency>
<groupId>org.apache.geode</groupId>
<artifactId>geode-core</artifactId>
<version>${geode.core}</version>
</dependency>
<!-- solr -->
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>${solr.solr-solrj.version}</version>
</dependency>
<!-- common -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- avro -->
<plugin>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>${avro.version}</version>
<executions>
<execution>
<id>schemas</id>
<phase>generate-sources</phase>
<goals>
<goal>schema</goal>
<goal>protocol</goal>
<goal>idl-protocol</goal>
</goals>
<configuration>
<sourceDirectory>${project.basedir}/src/main/resources/</sourceDirectory>
<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- meecrowave -->
<plugin>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-maven-plugin</artifactId>
<version>${meecrowave-maven-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<avro.version>1.8.2</avro.version>
<slf4j.version>1.7.25</slf4j.version>
<beam.version>2.19.0</beam.version>
<assertj.version>3.9.0</assertj.version>
<bval.version>1.1.2</bval.version>
<javax.validation.validation-api.version>1.1.0.Final</javax.validation.validation-api.version>
<meecrowave-junit.version>1.2.0</meecrowave-junit.version>
<okhttp.version>3.10.0</okhttp.version>
<meecrowave-jpa.version>1.2.1</meecrowave-jpa.version>
<meecrowave-core.version>1.2.1</meecrowave-core.version>
<meecrowave-maven-plugin.version>1.2.1</meecrowave-maven-plugin.version>
<opennlp.opennlp-tools.version>1.8.4</opennlp.opennlp-tools.version>
<pulsar-client.version>2.1.1-incubating</pulsar-client.version>
<zookeeper.version>3.4.11</zookeeper.version>
<curator.version>4.0.1</curator.version>
<avaitility.version>1.7.0</avaitility.version>
<geode.core>1.6.0</geode.core>
<solr.solr-solrj.version>6.4.0</solr.solr-solrj.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package com.baeldung.avro.model;
@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public enum Active {
YES, NO ;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"Active\",\"namespace\":\"com.baeldung.avro.model\",\"symbols\":[\"YES\",\"NO\"]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
}

View File

@ -0,0 +1,491 @@
/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package com.baeldung.avro.model;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public class AvroHttpRequest extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = -8649010116827875312L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"AvroHttpRequest\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"requestTime\",\"type\":\"long\"},{\"name\":\"clientIdentifier\",\"type\":{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}},{\"name\":\"employeeNames\",\"type\":{\"type\":\"array\",\"items\":\"string\"},\"default\":null},{\"name\":\"active\",\"type\":{\"type\":\"enum\",\"name\":\"Active\",\"symbols\":[\"YES\",\"NO\"]}}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<AvroHttpRequest> ENCODER =
new BinaryMessageEncoder<AvroHttpRequest>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<AvroHttpRequest> DECODER =
new BinaryMessageDecoder<AvroHttpRequest>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageDecoder instance used by this class.
*/
public static BinaryMessageDecoder<AvroHttpRequest> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
*/
public static BinaryMessageDecoder<AvroHttpRequest> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<AvroHttpRequest>(MODEL$, SCHEMA$, resolver);
}
/** Serializes this AvroHttpRequest to a ByteBuffer. */
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/** Deserializes a AvroHttpRequest from a ByteBuffer. */
public static AvroHttpRequest fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
@Deprecated public long requestTime;
@Deprecated public com.baeldung.avro.model.ClientIdentifier clientIdentifier;
@Deprecated public java.util.List<java.lang.CharSequence> employeeNames;
@Deprecated public com.baeldung.avro.model.Active active;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public AvroHttpRequest() {}
/**
* All-args constructor.
* @param requestTime The new value for requestTime
* @param clientIdentifier The new value for clientIdentifier
* @param employeeNames The new value for employeeNames
* @param active The new value for active
*/
public AvroHttpRequest(java.lang.Long requestTime, com.baeldung.avro.model.ClientIdentifier clientIdentifier, java.util.List<java.lang.CharSequence> employeeNames, com.baeldung.avro.model.Active active) {
this.requestTime = requestTime;
this.clientIdentifier = clientIdentifier;
this.employeeNames = employeeNames;
this.active = active;
}
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return requestTime;
case 1: return clientIdentifier;
case 2: return employeeNames;
case 3: return active;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
// Used by DatumReader. Applications should not call.
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: requestTime = (java.lang.Long)value$; break;
case 1: clientIdentifier = (com.baeldung.avro.model.ClientIdentifier)value$; break;
case 2: employeeNames = (java.util.List<java.lang.CharSequence>)value$; break;
case 3: active = (com.baeldung.avro.model.Active)value$; break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
/**
* Gets the value of the 'requestTime' field.
* @return The value of the 'requestTime' field.
*/
public java.lang.Long getRequestTime() {
return requestTime;
}
/**
* Sets the value of the 'requestTime' field.
* @param value the value to set.
*/
public void setRequestTime(java.lang.Long value) {
this.requestTime = value;
}
/**
* Gets the value of the 'clientIdentifier' field.
* @return The value of the 'clientIdentifier' field.
*/
public com.baeldung.avro.model.ClientIdentifier getClientIdentifier() {
return clientIdentifier;
}
/**
* Sets the value of the 'clientIdentifier' field.
* @param value the value to set.
*/
public void setClientIdentifier(com.baeldung.avro.model.ClientIdentifier value) {
this.clientIdentifier = value;
}
/**
* Gets the value of the 'employeeNames' field.
* @return The value of the 'employeeNames' field.
*/
public java.util.List<java.lang.CharSequence> getEmployeeNames() {
return employeeNames;
}
/**
* Sets the value of the 'employeeNames' field.
* @param value the value to set.
*/
public void setEmployeeNames(java.util.List<java.lang.CharSequence> value) {
this.employeeNames = value;
}
/**
* Gets the value of the 'active' field.
* @return The value of the 'active' field.
*/
public com.baeldung.avro.model.Active getActive() {
return active;
}
/**
* Sets the value of the 'active' field.
* @param value the value to set.
*/
public void setActive(com.baeldung.avro.model.Active value) {
this.active = value;
}
/**
* Creates a new AvroHttpRequest RecordBuilder.
* @return A new AvroHttpRequest RecordBuilder
*/
public static com.baeldung.avro.model.AvroHttpRequest.Builder newBuilder() {
return new com.baeldung.avro.model.AvroHttpRequest.Builder();
}
/**
* Creates a new AvroHttpRequest RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new AvroHttpRequest RecordBuilder
*/
public static com.baeldung.avro.model.AvroHttpRequest.Builder newBuilder(com.baeldung.avro.model.AvroHttpRequest.Builder other) {
return new com.baeldung.avro.model.AvroHttpRequest.Builder(other);
}
/**
* Creates a new AvroHttpRequest RecordBuilder by copying an existing AvroHttpRequest instance.
* @param other The existing instance to copy.
* @return A new AvroHttpRequest RecordBuilder
*/
public static com.baeldung.avro.model.AvroHttpRequest.Builder newBuilder(com.baeldung.avro.model.AvroHttpRequest other) {
return new com.baeldung.avro.model.AvroHttpRequest.Builder(other);
}
/**
* RecordBuilder for AvroHttpRequest instances.
*/
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<AvroHttpRequest>
implements org.apache.avro.data.RecordBuilder<AvroHttpRequest> {
private long requestTime;
private com.baeldung.avro.model.ClientIdentifier clientIdentifier;
private com.baeldung.avro.model.ClientIdentifier.Builder clientIdentifierBuilder;
private java.util.List<java.lang.CharSequence> employeeNames;
private com.baeldung.avro.model.Active active;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(com.baeldung.avro.model.AvroHttpRequest.Builder other) {
super(other);
if (isValidValue(fields()[0], other.requestTime)) {
this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.clientIdentifier)) {
this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier);
fieldSetFlags()[1] = true;
}
if (other.hasClientIdentifierBuilder()) {
this.clientIdentifierBuilder = com.baeldung.avro.model.ClientIdentifier.newBuilder(other.getClientIdentifierBuilder());
}
if (isValidValue(fields()[2], other.employeeNames)) {
this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.active)) {
this.active = data().deepCopy(fields()[3].schema(), other.active);
fieldSetFlags()[3] = true;
}
}
/**
* Creates a Builder by copying an existing AvroHttpRequest instance
* @param other The existing instance to copy.
*/
private Builder(com.baeldung.avro.model.AvroHttpRequest other) {
super(SCHEMA$);
if (isValidValue(fields()[0], other.requestTime)) {
this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.clientIdentifier)) {
this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier);
fieldSetFlags()[1] = true;
}
this.clientIdentifierBuilder = null;
if (isValidValue(fields()[2], other.employeeNames)) {
this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.active)) {
this.active = data().deepCopy(fields()[3].schema(), other.active);
fieldSetFlags()[3] = true;
}
}
/**
* Gets the value of the 'requestTime' field.
* @return The value.
*/
public java.lang.Long getRequestTime() {
return requestTime;
}
/**
* Sets the value of the 'requestTime' field.
* @param value The value of 'requestTime'.
* @return This builder.
*/
public com.baeldung.avro.model.AvroHttpRequest.Builder setRequestTime(long value) {
validate(fields()[0], value);
this.requestTime = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'requestTime' field has been set.
* @return True if the 'requestTime' field has been set, false otherwise.
*/
public boolean hasRequestTime() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'requestTime' field.
* @return This builder.
*/
public com.baeldung.avro.model.AvroHttpRequest.Builder clearRequestTime() {
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'clientIdentifier' field.
* @return The value.
*/
public com.baeldung.avro.model.ClientIdentifier getClientIdentifier() {
return clientIdentifier;
}
/**
* Sets the value of the 'clientIdentifier' field.
* @param value The value of 'clientIdentifier'.
* @return This builder.
*/
public com.baeldung.avro.model.AvroHttpRequest.Builder setClientIdentifier(com.baeldung.avro.model.ClientIdentifier value) {
validate(fields()[1], value);
this.clientIdentifierBuilder = null;
this.clientIdentifier = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'clientIdentifier' field has been set.
* @return True if the 'clientIdentifier' field has been set, false otherwise.
*/
public boolean hasClientIdentifier() {
return fieldSetFlags()[1];
}
/**
* Gets the Builder instance for the 'clientIdentifier' field and creates one if it doesn't exist yet.
* @return This builder.
*/
public com.baeldung.avro.model.ClientIdentifier.Builder getClientIdentifierBuilder() {
if (clientIdentifierBuilder == null) {
if (hasClientIdentifier()) {
setClientIdentifierBuilder(com.baeldung.avro.model.ClientIdentifier.newBuilder(clientIdentifier));
} else {
setClientIdentifierBuilder(com.baeldung.avro.model.ClientIdentifier.newBuilder());
}
}
return clientIdentifierBuilder;
}
/**
* Sets the Builder instance for the 'clientIdentifier' field
* @param value The builder instance that must be set.
* @return This builder.
*/
public com.baeldung.avro.model.AvroHttpRequest.Builder setClientIdentifierBuilder(com.baeldung.avro.model.ClientIdentifier.Builder value) {
clearClientIdentifier();
clientIdentifierBuilder = value;
return this;
}
/**
* Checks whether the 'clientIdentifier' field has an active Builder instance
* @return True if the 'clientIdentifier' field has an active Builder instance
*/
public boolean hasClientIdentifierBuilder() {
return clientIdentifierBuilder != null;
}
/**
* Clears the value of the 'clientIdentifier' field.
* @return This builder.
*/
public com.baeldung.avro.model.AvroHttpRequest.Builder clearClientIdentifier() {
clientIdentifier = null;
clientIdentifierBuilder = null;
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'employeeNames' field.
* @return The value.
*/
public java.util.List<java.lang.CharSequence> getEmployeeNames() {
return employeeNames;
}
/**
* Sets the value of the 'employeeNames' field.
* @param value The value of 'employeeNames'.
* @return This builder.
*/
public com.baeldung.avro.model.AvroHttpRequest.Builder setEmployeeNames(java.util.List<java.lang.CharSequence> value) {
validate(fields()[2], value);
this.employeeNames = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'employeeNames' field has been set.
* @return True if the 'employeeNames' field has been set, false otherwise.
*/
public boolean hasEmployeeNames() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'employeeNames' field.
* @return This builder.
*/
public com.baeldung.avro.model.AvroHttpRequest.Builder clearEmployeeNames() {
employeeNames = null;
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'active' field.
* @return The value.
*/
public com.baeldung.avro.model.Active getActive() {
return active;
}
/**
* Sets the value of the 'active' field.
* @param value The value of 'active'.
* @return This builder.
*/
public com.baeldung.avro.model.AvroHttpRequest.Builder setActive(com.baeldung.avro.model.Active value) {
validate(fields()[3], value);
this.active = value;
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'active' field has been set.
* @return True if the 'active' field has been set, false otherwise.
*/
public boolean hasActive() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'active' field.
* @return This builder.
*/
public com.baeldung.avro.model.AvroHttpRequest.Builder clearActive() {
active = null;
fieldSetFlags()[3] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public AvroHttpRequest build() {
try {
AvroHttpRequest record = new AvroHttpRequest();
record.requestTime = fieldSetFlags()[0] ? this.requestTime : (java.lang.Long) defaultValue(fields()[0]);
if (clientIdentifierBuilder != null) {
record.clientIdentifier = this.clientIdentifierBuilder.build();
} else {
record.clientIdentifier = fieldSetFlags()[1] ? this.clientIdentifier : (com.baeldung.avro.model.ClientIdentifier) defaultValue(fields()[1]);
}
record.employeeNames = fieldSetFlags()[2] ? this.employeeNames : (java.util.List<java.lang.CharSequence>) defaultValue(fields()[2]);
record.active = fieldSetFlags()[3] ? this.active : (com.baeldung.avro.model.Active) defaultValue(fields()[3]);
return record;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<AvroHttpRequest>
WRITER$ = (org.apache.avro.io.DatumWriter<AvroHttpRequest>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<AvroHttpRequest>
READER$ = (org.apache.avro.io.DatumReader<AvroHttpRequest>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}

View File

@ -0,0 +1,308 @@
/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package com.baeldung.avro.model;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public class ClientIdentifier extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = 8754570983127295424L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<ClientIdentifier> ENCODER =
new BinaryMessageEncoder<ClientIdentifier>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<ClientIdentifier> DECODER =
new BinaryMessageDecoder<ClientIdentifier>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageDecoder instance used by this class.
*/
public static BinaryMessageDecoder<ClientIdentifier> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
*/
public static BinaryMessageDecoder<ClientIdentifier> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<ClientIdentifier>(MODEL$, SCHEMA$, resolver);
}
/** Serializes this ClientIdentifier to a ByteBuffer. */
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/** Deserializes a ClientIdentifier from a ByteBuffer. */
public static ClientIdentifier fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
@Deprecated public java.lang.CharSequence hostName;
@Deprecated public java.lang.CharSequence ipAddress;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public ClientIdentifier() {}
/**
* All-args constructor.
* @param hostName The new value for hostName
* @param ipAddress The new value for ipAddress
*/
public ClientIdentifier(java.lang.CharSequence hostName, java.lang.CharSequence ipAddress) {
this.hostName = hostName;
this.ipAddress = ipAddress;
}
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return hostName;
case 1: return ipAddress;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
// Used by DatumReader. Applications should not call.
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: hostName = (java.lang.CharSequence)value$; break;
case 1: ipAddress = (java.lang.CharSequence)value$; break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
/**
* Gets the value of the 'hostName' field.
* @return The value of the 'hostName' field.
*/
public java.lang.CharSequence getHostName() {
return hostName;
}
/**
* Sets the value of the 'hostName' field.
* @param value the value to set.
*/
public void setHostName(java.lang.CharSequence value) {
this.hostName = value;
}
/**
* Gets the value of the 'ipAddress' field.
* @return The value of the 'ipAddress' field.
*/
public java.lang.CharSequence getIpAddress() {
return ipAddress;
}
/**
* Sets the value of the 'ipAddress' field.
* @param value the value to set.
*/
public void setIpAddress(java.lang.CharSequence value) {
this.ipAddress = value;
}
/**
* Creates a new ClientIdentifier RecordBuilder.
* @return A new ClientIdentifier RecordBuilder
*/
public static com.baeldung.avro.model.ClientIdentifier.Builder newBuilder() {
return new com.baeldung.avro.model.ClientIdentifier.Builder();
}
/**
* Creates a new ClientIdentifier RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new ClientIdentifier RecordBuilder
*/
public static com.baeldung.avro.model.ClientIdentifier.Builder newBuilder(com.baeldung.avro.model.ClientIdentifier.Builder other) {
return new com.baeldung.avro.model.ClientIdentifier.Builder(other);
}
/**
* Creates a new ClientIdentifier RecordBuilder by copying an existing ClientIdentifier instance.
* @param other The existing instance to copy.
* @return A new ClientIdentifier RecordBuilder
*/
public static com.baeldung.avro.model.ClientIdentifier.Builder newBuilder(com.baeldung.avro.model.ClientIdentifier other) {
return new com.baeldung.avro.model.ClientIdentifier.Builder(other);
}
/**
* RecordBuilder for ClientIdentifier instances.
*/
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<ClientIdentifier>
implements org.apache.avro.data.RecordBuilder<ClientIdentifier> {
private java.lang.CharSequence hostName;
private java.lang.CharSequence ipAddress;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(com.baeldung.avro.model.ClientIdentifier.Builder other) {
super(other);
if (isValidValue(fields()[0], other.hostName)) {
this.hostName = data().deepCopy(fields()[0].schema(), other.hostName);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.ipAddress)) {
this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress);
fieldSetFlags()[1] = true;
}
}
/**
* Creates a Builder by copying an existing ClientIdentifier instance
* @param other The existing instance to copy.
*/
private Builder(com.baeldung.avro.model.ClientIdentifier other) {
super(SCHEMA$);
if (isValidValue(fields()[0], other.hostName)) {
this.hostName = data().deepCopy(fields()[0].schema(), other.hostName);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.ipAddress)) {
this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress);
fieldSetFlags()[1] = true;
}
}
/**
* Gets the value of the 'hostName' field.
* @return The value.
*/
public java.lang.CharSequence getHostName() {
return hostName;
}
/**
* Sets the value of the 'hostName' field.
* @param value The value of 'hostName'.
* @return This builder.
*/
public com.baeldung.avro.model.ClientIdentifier.Builder setHostName(java.lang.CharSequence value) {
validate(fields()[0], value);
this.hostName = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'hostName' field has been set.
* @return True if the 'hostName' field has been set, false otherwise.
*/
public boolean hasHostName() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'hostName' field.
* @return This builder.
*/
public com.baeldung.avro.model.ClientIdentifier.Builder clearHostName() {
hostName = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'ipAddress' field.
* @return The value.
*/
public java.lang.CharSequence getIpAddress() {
return ipAddress;
}
/**
* Sets the value of the 'ipAddress' field.
* @param value The value of 'ipAddress'.
* @return This builder.
*/
public com.baeldung.avro.model.ClientIdentifier.Builder setIpAddress(java.lang.CharSequence value) {
validate(fields()[1], value);
this.ipAddress = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'ipAddress' field has been set.
* @return True if the 'ipAddress' field has been set, false otherwise.
*/
public boolean hasIpAddress() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'ipAddress' field.
* @return This builder.
*/
public com.baeldung.avro.model.ClientIdentifier.Builder clearIpAddress() {
ipAddress = null;
fieldSetFlags()[1] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public ClientIdentifier build() {
try {
ClientIdentifier record = new ClientIdentifier();
record.hostName = fieldSetFlags()[0] ? this.hostName : (java.lang.CharSequence) defaultValue(fields()[0]);
record.ipAddress = fieldSetFlags()[1] ? this.ipAddress : (java.lang.CharSequence) defaultValue(fields()[1]);
return record;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<ClientIdentifier>
WRITER$ = (org.apache.avro.io.DatumWriter<ClientIdentifier>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<ClientIdentifier>
READER$ = (org.apache.avro.io.DatumReader<ClientIdentifier>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.model; package com.baeldung.bval.model;
import java.io.File; import java.io.File;
@ -13,7 +13,7 @@ import org.apache.bval.extras.constraints.creditcard.Visa;
import org.apache.bval.extras.constraints.file.Directory; import org.apache.bval.extras.constraints.file.Directory;
import org.apache.bval.extras.constraints.net.InetAddress; import org.apache.bval.extras.constraints.net.InetAddress;
import com.baeldung.validation.Password; import com.baeldung.bval.validation.Password;
public class User { public class User {
@NotNull @NotNull

View File

@ -1,4 +1,4 @@
package com.baeldung.validation; package com.baeldung.bval.validation;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;

View File

@ -1,4 +1,4 @@
package com.baeldung.validation; package com.baeldung.bval.validation;
import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext; import javax.validation.ConstraintValidatorContext;

View File

@ -1,4 +1,4 @@
package com.baeldung; package com.baeldung.pulsar;
import java.io.IOException; import java.io.IOException;

View File

@ -1,4 +1,4 @@
package com.baeldung; package com.baeldung.pulsar;
import org.apache.pulsar.client.api.CompressionType; import org.apache.pulsar.client.api.CompressionType;
import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.Message;

View File

@ -1,4 +1,4 @@
package com.baeldung.subscriptions; package com.baeldung.pulsar.subscriptions;
import org.apache.pulsar.client.api.ConsumerBuilder; import org.apache.pulsar.client.api.ConsumerBuilder;
import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.Message;

View File

@ -1,4 +1,4 @@
package com.baeldung.subscriptions; package com.baeldung.pulsar.subscriptions;
import org.apache.pulsar.client.api.Consumer; import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.ConsumerBuilder; import org.apache.pulsar.client.api.ConsumerBuilder;

View File

@ -1,4 +1,4 @@
package com.baeldung.validation; package com.baeldung.bval.validation;
import java.io.File; import java.io.File;
import java.util.Set; import java.util.Set;
@ -13,9 +13,9 @@ import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*; import com.baeldung.bval.model.User;
import com.baeldung.model.User; import static org.junit.Assert.*;
public class ValidationIntegrationTest { public class ValidationIntegrationTest {
private static ValidatorFactory validatorFactory; private static ValidatorFactory validatorFactory;

View File

@ -1,7 +0,0 @@
## Apache Meecrowave
This module contains articles about Apache Meecrowave
### Relevant Articles:
- [Building a Microservice with Apache Meecrowave](https://www.baeldung.com/apache-meecrowave)

View File

@ -1,65 +0,0 @@
<?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>apache-meecrowave</artifactId>
<version>0.0.1</version>
<name>apache-meecrowave</name>
<description>A sample REST API application with Meecrowave</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-core -->
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-core</artifactId>
<version>${meecrowave-core.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-jpa -->
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-jpa</artifactId>
<version>${meecrowave-jpa.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-junit</artifactId>
<version>${meecrowave-junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-maven-plugin</artifactId>
<version>${meecrowave-maven-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<meecrowave-junit.version>1.2.0</meecrowave-junit.version>
<okhttp.version>3.10.0</okhttp.version>
<meecrowave-jpa.version>1.2.1</meecrowave-jpa.version>
<meecrowave-core.version>1.2.1</meecrowave-core.version>
<meecrowave-maven-plugin.version>1.2.1</meecrowave-maven-plugin.version>
</properties>
</project>

View File

@ -1,7 +0,0 @@
## Apache OpenNLP
This module contains articles about Apache OpenNLP
### Relevant Articles
- [Intro to Apache OpenNLP](https://www.baeldung.com/apache-open-nlp)

View File

@ -1,37 +0,0 @@
<?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>apache-opennlp</artifactId>
<version>1.0-SNAPSHOT</version>
<name>apache-opennlp</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.opennlp</groupId>
<artifactId>opennlp-tools</artifactId>
<version>${org.apache.opennlp.opennlp-tools.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${org.assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<org.assertj.version>3.9.0</org.assertj.version>
<org.apache.opennlp.opennlp-tools.version>1.8.4</org.apache.opennlp.opennlp-tools.version>
</properties>
</project>

View File

@ -1,8 +0,0 @@
.classpath
.project
.settings
target
.idea
*.iml
.gradle/
build/

View File

@ -1,7 +0,0 @@
## Apache Pulsar
This module contains articles about Apache Pulsar
### Relevant Articles:
- [Introduction to Apache Pulsar](https://www.baeldung.com/apache-pulsar)

View File

@ -1,32 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.pulsar</groupId>
<artifactId>apache-pulsar</artifactId>
<version>0.0.1</version>
<name>apache-pulsar</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.pulsar</groupId>
<artifactId>pulsar-client</artifactId>
<version>${pulsar-client.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<pulsar-client.version>2.1.1-incubating</pulsar-client.version>
</properties>
</project>

View File

@ -6,4 +6,4 @@ This module contains articles about Apache Shiro
- [Introduction to Apache Shiro](https://www.baeldung.com/apache-shiro) - [Introduction to Apache Shiro](https://www.baeldung.com/apache-shiro)
- [Permissions-Based Access Control with Apache Shiro](https://www.baeldung.com/apache-shiro-access-control) - [Permissions-Based Access Control with Apache Shiro](https://www.baeldung.com/apache-shiro-access-control)
- [Spring Security vs Apache Shiro](https://www.baeldung.com/spring-security-vs-apache-shiro)

View File

@ -39,10 +39,19 @@
<artifactId>jcl-over-slf4j</artifactId> <artifactId>jcl-over-slf4j</artifactId>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<!-- spring-sec -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
<apache-shiro-core-version>1.4.0</apache-shiro-core-version> <apache-shiro-core-version>1.5.3</apache-shiro-core-version>
<log4j-version>1.2.17</log4j-version> <log4j-version>1.2.17</log4j-version>
</properties> </properties>

View File

@ -0,0 +1,96 @@
package com.baeldung.comparison.shiro;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CustomRealm extends JdbcRealm {
private Logger logger = LoggerFactory.getLogger(CustomRealm.class);
private Map<String, String> credentials = new HashMap<>();
private Map<String, Set<String>> roles = new HashMap<>();
private Map<String, Set<String>> permissions = new HashMap<>();
{
credentials.put("Tom", "password");
credentials.put("Jerry", "password");
roles.put("Jerry", new HashSet<>(Arrays.asList("ADMIN")));
roles.put("Tom", new HashSet<>(Arrays.asList("USER")));
permissions.put("ADMIN", new HashSet<>(Arrays.asList("READ", "WRITE")));
permissions.put("USER", new HashSet<>(Arrays.asList("READ")));
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
if (userToken.getUsername() == null || userToken.getUsername()
.isEmpty() || !credentials.containsKey(userToken.getUsername())) {
throw new UnknownAccountException("User doesn't exist");
}
return new SimpleAuthenticationInfo(userToken.getUsername(), credentials.get(userToken.getUsername()), getName());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Set<String> roles = new HashSet<>();
Set<String> permissions = new HashSet<>();
for (Object user : principals) {
try {
roles.addAll(getRoleNamesForUser(null, (String) user));
permissions.addAll(getPermissions(null, null, roles));
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo(roles);
authInfo.setStringPermissions(permissions);
return authInfo;
}
@Override
protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
if (!roles.containsKey(username)) {
throw new SQLException("User doesn't exist");
}
return roles.get(username);
}
@Override
protected Set<String> getPermissions(Connection conn, String username, Collection<String> roles) throws SQLException {
Set<String> userPermissions = new HashSet<>();
for (String role : roles) {
if (!permissions.containsKey(role)) {
throw new SQLException("Role doesn't exist");
}
userPermissions.addAll(permissions.get(role));
}
return userPermissions;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.comparison.shiro;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class ShiroApplication {
public static void main(String... args) {
SpringApplication.run(ShiroApplication.class, args);
}
@Bean
public Realm customRealm() {
return new CustomRealm();
}
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition filter = new DefaultShiroFilterChainDefinition();
filter.addPathDefinition("/home", "authc");
filter.addPathDefinition("/**", "anon");
return filter;
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.comparison.shiro.controllers;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.baeldung.comparison.shiro.models.UserCredentials;
@Controller
public class ShiroController {
private Logger logger = LoggerFactory.getLogger(ShiroController.class);
@GetMapping("/")
public String getIndex() {
return "comparison/index";
}
@GetMapping("/login")
public String showLoginPage() {
return "comparison/login";
}
@PostMapping("/login")
public String doLogin(HttpServletRequest req, UserCredentials credentials, RedirectAttributes attr) {
Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword());
try {
subject.login(token);
} catch (AuthenticationException ae) {
logger.error(ae.getMessage());
attr.addFlashAttribute("error", "Invalid Credentials");
return "redirect:/login";
}
}
return "redirect:/home";
}
@GetMapping("/home")
public String getMeHome(Model model) {
addUserAttributes(model);
return "comparison/home";
}
@GetMapping("/admin")
public String adminOnly(Model model) {
addUserAttributes(model);
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.hasRole("ADMIN")) {
model.addAttribute("adminContent", "only admin can view this");
}
return "comparison/home";
}
@PostMapping("/logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/";
}
private void addUserAttributes(Model model) {
Subject currentUser = SecurityUtils.getSubject();
String permission = "";
if (currentUser.hasRole("ADMIN")) {
model.addAttribute("role", "ADMIN");
} else if (currentUser.hasRole("USER")) {
model.addAttribute("role", "USER");
}
if (currentUser.isPermitted("READ")) {
permission = permission + " READ";
}
if (currentUser.isPermitted("WRITE")) {
permission = permission + " WRITE";
}
model.addAttribute("username", currentUser.getPrincipal());
model.addAttribute("permission", permission);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.comparison.shiro.models;
public class UserCredentials {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "username = " + getUsername();
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.comparison.springsecurity;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAnnotationProcessorAutoConfiguration;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAutoConfiguration;
import org.apache.shiro.spring.config.web.autoconfigure.ShiroWebAutoConfiguration;
import org.apache.shiro.spring.config.web.autoconfigure.ShiroWebFilterConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(exclude = {ShiroAutoConfiguration.class,
ShiroAnnotationProcessorAutoConfiguration.class,
ShiroWebAutoConfiguration.class,
ShiroWebFilterConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.comparison.springsecurity.config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests(authorize -> authorize.antMatchers("/index", "/login")
.permitAll()
.antMatchers("/home", "/logout")
.authenticated()
.antMatchers("/admin/**")
.hasRole("ADMIN"))
.formLogin(formLogin -> formLogin.loginPage("/login")
.failureUrl("/login-error"));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("Jerry")
.password(passwordEncoder().encode("password"))
.authorities("READ", "WRITE")
.roles("ADMIN")
.and()
.withUser("Tom")
.password(passwordEncoder().encode("password"))
.authorities("READ")
.roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.comparison.springsecurity.web;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SpringController {
@GetMapping("/")
public String getIndex() {
return "comparison/index";
}
@GetMapping("/login")
public String showLoginPage() {
return "comparison/login";
}
@RequestMapping("/login-error")
public String loginError(Model model) {
model.addAttribute("error", "Invalid Credentials");
return "comparison/login";
}
@PostMapping("/login")
public String doLogin(HttpServletRequest req) {
return "redirect:/home";
}
@GetMapping("/home")
public String showHomePage(HttpServletRequest req, Model model) {
addUserAttributes(model);
return "comparison/home";
}
@GetMapping("/admin")
public String adminOnly(HttpServletRequest req, Model model) {
addUserAttributes(model);
model.addAttribute("adminContent", "only admin can view this");
return "comparison/home";
}
private void addUserAttributes(Model model) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (auth != null && !auth.getClass()
.equals(AnonymousAuthenticationToken.class)) {
User user = (User) auth.getPrincipal();
model.addAttribute("username", user.getUsername());
Collection<GrantedAuthority> authorities = user.getAuthorities();
for (GrantedAuthority authority : authorities) {
if (authority.getAuthority()
.contains("USER")) {
model.addAttribute("role", "USER");
model.addAttribute("permission", "READ");
} else if (authority.getAuthority()
.contains("ADMIN")) {
model.addAttribute("role", "ADMIN");
model.addAttribute("permission", "READ WRITE");
}
}
}
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung; package com.baeldung.intro;
import org.apache.shiro.SecurityUtils; import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationException;

View File

@ -1,4 +1,4 @@
package com.baeldung; package com.baeldung.intro;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;

View File

@ -1,4 +1,4 @@
package com.baeldung; package com.baeldung.intro;
import org.apache.shiro.realm.Realm; import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
@ -7,12 +7,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
/** /**
* Created by smatt on 21/08/2017. * Created by smatt on 21/08/2017.
*/ */
@SpringBootApplication @SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class ShiroSpringApplication { public class ShiroSpringApplication {
private static final transient Logger log = LoggerFactory.getLogger(ShiroSpringApplication.class); private static final transient Logger log = LoggerFactory.getLogger(ShiroSpringApplication.class);
@ -29,7 +30,7 @@ public class ShiroSpringApplication {
@Bean @Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() { public ShiroFilterChainDefinition filterChainDefinition() {
DefaultShiroFilterChainDefinition filter DefaultShiroFilterChainDefinition filter
= new DefaultShiroFilterChainDefinition(); = new DefaultShiroFilterChainDefinition();

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