Merge pull request #75 from eugenp/master

update
This commit is contained in:
Maiklins
2020-10-23 21:24:53 +02:00
committed by GitHub
119 changed files with 1501 additions and 206 deletions
+1 -1
View File
@@ -10,4 +10,4 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Introduction to Minimax Algorithm](https://www.baeldung.com/java-minimax-algorithm)
- [How to Calculate Levenshtein Distance in Java?](https://www.baeldung.com/java-levenshtein-distance)
- [How to Find the Kth Largest Element in Java](https://www.baeldung.com/java-kth-largest-element)
- More articles: [[next -->]](/../algorithms-miscellaneous-2)
- More articles: [[next -->]](/algorithms-miscellaneous-2)
+1 -1
View File
@@ -14,4 +14,4 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Displaying Money Amounts in Words](https://www.baeldung.com/java-money-into-words)
- [A Collaborative Filtering Recommendation System in Java](https://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Implementing A* Pathfinding in Java](https://www.baeldung.com/java-a-star-pathfinding)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-1) [[next -->]](/../algorithms-miscellaneous-3)
- More articles: [[<-- prev]](/algorithms-miscellaneous-1) [[next -->]](/algorithms-miscellaneous-3)
+1 -1
View File
@@ -15,5 +15,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays)
- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4) [[next -->]](/../algorithms-miscellaneous-6)
- More articles: [[<-- prev]](/algorithms-miscellaneous-4) [[next -->]](/algorithms-miscellaneous-6)
+1 -1
View File
@@ -10,4 +10,4 @@
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements)
- [Reversing a Linked List in Java](https://www.baeldung.com/java-reverse-linked-list)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5)
- More articles: [[<-- prev]](/algorithms-miscellaneous-5)
+1
View File
@@ -8,3 +8,4 @@ This module contains articles about Apache Spark
- [Building a Data Pipeline with Kafka, Spark Streaming and Cassandra](https://www.baeldung.com/kafka-spark-data-pipeline)
- [Machine Learning with Spark MLlib](https://www.baeldung.com/spark-mlib-machine-learning)
- [Introduction to Spark Graph Processing with GraphFrames](https://www.baeldung.com/spark-graph-graphframes)
- [Apache Spark: Differences between Dataframes, Datasets and RDDs](https://www.baeldung.com/java-spark-dataframe-dataset-rdd)
@@ -19,12 +19,12 @@ public class StudentDbService implements StudentService {
}
public Student update(Student student) {
logger.log(Level.INFO, "Updating sutdent in DB...");
logger.log(Level.INFO, "Updating student in DB...");
return student;
}
public String delete(String registrationId) {
logger.log(Level.INFO, "Deleteing sutdent in DB...");
logger.log(Level.INFO, "Deleting student in DB...");
return registrationId;
}
}
@@ -33,11 +33,15 @@ public class HashSetBenchmark {
private List<Employee> employeeList1 = new ArrayList<>();
private Set<Employee> employeeSet2 = new HashSet<>();
private List<Employee> employeeList2 = new ArrayList<>();
private Set<Employee> employeeSet3 = new HashSet<>();
private Set<Employee> employeeSet4 = new HashSet<>();
private long set1Size = 60000;
private long list1Size = 50000;
private long set2Size = 50000;
private long list2Size = 60000;
private long set3Size = 50000;
private long set4Size = 60000;
@Setup(Level.Trial)
public void setUp() {
@@ -57,6 +61,14 @@ public class HashSetBenchmark {
for (long i = 0; i < list2Size; i++) {
employeeList2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < set3Size; i++) {
employeeSet3.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < set4Size; i++) {
employeeSet4.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
}
@@ -71,6 +83,11 @@ public class HashSetBenchmark {
public boolean given_SizeOfHashsetSmallerThanSizeOfCollection_When_RemoveAllFromHashSet_Then_BadPerformance(MyState state) {
return state.employeeSet2.removeAll(state.employeeList2);
}
@Benchmark
public boolean given_SizeOfHashsetSmallerThanSizeOfAnotherHashSet_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) {
return state.employeeSet3.removeAll(state.employeeSet4);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder().include(HashSetBenchmark.class.getSimpleName())
@@ -73,7 +73,7 @@ public class LivelockExample {
public void tryLock(Lock lock, long millis) {
try {
lock.tryLock(10, TimeUnit.MILLISECONDS);
lock.tryLock(millis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
@@ -0,0 +1,6 @@
package com.baeldung.exceptions.classcastexception;
public interface Animal {
String getName();
}
@@ -0,0 +1,14 @@
package com.baeldung.exceptions.classcastexception;
public class Box<T> {
private T content;
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.exceptions.classcastexception;
public class Frog extends Reptile {
@Override
public String getName() {
return super.getName() + ": Frog";
}
}
@@ -0,0 +1,9 @@
package com.baeldung.exceptions.classcastexception;
public class Mammal implements Animal {
@Override
public String getName() {
return "Mammal";
}
}
@@ -0,0 +1,9 @@
package com.baeldung.exceptions.classcastexception;
public class Reptile implements Animal {
@Override
public String getName() {
return "Reptile";
}
}
@@ -0,0 +1,40 @@
package com.baeldung.exceptions.classcastexception;
import org.junit.Test;
import java.io.Serializable;
public class CheckedCastsUnitTest {
@Test(expected = ClassCastException.class)
public void givenBaseTypeVariableReferencingChildInstance_whenCastToIncompatibleSubtype_thenClassCastException() {
Animal animal = new Frog();
//A checked downcast to Mammal is incompatible from Frog because Frog is not a subtype of Mammal.
Mammal mammal = (Mammal) animal;
}
@Test(expected = ClassCastException.class)
public void givenBaseTypeVariableReferencingChildInstance_whenCastToIncompatibleInterface_thenClassCastException() {
Animal animal = new Frog();
//A checked cast to Serializable is incompatible from Frog because Frog is not a subtype of Serializable.
Serializable serial = (Serializable) animal;
}
@Test(expected = ClassCastException.class)
public void givenObjectVariableReferencingPrimitiveArray_whenCastToBoxedTypeArray_thenClassCastException() {
Object primitives = new int[1];
//A checked cast to Integer[] is incompatible from primitive arrays. Auto-boxing does not work for arrays.
Integer[] integers = (Integer[]) primitives;
}
@Test(expected = ClassCastException.class)
public void givenObjectVariableReferencingPrimitiveArray_whenCastToPromotedTypeArray_thenClassCastException() {
Object primitives = new int[1];
//A checked cast to long[] is incompatible from int[]. Type promotion does not work for arrays.
long[] longs = (long[]) primitives;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.exceptions.classcastexception;
import org.junit.Test;
public class GenericConversionUnitTest {
@Test(expected = ClassCastException.class)
public void givenIncompatibleType_whenConvertInstanceOfObject_thenClassCastException() {
// Should have been null, but due to type erasure, inside convertInstanceOfObject,
// it will attempt to cast to Object instead of String, so it casts to Object, which is always possible.
String shouldBeNull = convertInstanceOfObject(123);
}
public static <T> T convertInstanceOfObject(Object o) {
try {
return (T) o; // Casts to Object due to type erasure
} catch (ClassCastException e) {
return null; // Will never reach this
}
}
}
@@ -0,0 +1,17 @@
package com.baeldung.exceptions.classcastexception;
import org.junit.Test;
public class UncheckedConversionUnitTest {
@Test(expected = ClassCastException.class)
public void givenPollutedGenericType_whenGetProperty_thenClassCastException() {
Box<Long> originalBox = new Box<>();
Box raw = originalBox;
raw.setContent(2.5);
Box<Long> bound = (Box<Long>) raw;
//An incompatible element was found in the raw box.
Long content = bound.getContent();
}
}
@@ -7,4 +7,5 @@ This module contains articles about core features in the Java language
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
- [Checking if a Class Exists in Java](https://www.baeldung.com/java-check-class-exists)
- [The Difference Between a.getClass() and A.class in Java](https://www.baeldung.com/java-getclass-vs-class)
- [Constants in Java: Patterns and Anti-Patterns](https://www.baeldung.com/java-constants-good-practices)
- [[<-- Prev]](/core-java-modules/core-java-lang-2)
@@ -0,0 +1,37 @@
package com.baeldung.constantspatterns;
public class Calculator {
public static final double PI = 3.14159265359;
private static final double UPPER_LIMIT = 0x1.fffffffffffffP+1023;
public enum Operation {
ADD, SUBTRACT, DIVIDE, MULTIPLY
}
public double operateOnTwoNumbers(double numberOne, double numberTwo, Operation operation) {
if (numberOne > UPPER_LIMIT) {
throw new IllegalArgumentException("'numberOne' is too large");
}
if (numberTwo > UPPER_LIMIT) {
throw new IllegalArgumentException("'numberTwo' is too large");
}
double answer = 0;
switch (operation) {
case ADD:
answer = numberOne + numberTwo;
break;
case SUBTRACT:
answer = numberOne - numberTwo;
break;
case DIVIDE:
answer = numberOne / numberTwo;
break;
case MULTIPLY:
answer = numberOne * numberTwo;
break;
}
return answer;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.constantspatterns;
public interface CalculatorConstants {
double PI = 3.14159265359;
double UPPER_LIMIT = 0x1.fffffffffffffP+1023;
enum Operation {
ADD, SUBTRACT, MULTIPLY, DIVIDE
};
}
@@ -0,0 +1,32 @@
package com.baeldung.constantspatterns;
public class GeometryCalculator implements CalculatorConstants {
public static final double UPPER_LIMIT = 100000000000000000000.0;
public double operateOnTwoNumbers(double numberOne, double numberTwo, Operation operation) {
if (numberOne > UPPER_LIMIT) {
throw new IllegalArgumentException("'numberOne' is too large");
}
if (numberTwo > UPPER_LIMIT) {
throw new IllegalArgumentException("'numberTwo' is too large");
}
double answer = 0;
switch (operation) {
case ADD:
answer = numberOne + numberTwo;
break;
case SUBTRACT:
answer = numberOne - numberTwo;
break;
case DIVIDE:
answer = numberOne / numberTwo;
break;
case MULTIPLY:
answer = numberOne * numberTwo;
break;
}
return answer;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.constantspatterns.calculations;
public final class MathConstants {
public static final double PI = 3.14159265359;
static final double GOLDEN_RATIO = 1.6180;
static final double GRAVITATIONAL_ACCELERATION = 9.8;
static final double EULERS_NUMBER = 2.7182818284590452353602874713527;
public enum Operation {
ADD, SUBTRACT, DIVIDE, MULTIPLY
}
private MathConstants() {
}
}
@@ -0,0 +1,23 @@
package com.baeldung.constantspatterns;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class ConstantPatternUnitTest {
@Test
public void givenTwoNumbersAndAdd_whenCallingCalculatorOperatOneTwoNumbers_thenCorrectAnswerReturned() {
Calculator calculator = new Calculator();
double expected = 4;
double answer = calculator.operateOnTwoNumbers(2, 2, Calculator.Operation.ADD);
assertEquals(expected, answer);
}
@Test
public void givenTwoNumbersAndAdd_whenCallingGeometryCalculatorOperatOneTwoNumbers_thenCorrectAnswerReturned() {
GeometryCalculator calculator = new GeometryCalculator();
double expected = 4;
double answer = calculator.operateOnTwoNumbers(2, 2, GeometryCalculator.Operation.ADD);
assertEquals(expected, answer);
}
}
@@ -14,4 +14,5 @@ This module contains articles about networking in Java
- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception)
- [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address)
- [Sending Emails with Attachments in Java](https://www.baeldung.com/java-send-emails-attachments)
- [Finding a Free Port in Java](https://www.baeldung.com/java-free-port)
- [[<-- Prev]](/core-java-modules/core-java-networking)
@@ -3,7 +3,7 @@ package com.baeldung.hashing;
class SHACommonUtils {
public static String bytesToHex(byte[] hash) {
StringBuffer hexString = new StringBuffer();
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (byte h : hash) {
String hex = Integer.toHexString(0xff & h);
if (hex.length() == 1)
-4
View File
@@ -104,16 +104,12 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<joda-money.version>1.0.1</joda-money.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
</project>
+78
View File
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>mantis</artifactId>
<name>Mantis</name>
<packaging>jar</packaging>
<description>Sample project for Netflix Mantis</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>io.mantisrx</groupId>
<artifactId>mantis-runtime</artifactId>
<version>1.2.63</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
<dependency>
<groupId>net.andreinc.mockneat</groupId>
<artifactId>mockneat</artifactId>
<version>0.3.8</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<version>5.0.9.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
<version>0.9.12.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>SpringLibReleaseRepo</id>
<url>https://repo.spring.io/libs-release/</url>
</repository>
</repositories>
</project>
@@ -0,0 +1,23 @@
package com.baeldung.netflix.mantis;
import com.baeldung.netflix.mantis.job.LogAggregationJob;
import io.mantisrx.runtime.executor.LocalJobExecutorNetworked;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@Slf4j
@SpringBootApplication
public class MantisApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(MantisApplication.class, args);
}
@Override
public void run(String... args) {
LocalJobExecutorNetworked.execute(new LogAggregationJob().getJobInstance());
}
}
@@ -0,0 +1,37 @@
package com.baeldung.netflix.mantis.job;
import com.baeldung.netflix.mantis.model.LogAggregate;
import com.baeldung.netflix.mantis.source.RandomLogSource;
import com.baeldung.netflix.mantis.stage.CountLogStage;
import com.baeldung.netflix.mantis.stage.GroupLogStage;
import com.baeldung.netflix.mantis.stage.TransformLogStage;
import io.mantisrx.runtime.Job;
import io.mantisrx.runtime.MantisJob;
import io.mantisrx.runtime.MantisJobProvider;
import io.mantisrx.runtime.Metadata;
import io.mantisrx.runtime.sink.Sink;
import io.mantisrx.runtime.sink.Sinks;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
public class LogAggregationJob extends MantisJobProvider<LogAggregate> {
private Sink<LogAggregate> sink = Sinks.eagerSubscribe(Sinks.sse(LogAggregate::toJsonString));
@Override
public Job<LogAggregate> getJobInstance() {
return MantisJob
.source(new RandomLogSource())
.stage(new TransformLogStage(), TransformLogStage.stageConfig())
.stage(new GroupLogStage(), GroupLogStage.config())
.stage(new CountLogStage(), CountLogStage.config())
.sink(sink)
.metadata(new Metadata.Builder().build())
.create();
}
}
@@ -0,0 +1,34 @@
package com.baeldung.netflix.mantis.job;
import com.baeldung.netflix.mantis.model.LogEvent;
import com.baeldung.netflix.mantis.sink.LogSink;
import com.baeldung.netflix.mantis.source.RandomLogSource;
import com.baeldung.netflix.mantis.stage.TransformLogStage;
import io.mantisrx.runtime.Job;
import io.mantisrx.runtime.MantisJob;
import io.mantisrx.runtime.MantisJobProvider;
import io.mantisrx.runtime.Metadata;
import io.mantisrx.runtime.ScalarToScalar;
import io.mantisrx.runtime.sink.Sink;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
public class LogCollectingJob extends MantisJobProvider<LogEvent> {
private Sink<LogEvent> sink = new LogSink();
@Override
public Job<LogEvent> getJobInstance() {
return MantisJob
.source(new RandomLogSource())
.stage(new TransformLogStage(), new ScalarToScalar.Config<>())
.sink(sink)
.metadata(new Metadata.Builder().build())
.create();
}
}
@@ -0,0 +1,28 @@
package com.baeldung.netflix.mantis.model;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.mantisrx.runtime.codec.JsonType;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class LogAggregate implements JsonType {
private static final ObjectMapper mapper = new ObjectMapper();
private Integer count;
private String level;
public String toJsonString() {
try {
return mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
return null;
}
}
}

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