Merge branch 'master' of https://github.com/eugenp/tutorials into task/BAEL-8844

This commit is contained in:
Dhawal Kapil 2018-09-03 23:40:07 +05:30
commit 375df7f3aa
184 changed files with 4742 additions and 1747 deletions

View File

@ -1,4 +1,4 @@
package com.baeldung.linesintersection;
package com.baeldung.algorithms.linesintersection;
import java.awt.Point;
import java.util.Optional;

View File

@ -1,4 +1,4 @@
package com.baeldung.linesintersection;
package com.baeldung.algorithms.linesintersection;
import java.awt.Point;
import java.util.Optional;
@ -23,7 +23,7 @@ public class LinesIntersectionServiceUnitTest {
assertTrue(point.isPresent());
assertEquals(point.get().getX(), 1, 0.001);
assertEquals(point.get().getX(), 1, 0.001);
assertEquals(point.get().getY(), 0, 0.001);
}
@Test

View File

@ -15,24 +15,17 @@
- [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 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)
- [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)
- [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)
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [Java Optional orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
- [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)

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

@ -37,3 +37,9 @@
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)

View File

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

View File

@ -1,13 +1,17 @@
package com.baeldung.list;
package com.baeldung.java.list;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class CopyListServiceUnitTest {

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

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

View File

@ -52,6 +52,13 @@
<artifactId>icu4j</artifactId>
<version>${icu4j.version}</version>
</dependency>
<dependency>
<groupId>com.vdurmont</groupId>
<artifactId>emoji-java</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,78 @@
package com.baeldung.string;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import com.vdurmont.emoji.EmojiParser;
public class RemovingEmojiFromStringUnitTest {
String text = "la conférence, commencera à 10 heures 😅 ✿";
String regex = "[^\\p{L}\\p{N}\\p{P}\\p{Z}]";
@Test
public void whenRemoveEmojiUsingLibrary_thenSuccess() {
String result = EmojiParser.removeAllEmojis(text);
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("à"));
assertThat(result, containsString("la"));
assertThat(result, containsString("10"));
}
@Test
public void whenReplaceEmojiUsingLibrary_thenSuccess() {
String result = EmojiParser.parseToAliases(text);
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("sweat_smile"));
}
@Test
public void whenRemoveEmojiUsingRegex_thenSuccess() {
String result = text.replaceAll(regex, "");
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("à"));
assertThat(result, containsString("la"));
assertThat(result, containsString("10"));
}
@Test
public void whenRemoveEmojiUsingMatcher_thenSuccess() {
Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CHARACTER_CLASS);
Matcher matcher = pattern.matcher(text);
String result = matcher.replaceAll("");
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("à"));
assertThat(result, containsString("la"));
assertThat(result, containsString("10"));
}
@Test
public void whenRemoveEmojiUsingCodepoints_thenSuccess() {
String result = text.replaceAll("[\\x{0001f300}-\\x{0001f64f}]|[\\x{0001f680}-\\x{0001f6ff}]", "");
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("à"));
assertThat(result, containsString("la"));
assertThat(result, containsString("10"));
}
@Test
public void whenRemoveEmojiUsingUnicode_thenSuccess() {
String result = text.replaceAll("[\ud83c\udf00-\ud83d\ude4f]|[\ud83d\ude80-\ud83d\udeff]", "");
System.out.println(result);
assertThat(result, not(containsString("😅")));
assertThat(result, containsString("à"));
assertThat(result, containsString("la"));
assertThat(result, containsString("10"));
}
}

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,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>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<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>
</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)
- [Introduction to Javatuples](http://www.baeldung.com/java-tuples)
- [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 JSONassert](http://www.baeldung.com/jsonassert)
- [Intro to JaVers](http://www.baeldung.com/javers)
- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math)
- [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)
- [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay)
- [Introduction to Quartz](http://www.baeldung.com/quartz)
@ -54,10 +52,7 @@
- [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle)
- [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)
- [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)
- [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 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)
@ -77,7 +72,6 @@
- [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)
- [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)
- [Introduction to JavaPoet](http://www.baeldung.com/java-poet)
- [Introduction to Joda-Time](http://www.baeldung.com/joda-time)

View File

@ -106,21 +106,6 @@
<artifactId>javers-core</artifactId>
<version>${javers.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>io.nats</groupId>
@ -169,6 +154,17 @@
<artifactId>commons-dbutils</artifactId>
<version>${commons.dbutils.version}</version>
</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>
<groupId>org.apache.flink</groupId>
<artifactId>flink-core</artifactId>
@ -193,7 +189,7 @@
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-test-utils_2.10</artifactId>
<artifactId>flink-test-utils_2.11</artifactId>
<version>${flink.version}</version>
<scope>test</scope>
</dependency>
@ -243,6 +239,11 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- JDO -->
<dependency>
<groupId>org.datanucleus</groupId>
@ -379,11 +380,6 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -658,13 +654,7 @@
<classifier>test</classifier>
<scope>test</scope>
</dependency>
<!-- tomcat -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.milyn</groupId>
<artifactId>milyn-smooks-all</artifactId>
@ -919,12 +909,11 @@
<commons.io.version>2.5</commons.io.version>
<commons.dbutils.version>1.6</commons.dbutils.version>
<h2.version>1.4.196</h2.version>
<jetty.version>9.4.8.v20171121</jetty.version>
<jnats.version>1.0</jnats.version>
<httpclient.version>4.5.3</httpclient.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>
<neuroph.version>2.92</neuroph.version>
<serenity.version>1.9.26</serenity.version>
@ -932,7 +921,6 @@
<serenity.jira.version>1.9.0</serenity.jira.version>
<serenity.plugin.version>1.9.27</serenity.plugin.version>
<jUnitParams.version>1.1.0</jUnitParams.version>
<netty.version>4.1.20.Final</netty.version>
<commons.collections.version>4.1</commons.collections.version>
<junit.version>4.12</junit.version>
<java-lsh.version>0.10</java-lsh.version>
@ -961,7 +949,6 @@
<kafka.version>1.0.0</kafka.version>
<smooks.version>1.7.0</smooks.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>
<infinispan.version>9.1.5.Final</infinispan.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);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.optaplanner
import com.baeldung.optaplanner.Lecture;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder;
global HardSoftScoreHolder scoreHolder;
rule "noNullRoomPeriod"
when
Lecture( roomNumber == null );
Lecture( period == null );
then
scoreHolder.addHardConstraintMatch(kcontext, -1);
end

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<solver>
<scanAnnotatedClasses/>
<scoreDirectorFactory>
<scoreDrl>courseSchedule.drl</scoreDrl>
</scoreDirectorFactory>
<termination>
<secondsSpentLimit>10</secondsSpentLimit>
</termination>
</solver>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<solver>
<scanAnnotatedClasses/>
<scoreDirectorFactory>
<easyScoreCalculatorClass>com.baeldung.optaplanner.ScoreCalculator</easyScoreCalculatorClass>
</scoreDirectorFactory>
<termination>
<secondsSpentLimit>10</secondsSpentLimit>
</termination>
</solver>

View File

@ -0,0 +1,3 @@
<configuration>
<logger name="org.optaplanner" level="info"/>
</configuration>

View File

@ -0,0 +1,50 @@
package com.baeldung.optaplanner.test;
import com.baeldung.optaplanner.CourseSchedule;
import com.baeldung.optaplanner.Lecture;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.SolverFactory;
import java.util.Arrays;
public class OptaPlannerUnitTest {
static CourseSchedule unsolvedCourseSchedule;
@BeforeAll
public static void setUp() {
unsolvedCourseSchedule = new CourseSchedule();
for(int i = 0; i < 10; i++){
unsolvedCourseSchedule.getLectureList().add(new Lecture());
}
unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(new Integer[] { 1, 2, 3 }));
unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(new Integer[] { 1, 2 }));
}
@Test
public void test_whenCustomJavaSolver() {
SolverFactory<CourseSchedule> solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml");
Solver<CourseSchedule> solver = solverFactory.buildSolver();
CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule);
Assert.assertNotNull(solvedCourseSchedule.getScore());
Assert.assertEquals(-4, solvedCourseSchedule.getScore().getHardScore());
}
@Test
public void test_whenDroolsSolver() {
SolverFactory<CourseSchedule> solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml");
Solver<CourseSchedule> solver = solverFactory.buildSolver();
CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule);
Assert.assertNotNull(solvedCourseSchedule.getScore());
Assert.assertEquals(0, solvedCourseSchedule.getScore().getHardScore());
}
}

View File

@ -7,6 +7,5 @@
- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search)
- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
- [Introduction to Lettuce the Java Redis Client](http://www.baeldung.com/java-redis-lettuce)
- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging)
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)

View File

@ -1,3 +1,4 @@
# Relevant Articles
* [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
- [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)

View File

@ -20,4 +20,18 @@
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
<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>

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