Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
d37c9e8045
|
@ -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>
|
||||
|
|
|
@ -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/>
|
||||
|
|
|
@ -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);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import org.junit.Test;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import com.baeldung.algorithms.hillclimbing.HillClimbing;
|
||||
import com.baeldung.algorithms.hillclimbing.State;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
|
||||
import com.baeldung.algorithms.middleelementlookup.Node;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import com.baeldung.algorithms.automata.*;
|
||||
import org.junit.Test;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms;
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
|
||||
import org.junit.Assert;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms.binarysearch;
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
|
@ -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);
|
||||
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms.mcts;
|
||||
package com.baeldung.algorithms.mcts;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
|
@ -1,4 +1,4 @@
|
|||
package algorithms.minimax;
|
||||
package com.baeldung.algorithms.minimax;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -4,8 +4,9 @@
|
|||
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-tutorial</artifactId>
|
||||
<artifactId>apache-avro</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>Apache Avro</version>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
|
|
@ -5,29 +5,37 @@ 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 {
|
||||
|
||||
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) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
|
||||
|
||||
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) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,42 +3,48 @@ 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 {
|
||||
|
||||
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) {
|
||||
data =null;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
|
||||
|
||||
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) {
|
||||
data = null;
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -24,8 +24,10 @@ public class AvroSerealizerDeSerealizerTest {
|
|||
serealizer = new AvroSerealizer();
|
||||
deSerealizer = new AvroDeSerealizer();
|
||||
|
||||
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder().
|
||||
setHostName("localhost").setIpAddress("255.255.255.0").build();
|
||||
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder()
|
||||
.setHostName("localhost")
|
||||
.setIpAddress("255.255.255.0")
|
||||
.build();
|
||||
|
||||
List<CharSequence> employees = new ArrayList();
|
||||
employees.add("James");
|
||||
|
@ -33,43 +35,49 @@ public class AvroSerealizerDeSerealizerTest {
|
|||
employees.add("David");
|
||||
employees.add("Han");
|
||||
|
||||
request = AvroHttpRequest.newBuilder().setRequestTime(01l)
|
||||
.setActive(Active.YES).setClientIdentifier(clientIdentifier)
|
||||
.setEmployeeNames(employees).build();
|
||||
request = AvroHttpRequest.newBuilder()
|
||||
.setRequestTime(01l)
|
||||
.setActive(Active.YES)
|
||||
.setClientIdentifier(clientIdentifier)
|
||||
.setEmployeeNames(employees)
|
||||
.build();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
|
||||
assertTrue(Objects.nonNull(data));
|
||||
assertTrue(data.length > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
|
||||
assertTrue(Objects.nonNull(data));
|
||||
assertTrue(data.length > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
|
||||
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
|
||||
assertEquals(actualRequest,request);
|
||||
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
|
||||
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
|
||||
assertEquals(actualRequest,request);
|
||||
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
|
||||
}
|
||||
@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()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -20,7 +20,7 @@
|
|||
</properties>
|
||||
|
||||
<build>
|
||||
<finalName>${artifactId}</finalName>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>net.wasdev.wlp.maven.plugins</groupId>
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -95,7 +95,6 @@
|
|||
<gson.version>2.8.2</gson.version>
|
||||
<aws-java-sdk.version>1.11.241</aws-java-sdk.version>
|
||||
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
||||
<maven-dependency-plugin.version>2.10</maven-dependency-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1 +1,2 @@
|
|||
/target/
|
||||
.idea/
|
23
aws/pom.xml
23
aws/pom.xml
|
@ -100,26 +100,6 @@
|
|||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>${maven-dependency-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includeScope>test</includeScope>
|
||||
<includeTypes>so,dll,dylib</includeTypes>
|
||||
<outputDirectory>${project.basedir}/native-libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
@ -137,14 +117,13 @@
|
|||
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.0</gson.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>
|
||||
<dynamodblocal.version>1.11.86</dynamodblocal.version>
|
||||
<dynamodblocal.repository.url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</dynamodblocal.repository.url>
|
||||
<commons-codec-version>1.10.L001</commons-codec-version>
|
||||
<jets3t-version>0.9.4.0006L</jets3t-version>
|
||||
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
||||
<maven-dependency-plugin.version>2.10</maven-dependency-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,184 @@
|
|||
package com.baeldung.rds;
|
||||
|
||||
import com.amazonaws.auth.AWSCredentialsProvider;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.rds.AmazonRDS;
|
||||
import com.amazonaws.services.rds.AmazonRDSClientBuilder;
|
||||
import com.amazonaws.services.rds.model.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.sql.*;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class AWSRDSService {
|
||||
|
||||
|
||||
final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
|
||||
private AWSCredentialsProvider credentials;
|
||||
private AmazonRDS amazonRDS;
|
||||
private String db_username;
|
||||
private String db_password;
|
||||
private String db_database;
|
||||
private String db_hostname;
|
||||
|
||||
/*
|
||||
* User access key and secret key must be set before execute any operation.
|
||||
* Follow the link on how to get the user access and secret key
|
||||
* https://aws.amazon.com/blogs/security/wheres-my-secret-access-key/
|
||||
* **/
|
||||
public AWSRDSService() throws IOException {
|
||||
//Init RDS client with credentials and region.
|
||||
credentials = new
|
||||
AWSStaticCredentialsProvider(new
|
||||
BasicAWSCredentials("<ACCESS_KEY>",
|
||||
"<SECRET_KEY>"));
|
||||
amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials)
|
||||
.withRegion(Regions.AP_SOUTHEAST_2).build();
|
||||
Properties prop = new Properties();
|
||||
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
|
||||
prop.load(input);
|
||||
db_username = prop.getProperty("db_username");
|
||||
db_password = prop.getProperty("db_password");
|
||||
db_database = prop.getProperty("db_database");
|
||||
}
|
||||
|
||||
public AWSRDSService(AmazonRDS amazonRDS){
|
||||
this.amazonRDS = amazonRDS;
|
||||
}
|
||||
|
||||
/**
|
||||
* create the RDS instance.
|
||||
* After instance creation, update the db_hostname with endpoint in db.properties.
|
||||
* */
|
||||
|
||||
public String launchInstance() {
|
||||
|
||||
String identifier = "";
|
||||
CreateDBInstanceRequest request = new CreateDBInstanceRequest();
|
||||
// RDS instance name
|
||||
request.setDBInstanceIdentifier("Sydney");
|
||||
request.setEngine("postgres");
|
||||
request.setMultiAZ(false);
|
||||
request.setMasterUsername(db_username);
|
||||
request.setMasterUserPassword(db_password);
|
||||
request.setDBName(db_database);
|
||||
request.setStorageType("gp2");
|
||||
request.setAllocatedStorage(10);
|
||||
|
||||
DBInstance instance = amazonRDS.createDBInstance(request);
|
||||
|
||||
// Information about the new RDS instance
|
||||
identifier = instance.getDBInstanceIdentifier();
|
||||
String status = instance.getDBInstanceStatus();
|
||||
Endpoint endpoint = instance.getEndpoint();
|
||||
String endpoint_url = "Endpoint URL not available yet.";
|
||||
if (endpoint != null) {
|
||||
endpoint_url = endpoint.toString();
|
||||
}
|
||||
logger.info(identifier + "\t" + status);
|
||||
logger.info(endpoint_url);
|
||||
|
||||
return identifier;
|
||||
|
||||
}
|
||||
|
||||
// Describe DB instances
|
||||
public void listInstances() {
|
||||
DescribeDBInstancesResult result = amazonRDS.describeDBInstances();
|
||||
List<DBInstance> instances = result.getDBInstances();
|
||||
for (DBInstance instance : instances) {
|
||||
// Information about each RDS instance
|
||||
String identifier = instance.getDBInstanceIdentifier();
|
||||
String engine = instance.getEngine();
|
||||
String status = instance.getDBInstanceStatus();
|
||||
Endpoint endpoint = instance.getEndpoint();
|
||||
String endpoint_url = "Endpoint URL not available yet.";
|
||||
if (endpoint != null) {
|
||||
endpoint_url = endpoint.toString();
|
||||
}
|
||||
logger.info(identifier + "\t" + engine + "\t" + status);
|
||||
logger.info("\t" + endpoint_url);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Delete RDS instance
|
||||
public void terminateInstance(String identifier) {
|
||||
|
||||
DeleteDBInstanceRequest request = new DeleteDBInstanceRequest();
|
||||
request.setDBInstanceIdentifier(identifier);
|
||||
request.setSkipFinalSnapshot(true);
|
||||
|
||||
// Delete the RDS instance
|
||||
DBInstance instance = amazonRDS.deleteDBInstance(request);
|
||||
|
||||
// Information about the RDS instance being deleted
|
||||
String status = instance.getDBInstanceStatus();
|
||||
Endpoint endpoint = instance.getEndpoint();
|
||||
String endpoint_url = "Endpoint URL not available yet.";
|
||||
if (endpoint != null) {
|
||||
endpoint_url = endpoint.toString();
|
||||
}
|
||||
|
||||
logger.info(identifier + "\t" + status);
|
||||
logger.info(endpoint_url);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public void runJdbcTests() throws SQLException, IOException {
|
||||
|
||||
// Getting database properties from db.properties
|
||||
Properties prop = new Properties();
|
||||
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
|
||||
prop.load(input);
|
||||
db_hostname = prop.getProperty("db_hostname");
|
||||
String jdbc_url = "jdbc:postgresql://" + db_hostname + ":5432/" + db_database;
|
||||
|
||||
// Create a connection using the JDBC driver
|
||||
try (Connection conn = DriverManager.getConnection(jdbc_url, db_username, db_password)) {
|
||||
|
||||
// Create the test table if not exists
|
||||
Statement statement = conn.createStatement();
|
||||
String sql = "CREATE TABLE IF NOT EXISTS jdbc_test (id SERIAL PRIMARY KEY, content VARCHAR(80))";
|
||||
statement.executeUpdate(sql);
|
||||
|
||||
// Do some INSERT
|
||||
PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO jdbc_test (content) VALUES (?)");
|
||||
String content = "" + UUID.randomUUID();
|
||||
preparedStatement.setString(1, content);
|
||||
preparedStatement.executeUpdate();
|
||||
logger.info("INSERT: " + content);
|
||||
|
||||
// Do some SELECT
|
||||
sql = "SELECT * FROM jdbc_test";
|
||||
ResultSet resultSet = statement.executeQuery(sql);
|
||||
while (resultSet.next()) {
|
||||
String count = resultSet.getString("content");
|
||||
logger.info("Total Records: " + count);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException, SQLException {
|
||||
AWSRDSService awsrdsService = new AWSRDSService();
|
||||
|
||||
String instanceName = awsrdsService.launchInstance();
|
||||
|
||||
//Add some wait for instance creation.
|
||||
|
||||
awsrdsService.listInstances();
|
||||
|
||||
awsrdsService.runJdbcTests();
|
||||
|
||||
awsrdsService.terminateInstance(instanceName);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
db_hostname=<RDS EndPoint>
|
||||
db_username=username
|
||||
db_password=password
|
||||
db_database=mydb
|
|
@ -1,70 +1,91 @@
|
|||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor;
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor;
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
|
||||
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import org.jboss.weld.environment.se.Weld;
|
||||
import org.jboss.weld.environment.se.WeldContainer;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
|
||||
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
|
||||
public class ImageProcessorUnitTest {
|
||||
|
||||
|
||||
private static ImageFileProcessor imageFileProcessor;
|
||||
private static SimpleDateFormat dateFormat;
|
||||
private static Calendar calendar;
|
||||
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setImageProcessorInstance() {
|
||||
Weld weld = new Weld();
|
||||
WeldContainer container = weld.initialize();
|
||||
imageFileProcessor = container.select(ImageFileProcessor.class).get();
|
||||
imageFileProcessor = container.select(ImageFileProcessor.class)
|
||||
.get();
|
||||
container.shutdown();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setSimpleDateFormatInstance() {
|
||||
dateFormat = new SimpleDateFormat("HH:mm");
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setCalendarInstance() {
|
||||
calendar = Calendar.getInstance();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() {
|
||||
assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class);
|
||||
assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String openFileLog = imageFileProcessor.openFile("file1.png");
|
||||
assertThat(openFileLog).contains("Opening PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(openFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String editFileLog = imageFileProcessor.editFile("file1.png");
|
||||
assertThat(editFileLog).contains("Editing PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(editFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String writeFileLog = imageFileProcessor.writeFile("file1.png");
|
||||
assertThat(writeFileLog).contains("Writing PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(writeFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String saveFileLog = imageFileProcessor.saveFile("file1.png");
|
||||
assertThat(saveFileLog).contains("Saving PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(saveFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
private LocalTime getLoggedTime(String log) throws ParseException {
|
||||
String logTimeString = log.split("at: ")[1];
|
||||
|
||||
int hour = Integer.valueOf(logTimeString.split(":")[0]);
|
||||
int minutes = Integer.valueOf(logTimeString.split(":")[1]);
|
||||
|
||||
LocalTime loggedTime = LocalTime.of(hour, minutes);
|
||||
return loggedTime;
|
||||
}
|
||||
}
|
|
@ -41,27 +41,6 @@
|
|||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<!-- This plugin will set properties values using dependency information -->
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<!--
|
||||
Goal that sets a property pointing to the artifact file for each project dependency.
|
||||
For each dependency (direct and transitive) a project property will be set which
|
||||
follows the:
|
||||
|
||||
groupId:artifactId:type:[classifier]
|
||||
|
||||
form and contains the path to the resolved artifact. -->
|
||||
<goal>properties</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
|
|
|
@ -9,54 +9,26 @@
|
|||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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 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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
|
||||
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
|
||||
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
|
||||
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
|
||||
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
|
||||
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
|
||||
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
|
||||
|
|
|
@ -89,11 +89,6 @@
|
|||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>${streamex.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
|
@ -121,23 +116,6 @@
|
|||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
|
@ -151,6 +129,7 @@
|
|||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
|
@ -176,7 +155,6 @@
|
|||
<lombok.version>1.16.12</lombok.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
<protonpack.version>1.13</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<joda.version>2.10</joda.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
|
@ -184,6 +162,6 @@
|
|||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<jmh-core.version>1.19</jmh-core.version>
|
||||
<jmh-generator.version>1.19</jmh-generator.version>
|
||||
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.optional;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
public String findNameById(String id) {
|
||||
return id == null ? null : "Name";
|
||||
}
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class FloatPrimitiveLookup extends Lookup {
|
||||
private float[] elements;
|
||||
private final float pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
int common = 1;
|
||||
elements = new float[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 FloatPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class FloatWrapperLookup extends Lookup {
|
||||
private Float[] elements;
|
||||
private final float pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
float common = 1;
|
||||
elements = new Float[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;
|
||||
Float pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return FloatWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class IntPrimitiveLookup extends Lookup {
|
||||
|
||||
private int[] elements;
|
||||
private final int pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
int common = 1;
|
||||
elements = new int[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 IntPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class IntegerWrapperLookup extends Lookup {
|
||||
private Integer[] elements;
|
||||
private final int pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
int common = 1;
|
||||
elements = new Integer[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;
|
||||
Integer pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return IntegerWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class LongPrimitiveLookup extends Lookup {
|
||||
private long[] elements;
|
||||
private final long pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
long common = 1;
|
||||
elements = new long[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 LongPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class LongWrapperLookup extends Lookup{
|
||||
private Long[] elements;
|
||||
private final long pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
long common = 1;
|
||||
elements = new Long[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;
|
||||
Long pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return LongWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.results.RunResult;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* An abstract class that is to be extended by the classes that
|
||||
* perform lookup in the arrays either of Java primitive types or their wrappers.
|
||||
*/
|
||||
public abstract class Lookup {
|
||||
/**
|
||||
* the array size
|
||||
*/
|
||||
final protected int s = 50000000;
|
||||
|
||||
/**
|
||||
* Initialize the array: fill in the array with the same
|
||||
* elements except for the last one.
|
||||
*/
|
||||
abstract public void prepare();
|
||||
|
||||
/**
|
||||
* Free the array's reference.
|
||||
*/
|
||||
abstract public void clean();
|
||||
|
||||
/**
|
||||
* Find the position of the element that is different from the others.
|
||||
* By construction, it is the last array element.
|
||||
*
|
||||
* @return array's last element index
|
||||
*/
|
||||
abstract public int findPosition();
|
||||
|
||||
/**
|
||||
* Get the name of the class that extends this one. It is needed in order
|
||||
* to set up the benchmark.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
abstract public String getSimpleClassName();
|
||||
|
||||
Collection<RunResult> run() throws RunnerException {
|
||||
Options opt = new OptionsBuilder()
|
||||
.include(getSimpleClassName())
|
||||
.forks(1)
|
||||
.build();
|
||||
return new Runner(opt).run();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class ShortPrimitiveLookup extends Lookup {
|
||||
|
||||
private short[] elements;
|
||||
private final short pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
short common = 1;
|
||||
elements = new short[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 ShortPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class ShortWrapperLookup extends Lookup {
|
||||
private Short[] elements;
|
||||
private final short pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
short common = 1;
|
||||
elements = new Short[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;
|
||||
Short pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return ShortWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -5,25 +5,22 @@
|
|||
*/
|
||||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Kwaje Anthony <kwajeanthony@gmail.com>
|
||||
*/
|
||||
public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
|
||||
|
||||
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance =
|
||||
new NullSafeCollectionStreamsUsingJava8OptionalContainer();
|
||||
|
||||
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = new NullSafeCollectionStreamsUsingJava8OptionalContainer();
|
||||
|
||||
@Test
|
||||
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
|
||||
|
@ -49,5 +46,5 @@ public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
|
|||
assertEquals(iter1.next(), iter2.next());
|
||||
assert !iter1.hasNext() && !iter2.hasNext();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.optional;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
public class PersonRepositoryUnitTest {
|
||||
|
||||
PersonRepository personRepository = new PersonRepository();
|
||||
|
||||
@Test
|
||||
public void whenIdIsNull_thenExceptionIsThrown() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() ->
|
||||
Optional
|
||||
.ofNullable(personRepository.findNameById(null))
|
||||
.orElseThrow(IllegalArgumentException::new));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIdIsNonNull_thenNoExceptionIsThrown() {
|
||||
assertAll(
|
||||
() ->
|
||||
Optional
|
||||
.ofNullable(personRepository.findNameById("id"))
|
||||
.orElseThrow(RuntimeException::new));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIdNonNull_thenReturnsNameUpperCase() {
|
||||
String name = Optional
|
||||
.ofNullable(personRepository.findNameById("id"))
|
||||
.map(String::toUpperCase)
|
||||
.orElseThrow(RuntimeException::new);
|
||||
|
||||
assertEquals("NAME", name);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,7 +1,6 @@
|
|||
package com.baeldung.util;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
|
@ -10,8 +9,6 @@ import java.time.LocalTime;
|
|||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.DateTimeUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CurrentDateTimeUnitTest {
|
||||
|
|
|
@ -15,10 +15,7 @@
|
|||
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
|
||||
- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
|
||||
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
|
||||
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
||||
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
||||
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
||||
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
|
||||
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
|
||||
- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)
|
||||
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
|
||||
|
@ -26,3 +23,6 @@
|
|||
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
|
||||
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
|
||||
- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
|
||||
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.java9.process;
|
||||
|
||||
import java.util.Scanner;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class ChildProcess {
|
||||
|
||||
public static void main(String[] args) {
|
||||
@SuppressWarnings("resource")
|
||||
Scanner input = new Scanner(System.in);
|
||||
Logger log = Logger.getLogger(ChildProcess.class.getName());
|
||||
log.log(Level.INFO, input.nextLine());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.java9.process;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class OutputStreamExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Logger log = Logger.getLogger(OutputStreamExample.class.getName());
|
||||
log.log(Level.INFO, Integer.toString(sum(1,2)));
|
||||
}
|
||||
|
||||
public static int sum(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.java9.process;
|
||||
|
||||
public class ProcessCompilationError {
|
||||
//This method has been written to generate error to display
|
||||
//how process errorStream() can consume error
|
||||
public static void();
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
package com.baeldung.java9.process;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Writer;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class ProcessUnderstanding {
|
||||
|
||||
public static int compileAndRunJavaProgram() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
|
||||
process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
|
||||
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
int value = Integer.parseInt(output.readLine());
|
||||
return value;
|
||||
}
|
||||
|
||||
public static String getErrorStreamExample() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
|
||||
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
|
||||
String errorString = error.readLine();
|
||||
return errorString;
|
||||
}
|
||||
|
||||
public static void creatingNewProcess() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
}
|
||||
|
||||
public static int filterProcessWithStreamsInSpecificRangeReturnCount() {
|
||||
return (int) ProcessHandle.allProcesses()
|
||||
.filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
|
||||
.count();
|
||||
}
|
||||
|
||||
public static void destroyingProcessCreatedBySameProcess() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
}
|
||||
|
||||
public static void destroyingProcessCreatedByDifferentProcess() {
|
||||
// find out the process id of current running task by checking
|
||||
// task manager in windows and enter the integer value
|
||||
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
|
||||
ProcessHandle processHandle = optionalProcessHandle.get();
|
||||
processHandle.destroy();
|
||||
}
|
||||
|
||||
public static int waitForExample() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
return process.waitFor();
|
||||
}
|
||||
|
||||
public static int exitValueExample() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
process.destroy();
|
||||
return process.exitValue();
|
||||
}
|
||||
|
||||
public static void destroyExample() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
}
|
||||
|
||||
public static void destroyForciblyExample() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
if (process.isAlive()) {
|
||||
process.destroyForcibly();
|
||||
}
|
||||
}
|
||||
|
||||
public static void outputStreamDemo() throws IOException, InterruptedException {
|
||||
Logger log = Logger.getLogger(ProcessUnderstanding.class.getName());
|
||||
Process pr = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java");
|
||||
final Process process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess");
|
||||
try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) {
|
||||
w.write("send to child\n");
|
||||
}
|
||||
new Thread(() -> {
|
||||
try {
|
||||
int c;
|
||||
while ((c = process.getInputStream()
|
||||
.read()) != -1)
|
||||
System.out.write((byte) c);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}).start();
|
||||
// send to child
|
||||
log.log(Level.INFO, "rc=" + process.waitFor());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.java9.rangedates;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
|
||||
public class DatesCollectionIteration {
|
||||
|
||||
public void iteratingRangeOfDatesJava7(Collection<Date> dates) {
|
||||
|
||||
for (Date date : dates) {
|
||||
processDate(date);
|
||||
}
|
||||
}
|
||||
|
||||
public void iteratingRangeOfDatesJava8(Collection<Date> dates) {
|
||||
dates.stream()
|
||||
.forEach(this::processDate);
|
||||
}
|
||||
|
||||
private void processDate(Date date) {
|
||||
System.out.println(date);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.java9.rangedates;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class RangeDatesIteration {
|
||||
|
||||
public void iterateBetweenDatesJava9(LocalDate startDate, LocalDate endDate) {
|
||||
|
||||
startDate.datesUntil(endDate)
|
||||
.forEach(this::processDate);
|
||||
}
|
||||
|
||||
public void iterateBetweenDatesJava8(LocalDate start, LocalDate end) {
|
||||
for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
|
||||
processDate(date);
|
||||
}
|
||||
}
|
||||
|
||||
public void iterateBetweenDatesJava7(Date start, Date end) {
|
||||
Date current = start;
|
||||
|
||||
while (current.before(end)) {
|
||||
processDate(current);
|
||||
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(current);
|
||||
|
||||
calendar.add(Calendar.DATE, 1);
|
||||
|
||||
current = calendar.getTime();
|
||||
}
|
||||
}
|
||||
|
||||
private void processDate(LocalDate date) {
|
||||
System.out.println(date);
|
||||
}
|
||||
|
||||
private void processDate(Date date) {
|
||||
System.out.println(date);
|
||||
}
|
||||
}
|
|
@ -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>
|
||||
|
|
|
@ -0,0 +1,121 @@
|
|||
package com.baeldung.java9.process;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.String;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.lang.Integer;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ProcessUnderstandingTest {
|
||||
|
||||
@Test
|
||||
public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
|
||||
process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
|
||||
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
int value = Integer.parseInt(output.readLine());
|
||||
assertEquals(3, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
|
||||
process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
|
||||
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
int value = Integer.parseInt(output.readLine());
|
||||
assertEquals(3, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
|
||||
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
|
||||
String errorString = error.readLine();
|
||||
assertNotNull(errorString);
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenStarted_thenStartSuccessIsAlive() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
assertTrue(builder.start().isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
assertFalse(process.isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
if (process.isAlive()) {
|
||||
process.destroyForcibly();
|
||||
}
|
||||
assertFalse(process.isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenDestroyed_thenCheckIfAlive() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
assertFalse(process.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() {
|
||||
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
|
||||
ProcessHandle processHandle = optionalProcessHandle.get();
|
||||
processHandle.destroy();
|
||||
assertFalse(processHandle.isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
assertThat(process.waitFor() >= 0);
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
assertFalse(process.waitFor(1, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
assertThat(process.exitValue() >= 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() {
|
||||
assertThat(((int) ProcessHandle.allProcesses()
|
||||
.filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
|
||||
.count()) > 0);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.java9.rangedates;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DatesCollectionIterationUnitTest {
|
||||
|
||||
private Collection<LocalDate> localDates = LocalDate.now()
|
||||
.datesUntil(LocalDate.now()
|
||||
.plus(10L, ChronoUnit.DAYS))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
private Collection<Date> dates = localDates.stream()
|
||||
.map(localDate -> Date.from(localDate.atStartOfDay(ZoneId.systemDefault())
|
||||
.toInstant()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
@Test
|
||||
public void givenIteratingListOfDatesJava7_WhenStartTodayAndEnding10DaysAhead() {
|
||||
DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration();
|
||||
Calendar today = Calendar.getInstance();
|
||||
Calendar next10Ahead = (Calendar) today.clone();
|
||||
next10Ahead.add(Calendar.DATE, 10);
|
||||
|
||||
iterateInColleciton.iteratingRangeOfDatesJava7(createRangeDates(today.getTime(), next10Ahead.getTime()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIteratingListOfDatesJava8_WhenStartTodayAndEnd10DaysAhead() {
|
||||
DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration();
|
||||
|
||||
iterateInColleciton.iteratingRangeOfDatesJava8(dates);
|
||||
}
|
||||
|
||||
private List<Date> createRangeDates(Date start, Date end) {
|
||||
|
||||
List<Date> dates = new ArrayList<>();
|
||||
Date current = start;
|
||||
|
||||
while (current.before(end)) {
|
||||
dates.add(current);
|
||||
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(current);
|
||||
calendar.add(Calendar.DATE, 1);
|
||||
|
||||
current = calendar.getTime();
|
||||
}
|
||||
|
||||
return dates;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.java9.rangedates;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RangeDatesIterationUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIterateBetweenDatesJava9_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
|
||||
LocalDate start = LocalDate.now();
|
||||
LocalDate end = start.plus(10L, ChronoUnit.DAYS);
|
||||
|
||||
RangeDatesIteration iteration = new RangeDatesIteration();
|
||||
|
||||
iteration.iterateBetweenDatesJava9(start, end);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIterateBetweenDatesJava8_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
|
||||
LocalDate start = LocalDate.now();
|
||||
LocalDate end = start.plus(10L, ChronoUnit.DAYS);
|
||||
|
||||
RangeDatesIteration iteration = new RangeDatesIteration();
|
||||
|
||||
iteration.iterateBetweenDatesJava8(start, end);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIterateBetweenDatesJava7_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
|
||||
Calendar today = Calendar.getInstance();
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.clear();
|
||||
calendar.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
|
||||
Date start = calendar.getTime();
|
||||
|
||||
calendar.add(Calendar.DATE, 10);
|
||||
Date end = calendar.getTime();
|
||||
|
||||
RangeDatesIteration iteration = new RangeDatesIteration();
|
||||
|
||||
iteration.iterateBetweenDatesJava7(start, end);
|
||||
}
|
||||
|
||||
}
|
|
@ -36,3 +36,16 @@
|
|||
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
|
||||
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
|
||||
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
|
||||
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
|
||||
- [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)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
|
||||
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
|
||||
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
|
||||
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
|
||||
|
|
|
@ -53,15 +53,27 @@
|
|||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<properties>
|
||||
<openjdk.jmh.version>1.19</openjdk.jmh.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<eclipse.collections.version>9.2.0</eclipse.collections.version>
|
||||
<eclipse.collections.version>7.1.0</eclipse.collections.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.list;
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
|
@ -0,0 +1,77 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class ArrayListBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
List<Employee> employeeList = new ArrayList<>();
|
||||
//LinkedList<Employee> employeeList = new LinkedList<>();
|
||||
|
||||
long iterations = 100000;
|
||||
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
int employeeIndex = -1;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeList.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
employeeList.add(employee);
|
||||
employeeIndex = employeeList.indexOf(employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void testAddAt(ArrayListBenchmark.MyState state) {
|
||||
state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John"));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testContains(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int testIndexOf(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.indexOf(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testGet(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.get(state.employeeIndex);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testRemove(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.remove(state.employee);
|
||||
}
|
||||
|
||||
// @Benchmark
|
||||
// public void testAdd(ArrayListBenchmark.MyState state) {
|
||||
// state.employeeList.add(new Employee(state.iterations + 1, "John"));
|
||||
// }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(ArrayListBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
@Warmup(iterations = 5)
|
||||
public class CollectionsBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
private Set<Employee> employeeSet = new HashSet<>();
|
||||
private List<Employee> employeeList = new ArrayList<>();
|
||||
|
||||
private long iterations = 10000;
|
||||
|
||||
private Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeSet.add(new Employee(i, "John"));
|
||||
employeeList.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
employeeList.add(employee);
|
||||
employeeSet.add(employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testArrayList(MyState state) {
|
||||
return state.employeeList.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testHashSet(MyState state) {
|
||||
return state.employeeSet.contains(state.employee);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(CollectionsBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class CopyOnWriteBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
CopyOnWriteArrayList<Employee> employeeList = new CopyOnWriteArrayList<>();
|
||||
|
||||
long iterations = 100000;
|
||||
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
int employeeIndex = -1;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeList.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
employeeList.add(employee);
|
||||
|
||||
employeeIndex = employeeList.indexOf(employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void testAdd(CopyOnWriteBenchmark.MyState state) {
|
||||
state.employeeList.add(new Employee(state.iterations + 1, "John"));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void testAddAt(CopyOnWriteBenchmark.MyState state) {
|
||||
state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John"));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testContains(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int testIndexOf(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.indexOf(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testGet(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.get(state.employeeIndex);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testRemove(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.remove(state.employee);
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(CopyOnWriteBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
public class Employee {
|
||||
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
public Employee(Long id, String name) {
|
||||
this.name = name;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
Employee employee = (Employee) o;
|
||||
|
||||
if (!id.equals(employee.id)) return false;
|
||||
return name.equals(employee.name);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = id.hashCode();
|
||||
result = 31 * result + name.hashCode();
|
||||
return result;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class HashMapBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
Map<Long, Employee> employeeMap = new HashMap<>();
|
||||
//LinkedHashMap<Long, Employee> employeeMap = new LinkedHashMap<>();
|
||||
//IdentityHashMap<Long, Employee> employeeMap = new IdentityHashMap<>();
|
||||
//WeakHashMap<Long, Employee> employeeMap = new WeakHashMap<>();
|
||||
//ConcurrentHashMap<Long, Employee> employeeMap = new ConcurrentHashMap<>();
|
||||
//ConcurrentSkipListMap<Long, Employee> employeeMap = new ConcurrentSkipListMap <>();
|
||||
|
||||
// TreeMap
|
||||
|
||||
long iterations = 100000;
|
||||
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
int employeeIndex = -1;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeMap.put(i, new Employee(i, "John"));
|
||||
}
|
||||
|
||||
//employeeMap.put(iterations, employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testGet(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.get(state.iterations);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testRemove(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.remove(state.iterations);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testPut(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.put(state.employee.getId(), state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Boolean testContainsKey(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.containsKey(state.employee.getId());
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(HashMapBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.concurrent.ConcurrentSkipListSet;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class SetBenchMark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
//Set<Employee> employeeSet = new HashSet<>();
|
||||
LinkedHashSet<Employee> employeeSet = new LinkedHashSet<>();
|
||||
//ConcurrentSkipListSet<Employee> employeeSet = new ConcurrentSkipListSet <>();
|
||||
|
||||
// TreeSet
|
||||
|
||||
long iterations = 1000;
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeSet.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
//employeeSet.add(employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testAdd(SetBenchMark.MyState state) {
|
||||
return state.employeeSet.add(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Boolean testContains(SetBenchMark.MyState state) {
|
||||
return state.employeeSet.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testRemove(SetBenchMark.MyState state) {
|
||||
return state.employeeSet.remove(state.employee);
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(SetBenchMark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package com.baeldung.collection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class StreamOperateAndRemoveUnitTest {
|
||||
|
||||
private List<Item> itemList;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
|
||||
itemList = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
itemList.add(new Item(i));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() {
|
||||
|
||||
final List<Item> filteredList = itemList.stream().filter(item -> item.isQualified())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Assert.assertEquals(5, filteredList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
|
||||
|
||||
final Predicate<Item> isQualified = item -> item.isQualified();
|
||||
itemList.stream().filter(isQualified).forEach(item -> item.operate());
|
||||
itemList.removeIf(isQualified);
|
||||
|
||||
Assert.assertEquals(5, itemList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() {
|
||||
|
||||
final List<Item> operatedList = new ArrayList<>();
|
||||
itemList.stream().filter(item -> item.isQualified()).forEach(item -> {
|
||||
item.operate();
|
||||
operatedList.add(item);
|
||||
});
|
||||
itemList.removeAll(operatedList);
|
||||
|
||||
Assert.assertEquals(5, itemList.size());
|
||||
}
|
||||
|
||||
class Item {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
|
||||
|
||||
private final int value;
|
||||
|
||||
public Item(final int value) {
|
||||
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public boolean isQualified() {
|
||||
|
||||
return value % 2 == 0;
|
||||
}
|
||||
|
||||
public void operate() {
|
||||
|
||||
logger.info("Even Number: " + this.value);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,13 +1,17 @@
|
|||
package com.baeldung.list;
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CopyListServiceUnitTest {
|
||||
|
|
@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
|
|||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
|
@ -48,4 +49,14 @@ public class RemoveFirstElementUnitTest {
|
|||
assertThat(linkedList, not(contains("cat")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
|
||||
String[] stringArray = {"foo", "bar", "baz"};
|
||||
|
||||
String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
|
||||
|
||||
assertThat(modifiedArray.length, is(2));
|
||||
assertThat(modifiedArray[0], is("bar"));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,26 @@
|
|||
package org.baeldung.java.collections;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
class CollectionsEmpty {
|
||||
|
||||
@Test
|
||||
public void givenArrayList_whenAddingElement_addsNewElement() {
|
||||
ArrayList<String> mutableList = new ArrayList<>();
|
||||
mutableList.add("test");
|
||||
|
||||
Assert.assertEquals(mutableList.size(), 1);
|
||||
Assert.assertEquals(mutableList.get(0), "test");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() {
|
||||
List<String> immutableList = Collections.emptyList();
|
||||
immutableList.add("test");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue