Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2018-09-03 21:20:19 +03:00
commit 3a59756698
215 changed files with 5578 additions and 1983 deletions

View File

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

View File

@ -1,4 +1,4 @@
package com.baeldung.linesintersection; package com.baeldung.algorithms.linesintersection;
import java.awt.Point; import java.awt.Point;
import java.util.Optional; import java.util.Optional;
@ -14,24 +14,24 @@ public class LinesIntersectionServiceUnitTest {
@Test @Test
public void givenNotParallelLines_whenCalculatePoint_thenPresent() { public void givenNotParallelLines_whenCalculatePoint_thenPresent() {
float m1 = 0; double m1 = 0;
float b1 = 0; double b1 = 0;
float m2 = 1; double m2 = 1;
float b2 = -1; double b2 = -1;
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2); Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
assertTrue(point.isPresent()); assertTrue(point.isPresent());
assertEquals(point.get().x, 1); assertEquals(point.get().getX(), 1, 0.001);
assertEquals(point.get().y, 0); assertEquals(point.get().getY(), 0, 0.001);
} }
@Test @Test
public void givenParallelLines_whenCalculatePoint_thenEmpty() { public void givenParallelLines_whenCalculatePoint_thenEmpty() {
float m1 = 1; double m1 = 1;
float b1 = 0; double b1 = 0;
float m2 = 1; double m2 = 1;
float b2 = -1; double b2 = -1;
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2); Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);

View File

@ -1,70 +1,91 @@
package com.baeldung.test.dependencyinjection; 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.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.Weld;
import org.jboss.weld.environment.se.WeldContainer; import org.jboss.weld.environment.se.WeldContainer;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; 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 { public class ImageProcessorUnitTest {
private static ImageFileProcessor imageFileProcessor; private static ImageFileProcessor imageFileProcessor;
private static SimpleDateFormat dateFormat;
private static Calendar calendar;
@BeforeClass @BeforeClass
public static void setImageProcessorInstance() { public static void setImageProcessorInstance() {
Weld weld = new Weld(); Weld weld = new Weld();
WeldContainer container = weld.initialize(); WeldContainer container = weld.initialize();
imageFileProcessor = container.select(ImageFileProcessor.class).get(); imageFileProcessor = container.select(ImageFileProcessor.class)
.get();
container.shutdown(); container.shutdown();
} }
@BeforeClass
public static void setSimpleDateFormatInstance() {
dateFormat = new SimpleDateFormat("HH:mm");
}
@BeforeClass
public static void setCalendarInstance() {
calendar = Calendar.getInstance();
}
@Test @Test
public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() { public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() {
assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class); assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class);
assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class); assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class);
} }
@Test @Test
public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() { public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException {
String currentTime = dateFormat.format(calendar.getTime()); LocalTime currentTime = LocalTime.now();
assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime);
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 @Test
public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() { public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException {
String currentTime = dateFormat.format(calendar.getTime()); LocalTime currentTime = LocalTime.now();
assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime);
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 @Test
public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() { public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException {
String currentTime = dateFormat.format(calendar.getTime()); LocalTime currentTime = LocalTime.now();
assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime);
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 @Test
public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() { public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException {
String currentTime = dateFormat.format(calendar.getTime()); LocalTime currentTime = LocalTime.now();
assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime);
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;
} }
} }

View File

@ -15,24 +15,17 @@
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing) - [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional) - [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java) - [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode) - [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods) - [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency) - [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
- [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)
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator) - [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math) - [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations) - [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max) - [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization) - [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [Java Optional orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) - [Java Optional orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) - [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic) - [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference) - [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time) - [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)

View File

@ -5,25 +5,22 @@
*/ */
package com.baeldung.nullsafecollectionstreams; package com.baeldung.nullsafecollectionstreams;
import static org.junit.Assert.assertEquals;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.stream.Stream; 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 org.junit.Test;
import static org.junit.Assert.*;
/** /**
* *
* @author Kwaje Anthony <kwajeanthony@gmail.com> * @author Kwaje Anthony <kwajeanthony@gmail.com>
*/ */
public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = new NullSafeCollectionStreamsUsingJava8OptionalContainer();
new NullSafeCollectionStreamsUsingJava8OptionalContainer();
@Test @Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() { public void whenCollectionIsNull_thenExpectAnEmptyStream() {
@ -49,5 +46,5 @@ public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
assertEquals(iter1.next(), iter2.next()); assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext(); assert !iter1.hasNext() && !iter2.hasNext();
} }
} }

View File

@ -1,97 +0,0 @@
package com.baeldung.streamordering;
import org.junit.Test;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class BenchmarkUnitTest
{
@Test
public void
launchBenchmark() throws Exception {
Options opt = new OptionsBuilder()
// Specify which benchmarks to run.
// You can be more specific if you'd like to run only one benchmark per test.
.include(this.getClass().getName() + ".*")
// Set the following options as needed
.mode (Mode.AverageTime)
.timeUnit(TimeUnit.MICROSECONDS)
.warmupTime(TimeValue.seconds(1))
.warmupIterations(2)
.measurementTime(TimeValue.seconds(1))
.measurementIterations(2)
.threads(2)
.forks(1)
.shouldFailOnError(true)
.shouldDoGC(true)
//.jvmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining")
//.addProfiler(WinPerfAsmProfiler.class)
.build();
new Runner(opt).run();
}
@Benchmark
public void givenOrderedStreamInput_whenStreamFiltered_showOpsPerMS(){
IntStream.range(1, 100_000_000).parallel().filter(i -> i % 10 == 0).toArray();
}
@Benchmark
public void givenUnorderedStreamInput_whenStreamFiltered_showOpsPerMS(){
IntStream.range(1,100_000_000).unordered().parallel().filter(i -> i % 10 == 0).toArray();
}
@Benchmark
public void givenUnorderedStreamInput_whenStreamDistinct_showOpsPerMS(){
IntStream.range(1, 1_000_000).unordered().parallel().distinct().toArray();
}
@Benchmark
public void givenOrderedStreamInput_whenStreamDistinct_showOpsPerMS() {
//section 5.1.
IntStream.range(1, 1_000_000).parallel().distinct().toArray();
}
// The JMH samples are the best documentation for how to use it
// http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/
@State(Scope.Thread)
public static class BenchmarkState
{
List<Integer> list;
@Setup(Level.Trial) public void
initialize() {
Random rand = new Random();
list = new ArrayList<>();
for (int i = 0; i < 1000; i++)
list.add (rand.nextInt());
}
}
@Benchmark public void
benchmark1 (BenchmarkState state, Blackhole bh) {
List<Integer> list = state.list;
for (int i = 0; i < 1000; i++)
bh.consume (list.get (i));
}
}

