Merge pull request #1 from eugenp/master

sync repo
This commit is contained in:
Vaibhav Sahay 2018-09-29 15:59:41 +05:30 committed by GitHub
commit a4521a9b04
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2870 changed files with 70303 additions and 13302 deletions

14
.gitignore vendored
View File

@ -48,3 +48,17 @@ dependency-reduced-pom.xml
*.so
*.dylib
*.dll
xml/src/test/resources/example_dom4j_new.xml
xml/src/test/resources/example_dom4j_updated.xml
xml/src/test/resources/example_jaxb_new.xml
core-java-io/hard_link.txt
core-java-io/target_link.txt
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
ethereum/logs/
jmeter/src/main/resources/*-JMeter.csv
**/node_modules/
**/dist
**/tmp
**/out-tsc

View File

@ -4,7 +4,7 @@ before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: skip
script: travis_wait 60 mvn -q install
script: travis_wait 60 mvn -q install -Pdefault
sudo: required

View File

@ -3,10 +3,11 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>JGitSnippets</artifactId>
<artifactId>JGit</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<name>JGit</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -2,7 +2,7 @@
The "REST with Spring" Classes
==============================
After 5 months of work, here's the Master Class of REST With Spring: <br/>
Here's the Master Class of REST With Spring (price changes permanently next Friday): <br/>
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
And here's the Master Class of Learn Spring Security: <br/>
@ -19,7 +19,7 @@ In additional to Spring, the following technologies are in focus: `core Java`, `
Building the project
====================
To do the full build, do: `mvn install -Dgib.enabled=false`
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
Working with the code in Eclipse

View File

@ -1,13 +1,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mabsisa</groupId>
<artifactId>Twitter4J</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Twitter4J</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
@ -23,27 +19,6 @@
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/ApplicationTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<twitter4j-stream.version>4.0.6</twitter4j-stream.version>
</properties>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,7 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>activejdbc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
@ -79,55 +78,11 @@
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<reportFormat>brief</reportFormat>
<trimStackTrace>true</trimStackTrace>
<useFile>false</useFile>
<includes>
<include>**/*Spec*.java</include>
<include>**/*Test*.java</include>
</includes>
<excludes>
<exclude>**/helpers/*</exclude>
<exclude>**/*$*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>snapshots1</id>
<name>JavaLite Snapshots1</name>
<url>http://repo.javalite.io/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>warn</checksumPolicy>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>snapshots2</id>
<name>JavaLite Snapshots2</name>
<url>http://repo.javalite.io/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>warn</checksumPolicy>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties>
<activejdbc.version>1.4.13</activejdbc.version>
<activejdbc.version>2.0</activejdbc.version>
<environments>development.test,development</environments>
<mysql.connector.version>5.1.34</mysql.connector.version>
</properties>

View File

@ -16,4 +16,8 @@ public class Employee extends Model {
set("created_by",createdBy);
}
public String getLastName() {
return getString("last_name");
}
}

View File

@ -15,4 +15,8 @@ public class Role extends Model {
set("role_name",role);
set("created_by",createdBy);
}
public String getRoleName() {
return getString("role_name");
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -7,7 +7,7 @@ import org.junit.Test;
import java.util.List;
public class ActiveJDBCAppTest extends DBSpec
public class ActiveJDBCAppManualTest extends DBSpec
{
@Test
public void ifEmployeeCreated_thenIsValid() {

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -23,3 +23,8 @@
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)

View File

@ -0,0 +1 @@
/bin/

View File

@ -0,0 +1,20 @@
package com.java.src;
import java.util.Scanner;
public class RoundUpToHundred {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double input = scanner.nextDouble();
scanner.close();
RoundUpToHundred.round(input);
}
static long round(double input) {
long i = (long) Math.ceil(input);
return ((i + 99) / 100) * 100;
};
}

View File

@ -0,0 +1,14 @@
package com.java.src;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class RoundUpToHundredTest {
@Test
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.algorithms.distancebetweenpoints;
import java.awt.geom.Point2D;
public class DistanceBetweenPointsService {
public double calculateDistanceBetweenPoints(
double x1,
double y1,
double x2,
double y2) {
return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1));
}
public double calculateDistanceBetweenPointsWithHypot(
double x1,
double y1,
double x2,
double y2) {
double ac = Math.abs(y2 - y1);
double cb = Math.abs(x2 - x1);
return Math.hypot(ac, cb);
}
public double calculateDistanceBetweenPointsWithPoint2D(
double x1,
double y1,
double x2,
double y2) {
return Point2D.distance(x1, y1, x2, y2);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.algorithms.linesintersection;
import java.awt.Point;
import java.util.Optional;
public class LinesIntersectionService {
public Optional<Point> calculateIntersectionPoint(double m1, double b1, double m2, double b2) {
if (m1 == m2) {
return Optional.empty();
}
double x = (b2 - b1) / (m1 - m2);
double y = m1 * x + b1;
Point point = new Point();
point.setLocation(x, y);
return Optional.of(point);
}
}

View File

@ -87,7 +87,7 @@ public class State {
void randomPlay() {
List<Position> availablePositions = this.board.getEmptyPositions();
int totalPossibilities = availablePositions.size();
int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1));
int selectRandom = (int) (Math.random() * totalPossibilities);
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
}

View File

@ -65,7 +65,7 @@ public class Node {
public Node getRandomChildNode() {
int noOfPossibleMoves = this.childArray.size();
int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1));
int selectRandom = (int) (Math.random() * noOfPossibleMoves);
return this.childArray.get(selectRandom);
}

View File

@ -0,0 +1,29 @@
package com.baeldung.algorithms.rectanglesoverlap;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.algorithms.rectanglesoverlap;
public class Rectangle {
private Point bottomLeft;
private Point topRight;
public Rectangle(Point bottomLeft, Point topRight) {
this.bottomLeft = bottomLeft;
this.topRight = topRight;
}
public Point getBottomLeft() {
return bottomLeft;
}
public void setBottomLeft(Point bottomLeft) {
this.bottomLeft = bottomLeft;
}
public Point getTopRight() {
return topRight;
}
public void setTopRight(Point topRight) {
this.topRight = topRight;
}
public boolean isOverlapping(Rectangle other) {
// one rectangle is to the top of the other
if (this.topRight.getY() < other.bottomLeft.getY() || this.bottomLeft.getY() > other.topRight.getY()) {
return false;
}
// one rectangle is to the left of the other
if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.algorithms.string;
public class EnglishAlphabetLetters {
public static boolean checkStringForAllTheLetters(String input) {
boolean[] visited = new boolean[26];
int index = 0;
for (int id = 0; id < input.length(); id++) {
if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
index = input.charAt(id) - 'a';
} else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
index = input.charAt(id) - 'A';
}
visited[index] = true;
}
for (int id = 0; id < 26; id++) {
if (!visited[id]) {
return false;
}
}
return true;
}
public static boolean checkStringForAllLetterUsingStream(String input) {
long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count();
return c == 26;
}
public static void main(String[] args) {
checkStringForAllLetterUsingStream("intit");
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

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

View File

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

View File

@ -1,4 +1,4 @@
package algorithms;
package com.baeldung.algorithms;
import com.baeldung.algorithms.hillclimbing.HillClimbing;
import com.baeldung.algorithms.hillclimbing.State;

View File

@ -1,4 +1,4 @@
package algorithms;
package com.baeldung.algorithms;
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
import com.baeldung.algorithms.middleelementlookup.Node;

View File

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
package algorithms.binarysearch;
package com.baeldung.algorithms.binarysearch;
import java.util.Arrays;
import java.util.List;

View File

@ -0,0 +1,54 @@
package com.baeldung.algorithms.distancebetweenpoints;
import org.junit.Test;
import com.baeldung.algorithms.distancebetweenpoints.DistanceBetweenPointsService;
import static org.junit.Assert.assertEquals;
public class DistanceBetweenPointsServiceUnitTest {
private DistanceBetweenPointsService service = new DistanceBetweenPointsService();
@Test
public void givenTwoPoints_whenCalculateDistanceByFormula_thenCorrect() {
double x1 = 3;
double y1 = 4;
double x2 = 7;
double y2 = 1;
double distance = service.calculateDistanceBetweenPoints(x1, y1, x2, y2);
assertEquals(distance, 5, 0.001);
}
@Test
public void givenTwoPoints_whenCalculateDistanceWithHypot_thenCorrect() {
double x1 = 3;
double y1 = 4;
double x2 = 7;
double y2 = 1;
double distance = service.calculateDistanceBetweenPointsWithHypot(x1, y1, x2, y2);
assertEquals(distance, 5, 0.001);
}
@Test
public void givenTwoPoints_whenCalculateDistanceWithPoint2D_thenCorrect() {
double x1 = 3;
double y1 = 4;
double x2 = 7;
double y2 = 1;
double distance = service.calculateDistanceBetweenPointsWithPoint2D(x1, y1, x2, y2);
assertEquals(distance, 5, 0.001);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.algorithms.linesintersection;
import java.awt.Point;
import java.util.Optional;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
public class LinesIntersectionServiceUnitTest {
private LinesIntersectionService service = new LinesIntersectionService();
@Test
public void givenNotParallelLines_whenCalculatePoint_thenPresent() {
double m1 = 0;
double b1 = 0;
double m2 = 1;
double b2 = -1;
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
assertTrue(point.isPresent());
assertEquals(point.get().getX(), 1, 0.001);
assertEquals(point.get().getY(), 0, 0.001);
}
@Test
public void givenParallelLines_whenCalculatePoint_thenEmpty() {
double m1 = 1;
double b1 = 0;
double m2 = 1;
double b2 = -1;
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
assertFalse(point.isPresent());
}
}

View File

@ -1,4 +1,4 @@
package algorithms.mcts;
package com.baeldung.algorithms.mcts;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

View File

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

View File

@ -0,0 +1,42 @@
package com.baeldung.algorithms.rectanglesoverlap;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
import com.baeldung.algorithms.rectanglesoverlap.Point;
import com.baeldung.algorithms.rectanglesoverlap.Rectangle;
public class RectangleUnitTest {
@Test
public void givenTwoOverlappingRectangles_whenisOverlappingCalled_shouldReturnTrue() {
Rectangle rectangle1 = new Rectangle(new Point(2, 1), new Point(4, 3));
Rectangle rectangle2 = new Rectangle(new Point(1, 1), new Point(6, 4));
assertTrue(rectangle1.isOverlapping(rectangle2));
rectangle1 = new Rectangle(new Point(-5, -2), new Point(2, 3));
rectangle2 = new Rectangle(new Point(-2, -1), new Point(5, 2));
assertTrue(rectangle1.isOverlapping(rectangle2));
rectangle1 = new Rectangle(new Point(-5, 1), new Point(2, 4));
rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5));
assertTrue(rectangle1.isOverlapping(rectangle2));
}
@Test
public void givenTwoNonOverlappingRectangles_whenisOverlappingCalled_shouldReturnFalse() {
Rectangle rectangle1 = new Rectangle(new Point(-5, 1), new Point(-3, 4));
Rectangle rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5));
assertFalse(rectangle1.isOverlapping(rectangle2));
rectangle1 = new Rectangle(new Point(-5, 1), new Point(3, 4));
rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, -1));
assertFalse(rectangle1.isOverlapping(rectangle2));
rectangle1 = new Rectangle(new Point(-2, 1), new Point(0, 3));
rectangle2 = new Rectangle(new Point(3, 1), new Point(5, 4));
assertFalse(rectangle1.isOverlapping(rectangle2));
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.algorithms.string;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class EnglishAlphabetLettersUnitTest {
@Test
void givenString_whenContainsAllCharacter_thenTrue() {
String input = "Farmer jack realized that big yellow quilts were expensive";
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input));
}
@Test
void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() {
String input = "Farmer jack realized that big yellow quilts were expensive";
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input));
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

2
apache-avro/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Guide to Apache Avro](http://www.baeldung.com/java-apache-avro)

89
apache-avro/pom.xml Normal file
View File

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-avro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Apache Avro</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler-plugin.version>3.5</compiler-plugin.version>
<avro.version>1.8.2</avro.version>
<java.version>1.8</java.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<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.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<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>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.avro.util;
import org.apache.avro.Schema;
import org.apache.avro.compiler.specific.SpecificCompiler;
import java.io.File;
import java.io.IOException;
public class AvroClassGenerator {
public void generateAvroClasses() throws IOException {
SpecificCompiler compiler = new SpecificCompiler(new Schema.Parser().parse(new File("src/main/resources/avroHttpRequest-schema.avsc")));
compiler.compileToDestination(new File("src/main/resources"), new File("src/main/java"));
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.avro.util;
import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
public class AvroSchemaBuilder {
public Schema createAvroHttpRequestSchema(){
Schema clientIdentifier = SchemaBuilder.record("ClientIdentifier").namespace("com.baeldung.avro.model")
.fields().requiredString("hostName").requiredString("ipAddress").endRecord();
Schema avroHttpRequest = SchemaBuilder.record("AvroHttpRequest").namespace("com.baeldung.avro.model").fields()
.requiredLong("requestTime")
.name("clientIdentifier").type(clientIdentifier).noDefault()
.name("employeeNames").type().array().items().stringType().arrayDefault(null)
.name("active").type().enumeration("Active").symbols("YES", "NO").noDefault()
.endRecord();
return avroHttpRequest;
}
}

View File

@ -0,0 +1,13 @@
/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package com.baeldung.avro.util.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.util.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 ClientIdentifier clientIdentifier;
@Deprecated public java.util.List<java.lang.CharSequence> employeeNames;
@Deprecated public 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, ClientIdentifier clientIdentifier, java.util.List<java.lang.CharSequence> employeeNames, 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 = (ClientIdentifier)value$; break;
case 2: employeeNames = (java.util.List<java.lang.CharSequence>)value$; break;
case 3: active = (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 ClientIdentifier getClientIdentifier() {
return clientIdentifier;
}
/**
* Sets the value of the 'clientIdentifier' field.
* @param value the value to set.
*/
public void setClientIdentifier(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 Active getActive() {
return active;
}
/**
* Sets the value of the 'active' field.
* @param value the value to set.
*/
public void setActive(Active value) {
this.active = value;
}
/**
* Creates a new AvroHttpRequest RecordBuilder.
* @return A new AvroHttpRequest RecordBuilder
*/
public static AvroHttpRequest.Builder newBuilder() {
return new 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 AvroHttpRequest.Builder newBuilder(AvroHttpRequest.Builder other) {
return new 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 AvroHttpRequest.Builder newBuilder(AvroHttpRequest other) {
return new 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 ClientIdentifier clientIdentifier;
private ClientIdentifier.Builder clientIdentifierBuilder;
private java.util.List<java.lang.CharSequence> employeeNames;
private 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(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 = 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(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 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 AvroHttpRequest.Builder clearRequestTime() {
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'clientIdentifier' field.
* @return The value.
*/
public ClientIdentifier getClientIdentifier() {
return clientIdentifier;
}
/**
* Sets the value of the 'clientIdentifier' field.
* @param value The value of 'clientIdentifier'.
* @return This builder.
*/
public AvroHttpRequest.Builder setClientIdentifier(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 ClientIdentifier.Builder getClientIdentifierBuilder() {
if (clientIdentifierBuilder == null) {
if (hasClientIdentifier()) {
setClientIdentifierBuilder(ClientIdentifier.newBuilder(clientIdentifier));
} else {
setClientIdentifierBuilder(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 AvroHttpRequest.Builder setClientIdentifierBuilder(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 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 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 AvroHttpRequest.Builder clearEmployeeNames() {
employeeNames = null;
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'active' field.
* @return The value.
*/
public Active getActive() {
return active;
}
/**
* Sets the value of the 'active' field.
* @param value The value of 'active'.
* @return This builder.
*/
public AvroHttpRequest.Builder setActive(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 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 : (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 : (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.util.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 ClientIdentifier.Builder newBuilder() {
return new 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 ClientIdentifier.Builder newBuilder(ClientIdentifier.Builder other) {
return new 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 ClientIdentifier.Builder newBuilder(ClientIdentifier other) {
return new 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(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(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 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 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 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 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

@ -0,0 +1,41 @@
package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class AvroDeSerealizer {
private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) {
DatumReader<AvroHttpRequest> reader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = null;
try {
decoder = DecoderFactory.get()
.jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
return reader.read(null, decoder);
} catch (IOException e) {
logger.error("Deserialization error" + e.getMessage());
}
return null;
}
public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) {
DatumReader<AvroHttpRequest> employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = DecoderFactory.get()
.binaryDecoder(data, null);
try {
return employeeReader.read(null, decoder);
} catch (IOException e) {
logger.error("Deserialization error" + e.getMessage());
}
return null;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class AvroSerealizer {
private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) {
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = null;
try {
jsonEncoder = EncoderFactory.get()
.jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
logger.error("Serialization error " + e.getMessage());
}
return data;
}
public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request) {
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = EncoderFactory.get()
.binaryEncoder(stream, null);
try {
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
logger.error("Serialization error " + e.getMessage());
}
return data;
}
}

View File

@ -0,0 +1,47 @@
{
"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"
]
}
}
]
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,83 @@
package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.Active;
import com.baeldung.avro.util.model.AvroHttpRequest;
import com.baeldung.avro.util.model.ClientIdentifier;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static org.junit.Assert.*;
public class AvroSerealizerDeSerealizerTest {
AvroSerealizer serealizer;
AvroDeSerealizer deSerealizer;
AvroHttpRequest request;
@Before
public void setUp() throws Exception {
serealizer = new AvroSerealizer();
deSerealizer = new AvroDeSerealizer();
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder()
.setHostName("localhost")
.setIpAddress("255.255.255.0")
.build();
List<CharSequence> employees = new ArrayList();
employees.add("James");
employees.add("Alice");
employees.add("David");
employees.add("Han");
request = AvroHttpRequest.newBuilder()
.setRequestTime(01l)
.setActive(Active.YES)
.setClientIdentifier(clientIdentifier)
.setEmployeeNames(employees)
.build();
}
@After
public void tearDown() throws Exception {
}
@Test
public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() {
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() {
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() {
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
assertEquals(actualRequest, request);
assertTrue(actualRequest.getRequestTime()
.equals(request.getRequestTime()));
}
@Test
public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() {
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
assertEquals(actualRequest, request);
assertTrue(actualRequest.getRequestTime()
.equals(request.getRequestTime()));
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -3,3 +3,4 @@
- [Apache CXF Support for RESTful Web Services](http://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](http://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf)
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,5 +1,5 @@
<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">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId>
@ -17,6 +17,7 @@
<module>cxf-spring</module>
<module>cxf-jaxrs-implementation</module>
<module>cxf-aegis</module>
<module>sse-jaxrs</module>
</modules>
<build>

View File

@ -0,0 +1,21 @@
<?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>sse-jaxrs</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modules>
<module>sse-jaxrs-server</module>
<module>sse-jaxrs-client</module>
</modules>
</project>

View File

@ -0,0 +1,62 @@
<?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>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>sse-jaxrs</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>sse-jaxrs-client</artifactId>
<properties>
<cxf-version>3.2.0</cxf-version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
<execution>
<id>singleEvent</id>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.baeldung.sse.jaxrs.client.SseClientApp</mainClass>
</configuration>
</execution>
<execution>
<id>broadcast</id>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.baeldung.sse.jaxrs.client.SseClientBroadcastApp</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>${cxf-version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-sse</artifactId>
<version>${cxf-version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,48 @@
package com.baeldung.sse.jaxrs.client;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.sse.InboundSseEvent;
import javax.ws.rs.sse.SseEventSource;
import java.util.function.Consumer;
public class SseClientApp {
private static final String url = "http://127.0.0.1:9080/sse-jaxrs-server/sse/stock/prices";
public static void main(String... args) throws Exception {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
try (SseEventSource eventSource = SseEventSource.target(target).build()) {
eventSource.register(onEvent, onError, onComplete);
eventSource.open();
//Consuming events for one hour
Thread.sleep(60 * 60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.close();
System.out.println("End");
}
// A new event is received
private static Consumer<InboundSseEvent> onEvent = (inboundSseEvent) -> {
String data = inboundSseEvent.readData();
System.out.println(data);
};
//Error
private static Consumer<Throwable> onError = (throwable) -> {
throwable.printStackTrace();
};
//Connection close and there is nothing to receive
private static Runnable onComplete = () -> {
System.out.println("Done!");
};
}

View File

@ -0,0 +1,52 @@
package com.baeldung.sse.jaxrs.client;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.sse.InboundSseEvent;
import javax.ws.rs.sse.SseEventSource;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public class SseClientBroadcastApp {
private static final String subscribeUrl = "http://localhost:9080/sse-jaxrs-server/sse/stock/subscribe";
public static void main(String... args) throws Exception {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(subscribeUrl);
try (final SseEventSource eventSource = SseEventSource.target(target)
.reconnectingEvery(5, TimeUnit.SECONDS)
.build()) {
eventSource.register(onEvent, onError, onComplete);
eventSource.open();
System.out.println("Wainting for incoming event ...");
//Consuming events for one hour
Thread.sleep(60 * 60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.close();
System.out.println("End");
}
// A new event is received
private static Consumer<InboundSseEvent> onEvent = (inboundSseEvent) -> {
String data = inboundSseEvent.readData();
System.out.println(data);
};
//Error
private static Consumer<Throwable> onError = (throwable) -> {
throwable.printStackTrace();
};
//Connection close and there is nothing to receive
private static Runnable onComplete = () -> {
System.out.println("Done!");
};
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,85 @@
<?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>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>sse-jaxrs</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>sse-jaxrs-server</artifactId>
<packaging>war</packaging>
<properties>
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
<failOnMissingWebXml>false</failOnMissingWebXml>
<openliberty-version>18.0.0.2</openliberty-version>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>net.wasdev.wlp.maven.plugins</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>${liberty-maven-plugin.version}</version>
<configuration>
<assemblyArtifact>
<groupId>io.openliberty</groupId>
<artifactId>openliberty-webProfile8</artifactId>
<version>${openliberty-version}</version>
<type>zip</type>
</assemblyArtifact>
<installAppPackages>project</installAppPackages>
<looseApplication>true</looseApplication>
<configFile>src/main/liberty/config/server.xml</configFile>
</configuration>
<executions>
<execution>
<id>install-server</id>
<phase>prepare-package</phase>
<goals>
<goal>install-server</goal>
<goal>create-server</goal>
<goal>install-feature</goal>
</goals>
</execution>
<execution>
<id>install-apps</id>
<phase>package</phase>
<goals>
<goal>install-apps</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,8 @@
package com.baeldung.sse.jaxrs;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("sse")
public class AppConfig extends Application {
}

View File

@ -0,0 +1,119 @@
package com.baeldung.sse.jaxrs;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.sse.OutboundSseEvent;
import javax.ws.rs.sse.Sse;
import javax.ws.rs.sse.SseBroadcaster;
import javax.ws.rs.sse.SseEventSink;
@ApplicationScoped
@Path("stock")
public class SseResource {
@Inject
private StockService stockService;
private Sse sse;
private SseBroadcaster sseBroadcaster;
private OutboundSseEvent.Builder eventBuilder;
@Context
public void setSse(Sse sse) {
this.sse = sse;
this.eventBuilder = sse.newEventBuilder();
this.sseBroadcaster = sse.newBroadcaster();
}
@GET
@Path("prices")
@Produces("text/event-stream")
public void getStockPrices(@Context SseEventSink sseEventSink,
@HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastReceivedId) {
int lastEventId = 1;
if (lastReceivedId != -1) {
lastEventId = ++lastReceivedId;
}
boolean running = true;
while (running) {
Stock stock = stockService.getNextTransaction(lastEventId);
if (stock != null) {
OutboundSseEvent sseEvent = this.eventBuilder
.name("stock")
.id(String.valueOf(lastEventId))
.mediaType(MediaType.APPLICATION_JSON_TYPE)
.data(Stock.class, stock)
.reconnectDelay(3000)
.comment("price change")
.build();
sseEventSink.send(sseEvent);
lastEventId++;
}
//Simulate connection close
if (lastEventId % 5 == 0) {
sseEventSink.close();
break;
}
try {
//Wait 5 seconds
Thread.sleep(5 * 1000);
} catch (InterruptedException ex) {
// ...
}
//Simulatae a while boucle break
running = lastEventId <= 2000;
}
sseEventSink.close();
}
@GET
@Path("subscribe")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void listen(@Context SseEventSink sseEventSink) {
sseEventSink.send(sse.newEvent("Welcome !"));
this.sseBroadcaster.register(sseEventSink);
sseEventSink.send(sse.newEvent("You are registred !"));
}
@GET
@Path("publish")
public void broadcast() {
Runnable r = new Runnable() {
@Override
public void run() {
int lastEventId = 0;
boolean running = true;
while (running) {
lastEventId++;
Stock stock = stockService.getNextTransaction(lastEventId);
if (stock != null) {
OutboundSseEvent sseEvent = eventBuilder
.name("stock")
.id(String.valueOf(lastEventId))
.mediaType(MediaType.APPLICATION_JSON_TYPE)
.data(Stock.class, stock)
.reconnectDelay(3000)
.comment("price change")
.build();
sseBroadcaster.broadcast(sseEvent);
}
try {
//Wait 5 seconds
Thread.currentThread().sleep(5 * 1000);
} catch (InterruptedException ex) {
// ...
}
//Simulatae a while boucle break
running = lastEventId <= 2000;
}
}
};
new Thread(r).start();
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.sse.jaxrs;
import java.math.BigDecimal;
import java.time.LocalDateTime;
public class Stock {
private Integer id;
private String name;
private BigDecimal price;
LocalDateTime dateTime;
public Stock(Integer id, String name, BigDecimal price, LocalDateTime dateTime) {
this.id = id;
this.name = name;
this.price = price;
this.dateTime = dateTime;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public LocalDateTime getDateTime() {
return dateTime;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
}

View File

@ -0,0 +1,78 @@
package com.baeldung.sse.jaxrs;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Initialized;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.inject.Named;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
@ApplicationScoped
@Named
public class StockService {
private static final BigDecimal UP = BigDecimal.valueOf(1.05f);
private static final BigDecimal DOWN = BigDecimal.valueOf(0.95f);
List<String> stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO");
List<Stock> stocksDB = new ArrayList<>();
private AtomicInteger counter = new AtomicInteger(0);
public void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
//Open price
System.out.println("@Start Init ...");
stockNames.forEach(stockName -> {
stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now()));
});
Runnable runnable = new Runnable() {
@Override
public void run() {
//Simulate Change price and put every x seconds
while (true) {
int indx = new Random().nextInt(stockNames.size());
String stockName = stockNames.get(indx);
BigDecimal price = getLastPrice(stockName);
BigDecimal newprice = changePrice(price);
Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now());
stocksDB.add(stock);
int r = new Random().nextInt(30);
try {
Thread.currentThread().sleep(r*1000);
} catch (InterruptedException ex) {
// ...
}
}
}
};
new Thread(runnable).start();
System.out.println("@End Init ...");
}
public Stock getNextTransaction(Integer lastEventId) {
return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null);
}
BigDecimal generateOpenPrice() {
float min = 70;
float max = 120;
return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING);
}
BigDecimal changePrice(BigDecimal price) {
return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING);
}
private BigDecimal getLastPrice(String stockName) {
return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice();
}
}

View File

@ -0,0 +1,7 @@
<server description="OpenLiberty Server">
<featureManager>
<feature>jaxrs-2.1</feature>
<feature>cdi-2.0</feature>
</featureManager>
<httpEndpoint httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint" host="*"/>
</server>

View File

@ -0,0 +1,6 @@
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
bean-discovery-mode="all">
</beans>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>Hello Servlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

View File

@ -0,0 +1 @@
index

View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html>
<head>
<title>Server-Sent Event Broadcasting</title>
</head>
<body>
<h2>Stock prices :</h2>
<div>
<ul id="data">
</ul>
</div>
<script>
var source = new EventSource('sse/stock/subscribe');
source.onopen = function(event) {
console.log(event);
};
source.addEventListener("stock", function(event) {
append(event.data);
}, false);
source.onmessage = function(event) {
append(event.data);
};
source.onerror = function(event) {
console.log(event);
};
function append(data) {
var ul = document.getElementById("data");
var li = document.createElement("li");
li.appendChild(document.createTextNode(data));
ul.insertBefore(li, ul.childNodes[0]);
};
</script>
</body>
</html>

View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html>
<head>
<title>Server-Sent Event</title>
</head>
<body>
<h2>Stock prices :</h2>
<div>
<ul id="data">
</ul>
</div>
<script>
var source = new EventSource('sse/stock/prices');
source.onopen = function(event) {
console.log(event);
};
source.addEventListener("stock", function(event) {
append(event.data);
}, false);
source.onmessage = function(event) {
append(event.data);
};
source.onerror = function(event) {
console.log(event);
};
function append(data) {
var ul = document.getElementById("data");
var li = document.createElement("li");
li.appendChild(document.createTextNode(data));
ul.insertBefore(li, ul.childNodes[0]);
};
</script>
</body>
</html>

View File

@ -2,7 +2,7 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>

View File

@ -0,0 +1,3 @@
### Relevant Articles:
================================
- [Building a Microservice with Apache Meecrowave](http://www.baeldung.com/apache-meecrowave)

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -3,14 +3,14 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-shiro</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
</parent>
<dependencies>
@ -35,13 +35,11 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
@ -52,26 +50,9 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<java.version>1.8</java.version>
<log4j-version>1.2.17</log4j-version>
<slf4j-version>1.7.25</slf4j-version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -39,6 +39,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>${build-helper-maven-plugin.version}</version>
<executions>
<execution>
<phase>generate-sources</phase>
@ -60,6 +61,7 @@
<thrift.version>0.10.0</thrift.version>
<maven-thrift.version>0.1.11</maven-thrift.version>
<org.slf4j.slf4j-simple.version>1.7.12</org.slf4j.slf4j-simple.version>
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -2,7 +2,7 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,5 +1,4 @@
### Relevant articles
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book)
- [Introduction to Asciidoctor in Java](http://www.baeldung.com/asciidoctor)

View File

@ -61,9 +61,10 @@
</build>
<properties>
<asciidoctor-maven-plugin.version>1.5.5</asciidoctor-maven-plugin.version>
<asciidoctorj.version>1.5.4</asciidoctorj.version>
<asciidoctorj-pdf.src.version>1.5.0-alpha.11</asciidoctorj-pdf.src.version>
<asciidoctor-maven-plugin.version>1.5.6</asciidoctor-maven-plugin.version>
<asciidoctorj.version>1.5.6</asciidoctorj.version>
<asciidoctorj-pdf.version>1.5.0-alpha.15</asciidoctorj-pdf.version>
<asciidoctorj-pdf.plugin.version>1.5.0-alpha.15</asciidoctorj-pdf.plugin.version>
</properties>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -3,7 +3,7 @@ package com.baeldung.asciidoctor;
import org.junit.Assert;
import org.junit.Test;
public class AsciidoctorDemoTest {
public class AsciidoctorDemoIntegrationTest {
@Test
public void givenString_whenConverting_thenResultingHTMLCode() {

View File

@ -42,14 +42,6 @@
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<argLine>-javaagent:"C:\asm-1.0.jar"</argLine>
</configuration>
</plugin>
</plugins>
</build>

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