Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2018-12-14 02:00:25 +02:00
commit 6b96ead9b3
343 changed files with 4905 additions and 1049 deletions

View File

@ -28,14 +28,14 @@ public class Log {
System.out.println("Had " + count + " commits overall on current branch");
logs = git.log()
.add(repository.resolve("remotes/origin/testbranch"))
.add(repository.resolve(git.getRepository().getFullBranch()))
.call();
count = 0;
for (RevCommit rev : logs) {
System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
count++;
}
System.out.println("Had " + count + " commits overall on test-branch");
System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch());
logs = git.log()
.all()

View File

@ -1,3 +1,5 @@
package com.baeldung.jgit;
import com.baeldung.jgit.helper.Helper;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.ObjectReader;

View File

@ -17,6 +17,11 @@
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
@ -73,6 +78,7 @@
<commons-math3.version>3.6.1</commons-math3.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
<guava.version>25.1-jre</guava.version>
</properties>
</project>

View File

@ -0,0 +1,63 @@
package com.baeldung.algorithms.factorial;
import java.math.BigInteger;
import java.util.stream.LongStream;
import org.apache.commons.math3.util.CombinatoricsUtils;
import com.google.common.math.BigIntegerMath;
public class Factorial {
public long factorialUsingForLoop(int n) {
long fact = 1;
for (int i = 2; i <= n; i++) {
fact = fact * i;
}
return fact;
}
public long factorialUsingStreams(int n) {
return LongStream.rangeClosed(1, n)
.reduce(1, (long x, long y) -> x * y);
}
public long factorialUsingRecursion(int n) {
if (n <= 2) {
return n;
}
return n * factorialUsingRecursion(n - 1);
}
private Long[] factorials = new Long[20];
public long factorialUsingMemoize(int n) {
if (factorials[n] != null) {
return factorials[n];
}
if (n <= 2) {
return n;
}
long nthValue = n * factorialUsingMemoize(n - 1);
factorials[n] = nthValue;
return nthValue;
}
public BigInteger factorialHavingLargeResult(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++)
result = result.multiply(BigInteger.valueOf(i));
return result;
}
public long factorialUsingApacheCommons(int n) {
return CombinatoricsUtils.factorial(n);
}
public BigInteger factorialUsingGuava(int n) {
return BigIntegerMath.factorial(n);
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.algorithms.string;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class LongestSubstringNonRepeatingCharacters {
public static String getUniqueCharacterSubstringBruteForce(String input) {
String output = "";
for (int start = 0; start < input.length(); start++) {
Set<Character> visited = new HashSet<>();
int end = start;
for (; end < input.length(); end++) {
char currChar = input.charAt(end);
if (visited.contains(currChar)) {
break;
} else {
visited.add(currChar);
}
}
if (output.length() < end - start + 1) {
output = input.substring(start, end);
}
}
return output;
}
public static String getUniqueCharacterSubstring(String input) {
Map<Character, Integer> visited = new HashMap<>();
String output = "";
for (int start = 0, end = 0; end < input.length(); end++) {
char currChar = input.charAt(end);
if (visited.containsKey(currChar)) {
start = Math.max(visited.get(currChar) + 1, start);
}
if (output.length() < end - start + 1) {
output = input.substring(start, end + 1);
}
visited.put(currChar, end);
}
return output;
}
public static void main(String[] args) {
if(args.length > 0) {
System.out.println(getUniqueCharacterSubstring(args[0]));
} else {
System.err.println("This program expects command-line input. Please try again!");
}
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.algorithms.factorial;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigInteger;
import org.junit.Before;
import org.junit.Test;
public class FactorialUnitTest {
Factorial factorial;
@Before
public void setup() {
factorial = new Factorial();
}
@Test
public void whenCalculatingFactorialUsingForLoop_thenCorrect() {
int n = 5;
assertThat(factorial.factorialUsingForLoop(n)).isEqualTo(120);
}
@Test
public void whenCalculatingFactorialUsingStreams_thenCorrect() {
int n = 5;
assertThat(factorial.factorialUsingStreams(n)).isEqualTo(120);
}
@Test
public void whenCalculatingFactorialUsingRecursion_thenCorrect() {
int n = 5;
assertThat(factorial.factorialUsingRecursion(n)).isEqualTo(120);
}
@Test
public void whenCalculatingFactorialUsingMemoize_thenCorrect() {
int n = 5;
assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(120);
n = 6;
assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(720);
}
@Test
public void whenCalculatingFactorialHavingLargeResult_thenCorrect() {
int n = 22;
assertThat(factorial.factorialHavingLargeResult(n)).isEqualTo(new BigInteger("1124000727777607680000"));
}
@Test
public void whenCalculatingFactorialUsingApacheCommons_thenCorrect() {
int n = 5;
assertThat(factorial.factorialUsingApacheCommons(n)).isEqualTo(120);
}
@Test
public void whenCalculatingFactorialUsingGuava_thenCorrect() {
int n = 22;
assertThat(factorial.factorialUsingGuava(n)).isEqualTo(new BigInteger("1124000727777607680000"));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.algorithms.string;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstring;
import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstringBruteForce;
public class LongestSubstringNonRepeatingCharactersUnitTest {
@Test
void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpectedUnitTest() {
assertEquals("", getUniqueCharacterSubstringBruteForce(""));
assertEquals("A", getUniqueCharacterSubstringBruteForce("A"));
assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("AABCDEF"));
assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("ABCDEFF"));
assertEquals("NGISAWE", getUniqueCharacterSubstringBruteForce("CODINGISAWESOME"));
assertEquals("be coding", getUniqueCharacterSubstringBruteForce("always be coding"));
}
@Test
void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpectedUnitTest() {
assertEquals("", getUniqueCharacterSubstring(""));
assertEquals("A", getUniqueCharacterSubstring("A"));
assertEquals("ABCDEF", getUniqueCharacterSubstring("AABCDEF"));
assertEquals("ABCDEF", getUniqueCharacterSubstring("ABCDEFF"));
assertEquals("NGISAWE", getUniqueCharacterSubstring("CODINGISAWESOME"));
assertEquals("be coding", getUniqueCharacterSubstring("always be coding"));
}
}

View File

@ -33,6 +33,11 @@
<artifactId>jgrapht-core</artifactId>
<version>${org.jgrapht.core.version}</version>
</dependency>
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-ext</artifactId>
<version>${org.jgrapht.ext.version}</version>
</dependency>
<dependency>
<groupId>pl.allegro.finance</groupId>
<artifactId>tradukisto</artifactId>
@ -83,6 +88,7 @@
<commons-math3.version>3.6.1</commons-math3.version>
<tradukisto.version>1.0.1</tradukisto.version>
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
<org.jgrapht.ext.version>1.0.1</org.jgrapht.ext.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
</properties>

View File

@ -0,0 +1,47 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertTrue;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.junit.Before;
import org.junit.Test;
import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.util.mxCellRenderer;
public class GraphImageGenerationUnitTest {
static DefaultDirectedGraph<String, DefaultEdge> g;
@Before
public void createGraph() throws IOException {
File imgFile = new File("src/test/resources/graph.png");
imgFile.createNewFile();
g = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
String x1 = "x1";
String x2 = "x2";
String x3 = "x3";
g.addVertex(x1);
g.addVertex(x2);
g.addVertex(x3);
g.addEdge(x1, x2);
g.addEdge(x2, x3);
g.addEdge(x3, x1);
}
@Test
public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g);
mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent());
File imgFile = new File("src/test/resources/graph.png");
BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null);
ImageIO.write(image, "PNG", imgFile);
assertTrue(imgFile.exists());
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

@ -34,7 +34,7 @@ public class MergeSort {
while (i < left && j < right) {
if (l[i] < r[j])
if (l[i] <= r[j])
a[k++] = l[i++];
else
a[k++] = r[j++];

View File

@ -12,4 +12,4 @@
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
- [Array Operations in Java](http://www.baeldung.com/java-common-array-operations)
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)

View File

@ -51,3 +51,4 @@
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map)
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)

View File

@ -31,3 +31,4 @@
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)
- [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads)
- [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch)