View File

@ -1,149 +0,0 @@
package com.baeldung.streamordering;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
public class StreamsOrderingUnitTest {
Logger logger = Logger.getLogger( StreamsOrderingUnitTest.class.getName());
@Before
public void setUp() throws Exception {
logger.setLevel(Level.ALL);
}
@Test
public void givenTwoCollections_whenStreamed_thenCheckOutputDifferent(){
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
Object[] listOutput = list.stream().toArray();
Object[] setOutput = set.stream().toArray();
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
}
@Test
public void givenTwoCollections_whenStreamedInParallel_thenCheckOutputDifferent(){
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
Object[] listOutput = list.stream().parallel().toArray();
Object[] setOutput = set.stream().parallel().toArray();
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
}
@Test
public void givenOrderedInput_whenUnorderedAndOrderedCompared_thenCheckUnorderedOutputChanges(){
Set<Integer> set = new TreeSet<>(
Arrays.asList(-9, -5, -4, -2, 1, 2, 4, 5, 7, 9, 12, 13, 16, 29, 23, 34, 57, 68, 90, 102, 230));
Object[] orderedArray = set.stream()
.parallel()
.limit(5)
.toArray();
Object[] unorderedArray = set.stream()
.unordered()
.parallel()
.limit(5)
.toArray();
logger.info(Arrays.toString(orderedArray));
logger.info(Arrays.toString(unorderedArray));
}
@Test
public void givenUnsortedStreamInput_whenStreamSorted_thenCheckOrderChanged(){
List<Integer> list = Arrays.asList(-3,10,-4,1,3);
Object[] listOutput = list.stream().toArray();
Object[] listOutputSorted = list.stream().sorted().toArray();
assertEquals("[-3, 10, -4, 1, 3]", Arrays.toString(listOutput));
assertEquals("[-4, -3, 1, 3, 10]", Arrays.toString(listOutputSorted));
}
@Test
public void givenUnsortedStreamInput_whenStreamDistinct_thenShowTimeTaken(){
long start, end;
start = System.currentTimeMillis();
IntStream.range(1,1_000_000).unordered().parallel().distinct().toArray();
end = System.currentTimeMillis();
System.out.println(String.format("Time taken when unordered: %d ms", (end - start)));
}
@Test
public void givenSameCollection_whenStreamTerminated_thenCheckEachVsEachOrdered(){
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
list.stream().parallel().forEach(e -> logger.log(Level.INFO, e));
list.stream().parallel().forEachOrdered(e -> logger.log(Level.INFO, e));
}
@Test
public void givenSameCollection_whenStreamCollected_thenCheckOutput(){
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
List<String> collectionList = list.stream().parallel().collect(Collectors.toList());
Set<String> collectionSet = list.stream().parallel().collect(Collectors.toCollection(TreeSet::new));
assertEquals("[B, A, C, D, F]", collectionList.toString());
assertEquals("[A, B, C, D, F]", collectionSet.toString());
}
@Test
public void givenListIterationOrder_whenStreamCollectedToMap_thenCeckOrderChanged() {
List<String> list = Arrays.asList("A", "BB", "CCC");
Map<String, Integer> hashMap = list.stream().collect(Collectors.toMap(Function.identity(), String::length));
Object[] keySet = hashMap.keySet().toArray();
assertEquals("[BB, A, CCC]", Arrays.toString(keySet));
}
@Test
public void givenListIteration_whenStreamCollectedtoHashMap_thenCheckOrderMaintained() {
List<String> list = Arrays.asList("A", "BB", "CCC", "CCC");
Map<String, Integer> linkedHashMap = list.stream().collect(Collectors.toMap(
Function.identity(),
String::length,
(u, v) -> u,
LinkedHashMap::new
));
Object[] keySet = linkedHashMap.keySet().toArray();
assertEquals("[A, BB, CCC]", Arrays.toString(keySet));
}
}

View File

@ -1,7 +1,6 @@
package com.baeldung.util; package com.baeldung.util;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.Clock; import java.time.Clock;
import java.time.Instant; import java.time.Instant;
@ -10,8 +9,6 @@ import java.time.LocalTime;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.temporal.ChronoField; import java.time.temporal.ChronoField;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.junit.Test; import org.junit.Test;
public class CurrentDateTimeUnitTest { public class CurrentDateTimeUnitTest {

View File

@ -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());
}
}

View File

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

View File

@ -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();
}

View File

@ -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());
}
}

View File

@ -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_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_checkAlive() 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);
}
}

View File

@ -37,3 +37,9 @@
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map) - [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) - [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) - [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)

View File

@ -1,4 +1,4 @@
package com.baeldung.list; package com.baeldung.java.list;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;

View File

