Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Denis 2018-08-27 21:34:10 +02:00
commit 913ec96209
1507 changed files with 36810 additions and 5207 deletions

5
.gitignore vendored
View File

@ -57,3 +57,8 @@ core-java-io/target_link.txt
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
ethereum/logs/ ethereum/logs/
jmeter/src/main/resources/*-JMeter.csv jmeter/src/main/resources/*-JMeter.csv
**/node_modules/
**/dist
**/tmp
**/out-tsc

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

@ -23,3 +23,4 @@
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic) - [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) - [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) - [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)

View File

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

View File

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

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.Assert;
import org.junit.Test; import org.junit.Test;

View File

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

View File

@ -1,4 +1,4 @@
package algorithms; package com.baeldung.algorithms;
import org.junit.Test; 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.HillClimbing;
import com.baeldung.algorithms.hillclimbing.State; 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.MiddleElementLookup;
import com.baeldung.algorithms.middleelementlookup.Node; import com.baeldung.algorithms.middleelementlookup.Node;

View File

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

View File

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

View File

@ -1,4 +1,4 @@
package algorithms; package com.baeldung.algorithms;
import org.junit.Assert; 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.Arrays;
import java.util.List; import java.util.List;

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.assertEquals;
import static org.junit.Assert.assertTrue; 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.Before;
import org.junit.Test; import org.junit.Test;

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)

View File

@ -5,29 +5,37 @@ import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder; import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory; import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificDatumReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
public class AvroDeSerealizer { public class AvroDeSerealizer {
public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data){ private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
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) {
return null;
}
}
public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data){ public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) {
DatumReader<AvroHttpRequest> employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class); DatumReader<AvroHttpRequest> reader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = DecoderFactory.get().binaryDecoder(data, null); Decoder decoder = null;
try { try {
return employeeReader.read(null, decoder); decoder = DecoderFactory.get()
} catch (IOException e) { .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; return null;
} }
} }
}

View File

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

@ -24,8 +24,10 @@ public class AvroSerealizerDeSerealizerTest {
serealizer = new AvroSerealizer(); serealizer = new AvroSerealizer();
deSerealizer = new AvroDeSerealizer(); deSerealizer = new AvroDeSerealizer();
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder(). ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder()
setHostName("localhost").setIpAddress("255.255.255.0").build(); .setHostName("localhost")
.setIpAddress("255.255.255.0")
.build();
List<CharSequence> employees = new ArrayList(); List<CharSequence> employees = new ArrayList();
employees.add("James"); employees.add("James");
@ -33,43 +35,49 @@ public class AvroSerealizerDeSerealizerTest {
employees.add("David"); employees.add("David");
employees.add("Han"); employees.add("Han");
request = AvroHttpRequest.newBuilder().setRequestTime(01l) request = AvroHttpRequest.newBuilder()
.setActive(Active.YES).setClientIdentifier(clientIdentifier) .setRequestTime(01l)
.setEmployeeNames(employees).build(); .setActive(Active.YES)
.setClientIdentifier(clientIdentifier)
.setEmployeeNames(employees)
.build();
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
} }
@Test @Test
public void WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){ public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() {
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request); byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
assertTrue(Objects.nonNull(data)); assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0); assertTrue(data.length > 0);
} }
@Test @Test
public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){ public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() {
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request); byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
assertTrue(Objects.nonNull(data)); assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0); assertTrue(data.length > 0);
} }
@Test @Test
public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){ public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() {
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request); byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data); AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
assertEquals(actualRequest,request); assertEquals(actualRequest, request);
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime())); assertTrue(actualRequest.getRequestTime()
} .equals(request.getRequestTime()));
}
@Test
public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){ @Test
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request); public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() {
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data); byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
assertEquals(actualRequest,request); AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime())); 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