View File

@ -1,34 +1,52 @@
package com.baeldung.concurrent.Scheduledexecutorservice;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
public class ScheduledExecutorServiceDemo {
public void execute() {
private void execute() {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> scheduledFuture = executorService.schedule(() -> {
// Task
}, 1, TimeUnit.SECONDS);
executorService.scheduleAtFixedRate(() -> {
// Task
}, 1, 10, TimeUnit.SECONDS);
executorService.scheduleWithFixedDelay(() -> {
// Task
}, 1, 10, TimeUnit.SECONDS);
Future<String> future = executorService.schedule(() -> {
// Task
return "Hellow world";
}, 1, TimeUnit.SECONDS);
getTasksToRun().apply(executorService);
executorService.shutdown();
}
private void executeWithMultiThread() {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
getTasksToRun().apply(executorService);
executorService.shutdown();
}
private Function<ScheduledExecutorService, Void> getTasksToRun() {
return (executorService -> {
ScheduledFuture<?> scheduledFuture1 = executorService.schedule(() -> {
// Task
}, 1, TimeUnit.SECONDS);
ScheduledFuture<?> scheduledFuture2 = executorService.scheduleAtFixedRate(() -> {
// Task
}, 1, 10, TimeUnit.SECONDS);
ScheduledFuture<?> scheduledFuture3 = executorService.scheduleWithFixedDelay(() -> {
// Task
}, 1, 10, TimeUnit.SECONDS);
ScheduledFuture<String> scheduledFuture4 = executorService.schedule(() -> {
// Task
return "Hellow world";
}, 1, TimeUnit.SECONDS);
return null;
});
}
public static void main(String... args) {
ScheduledExecutorServiceDemo demo = new ScheduledExecutorServiceDemo();
demo.execute();
demo.executeWithMultiThread();
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.concurrent.daemon;
public class MultipleThreadsExample {
public static void main(String[] args) {
NewThread t1 = new NewThread();
t1.setName("MyThread-1");
NewThread t2 = new NewThread();
t2.setName("MyThread-2");
t1.start();
t2.start();
}
}

View File

@ -1,14 +1,18 @@
package com.baeldung.concurrent.daemon;
public class NewThread extends Thread {
public void run() {
long startTime = System.currentTimeMillis();
while (true) {
for (int i = 0; i < 10; i++) {
System.out.println("New Thread is running..." + i);
System.out.println(this.getName() + ": New Thread is running..." + i);
try {
//Wait for one sec so it doesn't print too fast
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// prevent the Thread to run forever. It will finish it's execution after 2 seconds
if (System.currentTimeMillis() - startTime > 2000) {
Thread.currentThread().interrupt();

View File

@ -0,0 +1,8 @@
package com.baeldung.concurrent.daemon;
public class SingleThreadExample {
public static void main(String[] args) {
NewThread t = new NewThread();
t.start();
}
}

View File

@ -58,4 +58,4 @@
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)

View File

@ -1,3 +0,0 @@
=========
## Core Java Net

View File

@ -0,0 +1,7 @@
=========
## Core Java Networking
### Relevant Articles
- [Connecting Through Proxy Servers in Core Java](https://www.baeldung.com/java-connect-via-proxy-server)

View File

@ -1,10 +1,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-net</artifactId>
<artifactId>core-java-networking</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-net</name>
<name>core-java-networking</name>
<parent>
<groupId>com.baeldung</groupId>
@ -14,6 +14,6 @@
</parent>
<build>
<finalName>core-java-net</finalName>
<finalName>core-java-networking</finalName>
</build>
</project>

View File

@ -89,3 +89,6 @@
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
- [Calculate the Area of a Circle in Java](https://www.baeldung.com/java-calculate-circle-area)
- [A Guide to the Java Math Class](https://www.baeldung.com/java-lang-math)
- [Graphs in Java](https://www.baeldung.com/java-graphs)

View File

@ -0,0 +1,11 @@
package com.baeldung.basicsyntax;
public class SimpleAddition {
public static void main(String[] args) {
int a = 10;
int b = 5;
double c = a + b;
System.out.println( a + " + " + b + " = " + c);
}
}

View File

@ -0,0 +1,171 @@
package com.baeldung.java.properties;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import org.junit.Test;
public class PropertiesUnitTest {
@Test
public void givenPropertyValue_whenPropertiesFileLoaded_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
String catalogConfigPath = rootPath + "catalog";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
Properties catalogProps = new Properties();
catalogProps.load(new FileInputStream(catalogConfigPath));
String appVersion = appProps.getProperty("version");
assertEquals("1.0", appVersion);
assertEquals("files", catalogProps.getProperty("c1"));
}
@Test
public void givenPropertyValue_whenXMLPropertiesFileLoaded_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String iconConfigPath = rootPath + "icons.xml";
Properties iconProps = new Properties();
iconProps.loadFromXML(new FileInputStream(iconConfigPath));
assertEquals("icon1.jpg", iconProps.getProperty("fileIcon"));
}
@Test
public void givenAbsentProperty_whenPropertiesFileLoaded_thenReturnsDefault() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
String appVersion = appProps.getProperty("version");
String appName = appProps.getProperty("name", "defaultName");
String appGroup = appProps.getProperty("group", "baeldung");
String appDownloadAddr = appProps.getProperty("downloadAddr");
assertEquals("1.0", appVersion);
assertEquals("TestApp", appName);
assertEquals("baeldung", appGroup);
assertNull(appDownloadAddr);
}
@Test(expected = Exception.class)
public void givenImproperObjectCasting_whenPropertiesFileLoaded_thenThrowsException() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
float appVerFloat = (float) appProps.get("version");
}
@Test
public void givenPropertyValue_whenPropertiesSet_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
appProps.setProperty("name", "NewAppName");
appProps.setProperty("downloadAddr", "www.baeldung.com/downloads");
String newAppName = appProps.getProperty("name");
assertEquals("NewAppName", newAppName);
String newAppDownloadAddr = appProps.getProperty("downloadAddr");
assertEquals("www.baeldung.com/downloads", newAppDownloadAddr);
}
@Test
public void givenPropertyValueNull_whenPropertiesRemoved_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
String versionBeforeRemoval = appProps.getProperty("version");
assertEquals("1.0", versionBeforeRemoval);
appProps.remove("version");
String versionAfterRemoval = appProps.getProperty("version");
assertNull(versionAfterRemoval);
}
@Test
public void whenPropertiesStoredInFile_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
String newAppConfigPropertiesFile = rootPath + "newApp.properties";
appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file");
String newAppConfigXmlFile = rootPath + "newApp.xml";
appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file");
}
@Test
public void givenPropertyValueAbsent_LoadsValuesFromDefaultProperties() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String defaultConfigPath = rootPath + "default.properties";
Properties defaultProps = new Properties();
defaultProps.load(new FileInputStream(defaultConfigPath));
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties(defaultProps);
appProps.load(new FileInputStream(appConfigPath));
String appName = appProps.getProperty("name");
String appVersion = appProps.getProperty("version");
String defaultSite = appProps.getProperty("site");
assertEquals("1.0", appVersion);
assertEquals("TestApp", appName);
assertEquals("www.google.com", defaultSite);
}
@Test
public void givenPropertiesSize_whenPropertyFileLoaded_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appPropsPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appPropsPath));
appProps.list(System.out); // list all key-value pairs
Enumeration<Object> valueEnumeration = appProps.elements();
while (valueEnumeration.hasMoreElements()) {
System.out.println(valueEnumeration.nextElement());
}
Enumeration<Object> keyEnumeration = appProps.keys();
while (keyEnumeration.hasMoreElements()) {
System.out.println(keyEnumeration.nextElement());
}
int size = appProps.size();
assertEquals(3, size);
}
}

View File

@ -0,0 +1,3 @@
version=1.0
name=TestApp
date=2016-11-12

View File

@ -0,0 +1,3 @@
c1=files
c2=images
c3=videos

View File

@ -0,0 +1,4 @@
site=www.google.com
name=DefaultAppName
topic=Properties
category=core-java

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>xml example</comment>
<entry key="fileIcon">icon1.jpg</entry>
<entry key="imageIcon">icon2.jpg</entry>
<entry key="videoIcon">icon3.jpg</entry>
</properties>

View File

@ -47,3 +47,4 @@
- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort)
- [Dependency Injection for Kotlin with Injekt](https://www.baeldung.com/kotlin-dependency-injection-with-injekt)
- [Implementing a Binary Tree in Kotlin](https://www.baeldung.com/kotlin-binary-tree)
- [Generate a Random Alphanumeric String in Kotlin](https://www.baeldung.com/kotlin-random-alphanumeric-string)

View File

@ -0,0 +1,28 @@
package com.baeldung.functions
import kotlin.random.Random
/**
* An extension function on all collections to apply a function to all collection
* elements.
*/
fun <T> Collection<T>.each(block: (T) -> Unit) {
for (e in this) block(e)
}
/**
* In order to see the the JVM bytecode:
* 1. Compile the Kotlin file using `kotlinc Inline.kt`
* 2. Take a peek at the bytecode using the `javap -c InlineKt`
*/
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
val random = random()
numbers.each { println(random * it) } // capturing the random variable
}
/**
* Generates a random number.
*/
private fun random(): Int = Random.nextInt()

View File

@ -1 +0,0 @@
## Relevant articles:

View File

@ -24,4 +24,5 @@
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
- [Guide to DateTimeFormatter](https://www.baeldung.com/java-datetimeformatter)
- [Format ZonedDateTime to String](https://www.baeldung.com/java-format-zoned-datetime-string)
- [Convert Between java.time.Instant and java.sql.Timestamp](Convert Between java.time.Instant and java.sql.Timestamp)
- [Convert Between java.time.Instant and java.sql.Timestamp](https://www.baeldung.com/java-time-instant-to-java-sql-timestamp)
- [Convert between String and Timestamp](https://www.baeldung.com/java-string-to-timestamp)

View File

@ -8,6 +8,7 @@ import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
@ -51,6 +52,16 @@ public class DateDiffUnitTest {
assertEquals(diff, 6);
}
@Test
public void givenTwoDateTimesInJava8_whenDifferentiatingInSeconds_thenWeGetTen() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime tenSecondsLater = now.plusSeconds(10);
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
assertEquals(diff, 10);
}
@Test
public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() {
LocalDateTime ldt = LocalDateTime.now();
@ -60,6 +71,16 @@ public class DateDiffUnitTest {
assertEquals(diff, 6);
}
@Test
public void givenTwoDateTimesInJava8_whenDifferentiatingInSecondsUsingUntil_thenWeGetTen() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime tenSecondsLater = now.plusSeconds(10);
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
assertEquals(diff, 10);
}
@Test
public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() {
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();

View File

@ -74,6 +74,11 @@
<artifactId>aspectjweaver</artifactId>
<version>${asspectj.version}</version>
</dependency>
<dependency>
<groupId>pl.touk</groupId>
<artifactId>throwing-function</artifactId>
<version>${throwing-function.version}</version>
</dependency>
</dependencies>
<build>
@ -108,8 +113,9 @@
<protonpack.version>1.15</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<joda.version>2.10</joda.version>
<throwing-function.version>1.3</throwing-function.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<assertj.version>3.11.1</assertj.version>
<asspectj.version>1.8.9</asspectj.version>
</properties>
</project>

View File

@ -0,0 +1,55 @@
package com.baeldung.stream.filter;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Customer {
private String name;
private int points;
private String profilePhotoUrl;
public Customer(String name, int points) {
this(name, points, "");
}
public Customer(String name, int points, String profilePhotoUrl) {
this.name = name;
this.points = points;
this.profilePhotoUrl = profilePhotoUrl;
}
public String getName() {
return name;
}
public int getPoints() {
return points;
}
public boolean hasOver(int points) {
return this.points > points;
}
public boolean hasOverThousandPoints() {
return this.points > 100;
}
public boolean hasValidProfilePhoto() throws IOException {
URL url = new URL(this.profilePhotoUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
}
public boolean hasValidProfilePhotoWithoutCheckedException() {
try {
URL url = new URL(this.profilePhotoUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,159 @@
package com.baeldung.stream.filter;
import org.junit.jupiter.api.Test;
import pl.touk.throwing.ThrowingPredicate;
import pl.touk.throwing.exception.WrappedException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
public class StreamFilterUnitTest {
@Test
public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() {
Customer john = new Customer("John P.", 15);
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1);
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> customersWithMoreThan100Points = customers
.stream()
.filter(c -> c.getPoints() > 100)
.collect(Collectors.toList());
assertThat(customersWithMoreThan100Points).hasSize(2);
assertThat(customersWithMoreThan100Points).contains(sarah, charles);
}
@Test
public void givenListOfCustomers_whenFilterByPointsAndName_thenGetOne() {
Customer john = new Customer("John P.", 15);
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1);
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> charlesWithMoreThan100Points = customers
.stream()
.filter(c -> c.getPoints() > 100 && c
.getName()
.startsWith("Charles"))
.collect(Collectors.toList());
assertThat(charlesWithMoreThan100Points).hasSize(1);
assertThat(charlesWithMoreThan100Points).contains(charles);
}
@Test
public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() {
Customer john = new Customer("John P.", 15);
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1);
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> customersWithMoreThan100Points = customers
.stream()
.filter(Customer::hasOverThousandPoints)
.collect(Collectors.toList());
assertThat(customersWithMoreThan100Points).hasSize(2);
assertThat(customersWithMoreThan100Points).contains(sarah, charles);
}
@Test
public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() {
Optional<Customer> john = Optional.of(new Customer("John P.", 15));
Optional<Customer> sarah = Optional.of(new Customer("Sarah M.", 200));
Optional<Customer> mary = Optional.of(new Customer("Mary T.", 300));
List<Optional<Customer>> customers = Arrays.asList(john, sarah, Optional.empty(), mary, Optional.empty());
List<Customer> customersWithMoreThan100Points = customers
.stream()
.flatMap(c -> c
.map(Stream::of)
.orElseGet(Stream::empty))
.filter(Customer::hasOverThousandPoints)
.collect(Collectors.toList());
assertThat(customersWithMoreThan100Points).hasSize(2);
assertThat(customersWithMoreThan100Points).contains(sarah.get(), mary.get());
}
@Test
public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
assertThatThrownBy(() -> customers
.stream()
.filter(Customer::hasValidProfilePhotoWithoutCheckedException)
.count()).isInstanceOf(RuntimeException.class);
}
@Test
public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
assertThatThrownBy(() -> customers
.stream()
.filter((ThrowingPredicate.unchecked(Customer::hasValidProfilePhoto)))
.collect(Collectors.toList())).isInstanceOf(WrappedException.class);
}
@Test
public void givenListOfCustomers_whenFilterWithTryCatch_thenGetTwo() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> customersWithValidProfilePhoto = customers
.stream()
.filter(c -> {
try {
return c.hasValidProfilePhoto();
} catch (IOException e) {
//handle exception
}
return false;
})
.collect(Collectors.toList());
assertThat(customersWithValidProfilePhoto).hasSize(2);
assertThat(customersWithValidProfilePhoto).contains(john, mary);
}
@Test
public void givenListOfCustomers_whenFilterWithTryCatchAndRuntime_thenThrowException() {
List<Customer> customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150),
new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"));
assertThatThrownBy(() -> customers
.stream()
.filter(c -> {
try {
return c.hasValidProfilePhoto();
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.toList())).isInstanceOf(RuntimeException.class);
}
}

View File

@ -39,3 +39,7 @@
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline)
- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)

View File

@ -0,0 +1,90 @@
package com.baeldung.string;
import java.util.HashSet;
import java.util.Set;
public class SubstringPalindrome {
public Set<String> findAllPalindromesUsingCenter(String input) {
final Set<String> palindromes = new HashSet<>();
if (input == null || input.isEmpty()) {
return palindromes;
}
if (input.length() == 1) {
palindromes.add(input);
return palindromes;
}
for (int i = 0; i < input.length(); i++) {
palindromes.addAll(findPalindromes(input, i, i + 1));
palindromes.addAll(findPalindromes(input, i, i));
}
return palindromes;
}
private Set<String> findPalindromes(String input, int low, int high) {
Set<String> result = new HashSet<>();
while (low >= 0 && high < input.length() && input.charAt(low) == input.charAt(high)) {
result.add(input.substring(low, high + 1));
low--;
high++;
}
return result;
}
public Set<String> findAllPalindromesUsingBruteForceApproach(String input) {
Set<String> palindromes = new HashSet<>();
if (input == null || input.isEmpty()) {
return palindromes;
}
if (input.length() == 1) {
palindromes.add(input);
return palindromes;
}
for (int i = 0; i < input.length(); i++) {
for (int j = i + 1; j <= input.length(); j++)
if (isPalindrome(input.substring(i, j))) {
palindromes.add(input.substring(i, j));
}
}
return palindromes;
}
private boolean isPalindrome(String input) {
StringBuilder plain = new StringBuilder(input);
StringBuilder reverse = plain.reverse();
return (reverse.toString()).equals(input);
}
public Set<String> findAllPalindromesUsingManachersAlgorithm(String input) {
Set<String> palindromes = new HashSet<>();
String formattedInput = "@" + input + "#";
char inputCharArr[] = formattedInput.toCharArray();
int max;
int radius[][] = new int[2][input.length() + 1];
for (int j = 0; j <= 1; j++) {
radius[j][0] = max = 0;
int i = 1;
while (i <= input.length()) {
palindromes.add(Character.toString(inputCharArr[i]));
while (inputCharArr[i - max - 1] == inputCharArr[i + j + max])
max++;
radius[j][i] = max;
int k = 1;
while ((radius[j][i - k] != max - k) && (k < max)) {
radius[j][i + k] = Math.min(radius[j][i - k], max - k);
k++;
}
max = Math.max(max - k, 0);
i += k;
}
}
for (int i = 1; i <= input.length(); i++) {
for (int j = 0; j <= 1; j++) {
for (max = radius[j][i]; max > 0; max--) {
palindromes.add(input.substring(i - max - 1, max + j + i - 1));
}
}
}
return palindromes;
}
}

View File

@ -0,0 +1,135 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
public class ConvertStringToListUnitTest {
private final String countries = "Russia,Germany,England,France,Italy";
private final String ranks = "1,2,3,4,5, 6,7";
private final String emptyStrings = ",,,,,";
private final List<String> expectedCountriesList = Arrays.asList("Russia", "Germany", "England", "France", "Italy");
private final List<Integer> expectedRanksList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
private final List<String> expectedEmptyStringsList = Arrays.asList("", "", "", "", "", "");
@Test
public void givenString_thenGetListOfStringByJava() {
List<String> convertedCountriesList = Arrays.asList(countries.split(",", -1));
assertEquals(expectedCountriesList, convertedCountriesList);
}
@Test
public void givenString_thenGetListOfStringByApache() {
List<String> convertedCountriesList = Arrays.asList(StringUtils.splitPreserveAllTokens(countries, ","));
assertEquals(expectedCountriesList, convertedCountriesList);
}
@Test
public void givenString_thenGetListOfStringByGuava() {
List<String> convertedCountriesList = Splitter.on(",")
.trimResults()
.splitToList(countries);
assertEquals(expectedCountriesList, convertedCountriesList);
}
@Test
public void givenString_thenGetListOfStringByJava8() {
List<String> convertedCountriesList = Stream.of(countries.split(",", -1))
.collect(Collectors.toList());
assertEquals(expectedCountriesList, convertedCountriesList);
}
@Test
public void givenString_thenGetListOfIntegerByJava() {
String[] convertedRankArray = ranks.split(",");
List<Integer> convertedRankList = new ArrayList<Integer>();
for (String number : convertedRankArray) {
convertedRankList.add(Integer.parseInt(number.trim()));
}
assertEquals(expectedRanksList, convertedRankList);
}
@Test
public void givenString_thenGetListOfIntegerByGuava() {
List<Integer> convertedRankList = Lists.transform(Splitter.on(",")
.trimResults()
.splitToList(ranks), new Function<String, Integer>() {
@Override
public Integer apply(String input) {
return Integer.parseInt(input.trim());
}
});
assertEquals(expectedRanksList, convertedRankList);
}
@Test
public void givenString_thenGetListOfIntegerByJava8() {
List<Integer> convertedRankList = Stream.of(ranks.split(","))
.map(String::trim)
.map(Integer::parseInt)
.collect(Collectors.toList());
assertEquals(expectedRanksList, convertedRankList);
}
@Test
public void givenString_thenGetListOfIntegerByApache() {
String[] convertedRankArray = StringUtils.split(ranks, ",");
List<Integer> convertedRankList = new ArrayList<Integer>();
for (String number : convertedRankArray) {
convertedRankList.add(Integer.parseInt(number.trim()));
}
assertEquals(expectedRanksList, convertedRankList);
}
@Test
public void givenEmptyStrings_thenGetListOfStringByJava() {
List<String> convertedEmptyStringsList = Arrays.asList(emptyStrings.split(",", -1));
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
}
@Test
public void givenEmptyStrings_thenGetListOfStringByApache() {
List<String> convertedEmptyStringsList = Arrays.asList(StringUtils.splitPreserveAllTokens(emptyStrings, ","));
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
}
@Test
public void givenEmptyStrings_thenGetListOfStringByGuava() {
List<String> convertedEmptyStringsList = Splitter.on(",")
.trimResults()
.splitToList(emptyStrings);
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
}
@Test
public void givenEmptyStrings_thenGetListOfStringByJava8() {
List<String> convertedEmptyStringsList = Stream.of(emptyStrings.split(",", -1))
.collect(Collectors.toList());
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.string;
import static org.junit.Assert.assertEquals;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
public class SubstringPalindromeUnitTest {
private static final String INPUT_BUBBLE = "bubble";
private static final String INPUT_CIVIC = "civic";
private static final String INPUT_INDEED = "indeed";
private static final String INPUT_ABABAC = "ababac";
Set<String> EXPECTED_PALINDROME_BUBBLE = new HashSet<String>() {
{
add("b");
add("u");
add("l");
add("e");
add("bb");
add("bub");
}
};
Set<String> EXPECTED_PALINDROME_CIVIC = new HashSet<String>() {
{
add("civic");
add("ivi");
add("i");
add("c");
add("v");
}
};
Set<String> EXPECTED_PALINDROME_INDEED = new HashSet<String>() {
{
add("i");
add("n");
add("d");
add("e");
add("ee");
add("deed");
}
};
Set<String> EXPECTED_PALINDROME_ABABAC = new HashSet<String>() {
{
add("a");
add("b");
add("c");
add("aba");
add("bab");
add("ababa");
}
};
private SubstringPalindrome palindrome = new SubstringPalindrome();
@Test
public void whenUsingManachersAlgorithm_thenFindsAllPalindromes() {
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_BUBBLE));
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_INDEED));
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_CIVIC));
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_ABABAC));
}
@Test
public void whenUsingCenterApproach_thenFindsAllPalindromes() {
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingCenter(INPUT_BUBBLE));
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingCenter(INPUT_INDEED));
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingCenter(INPUT_CIVIC));
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingCenter(INPUT_ABABAC));
}
@Test
public void whenUsingBruteForceApproach_thenFindsAllPalindromes() {
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_BUBBLE));
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_INDEED));
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_CIVIC));
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_ABABAC));
}
}