@ -1,13 +1,17 @@
package com.baeldung.list; package com.baeldung.java.list;
import org.junit.Before; import static org.junit.Assert.assertEquals;
import org.junit.Test; 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.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.junit.Assert.*; import org.junit.Before;
import org.junit.Test;
public class CopyListServiceUnitTest { public class CopyListServiceUnitTest {

View File

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

View File

@ -0,0 +1,45 @@
/**
*
*/
package com.baeldung.string;
/**
* @author swpraman
*
*/
public class AppendCharAtPositionX {
public String addCharUsingCharArray(String str, char ch, int position) {
validate(str, position);
int len = str.length();
char[] updatedArr = new char[len + 1];
str.getChars(0, position, updatedArr, 0);
updatedArr[position] = ch;
str.getChars(position, len, updatedArr, position + 1);
return new String(updatedArr);
}
public String addCharUsingSubstring(String str, char ch, int position) {
validate(str, position);
return str.substring(0, position) + ch + str.substring(position);
}
public String addCharUsingStringBuilder(String str, char ch, int position) {
validate(str, position);
StringBuilder sb = new StringBuilder(str);
sb.insert(position, ch);
return sb.toString();
}
private void validate(String str, int position) {
if (str == null) {
throw new IllegalArgumentException("Str should not be null");
}
int len = str.length();
if (position < 0 || position > len) {
throw new IllegalArgumentException("position[" + position + "] should be "
+ "in the range 0.." + len + " for string " + str);
}
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.synthetic;
import java.util.Comparator;
/**
* Class which contains a synthetic bridge method.
*
* @author Donato Rimenti
*
*/
public class BridgeMethodDemo implements Comparator<Integer> {
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Integer o1, Integer o2) {
return 0;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains a synthetic constructor.
*
* @author Donato Rimenti
*
*/
public class SyntheticConstructorDemo {
/**
* We need to instantiate the {@link NestedClass} using a private
* constructor from the enclosing instance in order to generate a synthetic
* constructor.
*/
private NestedClass nestedClass = new NestedClass();
/**
* Class which contains a synthetic constructor.
*
* @author Donato Rimenti
*
*/
class NestedClass {
/**
* In order to generate a synthetic constructor, this class must have a
* private constructor.
*/
private NestedClass() {
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains a synthetic field reference to the outer
* class.
*
* @author Donato Rimenti
*
*/
public class SyntheticFieldDemo {
/**
* Class which contains a synthetic field reference to the outer class.
*
* @author Donato Rimenti
*
*/
class NestedClass {
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains two synthetic methods accessors to a
* private field.
*
* @author Donato Rimenti
*
*/
public class SyntheticMethodDemo {
/**
* Class which contains two synthetic methods accessors to a private field.
*
* @author Donato Rimenti
*
*/
class NestedClass {
/**
* Field for which will be generated synthetic methods accessors. It's
* important that this field is private for this purpose.
*/
private String nestedField;
}
/**
* Gets the private nested field. We need to read the nested field in order
* to generate the synthetic getter.
*
* @return the {@link NestedClass#nestedField}
*/
public String getNestedField() {
return new NestedClass().nestedField;
}
/**
* Sets the private nested field. We need to write the nested field in order
* to generate the synthetic setter.
*
* @param nestedField
* the {@link NestedClass#nestedField}
*/
public void setNestedField(String nestedField) {
new NestedClass().nestedField = nestedField;
}
}

View File

@ -0,0 +1,110 @@
/**
*
*/
package com.baeldung.string;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* @author swpraman
*
*/
public class AppendCharAtPositionXUnitTest {
private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX();
private String word = "Titanc";
private char letter = 'i';
@Test
public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() {
assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0));
}
@Test
public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() {
assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0));
}
@Test
public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() {
assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0));
}
@Test
public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() {
assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3));
}
@Test
public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() {
assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3));
}
@Test
public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() {
assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3));
}
@Test
public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() {
assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length()));
}
@Test
public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() {
assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length()));
}
@Test
public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() {
assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length()));
}
@Test(expected=IllegalArgumentException.class)
public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() {
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
}
@Test(expected=IllegalArgumentException.class)
public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() {
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
}
@Test(expected=IllegalArgumentException.class)
public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() {
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
}
@Test(expected=IllegalArgumentException.class)
public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() {
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
}
@Test(expected=IllegalArgumentException.class)
public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() {
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
}
@Test(expected=IllegalArgumentException.class)
public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() {
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
}
@Test(expected=IllegalArgumentException.class)
public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
}
@Test(expected=IllegalArgumentException.class)
public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
}
@Test(expected=IllegalArgumentException.class)
public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.synthetic;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit test for {@link SyntheticFieldDemo}, {@link SyntheticMethodDemo},
* {@link SyntheticConstructorDemo} and {@link BridgeMethodDemo} classes.
*
* @author Donato Rimenti
*
*/
public class SyntheticUnitTest {
/**
* Tests that the {@link SyntheticMethodDemo.NestedClass} contains two synthetic
* methods.
*/
@Test
public void givenSyntheticMethod_whenIsSinthetic_thenTrue() {
// Checks that the nested class contains exactly two synthetic methods.
Method[] methods = SyntheticMethodDemo.NestedClass.class.getDeclaredMethods();
Assert.assertEquals("This class should contain only two methods", 2, methods.length);
for (Method m : methods) {
System.out.println("Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic());
Assert.assertTrue("All the methods of this class should be synthetic", m.isSynthetic());
}
}
/**
* Tests that {@link SyntheticConstructorDemo.NestedClass} contains a synthetic
* constructor.
*/
@Test
public void givenSyntheticConstructor_whenIsSinthetic_thenTrue() {
// Checks that the nested class contains exactly a synthetic
// constructor.
int syntheticConstructors = 0;
Constructor<?>[] constructors = SyntheticConstructorDemo.NestedClass.class.getDeclaredConstructors();
Assert.assertEquals("This class should contain only two constructors", 2, constructors.length);
for (Constructor<?> c : constructors) {
System.out.println("Constructor: " + c.getName() + ", isSynthetic: " + c.isSynthetic());
// Counts the synthetic constructors.
if (c.isSynthetic()) {
syntheticConstructors++;
}
}
// Checks that there's exactly one synthetic constructor.
Assert.assertEquals(1, syntheticConstructors);
}
/**
* Tests that {@link SyntheticFieldDemo.NestedClass} contains a synthetic field.
*/
@Test
public void givenSyntheticField_whenIsSinthetic_thenTrue() {
// This class should contain exactly one synthetic field.
Field[] fields = SyntheticFieldDemo.NestedClass.class.getDeclaredFields();
Assert.assertEquals("This class should contain only one field", 1, fields.length);
for (Field f : fields) {
System.out.println("Field: " + f.getName() + ", isSynthetic: " + f.isSynthetic());
Assert.assertTrue("All the fields of this class should be synthetic", f.isSynthetic());
}
}
/**
* Tests that {@link BridgeMethodDemo} contains a synthetic bridge method.
*/
@Test
public void givenBridgeMethod_whenIsBridge_thenTrue() {
// This class should contain exactly one synthetic bridge method.
int syntheticMethods = 0;
Method[] methods = BridgeMethodDemo.class.getDeclaredMethods();
for (Method m : methods) {
System.out.println(
"Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic() + ", isBridge: " + m.isBridge());
// Counts the synthetic methods and checks that they are also bridge
// methods.
if (m.isSynthetic()) {
syntheticMethods++;
Assert.assertTrue("The synthetic method in this class should also be a bridge method", m.isBridge());
}
}
// Checks that there's exactly one synthetic bridge method.
Assert.assertEquals("There should be exactly 1 synthetic bridge method in this class", 1, syntheticMethods);
}
}

View File

@ -1,7 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>java-streams</artifactId> <artifactId>java-streams</artifactId>
<version>0.1.0-SNAPSHOT</version> <version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
@ -15,17 +14,17 @@
</parent> </parent>
<dependencies> <dependencies>
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core --> <!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
<dependency> <dependency>
<groupId>org.openjdk.jmh</groupId> <groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId> <artifactId>jmh-core</artifactId>
<version>${jmh.version}</version> <version>${jmh.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.openjdk.jmh</groupId> <groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId> <artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version> <version>${jmh.version}</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>

View File

@ -1,15 +1,14 @@
package com.baeldung.stream; package com.baeldung.stream;
import org.junit.Test; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.Assert.assertEquals; import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class PrimitiveStreamsUnitTest { public class PrimitiveStreamsUnitTest {
@ -17,7 +16,7 @@ public class PrimitiveStreamsUnitTest {
@Test @Test
public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() { public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() {
int[] integers = new int[] {20, 98, 12, 7, 35}; int[] integers = new int[] { 20, 98, 12, 7, 35 };
int min = streams.min(integers); // returns 7 int min = streams.min(integers); // returns 7
assertEquals(7, min); assertEquals(7, min);
@ -66,19 +65,14 @@ public class PrimitiveStreamsUnitTest {
@Test @Test
public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() { public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() {
int sum = Stream.of(33,45) int sum = Stream.of(33, 45).mapToInt(i -> i).sum();
.mapToInt(i -> i)
.sum();
assertEquals(78, sum); assertEquals(78, sum);
} }
@Test @Test
public void givenAnIntStreamThenGetTheEvenIntegers() { public void givenAnIntStreamThenGetTheEvenIntegers() {
List<Integer> evenInts = IntStream.rangeClosed(1, 10) List<Integer> evenInts = IntStream.rangeClosed(1, 10).filter(i -> i % 2 == 0).boxed().collect(Collectors.toList());
.filter(i -> i % 2 == 0)
.boxed()
.collect(Collectors.toList());
List<Integer> expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList()); List<Integer> expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList());

View File

@ -18,7 +18,6 @@ import java.util.stream.IntStream;
public class BenchmarkUnitTest public class BenchmarkUnitTest
{ {
@Test
public void public void
launchBenchmark() throws Exception { launchBenchmark() throws Exception {

View File

@ -0,0 +1,29 @@
package com.baeldung.string.sorting;
import java.util.Arrays;
public class AnagramValidator {
public static boolean isValid(String text, String anagram) {
text = prepare(text);
anagram = prepare(anagram);
String sortedText = sort(text);
String sortedAnagram = sort(anagram);
return sortedText.equals(sortedAnagram);
}
private static String sort(String text) {
char[] chars = prepare(text).toCharArray();
Arrays.sort(chars);
return new String(chars);
}
private static String prepare(String text) {
return text.toLowerCase()
.trim()
.replaceAll("\\s+", "");
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.string.formatter;
import org.junit.BeforeClass;
import org.junit.Test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import static org.junit.Assert.assertEquals;
public class DateToStringFormatterUnitTest {
private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a";
private static final String EXPECTED_STRING_DATE = "Aug 1, 2018 12:00 PM";
private static Date date;
@BeforeClass
public static void setUp() {
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
Calendar calendar = Calendar.getInstance();
calendar.set(2018, Calendar.AUGUST, 1, 12, 0);
date = calendar.getTime();
}
@Test
public void whenDateConvertedUsingSimpleDateFormatToString_thenCorrect() {
DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
String formattedDate = formatter.format(date);
assertEquals(EXPECTED_STRING_DATE, formattedDate);
}
@Test
public void whenDateConvertedUsingDateFormatToString_thenCorrect() {
String formattedDate = DateFormat
.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
.format(date);
assertEquals(EXPECTED_STRING_DATE, formattedDate);
}
@Test
public void whenDateConvertedUsingFormatterToString_thenCorrect() {
String formattedDate = String.format("%1$tb %1$te, %1$tY %1$tI:%1$tM %1$Tp", date);
assertEquals(EXPECTED_STRING_DATE, formattedDate);
}
@Test
public void whenDateConvertedUsingDateTimeApiToString_thenCorrect() {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(DATE_FORMAT);
Instant instant = date.toInstant();
LocalDateTime ldt = instant
.atZone(ZoneId.of("CET"))
.toLocalDateTime();
String formattedDate = ldt.format(fmt);
assertEquals(EXPECTED_STRING_DATE, formattedDate);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.string.sorting;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
import com.baeldung.string.sorting.AnagramValidator;
class AnagramValidatorUnitTest {
@Test
void givenValidAnagrams_whenSorted_thenEqual() {
boolean isValidAnagram = AnagramValidator.isValid("Avida Dollars", "Salvador Dali");
assertTrue(isValidAnagram);
}
@Test
void givenNotValidAnagrams_whenSorted_thenNotEqual() {
boolean isValidAnagram = AnagramValidator.isValid("abc", "def");
assertFalse(isValidAnagram);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.string.sorting;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class SortStringUnitTest {
@Test
void givenString_whenSort_thenSorted() {
String abcd = "bdca";
char[] chars = abcd.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
assertThat(sorted).isEqualTo("abcd");
}
@Test
void givenString_whenSortJava8_thenSorted() {
String sorted = "bdca".chars()
.sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
assertThat(sorted).isEqualTo("abcd");
}
}

View File

@ -1,67 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.samples</groupId>
<artifactId>jersey-client-rx</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext.rx</groupId>
<artifactId>jersey-rx-client-rxjava</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext.rx</groupId>
<artifactId>jersey-rx-client-rxjava2</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>1.58</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.10.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>

View File

@ -1,3 +0,0 @@
# Fluent, Reactive Jersey Client Orchestration #
### Sample code demonstrating the options for asynchronous, reactive RESTful service consumption with JAX-RS ###

View File

@ -0,0 +1,102 @@
package com.baeldung.jersey.server;
import com.baeldung.jersey.server.model.Person;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/response")
public class Responder {
@GET
@Path("/ok")
public Response getOkResponse() {
String message = "This is a text response";
return Response
.status(Response.Status.OK)
.entity(message)
.build();
}
@GET
@Path("/not_ok")
public Response getNOkTextResponse() {
String message = "There was an internal server error";
return Response
.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(message)
.build();
}
@GET
@Path("/text_plain")
public Response getTextResponseTypeDefined() {
String message = "This is a plain text response";
return Response
.status(Response.Status.OK)
.entity(message)
.type(MediaType.TEXT_PLAIN)
.build();
}
@GET
@Path("/text_plain_annotation")
@Produces({ MediaType.TEXT_PLAIN })
public Response getTextResponseTypeAnnotated() {
String message = "This is a plain text response via annotation";
return Response
.status(Response.Status.OK)
.entity(message)
.build();
}
@GET
@Path("/pojo")
public Response getPojoResponse() {
Person person = new Person("Abh", "Nepal");
return Response
.status(Response.Status.OK)
.entity(person)
.build();
}
@GET
@Path("/json")
public Response getJsonResponse() {
String message = "{\"hello\": \"This is a JSON response\"}";
return Response
.status(Response.Status.OK)
.entity(message)
.type(MediaType.APPLICATION_JSON)
.build();
}
@GET
@Path("/xml")
@Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> This is a xml response </hello>";
}
@GET
@Path("/html")
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + " This is a html title </title>" + "<body><h1>" + " This is a html response body " + "</body></h1>" + "</html> ";
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.jersey.server.model;
public class Person {
String name;
String address;
public Person(String name, String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person [name: " + getName() + " address: " + getAddress() + "]";
}
}

View File

@ -1,2 +0,0 @@
### Relevant Articles:
- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)

View File

@ -1,65 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>jpa-storedprocedure</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- core library -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${jee.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- MySql JDBC -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
<build>
<finalName>JpaStoredProcedure</finalName>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<!--archive> <manifest> <mainClass>fully.qualified.MainClass</mainClass> </manifest> </archive -->
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<jee.version>7.0</jee.version>
<hibernate.version>5.2.5.Final</hibernate.version>
<mysql.version>6.0.5</mysql.version>
<commons-io.version>2.5</commons-io.version>
</properties>
</project>

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="jpa-db">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.model.Car</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung" />
<property name="javax.persistence.jdbc.user" value="baeldung" />
<property name="javax.persistence.jdbc.password" value="YourPassword" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>

View File

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

View File

@ -0,0 +1,9 @@
### Relevant articles
- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded)
- [Introduction to Netty](http://www.baeldung.com/netty)
- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling)
- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup)
- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)
- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel)

View File

@ -14,6 +14,73 @@
<groupId>org.eclipse.paho</groupId> <groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version> <version>1.2.0</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.assertj/assertj-core -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- tomcat -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>${tomcat.version}</version>
</dependency>
</dependencies> </dependencies>
</project>
<properties>
<assertj.version>3.6.2</assertj.version>
<httpclient.version>4.5.3</httpclient.version>
<commons.io.version>2.5</commons.io.version>
<jetty.version>9.4.8.v20171121</jetty.version>
<netty.version>4.1.20.Final</netty.version>
<commons.collections.version>4.1</commons.collections.version>
<junit.version>4.12</junit.version>
<tomcat.version>8.5.24</tomcat.version>
</properties>
</project>

View File

@ -5,13 +5,11 @@
- [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang) - [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang)
- [Introduction to Javatuples](http://www.baeldung.com/java-tuples) - [Introduction to Javatuples](http://www.baeldung.com/java-tuples)
- [Introduction to Javassist](http://www.baeldung.com/javassist) - [Introduction to Javassist](http://www.baeldung.com/javassist)
- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded)
- [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink) - [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink)
- [Introduction to JSONassert](http://www.baeldung.com/jsonassert) - [Introduction to JSONassert](http://www.baeldung.com/jsonassert)
- [Intro to JaVers](http://www.baeldung.com/javers) - [Intro to JaVers](http://www.baeldung.com/javers)
- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math) - [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math)
- [Intro to Serenity BDD](http://www.baeldung.com/serenity-bdd) - [Intro to Serenity BDD](http://www.baeldung.com/serenity-bdd)
- [Introduction to Netty](http://www.baeldung.com/netty)
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) - [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
- [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay) - [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay)
- [Introduction to Quartz](http://www.baeldung.com/quartz) - [Introduction to Quartz](http://www.baeldung.com/quartz)
@ -54,10 +52,7 @@
- [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle) - [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle)
- [Guide to google-http-client](http://www.baeldung.com/google-http-client) - [Guide to google-http-client](http://www.baeldung.com/google-http-client)
- [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client) - [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client)
- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup)
- [A Docker Guide for Java](http://www.baeldung.com/docker-java-api) - [A Docker Guide for Java](http://www.baeldung.com/docker-java-api)
- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling)
- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)
- [Introduction To OpenCSV](http://www.baeldung.com/opencsv) - [Introduction To OpenCSV](http://www.baeldung.com/opencsv)
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client) - [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client)
@ -77,7 +72,6 @@
- [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client) - [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client)
- [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools) - [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools)
- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) - [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils)
- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel)
- [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices) - [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices)
- [Introduction to JavaPoet](http://www.baeldung.com/java-poet) - [Introduction to JavaPoet](http://www.baeldung.com/java-poet)
- [Introduction to Joda-Time](http://www.baeldung.com/joda-time) - [Introduction to Joda-Time](http://www.baeldung.com/joda-time)

View File

@ -106,21 +106,6 @@
<artifactId>javers-core</artifactId> <artifactId>javers-core</artifactId>
<version>${javers.version}</version> <version>${javers.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency> <dependency>
<groupId>io.nats</groupId> <groupId>io.nats</groupId>
@ -169,6 +154,17 @@
<artifactId>commons-dbutils</artifactId> <artifactId>commons-dbutils</artifactId>
<version>${commons.dbutils.version}</version> <version>${commons.dbutils.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-kafka-0.11_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-java_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.flink</groupId> <groupId>org.apache.flink</groupId>
<artifactId>flink-core</artifactId> <artifactId>flink-core</artifactId>
@ -193,7 +189,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.flink</groupId> <groupId>org.apache.flink</groupId>
<artifactId>flink-test-utils_2.10</artifactId> <artifactId>flink-test-utils_2.11</artifactId>
<version>${flink.version}</version> <version>${flink.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
@ -243,6 +239,11 @@
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version> <version>${jackson.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- JDO --> <!-- JDO -->
<dependency> <dependency>
<groupId>org.datanucleus</groupId> <groupId>org.datanucleus</groupId>
@ -379,11 +380,6 @@
<artifactId>jmh-generator-annprocess</artifactId> <artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version> <version>${jmh.version}</version>
</dependency> </dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
@ -658,13 +654,7 @@
<classifier>test</classifier> <classifier>test</classifier>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- tomcat -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.milyn</groupId> <groupId>org.milyn</groupId>
<artifactId>milyn-smooks-all</artifactId> <artifactId>milyn-smooks-all</artifactId>
@ -924,12 +914,11 @@
<commons.io.version>2.5</commons.io.version> <commons.io.version>2.5</commons.io.version>
<commons.dbutils.version>1.6</commons.dbutils.version> <commons.dbutils.version>1.6</commons.dbutils.version>
<h2.version>1.4.196</h2.version> <h2.version>1.4.196</h2.version>
<jetty.version>9.4.8.v20171121</jetty.version>
<jnats.version>1.0</jnats.version> <jnats.version>1.0</jnats.version>
<httpclient.version>4.5.3</httpclient.version> <httpclient.version>4.5.3</httpclient.version>
<commons.io.version>2.5</commons.io.version> <commons.io.version>2.5</commons.io.version>
<flink.version>1.2.0</flink.version> <flink.version>1.5.0</flink.version>
<jackson.version>2.8.5</jackson.version> <jackson.version>2.8.5</jackson.version>
<neuroph.version>2.92</neuroph.version> <neuroph.version>2.92</neuroph.version>
<serenity.version>1.9.26</serenity.version> <serenity.version>1.9.26</serenity.version>
@ -937,7 +926,6 @@
<serenity.jira.version>1.9.0</serenity.jira.version> <serenity.jira.version>1.9.0</serenity.jira.version>
<serenity.plugin.version>1.9.27</serenity.plugin.version> <serenity.plugin.version>1.9.27</serenity.plugin.version>
<jUnitParams.version>1.1.0</jUnitParams.version> <jUnitParams.version>1.1.0</jUnitParams.version>
<netty.version>4.1.20.Final</netty.version>
<commons.collections.version>4.1</commons.collections.version> <commons.collections.version>4.1</commons.collections.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<java-lsh.version>0.10</java-lsh.version> <java-lsh.version>0.10</java-lsh.version>
@ -966,7 +954,6 @@
<kafka.version>1.0.0</kafka.version> <kafka.version>1.0.0</kafka.version>
<smooks.version>1.7.0</smooks.version> <smooks.version>1.7.0</smooks.version>
<docker.version>3.0.14</docker.version> <docker.version>3.0.14</docker.version>
<tomcat.version>8.5.24</tomcat.version>
<async.http.client.version>2.2.0</async.http.client.version> <async.http.client.version>2.2.0</async.http.client.version>
<infinispan.version>9.1.5.Final</infinispan.version> <infinispan.version>9.1.5.Final</infinispan.version>
<opencsv.version>4.1</opencsv.version> <opencsv.version>4.1</opencsv.version>

View File

@ -0,0 +1,82 @@
package com.baeldung.flink;
import com.baeldung.flink.model.Backup;
import com.baeldung.flink.model.InputMessage;
import com.baeldung.flink.operator.BackupAggregator;
import com.baeldung.flink.operator.InputMessageTimestampAssigner;
import com.baeldung.flink.operator.WordsCapitalizer;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011;
import static com.baeldung.flink.connector.Consumers.*;
import static com.baeldung.flink.connector.Producers.*;
public class FlinkDataPipeline {
public static void capitalize() throws Exception {
String inputTopic = "flink_input";
String outputTopic = "flink_output";
String consumerGroup = "baeldung";
String address = "localhost:9092";
StreamExecutionEnvironment environment =
StreamExecutionEnvironment.getExecutionEnvironment();
FlinkKafkaConsumer011<String> flinkKafkaConsumer =
createStringConsumerForTopic(inputTopic, address, consumerGroup);
flinkKafkaConsumer.setStartFromEarliest();
DataStream<String> stringInputStream =
environment.addSource(flinkKafkaConsumer);
FlinkKafkaProducer011<String> flinkKafkaProducer =
createStringProducer(outputTopic, address);
stringInputStream
.map(new WordsCapitalizer())
.addSink(flinkKafkaProducer);
environment.execute();
}
public static void createBackup () throws Exception {
String inputTopic = "flink_input";
String outputTopic = "flink_output";
String consumerGroup = "baeldung";
String kafkaAddress = "localhost:9092";
StreamExecutionEnvironment environment =
StreamExecutionEnvironment.getExecutionEnvironment();
environment.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
FlinkKafkaConsumer011<InputMessage> flinkKafkaConsumer =
createInputMessageConsumer(inputTopic, kafkaAddress, consumerGroup);
flinkKafkaConsumer.setStartFromEarliest();
flinkKafkaConsumer
.assignTimestampsAndWatermarks(new InputMessageTimestampAssigner());
FlinkKafkaProducer011<Backup> flinkKafkaProducer =
createBackupProducer(outputTopic, kafkaAddress);
DataStream<InputMessage> inputMessagesStream =
environment.addSource(flinkKafkaConsumer);
inputMessagesStream
.timeWindowAll(Time.hours(24))
.aggregate(new BackupAggregator())
.addSink(flinkKafkaProducer);
environment.execute();
}
public static void main(String[] args) throws Exception {
createBackup();
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.flink.connector;
import com.baeldung.flink.model.InputMessage;
import com.baeldung.flink.schema.InputMessageDeserializationSchema;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011;
import java.util.Properties;
public class Consumers {
public static FlinkKafkaConsumer011<String> createStringConsumerForTopic(
String topic, String kafkaAddress, String kafkaGroup ) {
Properties props = new Properties();
props.setProperty("bootstrap.servers", kafkaAddress);
props.setProperty("group.id",kafkaGroup);
FlinkKafkaConsumer011<String> consumer =
new FlinkKafkaConsumer011<>(topic, new SimpleStringSchema(),props);
return consumer;
}
public static FlinkKafkaConsumer011<InputMessage> createInputMessageConsumer(String topic, String kafkaAddress, String kafkaGroup ) {
Properties properties = new Properties();
properties.setProperty("bootstrap.servers", kafkaAddress);
properties.setProperty("group.id",kafkaGroup);
FlinkKafkaConsumer011<InputMessage> consumer = new FlinkKafkaConsumer011<InputMessage>(
topic, new InputMessageDeserializationSchema(),properties);
return consumer;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.flink.connector;
import com.baeldung.flink.model.Backup;
import com.baeldung.flink.schema.BackupSerializationSchema;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011;
public class Producers {
public static FlinkKafkaProducer011<String> createStringProducer(String topic, String kafkaAddress) {
return new FlinkKafkaProducer011<>(kafkaAddress, topic, new SimpleStringSchema());
}
public static FlinkKafkaProducer011<Backup> createBackupProducer(String topic, String kafkaAddress) {
return new FlinkKafkaProducer011<Backup>(kafkaAddress, topic, new BackupSerializationSchema());
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.flink.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
public class Backup {
@JsonProperty("inputMessages")
List<InputMessage> inputMessages;
@JsonProperty("backupTimestamp")
LocalDateTime backupTimestamp;
@JsonProperty("uuid")
UUID uuid;
public Backup(List<InputMessage> inputMessages, LocalDateTime backupTimestamp) {
this.inputMessages = inputMessages;
this.backupTimestamp = backupTimestamp;
this.uuid = UUID.randomUUID();
}
public List<InputMessage> getInputMessages() {
return inputMessages;
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.flink.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.base.Objects;
import java.time.LocalDateTime;
@JsonSerialize
public class InputMessage {
String sender;
String recipient;
LocalDateTime sentAt;
String message;
public InputMessage() {
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
public LocalDateTime getSentAt() {
return sentAt;
}
public void setSentAt(LocalDateTime sentAt) {
this.sentAt = sentAt;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public InputMessage(String sender, String recipient, LocalDateTime sentAt, String message) {
this.sender = sender;
this.recipient = recipient;
this.sentAt = sentAt;
this.message = message;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InputMessage message1 = (InputMessage) o;
return Objects.equal(sender, message1.sender) &&
Objects.equal(recipient, message1.recipient) &&
Objects.equal(sentAt, message1.sentAt) &&
Objects.equal(message, message1.message);
}
@Override
public int hashCode() {
return Objects.hashCode(sender, recipient, sentAt, message);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.flink.operator;
import com.baeldung.flink.model.Backup;
import com.baeldung.flink.model.InputMessage;
import org.apache.flink.api.common.functions.AggregateFunction;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class BackupAggregator implements AggregateFunction<InputMessage, List<InputMessage>, Backup> {
@Override
public List<InputMessage> createAccumulator() {
return new ArrayList<>();
}
@Override
public List<InputMessage> add(InputMessage inputMessage, List<InputMessage> inputMessages) {
inputMessages.add(inputMessage);
return inputMessages;
}
@Override
public Backup getResult(List<InputMessage> inputMessages) {
Backup backup = new Backup(inputMessages, LocalDateTime.now());
return backup;
}
@Override
public List<InputMessage> merge(List<InputMessage> inputMessages, List<InputMessage> acc1) {
inputMessages.addAll(acc1);
return inputMessages;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.flink.operator;
import com.baeldung.flink.model.InputMessage;
import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks;
import org.apache.flink.streaming.api.watermark.Watermark;
import javax.annotation.Nullable;
import java.time.ZoneId;
public class InputMessageTimestampAssigner implements AssignerWithPunctuatedWatermarks<InputMessage> {
@Override
public long extractTimestamp(InputMessage element, long previousElementTimestamp) {
ZoneId zoneId = ZoneId.systemDefault();
return element.getSentAt().atZone(zoneId).toEpochSecond() * 1000;
}
@Nullable
@Override
public Watermark checkAndGetNextWatermark(InputMessage lastElement, long extractedTimestamp) {
return new Watermark(extractedTimestamp - 15);
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.flink.operator;
import org.apache.flink.api.common.functions.MapFunction;
public class WordsCapitalizer implements MapFunction<String, String> {
@Override
public String map(String s) {
return s.toUpperCase();
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.flink.schema;
import com.baeldung.flink.model.Backup;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BackupSerializationSchema
implements SerializationSchema<Backup> {
static ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
Logger logger = LoggerFactory.getLogger(BackupSerializationSchema.class);
@Override
public byte[] serialize(Backup backupMessage) {
if(objectMapper == null) {
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
}
try {
String json = objectMapper.writeValueAsString(backupMessage);
return json.getBytes();
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
logger.error("Failed to parse JSON", e);
}
return new byte[0];
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.flink.schema;
import com.baeldung.flink.model.InputMessage;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import java.io.IOException;
public class InputMessageDeserializationSchema implements
DeserializationSchema<InputMessage> {
static ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
@Override
public InputMessage deserialize(byte[] bytes) throws IOException {
return objectMapper.readValue(bytes, InputMessage.class);
}
@Override
public boolean isEndOfStream(InputMessage inputMessage) {
return false;
}
@Override
public TypeInformation<InputMessage> getProducedType() {
return TypeInformation.of(InputMessage.class);
}
}

View File

@ -0,0 +1,103 @@
package com.baeldung.flink;
import com.baeldung.flink.model.Backup;
import com.baeldung.flink.model.InputMessage;
import com.baeldung.flink.operator.BackupAggregator;
import com.baeldung.flink.operator.InputMessageTimestampAssigner;
import com.baeldung.flink.schema.BackupSerializationSchema;
import com.baeldung.flink.schema.InputMessageDeserializationSchema;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.apache.commons.collections.ListUtils;
import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class BackupCreatorIntegrationTest {
public static ObjectMapper mapper;
@Before
public void setup() {
mapper = new ObjectMapper().registerModule(new JavaTimeModule());
}
@Test
public void givenProperJson_whenDeserializeIsInvoked_thenProperObjectIsReturned() throws IOException {
InputMessage message = new InputMessage("Me", "User", LocalDateTime.now(), "Test Message");
byte[] messageSerialized = mapper.writeValueAsBytes(message);
DeserializationSchema<InputMessage> deserializationSchema = new InputMessageDeserializationSchema();
InputMessage messageDeserialized = deserializationSchema.deserialize(messageSerialized);
assertEquals(message, messageDeserialized);
}
@Test
public void givenMultipleInputMessagesFromDifferentDays_whenBackupCreatorIsUser_thenMessagesAreGroupedProperly() throws Exception {
LocalDateTime currentTime = LocalDateTime.now();
InputMessage message = new InputMessage("Me", "User", currentTime, "First TestMessage");
InputMessage secondMessage = new InputMessage("Me", "User", currentTime.plusHours(1), "First TestMessage");
InputMessage thirdMessage = new InputMessage("Me", "User", currentTime.plusHours(2), "First TestMessage");
InputMessage fourthMessage = new InputMessage("Me", "User", currentTime.plusHours(3), "First TestMessage");
InputMessage fifthMessage = new InputMessage("Me", "User", currentTime.plusHours(25), "First TestMessage");
InputMessage sixthMessage = new InputMessage("Me", "User", currentTime.plusHours(26), "First TestMessage");
List<InputMessage> firstBackupMessages = Arrays.asList(message, secondMessage, thirdMessage, fourthMessage);
List<InputMessage> secondBackupMessages = Arrays.asList(fifthMessage, sixthMessage);
List<InputMessage> inputMessages = ListUtils.union(firstBackupMessages, secondBackupMessages);
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
env.setParallelism(1);
DataStreamSource<InputMessage> testDataSet = env.fromCollection(inputMessages);
CollectingSink sink = new CollectingSink();
testDataSet.assignTimestampsAndWatermarks(new InputMessageTimestampAssigner())
.timeWindowAll(Time.hours(24))
.aggregate(new BackupAggregator())
.addSink(sink);
env.execute();
Awaitility.await().until(() -> sink.backups.size() == 2);
assertEquals(2, sink.backups.size());
assertEquals(firstBackupMessages, sink.backups.get(0).getInputMessages());
assertEquals(secondBackupMessages, sink.backups.get(1).getInputMessages());
}
@Test
public void givenProperBackupObject_whenSerializeIsInvoked_thenObjectIsProperlySerialized() throws IOException {
InputMessage message = new InputMessage("Me", "User", LocalDateTime.now(), "Test Message");
List<InputMessage> messages = Arrays.asList(message);
Backup backup = new Backup(messages, LocalDateTime.now());
byte[] backupSerialized = mapper.writeValueAsBytes(backup);
SerializationSchema<Backup> serializationSchema = new BackupSerializationSchema();
byte[] backupProcessed = serializationSchema.serialize(backup);
assertEquals(backupSerialized, backupProcessed);
}
private static class CollectingSink implements SinkFunction<Backup> {
public static List<Backup> backups = new ArrayList<>();
@Override
public synchronized void invoke(Backup value, Context context) throws Exception {
backups.add(value);
}
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.flink;
import com.baeldung.flink.operator.WordsCapitalizer;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class WordCapitalizerIntegrationTest {
@Test
public void givenDataSet_whenExecuteWordCapitalizer_thenReturnCapitalizedWords() throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
List<String> data = Arrays.asList("dog", "cat", "wolf", "pig");
DataSet<String> testDataSet = env.fromCollection(data);
List<String> dataProcessed = testDataSet
.map(new WordsCapitalizer())
.collect();
List<String> testDataCapitalized = data.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
Assert.assertEquals(testDataCapitalized, dataProcessed);
}
}

27
optaplanner/pom.xml Normal file
View File

@ -0,0 +1,27 @@
<?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">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>optaplanner</artifactId>
<dependencies>
<dependency>
<groupId>org.optaplanner</groupId>
<artifactId>optaplanner-core</artifactId>
<version>7.9.0.Final</version>
</dependency>
<!--<dependency>-->
<!--<groupId></groupId>-->
<!--<artifactId></artifactId>-->
<!--</dependency>-->
</dependencies>
</project>

View File

@ -0,0 +1,63 @@
package com.baeldung.optaplanner;
import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty;
import org.optaplanner.core.api.domain.solution.PlanningScore;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty;
import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
@PlanningSolution
public class CourseSchedule {
Logger logger = LoggerFactory.getLogger("CourseSchedule");
private List<Integer> roomList;
private List<Integer> periodList;
private List<Lecture> lectureList;
private HardSoftScore score;
public CourseSchedule(){
roomList = new ArrayList<>();
periodList = new ArrayList<>();
lectureList = new ArrayList<>();
}
@ValueRangeProvider(id = "availableRooms")
@ProblemFactCollectionProperty
public List<Integer> getRoomList() {
return roomList;
}
@ValueRangeProvider(id = "availablePeriods")
@ProblemFactCollectionProperty
public List<Integer> getPeriodList() {
return periodList;
}
@PlanningEntityCollectionProperty
public List<Lecture> getLectureList() {
return lectureList;
}
@PlanningScore
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
public void printCourseSchedule() {
lectureList.stream()
.map(c -> "Lecture in Room " + c.getRoomNumber().toString() + " during Period " + c.getPeriod().toString())
.forEach(k -> logger.info(k));
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.optaplanner;
import org.optaplanner.core.api.domain.entity.PlanningEntity;
import org.optaplanner.core.api.domain.variable.PlanningVariable;
@PlanningEntity
public class Lecture {
private Integer roomNumber;
private Integer period;
@PlanningVariable(valueRangeProviderRefs = {"availablePeriods"})
public Integer getPeriod() {
return period;
}
@PlanningVariable(valueRangeProviderRefs = {"availableRooms"})
public Integer getRoomNumber() {
return roomNumber;
}
public void setPeriod(Integer period) {
this.period = period;
}
public void setRoomNumber(Integer roomNumber) {
this.roomNumber = roomNumber;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.optaplanner;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator;
import java.util.HashSet;
public class ScoreCalculator implements EasyScoreCalculator<CourseSchedule> {
@Override
public Score calculateScore(CourseSchedule courseSchedule) {
int hardScore = 0;
int softScore = 0;
HashSet<String> occupiedRooms = new HashSet<>();
for (Lecture lecture : courseSchedule.getLectureList()) {
if(lecture.getPeriod() != null && lecture.getRoomNumber() != null) {
String roomInUse = lecture.getPeriod().toString() + ":" + lecture.getRoomNumber().toString();
if (occupiedRooms.contains(roomInUse)) {
hardScore += -1;
} else {
occupiedRooms.add(roomInUse);
}
} else {
hardScore += -1;
}
}
return HardSoftScore.valueOf(hardScore, softScore);
}
}

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