@ -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" <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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId> <artifactId>apache-cxf</artifactId>
@ -17,6 +17,7 @@
<module>cxf-spring</module> <module>cxf-spring</module>
<module>cxf-jaxrs-implementation</module> <module>cxf-jaxrs-implementation</module>
<module>cxf-aegis</module> <module>cxf-aegis</module>
<module>sse-jaxrs</module>
</modules> </modules>
<build> <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>${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> <configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder> <encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern> </pattern>
</encoder> </encoder>
</appender> </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

@ -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

@ -8,9 +8,10 @@
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <artifactId>parent-boot-1</artifactId>
<artifactId>spring-boot-starter-parent</artifactId> <groupId>com.baeldung</groupId>
<version>1.5.2.RELEASE</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
</parent> </parent>
<dependencies> <dependencies>

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> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId> <artifactId>build-helper-maven-plugin</artifactId>
<version>${build-helper-maven-plugin.version}</version>
<executions> <executions>
<execution> <execution>
<phase>generate-sources</phase> <phase>generate-sources</phase>
@ -60,6 +61,7 @@
<thrift.version>0.10.0</thrift.version> <thrift.version>0.10.0</thrift.version>
<maven-thrift.version>0.1.11</maven-thrift.version> <maven-thrift.version>0.1.11</maven-thrift.version>
<org.slf4j.slf4j-simple.version>1.7.12</org.slf4j.slf4j-simple.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> </properties>
</project> </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> <configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder> <encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern> </pattern>
</encoder> </encoder>
</appender> </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

@ -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

@ -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

@ -137,7 +137,7 @@
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version> <aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
<gson.version>2.8.0</gson.version> <gson.version>2.8.0</gson.version>
<aws-java-sdk.version>1.11.290</aws-java-sdk.version> <aws-java-sdk.version>1.11.290</aws-java-sdk.version>
<mockito-core.version>2.8.9</mockito-core.version> <mockito-core.version>2.21.0</mockito-core.version>
<assertj-core.version>3.8.0</assertj-core.version> <assertj-core.version>3.8.0</assertj-core.version>
<dynamodblocal.version>1.11.86</dynamodblocal.version> <dynamodblocal.version>1.11.86</dynamodblocal.version>
<dynamodblocal.repository.url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</dynamodblocal.repository.url> <dynamodblocal.repository.url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</dynamodblocal.repository.url>

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

@ -10,10 +10,10 @@
<description>Demo project for Spring Boot</description> <description>Demo project for Spring Boot</description>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <artifactId>parent-boot-1</artifactId>
<artifactId>spring-boot-starter-parent</artifactId> <groupId>com.baeldung</groupId>
<version>1.5.13.RELEASE</version> <version>0.0.1-SNAPSHOT</version>
<relativePath /> <!-- lookup parent from repository --> <relativePath>../../parent-boot-1</relativePath>
</parent> </parent>
<dependencies> <dependencies>

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

@ -3,3 +3,4 @@
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference) - [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
- [Guide to Java 10](http://www.baeldung.com/java-10-overview) - [Guide to Java 10](http://www.baeldung.com/java-10-overview)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)

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

@ -9,50 +9,30 @@
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features) - [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector) - [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern) - [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams)
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions) - [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing) - [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api)
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional) - [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java) - [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) - [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode) - [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
- [Copy a File with Java](http://www.baeldung.com/java-copy-file) - [Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods) - [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency) - [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) - [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection) - [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator) - [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math) - [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations) - [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max) - [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization) - [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) - [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
- [Java Optional orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) - [Java Optional orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) - [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) - [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic) - [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference) - [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) - [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Calculate Age in Java](http://www.baeldung.com/java-get-age) - [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)

View File

@ -89,11 +89,6 @@
<artifactId>vavr</artifactId> <artifactId>vavr</artifactId>
<version>${vavr.version}</version> <version>${vavr.version}</version>
</dependency> </dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency> <dependency>
<groupId>joda-time</groupId> <groupId>joda-time</groupId>
<artifactId>joda-time</artifactId> <artifactId>joda-time</artifactId>
@ -151,6 +146,7 @@
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -176,7 +172,6 @@
<lombok.version>1.16.12</lombok.version> <lombok.version>1.16.12</lombok.version>
<vavr.version>0.9.0</vavr.version> <vavr.version>0.9.0</vavr.version>
<protonpack.version>1.13</protonpack.version> <protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<joda.version>2.10</joda.version> <joda.version>2.10</joda.version>
<!-- testing --> <!-- testing -->
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
@ -184,6 +179,6 @@
<avaitility.version>1.7.0</avaitility.version> <avaitility.version>1.7.0</avaitility.version>
<jmh-core.version>1.19</jmh-core.version> <jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version> <jmh-generator.version>1.19</jmh-generator.version>
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,19 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
/**
* This method shows how to make a null safe stream from a collection through the use of
* emptyIfNull() method from Apache Commons CollectionUtils library
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return emptyIfNull(collection).stream();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
/**
* This method shows how to make a null safe stream from a collection through the use of
* Java SE 8s Optional Container
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return Optional.ofNullable(collection)
.map(Collection::stream)
.orElseGet(Stream::empty);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
/**
* This method shows how to make a null safe stream from a collection through the use of a check
* to prevent null dereferences
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return collection == null ? Stream.empty() : collection.stream();
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.primitive;
public class BenchmarkRunner {
public static void main(String[] args) throws Exception {
new IntPrimitiveLookup().run();
new IntegerWrapperLookup().run();
new FloatPrimitiveLookup().run();
new FloatWrapperLookup().run();
new DoublePrimitiveLookup().run();
new DoubleWrapperLookup().run();
new ShortPrimitiveLookup().run();
new ShortWrapperLookup().run();
new BooleanPrimitiveLookup().run();
new BooleanWrapperLookup().run();
new CharPrimitiveLookup().run();
new CharacterWrapperLookup().run();
new BytePrimitiveLookup().run();
new ByteWrapperLookup().run();
new LongPrimitiveLookup().run();
new LongWrapperLookup().run();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class BooleanPrimitiveLookup extends Lookup {
private boolean[] elements;
private final boolean pivot = false;
@Setup
@Override
public void prepare() {
elements = new boolean[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = true;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return BooleanPrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class BooleanWrapperLookup extends Lookup {
private Boolean[] elements;
private final boolean pivot = false;
@Override
@Setup
public void prepare() {
elements = new Boolean[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = true;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Boolean pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return BooleanWrapperLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class BytePrimitiveLookup extends Lookup {
private byte[] elements;
private final byte pivot = 2;
@Setup
@Override
public void prepare() {
byte common = 1;
elements = new byte[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return BytePrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class ByteWrapperLookup extends Lookup {
private Byte[] elements;
private final byte pivot = 2;
@Override
@Setup
public void prepare() {
byte common = 1;
elements = new Byte[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Byte pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return ByteWrapperLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class CharPrimitiveLookup extends Lookup {
private char[] elements;
private final char pivot = 'b';
@Setup
@Override
public void prepare() {
char common = 'a';
elements = new char[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return CharPrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class CharacterWrapperLookup extends Lookup {
private Character[] elements;
private final char pivot = 'b';
@Override
@Setup
public void prepare() {
char common = 'a';
elements = new Character[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Character pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return CharacterWrapperLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class DoublePrimitiveLookup extends Lookup {
private double[] elements;
private final double pivot = 2;
@Setup
@Override
public void prepare() {
double common = 1;
elements = new double[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return DoublePrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class DoubleWrapperLookup extends Lookup {
private Double[] elements;
private final double pivot = 2d;
@Override
@Setup
public void prepare() {
double common = 1;
elements = new Double[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Double pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return DoubleWrapperLookup.class.getSimpleName();
}
}

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