View File

@ -33,6 +33,16 @@
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>javax.json.bind</groupId>

View File

@ -0,0 +1,41 @@
package com.baeldung.escape;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import org.json.JSONObject;
class JsonEscape {
String escapeJson(String input) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", input);
return jsonObject.toString();
}
String escapeGson(String input) {
JsonObject gsonObject = new JsonObject();
gsonObject.addProperty("message", input);
return gsonObject.toString();
}
String escapeJackson(String input) throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(new Payload(input));
}
static class Payload {
String message;
Payload(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.escape;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class JsonEscapeUnitTest {
private JsonEscape testedInstance;
private static final String EXPECTED = "{\"message\":\"Hello \\\"World\\\"\"}";
@BeforeEach
void setUp() {
testedInstance = new JsonEscape();
}
@Test
void escapeJson() {
String actual = testedInstance.escapeJson("Hello \"World\"");
assertEquals(EXPECTED, actual);
}
@Test
void escapeGson() {
String actual = testedInstance.escapeGson("Hello \"World\"");
assertEquals(EXPECTED, actual);
}
@Test
void escapeJackson() throws JsonProcessingException {
String actual = testedInstance.escapeJackson("Hello \"World\"");
assertEquals(EXPECTED, actual);
}
}

View File

@ -8,3 +8,4 @@
- [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor)
- [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence)
- [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates)
- [Introduction to Arrow in Kotlin](https://www.baeldung.com/kotlin-arrow)

View File

@ -14,3 +14,4 @@
- [Building a Data Pipeline with Flink and Kafka](https://www.baeldung.com/kafka-flink-data-pipeline)
- [Intro to Apache Storm](https://www.baeldung.com/apache-storm)
- [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm)
- [Introduction to Kafka Connectors](https://www.baeldung.com/kafka-connectors-guide)

View File

@ -717,6 +717,12 @@
<version>${suanshu.version}</version>
</dependency>
<dependency>
<groupId>org.derive4j</groupId>
<artifactId>derive4j</artifactId>
<version>${derive4j.version}</version>
<optional>true</optional>
</dependency>
</dependencies>
<repositories>
@ -942,7 +948,7 @@
<yarg.version>2.0.4</yarg.version>
<mbassador.version>1.3.1</mbassador.version>
<jdeferred.version>1.2.6</jdeferred.version>
<functionaljava.version>4.7</functionaljava.version>
<functionaljava.version>4.8.1</functionaljava.version>
<jgrapht.version>1.0.1</jgrapht.version>
<docx4j.version>3.3.5</docx4j.version>
<jaxb-api.version>2.1</jaxb-api.version>
@ -952,6 +958,7 @@
<fugue.version>4.5.1</fugue.version>
<maven-bundle-plugin.version>3.3.0</maven-bundle-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<derive4j.version>1.1.0</derive4j.version>
</properties>
</project>

View File

@ -0,0 +1,10 @@
package com.baeldung.derive4j.adt;
import org.derive4j.Data;
import java.util.function.Function;
@Data
interface Either<A,B>{
<X> X match(Function<A, X> left, Function<B, X> right);
}

View File

@ -0,0 +1,21 @@
package com.baeldung.derive4j.lazy;
import org.derive4j.Data;
import org.derive4j.Derive;
import org.derive4j.Make;
@Data(value = @Derive(
inClass = "{ClassName}Impl",
make = {Make.lazyConstructor, Make.constructors}
))
public interface LazyRequest {
interface Cases<R>{
R GET(String path);
R POST(String path, String body);
R PUT(String path, String body);
R DELETE(String path);
}
<R> R match(LazyRequest.Cases<R> method);
}

View File

@ -0,0 +1,15 @@
package com.baeldung.derive4j.pattern;
import org.derive4j.Data;
@Data
interface HTTPRequest {
interface Cases<R>{
R GET(String path);
R POST(String path, String body);
R PUT(String path, String body);
R DELETE(String path);
}
<R> R match(Cases<R> method);
}

View File

@ -0,0 +1,19 @@
package com.baeldung.derive4j.pattern;
public class HTTPResponse {
private int statusCode;
private String responseBody;
public int getStatusCode() {
return statusCode;
}
public String getResponseBody() {
return responseBody;
}
public HTTPResponse(int statusCode, String responseBody) {
this.statusCode = statusCode;
this.responseBody = responseBody;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.derive4j.pattern;
public class HTTPServer {
public static String GET_RESPONSE_BODY = "Success!";
public static String PUT_RESPONSE_BODY = "Resource Created!";
public static String POST_RESPONSE_BODY = "Resource Updated!";
public static String DELETE_RESPONSE_BODY = "Resource Deleted!";
public HTTPResponse acceptRequest(HTTPRequest request) {
return HTTPRequests.caseOf(request)
.GET((path) -> new HTTPResponse(200, GET_RESPONSE_BODY))
.POST((path,body) -> new HTTPResponse(201, POST_RESPONSE_BODY))
.PUT((path,body) -> new HTTPResponse(200, PUT_RESPONSE_BODY))
.DELETE(path -> new HTTPResponse(200, DELETE_RESPONSE_BODY));
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.derive4j.adt;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Optional;
import java.util.function.Function;
@RunWith(MockitoJUnitRunner.class)
public class EitherUnitTest {
@Test
public void testEitherIsCreatedFromRight() {
Either<Exception, String> either = Eithers.right("Okay");
Optional<Exception> leftOptional = Eithers.getLeft(either);
Optional<String> rightOptional = Eithers.getRight(either);
Assertions.assertThat(leftOptional).isEmpty();
Assertions.assertThat(rightOptional).hasValue("Okay");
}
@Test
public void testEitherIsMatchedWithRight() {
Either<Exception, String> either = Eithers.right("Okay");
Function<Exception, String> leftFunction = Mockito.mock(Function.class);
Function<String, String> rightFunction = Mockito.mock(Function.class);
either.match(leftFunction, rightFunction);
Mockito.verify(rightFunction, Mockito.times(1)).apply("Okay");
Mockito.verify(leftFunction, Mockito.times(0)).apply(Mockito.any(Exception.class));
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.derive4j.lazy;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.function.Supplier;
public class LazyRequestUnitTest {
@Test
public void givenLazyContstructedRequest_whenRequestIsReferenced_thenRequestIsLazilyContructed() {
LazyRequestSupplier mockSupplier = Mockito.spy(new LazyRequestSupplier());
LazyRequest request = LazyRequestImpl.lazy(() -> mockSupplier.get());
Mockito.verify(mockSupplier, Mockito.times(0)).get();
Assert.assertEquals(LazyRequestImpl.getPath(request), "http://test.com/get");
Mockito.verify(mockSupplier, Mockito.times(1)).get();
}
class LazyRequestSupplier implements Supplier<LazyRequest> {
@Override
public LazyRequest get() {
return LazyRequestImpl.GET("http://test.com/get");
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.derive4j.pattern;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class HTTPRequestUnitTest {
public static HTTPServer server;
@BeforeClass
public static void setUp() {
server = new HTTPServer();
}
@Test
public void givenHttpGETRequest_whenRequestReachesServer_thenProperResponseIsReturned() {
HTTPRequest postRequest = HTTPRequests.POST("http://test.com/post", "Resource");
HTTPResponse response = server.acceptRequest(postRequest);
Assert.assertEquals(201, response.getStatusCode());
Assert.assertEquals(HTTPServer.POST_RESPONSE_BODY, response.getResponseBody());
}
}

View File

@ -1,10 +1,13 @@
package com.baeldung.fj;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import fj.F;
import fj.Show;
import fj.data.Array;
import fj.data.List;
import fj.data.Option;
@ -15,14 +18,41 @@ public class FunctionalJavaUnitTest {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
public static final Integer timesTwoRegular(Integer i) {
return i * 2;
}
public static final F<Integer, Integer> timesTwo = i -> i * 2;
public static final F<Integer, Integer> plusOne = i -> i + 1;
@Test
public void multiplyNumbers_givenIntList_returnTrue() {
List<Integer> fList = List.list(1, 2, 3, 4);
List<Integer> fList1 = fList.map(timesTwo);
List<Integer> fList2 = fList.map(i -> i * 2);
assertTrue(fList1.equals(fList2));
}
@Test
public void applyMultipleFunctions_givenIntList_returnFalse() {
List<Integer> fList = List.list(1, 2, 3, 4);
List<Integer> fList1 = fList.map(timesTwo).map(plusOne);
Show.listShow(Show.intShow).println(fList1);
List<Integer> fList2 = fList.map(plusOne).map(timesTwo);
Show.listShow(Show.intShow).println(fList2);
assertFalse(fList1.equals(fList2));
}
@Test
public void calculateEvenNumbers_givenIntList_returnTrue() {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
List<Boolean> evenListTrueResult = List.list(false, true, false, true);
List<Boolean> evenListFalseResult = List.list(true, false, false, true);
assertEquals(evenList.equals(evenListTrueResult), true);
assertEquals(evenList.equals(evenListFalseResult), false);
assertTrue(evenList.equals(evenListTrueResult));
}
@Test
@ -30,50 +60,57 @@ public class FunctionalJavaUnitTest {
List<Integer> fList = List.list(3, 4, 5, 6);
fList = fList.map(i -> i + 100);
List<Integer> resultList = List.list(103, 104, 105, 106);
List<Integer> falseResultList = List.list(15, 504, 105, 106);
assertEquals(fList.equals(resultList), true);
assertEquals(fList.equals(falseResultList), false);
assertTrue(fList.equals(resultList));
}
@Test
public void filterList_givenIntList_returnResult() {
Array<Integer> array = Array.array(3, 4, 5, 6);
Array<Integer> filteredArray = array.filter(Integers.even);
Array<Integer> filteredArray = array.filter(isEven);
Array<Integer> result = Array.array(4, 6);
Array<Integer> wrongResult = Array.array(3, 5);
assertEquals(filteredArray.equals(result), true);
assertEquals(filteredArray.equals(wrongResult), false);
assertTrue(filteredArray.equals(result));
}
@Test
public void checkForLowerCase_givenStringArray_returnResult() {
Array<String> array = Array.array("Welcome", "To", "baeldung");
assertTrue(array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)));
Array<String> array2 = Array.array("Welcome", "To", "Baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
assertEquals(isExist, true);
assertEquals(isExist2, false);
assertFalse(array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase)));
assertFalse(array.forall(s -> List.fromString(s).forall(Characters.isLowerCase)));
}
@Test
public void checkOptions_givenOptions_returnResult() {
Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2);
Option<Integer> n3 = Option.none();
F<Integer, Option<Integer>> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
F<Integer, Option<Integer>> function = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
Option<Integer> result1 = n1.bind(f1);
Option<Integer> result2 = n2.bind(f1);
Option<Integer> result1 = n1.bind(function);
Option<Integer> result2 = n2.bind(function);
Option<Integer> result3 = n3.bind(function);
assertEquals(result1, Option.none());
assertEquals(result2, Option.some(102));
assertEquals(Option.none(), result1);
assertEquals(Option.some(102), result2);
assertEquals(Option.none(), result3);
}
@Test
public void foldLeft_givenArray_returnResult() {
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0);
assertEquals(sum, 260);
int sumAll = intArray.foldLeft(Integers.add, 0);
assertEquals(260, sumAll);
int sumEven = intArray.filter(isEven).foldLeft(Integers.add, 0);
assertEquals(148, sumEven);
}
}

View File

@ -7,15 +7,10 @@
<properties>
<exec.mainClass>com.baeldung.micronaut.helloworld.server.ServerApplication</exec.mainClass>
<micronaut.version>1.0.0.M2</micronaut.version>
<jdk.version>9</jdk.version>
<micronaut.version>1.0.0.RC2</micronaut.version>
<jdk.version>1.8</jdk.version>
</properties>
<repositories>
<repository>
<id>jcenter.bintray.com</id>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>

View File

@ -1,7 +1,7 @@
package com.baeldung.micronaut.helloworld.client;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.Client;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.RxHttpClient;
import io.reactivex.Single;

View File

@ -1,10 +1,7 @@
package com.baeldung.micronaut.helloworld.client;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.client.Client;
import io.micronaut.http.client.RxHttpClient;
import javax.inject.Inject;
import io.micronaut.http.client.annotation.Client;
@Client("/greet")
public interface GreetingClient {

View File

@ -0,0 +1,2 @@
This pom will be ued only temporary until we migrate parent-boot-2 to 2.1.0 for ticket BAEL-10354

View File

@ -0,0 +1,85 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>parent-boot-2.0-temp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<description>Temporary Parent for all Spring Boot 2.0.x modules</description>
<!-- This pom will be ued only temporary until we migrate parent-boot-2 to 2.1.0 for ticket BAEL-10354 -->
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>${start-class}</mainClass>
<!-- this is necessary as we're not using the Boot parent -->
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<profile>
<id>thin-jar</id>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<!-- The following enables the "thin jar" deployment option. -->
<dependency>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-thin-layout</artifactId>
<version>${thin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<rest-assured.version>3.1.0</rest-assured.version>
<!-- plugins -->
<thin.version>1.0.11.RELEASE</thin.version>
<spring-boot.version>2.0.5.RELEASE</spring-boot.version>
</properties>
</project>

View File

@ -78,7 +78,7 @@
<rest-assured.version>3.1.0</rest-assured.version>
<!-- plugins -->
<thin.version>1.0.11.RELEASE</thin.version>
<spring-boot.version>2.0.5.RELEASE</spring-boot.version>
<spring-boot.version>2.1.1.RELEASE</spring-boot.version>
</properties>
</project>

View File

@ -10,3 +10,4 @@
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all)
- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive)

View File

@ -19,3 +19,5 @@
- [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy)
- [Proxy in Hibernate load() Method](https://www.baeldung.com/hibernate-proxy-load-method)
- [Custom Types in Hibernate](https://www.baeldung.com/hibernate-custom-types)
- [Criteria API An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions)
- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby)

View File

@ -51,6 +51,11 @@
<artifactId>hibernate-testing</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
@ -69,6 +74,7 @@
<mariaDB4j.version>2.2.3</mariaDB4j.version>
<h2database.version>1.4.196</h2database.version>
<assertj-core.version>3.8.0</assertj-core.version>
<jackson.version>2.8.11.3</jackson.version>
</properties>
</project>

View File

@ -1,7 +1,17 @@
package com.baeldung.hibernate.entities;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) })
@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class),
@org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) })
@Entity
public class DeptEmployee {
@Id

View File

@ -0,0 +1,66 @@
package com.baeldung.hibernate.onetoone;
import com.baeldung.hibernate.customtypes.LocalDateStringType;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil() {
}
public static SessionFactory getSessionFactory(Strategy strategy) {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory(strategy);
}
return sessionFactory;
}
private static SessionFactory buildSessionFactory(Strategy strategy) {
try {
ServiceRegistry serviceRegistry = configureServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
for (Class<?> entityClass : strategy.getEntityClasses()) {
metadataSources.addAnnotatedClass(entityClass);
}
Metadata metadata = metadataSources.getMetadataBuilder()
.applyBasicType(LocalDateStringType.INSTANCE)
.build();
return metadata.getSessionFactoryBuilder()
.build();
} catch (IOException ex) {
throw new ExceptionInInitializerError(ex);
}
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate.properties");
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}

View File

@ -0,0 +1,114 @@
package com.baeldung.hibernate.operations;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.baeldung.hibernate.pojo.Movie;
/**
*
*Class to illustrate the usage of EntityManager API.
*/
public class HibernateOperations {
private static final EntityManagerFactory emf;
/**
* Static block for creating EntityManagerFactory. The Persistence class looks for META-INF/persistence.xml in the classpath.
*/
static {
emf = Persistence.createEntityManagerFactory("com.baeldung.movie_catalog");
}
/**
* Static method returning EntityManager.
* @return EntityManager
*/
public static EntityManager getEntityManager() {
return emf.createEntityManager();
}
/**
* Saves the movie entity into the database. Here we are using Application Managed EntityManager, hence should handle transactions by ourselves.
*/
public void saveMovie() {
EntityManager em = HibernateOperations.getEntityManager();
em.getTransaction()
.begin();
Movie movie = new Movie();
movie.setId(1L);
movie.setMovieName("The Godfather");
movie.setReleaseYear(1972);
movie.setLanguage("English");
em.persist(movie);
em.getTransaction()
.commit();
}
/**
* Method to illustrate the querying support in EntityManager when the result is a single object.
* @return Movie
*/
public Movie queryForMovieById() {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = (Movie) em.createQuery("SELECT movie from Movie movie where movie.id = ?1")
.setParameter(1, new Long(1L))
.getSingleResult();
return movie;
}
/**
* Method to illustrate the querying support in EntityManager when the result is a list.
* @return
*/
public List<?> queryForMovies() {
EntityManager em = HibernateOperations.getEntityManager();
List<?> movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1")
.setParameter(1, "English")
.getResultList();
return movies;
}
/**
* Method to illustrate the usage of find() method.
* @param movieId
* @return Movie
*/
public Movie getMovie(Long movieId) {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = em.find(Movie.class, new Long(movieId));
return movie;
}
/**
* Method to illustrate the usage of merge() function.
*/
public void mergeMovie() {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = getMovie(1L);
em.detach(movie);
movie.setLanguage("Italian");
em.getTransaction()
.begin();
em.merge(movie);
em.getTransaction()
.commit();
}
/**
* Method to illustrate the usage of remove() function.
*/
public void removeMovie() {
EntityManager em = HibernateOperations.getEntityManager();
em.getTransaction()
.begin();
Movie movie = em.find(Movie.class, new Long(1L));
em.remove(movie);
em.getTransaction()
.commit();
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.hibernate.persistjson;
import java.io.IOException;
import java.util.Map;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Entity
@Table(name = "Customers")
public class Customer {
@Id
private int id;
private String firstName;
private String lastName;
private String customerAttributeJSON;
@Convert(converter = HashMapConverter.class)
private Map<String, Object> customerAttributes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCustomerAttributeJSON() {
return customerAttributeJSON;
}
public void setCustomerAttributeJSON(String customerAttributeJSON) {
this.customerAttributeJSON = customerAttributeJSON;
}
public Map<String, Object> getCustomerAttributes() {
return customerAttributes;
}
public void setCustomerAttributes(Map<String, Object> customerAttributes) {
this.customerAttributes = customerAttributes;
}
private static final ObjectMapper objectMapper = new ObjectMapper();
public void serializeCustomerAttributes() throws JsonProcessingException {
this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes);
}
public void deserializeCustomerAttributes() throws IOException {
this.customerAttributes = objectMapper.readValue(customerAttributeJSON, Map.class);
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.hibernate.persistjson;
import java.io.IOException;
import java.util.Map;
import javax.persistence.AttributeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.hibernate.interceptors.CustomInterceptor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HashMapConverter implements AttributeConverter<Map<String, Object>, String> {
private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(Map<String, Object> customerInfo) {
String customerInfoJson = null;
try {
customerInfoJson = objectMapper.writeValueAsString(customerInfo);
} catch (final JsonProcessingException e) {
logger.error("JSON writing error", e);
}
return customerInfoJson;
}
@Override
public Map<String, Object> convertToEntityAttribute(String customerInfoJSON) {
Map<String, Object> customerInfo = null;
try {
customerInfo = objectMapper.readValue(customerInfoJSON, Map.class);
} catch (final IOException e) {
logger.error("JSON reading error", e);
}
return customerInfo;
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "MOVIE")
public class Movie {
@Id
private Long id;
private String movieName;
private Integer releaseYear;
private String language;
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public Integer getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(Integer releaseYear) {
this.releaseYear = releaseYear;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="com.baeldung.movie_catalog">
<description>Hibernate EntityManager Demo</description>
<class>com.baeldung.hibernate.pojo.Movie</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<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/moviecatalog"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,10 @@
CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
@CODE
void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException {
CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'");
updateStatement.execute();
}
$$;

View File

@ -0,0 +1,98 @@
package com.baeldung.hibernate;
import com.baeldung.hibernate.entities.Department;
import com.baeldung.hibernate.entities.DeptEmployee;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.junit.*;
import java.io.IOException;
public class NamedQueryIntegrationTest {
private static Session session;
private Transaction transaction;
private Long purchaseDeptId;
@BeforeClass
public static void setUpClass() throws IOException {
session = HibernateUtil.getSessionFactory("hibernate-namedquery.properties").openSession();
}
@Before
public void setUp() throws IOException {
transaction = session.beginTransaction();
session.createNativeQuery("delete from deptemployee").executeUpdate();
session.createNativeQuery("delete from department").executeUpdate();
Department salesDepartment = new Department("Sales");
Department purchaseDepartment = new Department("Purchase");
DeptEmployee employee1 = new DeptEmployee("John Wayne", "001", salesDepartment);
DeptEmployee employee2 = new DeptEmployee("Sarah Vinton", "002", salesDepartment);
DeptEmployee employee3 = new DeptEmployee("Lisa Carter", "003", salesDepartment);
session.persist(salesDepartment);
session.persist(purchaseDepartment);
purchaseDeptId = purchaseDepartment.getId();
session.persist(employee1);
session.persist(employee2);
session.persist(employee3);
transaction.commit();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
if(transaction.isActive()) {
transaction.rollback();
}
}
@Test
public void whenNamedQueryIsCalledUsingCreateNamedQuery_ThenOk() {
Query<DeptEmployee> query = session.createNamedQuery("DeptEmployee_FindByEmployeeNumber", DeptEmployee.class);
query.setParameter("employeeNo", "001");
DeptEmployee result = query.getSingleResult();
Assert.assertNotNull(result);
Assert.assertEquals("John Wayne", result.getName());
}
@Test
public void whenNamedNativeQueryIsCalledUsingCreateNamedQuery_ThenOk() {
Query<DeptEmployee> query = session.createNamedQuery("DeptEmployee_FindByEmployeeName", DeptEmployee.class);
query.setParameter("name", "John Wayne");
DeptEmployee result = query.getSingleResult();
Assert.assertNotNull(result);
Assert.assertEquals("001", result.getEmployeeNumber());
}
@Test
public void whenNamedNativeQueryIsCalledUsingGetNamedNativeQuery_ThenOk() {
@SuppressWarnings("rawtypes")
NativeQuery query = session.getNamedNativeQuery("DeptEmployee_FindByEmployeeName");
query.setParameter("name", "John Wayne");
DeptEmployee result = (DeptEmployee) query.getSingleResult();
Assert.assertNotNull(result);
Assert.assertEquals("001", result.getEmployeeNumber());
}
@Test
public void whenUpdateQueryIsCalledWithCreateNamedQuery_ThenOk() {
Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDepartment");
spQuery.setParameter("employeeNo", "001");
Department newDepartment = session.find(Department.class, purchaseDeptId);
spQuery.setParameter("newDepartment", newDepartment);
spQuery.executeUpdate();
transaction.commit();
}
@Test
public void whenNamedStoredProcedureIsCalledWithCreateNamedQuery_ThenOk() {
Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDesignation");
spQuery.setParameter("employeeNumber", "002");
spQuery.setParameter("newDesignation", "Supervisor");
spQuery.executeUpdate();
transaction.commit();
}
}

View File

@ -0,0 +1,111 @@
package com.baeldung.hibernate.persistjson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PersistJSONUnitTest {
private Session session;
@Before
public void init() {
try {
Configuration configuration = new Configuration();
Properties properties = new Properties();
properties.load(Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("hibernate-persistjson.properties"));
configuration.setProperties(properties);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
.build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(Customer.class);
SessionFactory factory = metadataSources.buildMetadata()
.buildSessionFactory();
session = factory.openSession();
} catch (HibernateException | IOException e) {
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
}
}
@After
public void close() {
if (session != null)
session.close();
}
@Test
public void givenCustomer_whenCallingSerializeCustomerAttributes_thenAttributesAreConverted() throws IOException {
Customer customer = new Customer();
customer.setFirstName("first name");
customer.setLastName("last name");
Map<String, Object> attributes = new HashMap<>();
attributes.put("address", "123 Main Street");
attributes.put("zipcode", 12345);
customer.setCustomerAttributes(attributes);
customer.serializeCustomerAttributes();
String serialized = customer.getCustomerAttributeJSON();
customer.setCustomerAttributeJSON(serialized);
customer.deserializeCustomerAttributes();
Map<String, Object> deserialized = customer.getCustomerAttributes();
assertEquals("123 Main Street", deserialized.get("address"));
}
@Test
public void givenCustomer_whenSaving_thenAttributesAreConverted() {
Customer customer = new Customer();
customer.setFirstName("first name");
customer.setLastName("last name");
Map<String, Object> attributes = new HashMap<>();
attributes.put("address", "123 Main Street");
attributes.put("zipcode", 12345);
customer.setCustomerAttributes(attributes);
session.beginTransaction();
int id = (int) session.save(customer);
session.flush();
session.clear();
Customer result = session.createNativeQuery("select * from Customers where Customers.id = :id", Customer.class)
.setParameter("id", id)
.getSingleResult();
assertEquals(2, result.getCustomerAttributes()
.size());
}
}

View File

@ -0,0 +1,9 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/main/resources/init_database.sql'
hibernate.connection.username=sa
hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop

View File

@ -0,0 +1,7 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop

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