Merge remote-tracking branch 'upstream/master' into BAEL-2440
This commit is contained in:
commit
b897ed9b07
|
@ -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()
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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"));
|
||||
}
|
||||
|
||||
}
|
|
@ -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>
|
||||
|
|
|
@ -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 |
|
@ -1,3 +0,0 @@
|
|||
=========
|
||||
|
||||
## Core Java Net
|
|
@ -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)
|
|
@ -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>
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
version=1.0
|
||||
name=TestApp
|
||||
date=2016-11-12
|
|
@ -0,0 +1,3 @@
|
|||
c1=files
|
||||
c2=images
|
||||
c3=videos
|
|
@ -0,0 +1,4 @@
|
|||
site=www.google.com
|
||||
name=DefaultAppName
|
||||
topic=Properties
|
||||
category=core-java
|
|
@ -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>
|
|
@ -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()
|
Binary file not shown.
Binary file not shown.
|
@ -1 +0,0 @@
|
|||
## Relevant articles:
|
Binary file not shown.
Binary file not shown.
|
@ -1,75 +0,0 @@
|
|||
package com.baeldung.hibernate.entities;
|
||||
|
||||
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
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private long id;
|
||||
|
||||
private String employeeNumber;
|
||||
|
||||
private String designation;
|
||||
|
||||
private String name;
|
||||
|
||||
@ManyToOne
|
||||
private Department department;
|
||||
|
||||
public DeptEmployee(String name, String employeeNumber, Department department) {
|
||||
this.name = name;
|
||||
this.employeeNumber = employeeNumber;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmployeeNumber() {
|
||||
return employeeNumber;
|
||||
}
|
||||
|
||||
public void setEmployeeNumber(String employeeNumber) {
|
||||
this.employeeNumber = employeeNumber;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Department getDepartment() {
|
||||
return department;
|
||||
}
|
||||
|
||||
public void setDepartment(Department department) {
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
public String getDesignation() {
|
||||
return designation;
|
||||
}
|
||||
|
||||
public void setDesignation(String designation) {
|
||||
this.designation = designation;
|
||||
}
|
||||
}
|
|
@ -1,10 +0,0 @@
|
|||
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 designation) throws SQLException {
|
||||
CallableStatement updateStatement = conn.prepareCall("update deptemployee set designation = '" + designation + "' where employeeNumber = '" + employeeNumber + "'");
|
||||
updateStatement.execute();
|
||||
}
|
||||
$$;
|
|
@ -1,103 +0,0 @@
|
|||
package com.baeldung.hibernate;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.hibernate.query.NativeQuery;
|
||||
import org.hibernate.query.Query;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.entities.Department;
|
||||
import com.baeldung.hibernate.entities.DeptEmployee;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,228 @@
|
|||
package com.baeldung.java.map.compare;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.collection.IsMapContaining.hasEntry;
|
||||
import static org.hamcrest.collection.IsMapContaining.hasKey;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Equivalence;
|
||||
import com.google.common.collect.MapDifference;
|
||||
import com.google.common.collect.MapDifference.ValueDifference;
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
public class HashMapComparisonUnitTest {
|
||||
|
||||
Map<String, String> asiaCapital1;
|
||||
Map<String, String> asiaCapital2;
|
||||
Map<String, String> asiaCapital3;
|
||||
|
||||
Map<String, String[]> asiaCity1;
|
||||
Map<String, String[]> asiaCity2;
|
||||
Map<String, String[]> asiaCity3;
|
||||
|
||||
@Before
|
||||
public void setup(){
|
||||
asiaCapital1 = new HashMap<String, String>();
|
||||
asiaCapital1.put("Japan", "Tokyo");
|
||||
asiaCapital1.put("South Korea", "Seoul");
|
||||
|
||||
asiaCapital2 = new HashMap<String, String>();
|
||||
asiaCapital2.put("South Korea", "Seoul");
|
||||
asiaCapital2.put("Japan", "Tokyo");
|
||||
|
||||
asiaCapital3 = new HashMap<String, String>();
|
||||
asiaCapital3.put("Japan", "Tokyo");
|
||||
asiaCapital3.put("China", "Beijing");
|
||||
|
||||
asiaCity1 = new HashMap<String, String[]>();
|
||||
asiaCity1.put("Japan", new String[] { "Tokyo", "Osaka" });
|
||||
asiaCity1.put("South Korea", new String[] { "Seoul", "Busan" });
|
||||
|
||||
asiaCity2 = new HashMap<String, String[]>();
|
||||
asiaCity2.put("South Korea", new String[] { "Seoul", "Busan" });
|
||||
asiaCity2.put("Japan", new String[] { "Tokyo", "Osaka" });
|
||||
|
||||
asiaCity3 = new HashMap<String, String[]>();
|
||||
asiaCity3.put("Japan", new String[] { "Tokyo", "Osaka" });
|
||||
asiaCity3.put("China", new String[] { "Beijing", "Hong Kong" });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompareTwoHashMapsUsingEquals_thenSuccess() {
|
||||
assertTrue(asiaCapital1.equals(asiaCapital2));
|
||||
assertFalse(asiaCapital1.equals(asiaCapital3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompareTwoHashMapsWithArrayValuesUsingEquals_thenFail() {
|
||||
assertFalse(asiaCity1.equals(asiaCity2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompareTwoHashMapsUsingStreamAPI_thenSuccess() {
|
||||
assertTrue(areEqual(asiaCapital1, asiaCapital2));
|
||||
assertFalse(areEqual(asiaCapital1, asiaCapital3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompareTwoHashMapsWithArrayValuesUsingStreamAPI_thenSuccess() {
|
||||
assertTrue(areEqualWithArrayValue(asiaCity1, asiaCity2));
|
||||
assertFalse(areEqualWithArrayValue(asiaCity1, asiaCity3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompareTwoHashMapKeys_thenSuccess() {
|
||||
assertTrue(asiaCapital1.keySet().equals(asiaCapital2.keySet()));
|
||||
assertFalse(asiaCapital1.keySet().equals(asiaCapital3.keySet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompareTwoHashMapKeyValuesUsingStreamAPI_thenSuccess() {
|
||||
Map<String, String> asiaCapital3 = new HashMap<String, String>();
|
||||
asiaCapital3.put("Japan", "Tokyo");
|
||||
asiaCapital3.put("South Korea", "Seoul");
|
||||
asiaCapital3.put("China", "Beijing");
|
||||
|
||||
Map<String, String> asiaCapital4 = new HashMap<String, String>();
|
||||
asiaCapital4.put("South Korea", "Seoul");
|
||||
asiaCapital4.put("Japan", "Osaka");
|
||||
asiaCapital4.put("China", "Beijing");
|
||||
|
||||
Map<String, Boolean> result = areEqualKeyValues(asiaCapital3, asiaCapital4);
|
||||
|
||||
assertEquals(3, result.size());
|
||||
assertThat(result, hasEntry("Japan", false));
|
||||
assertThat(result, hasEntry("South Korea", true));
|
||||
assertThat(result, hasEntry("China", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDifferentMaps_whenGetDiffUsingGuava_thenSuccess() {
|
||||
Map<String, String> asia1 = new HashMap<String, String>();
|
||||
asia1.put("Japan", "Tokyo");
|
||||
asia1.put("South Korea", "Seoul");
|
||||
asia1.put("India", "New Delhi");
|
||||
|
||||
Map<String, String> asia2 = new HashMap<String, String>();
|
||||
asia2.put("Japan", "Tokyo");
|
||||
asia2.put("China", "Beijing");
|
||||
asia2.put("India", "Delhi");
|
||||
|
||||
MapDifference<String, String> diff = Maps.difference(asia1, asia2);
|
||||
Map<String, ValueDifference<String>> entriesDiffering = diff.entriesDiffering();
|
||||
|
||||
assertFalse(diff.areEqual());
|
||||
assertEquals(1, entriesDiffering.size());
|
||||
assertThat(entriesDiffering, hasKey("India"));
|
||||
assertEquals("New Delhi", entriesDiffering.get("India").leftValue());
|
||||
assertEquals("Delhi", entriesDiffering.get("India").rightValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDifferentMaps_whenGetEntriesOnOneSideUsingGuava_thenSuccess() {
|
||||
Map<String, String> asia1 = new HashMap<String, String>();
|
||||
asia1.put("Japan", "Tokyo");
|
||||
asia1.put("South Korea", "Seoul");
|
||||
asia1.put("India", "New Delhi");
|
||||
|
||||
Map<String, String> asia2 = new HashMap<String, String>();
|
||||
asia2.put("Japan", "Tokyo");
|
||||
asia2.put("China", "Beijing");
|
||||
asia2.put("India", "Delhi");
|
||||
|
||||
MapDifference<String, String> diff = Maps.difference(asia1, asia2);
|
||||
Map<String, String> entriesOnlyOnRight = diff.entriesOnlyOnRight();
|
||||
Map<String, String> entriesOnlyOnLeft = diff.entriesOnlyOnLeft();
|
||||
|
||||
assertEquals(1, entriesOnlyOnRight.size());
|
||||
assertThat(entriesOnlyOnRight, hasEntry("China", "Beijing"));
|
||||
assertEquals(1, entriesOnlyOnLeft.size());
|
||||
assertThat(entriesOnlyOnLeft, hasEntry("South Korea", "Seoul"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDifferentMaps_whenGetCommonEntriesUsingGuava_thenSuccess() {
|
||||
Map<String, String> asia1 = new HashMap<String, String>();
|
||||
asia1.put("Japan", "Tokyo");
|
||||
asia1.put("South Korea", "Seoul");
|
||||
asia1.put("India", "New Delhi");
|
||||
|
||||
Map<String, String> asia2 = new HashMap<String, String>();
|
||||
asia2.put("Japan", "Tokyo");
|
||||
asia2.put("China", "Beijing");
|
||||
asia2.put("India", "Delhi");
|
||||
|
||||
MapDifference<String, String> diff = Maps.difference(asia1, asia2);
|
||||
Map<String, String> entriesInCommon = diff.entriesInCommon();
|
||||
|
||||
assertEquals(1, entriesInCommon.size());
|
||||
assertThat(entriesInCommon, hasEntry("Japan", "Tokyo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSimilarMapsWithArrayValue_whenCompareUsingGuava_thenFail() {
|
||||
MapDifference<String, String[]> diff = Maps.difference(asiaCity1, asiaCity2);
|
||||
assertFalse(diff.areEqual());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSimilarMapsWithArrayValue_whenCompareUsingGuavaEquivalence_thenSuccess() {
|
||||
Equivalence<String[]> eq = new Equivalence<String[]>() {
|
||||
@Override
|
||||
protected boolean doEquivalent(String[] a, String[] b) {
|
||||
return Arrays.equals(a, b);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int doHash(String[] value) {
|
||||
return value.hashCode();
|
||||
}
|
||||
};
|
||||
|
||||
MapDifference<String, String[]> diff = Maps.difference(asiaCity1, asiaCity2, eq);
|
||||
assertTrue(diff.areEqual());
|
||||
|
||||
diff = Maps.difference(asiaCity1, asiaCity3, eq);
|
||||
assertFalse(diff.areEqual());
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
|
||||
private boolean areEqual(Map<String, String> first, Map<String, String> second) {
|
||||
if (first.size() != second.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return first.entrySet()
|
||||
.stream()
|
||||
.allMatch(e -> e.getValue()
|
||||
.equals(second.get(e.getKey())));
|
||||
}
|
||||
|
||||
private boolean areEqualWithArrayValue(Map<String, String[]> first, Map<String, String[]> second) {
|
||||
if (first.size() != second.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return first.entrySet()
|
||||
.stream()
|
||||
.allMatch(e -> Arrays.equals(e.getValue(), second.get(e.getKey())));
|
||||
}
|
||||
|
||||
private Map<String, Boolean> areEqualKeyValues(Map<String, String> first, Map<String, String> second) {
|
||||
return first.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().equals(second.get(e.getKey()))));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>java-streams</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
|
@ -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>
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
10
json/pom.xml
10
json/pom.xml
|
@ -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>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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>
|
||||
|
@ -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>
|
||||
|
|
|
@ -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);
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -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>
|
||||
|
|
|
@ -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;
|
||||
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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
|
||||
|
|
@ -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>
|
||||
|
||||
|
|
@ -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>
|
||||
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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>
|
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,9 +1,7 @@
|
|||
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.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
|
||||
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
|
|
@ -1,13 +1,12 @@
|
|||
package com.baeldung.jpa.stringcast;
|
||||
|
||||
import com.sun.istack.internal.Nullable;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.Query;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.Query;
|
||||
|
||||
public class QueryExecutor {
|
||||
|
||||
public static List<String[]> executeNativeQueryNoCastCheck(String statement, EntityManager em) {
|
||||
|
@ -24,10 +23,7 @@ public class QueryExecutor {
|
|||
}
|
||||
|
||||
if (results.get(0) instanceof String) {
|
||||
return ((List<String>) results)
|
||||
.stream()
|
||||
.map(s -> new String[] { s })
|
||||
.collect(Collectors.toList());
|
||||
return ((List<String>) results).stream().map(s -> new String[] { s }).collect(Collectors.toList());
|
||||
} else {
|
||||
return (List<String[]>) results;
|
||||
}
|
||||
|
|
|
@ -1,13 +1,14 @@
|
|||
package com.baeldung.config;
|
||||
|
||||
import com.baeldung.services.IBarService;
|
||||
import com.baeldung.services.impl.BarSpringDataJpaService;
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl;
|
||||
import com.baeldung.services.IFooService;
|
||||
import com.baeldung.services.impl.FooService;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
|
@ -20,13 +21,15 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
|||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl;
|
||||
import com.baeldung.services.IBarService;
|
||||
import com.baeldung.services.impl.BarSpringDataJpaService;
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan({"com.baeldung.dao", "com.baeldung.services"})
|
||||
@ComponentScan({ "com.baeldung.dao", "com.baeldung.services" })
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(basePackages = {"com.baeldung.dao"}, repositoryBaseClass = ExtendedRepositoryImpl.class)
|
||||
@EnableJpaRepositories(basePackages = { "com.baeldung.dao" }, repositoryBaseClass = ExtendedRepositoryImpl.class)
|
||||
@EnableJpaAuditing
|
||||
@PropertySource("classpath:persistence.properties")
|
||||
public class PersistenceConfiguration {
|
||||
|
@ -79,11 +82,6 @@ public class PersistenceConfiguration {
|
|||
return new BarSpringDataJpaService();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IFooService fooService() {
|
||||
return new FooService();
|
||||
}
|
||||
|
||||
private final Properties hibernateProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
|
@ -94,7 +92,8 @@ public class PersistenceConfiguration {
|
|||
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
|
||||
|
||||
// Envers properties
|
||||
hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
|
||||
hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix",
|
||||
env.getProperty("envers.audit_table_suffix"));
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
|
|
@ -13,3 +13,5 @@ hibernate.cache.use_query_cache=true
|
|||
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
|
||||
|
||||
spring.datasource.data=import_entities.sql
|
||||
|
||||
spring.main.allow-bean-definition-overriding=true
|
|
@ -2,17 +2,12 @@ package org.baeldung;
|
|||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.config.PersistenceConfiguration;
|
||||
import com.baeldung.config.PersistenceProductConfiguration;
|
||||
import com.baeldung.config.PersistenceUserConfiguration;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class})
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class SpringContextIntegrationTest {
|
||||
|
||||
|
|
|
@ -0,0 +1,25 @@
|
|||
package org.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.config.PersistenceConfiguration;
|
||||
import com.baeldung.config.PersistenceProductConfiguration;
|
||||
import com.baeldung.config.PersistenceUserConfiguration;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(excludeAutoConfiguration = {
|
||||
PersistenceConfiguration.class,
|
||||
PersistenceUserConfiguration.class,
|
||||
PersistenceProductConfiguration.class })
|
||||
@ContextConfiguration(classes = Application.class)
|
||||
public class SpringJpaContextIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
|
@ -47,21 +47,9 @@
|
|||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
@ -97,8 +85,6 @@
|
|||
<nosqlunit.version>0.10.0</nosqlunit.version>
|
||||
<spring-data-commons.version>2.0.3.RELEASE</spring-data-commons.version>
|
||||
<embedded-redis.version>0.6</embedded-redis.version>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<junit.jupiter.version>5.0.2</junit.jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -5,6 +5,7 @@
|
|||
|
||||
### Relevant ArticleS:
|
||||
- [Hibernate 3 with Spring](http://www.baeldung.com/hibernate3-spring)
|
||||
- [HibernateException: No Hibernate Session Bound to Thread in Hibernate 3](http://www.baeldung.com/no-hibernate-session-bound-to-thread-exception)
|
||||
|
||||
|
||||
### Quick Start
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
package org.baeldung.persistence.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.persistence.model.Event;
|
||||
import org.baeldung.spring.PersistenceConfigHibernate3;
|
||||
import org.hamcrest.core.IsInstanceOf;
|
|
@ -1,7 +1,5 @@
|
|||
package org.baeldung.persistence.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.persistence.model.Event;
|
||||
import org.baeldung.spring.PersistenceConfig;
|
||||
import org.hamcrest.core.IsInstanceOf;
|
|
@ -1,2 +0,0 @@
|
|||
## Relevant articles:
|
||||
- [HibernateException: No Hibernate Session Bound to Thread in Hibernate 3](http://www.baeldung.com/no-hibernate-session-bound-to-thread-exception)
|
|
@ -1 +0,0 @@
|
|||
## Relevant articles:
|
|
@ -1,3 +0,0 @@
|
|||
grant {
|
||||
permission java.security.AllPermission;
|
||||
};
|
|
@ -1,3 +0,0 @@
|
|||
grant {
|
||||
permission java.security.AllPermission;
|
||||
};
|
|
@ -1,20 +0,0 @@
|
|||
package org.baeldung;
|
||||
|
||||
import java.rmi.NotBoundException;
|
||||
import java.rmi.RemoteException;
|
||||
import java.rmi.registry.LocateRegistry;
|
||||
import java.rmi.registry.Registry;
|
||||
|
||||
public class Client {
|
||||
public static void main(String[] args) throws RemoteException, NotBoundException {
|
||||
System.setProperty("java.security.policy", "file:./client.policy");
|
||||
if (System.getSecurityManager() == null) {
|
||||
System.setSecurityManager(new SecurityManager());
|
||||
}
|
||||
String name = "RandomNumberGenerator";
|
||||
Registry registry = LocateRegistry.getRegistry();
|
||||
RandomNumberGenerator randomNumberGenerator = (RandomNumberGenerator) registry.lookup(name);
|
||||
int number = randomNumberGenerator.get();
|
||||
System.out.println("Received random number:" + number);
|
||||
}
|
||||
}
|
|
@ -1,8 +0,0 @@
|
|||
package org.baeldung;
|
||||
|
||||
import java.rmi.Remote;
|
||||
import java.rmi.RemoteException;
|
||||
|
||||
public interface RandomNumberGenerator extends Remote{
|
||||
int get() throws RemoteException;
|
||||
}
|
|
@ -1,10 +0,0 @@
|
|||
package org.baeldung;
|
||||
|
||||
import java.rmi.RemoteException;
|
||||
|
||||
public class RandomNumberGeneratorEngine implements RandomNumberGenerator {
|
||||
@Override
|
||||
public int get() throws RemoteException {
|
||||
return (int) (100 * Math.random());
|
||||
}
|
||||
}
|
|
@ -1,22 +0,0 @@
|
|||
package org.baeldung;
|
||||
|
||||
import java.rmi.RemoteException;
|
||||
import java.rmi.registry.LocateRegistry;
|
||||
import java.rmi.registry.Registry;
|
||||
import java.rmi.server.UnicastRemoteObject;
|
||||
|
||||
public class Server {
|
||||
public static void main(String[] args) throws RemoteException {
|
||||
System.setProperty("java.security.policy", "file:./server.policy");
|
||||
if (System.getSecurityManager() == null) {
|
||||
System.setSecurityManager(new SecurityManager());
|
||||
}
|
||||
String name = "RandomNumberGenerator";
|
||||
RandomNumberGenerator randomNumberGenerator = new RandomNumberGeneratorEngine();
|
||||
RandomNumberGenerator stub =
|
||||
(RandomNumberGenerator) UnicastRemoteObject.exportObject(randomNumberGenerator, 0);
|
||||
Registry registry = LocateRegistry.getRegistry();
|
||||
registry.rebind(name, stub);
|
||||
System.out.println("RandomNumberGenerator bound");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>rsocket</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>rsocket</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.rsocket</groupId>
|
||||
<artifactId>rsocket-core</artifactId>
|
||||
<version>0.11.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.rsocket</groupId>
|
||||
<artifactId>rsocket-transport-netty</artifactId>
|
||||
<version>0.11.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>1.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>1.2.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-core</artifactId>
|
||||
<version>1.2.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.25</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.rsocket;
|
||||
|
||||
import static com.baeldung.rsocket.support.Constants.*;
|
||||
import com.baeldung.rsocket.support.GameController;
|
||||
import io.rsocket.RSocket;
|
||||
import io.rsocket.RSocketFactory;
|
||||
import io.rsocket.transport.netty.client.TcpClientTransport;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class ChannelClient {
|
||||
|
||||
private final RSocket socket;
|
||||
private final GameController gameController;
|
||||
|
||||
public ChannelClient() {
|
||||
this.socket = RSocketFactory.connect()
|
||||
.transport(TcpClientTransport.create("localhost", TCP_PORT))
|
||||
.start()
|
||||
.block();
|
||||
|
||||
this.gameController = new GameController("Client Player");
|
||||
}
|
||||
|
||||
public void playGame() {
|
||||
socket.requestChannel(Flux.from(gameController))
|
||||
.doOnNext(gameController::processPayload)
|
||||
.blockLast();
|
||||
}
|
||||
|
||||
public void dispose() {
|
||||
this.socket.dispose();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,85 @@
|
|||
package com.baeldung.rsocket;
|
||||
|
||||
import static com.baeldung.rsocket.support.Constants.*;
|
||||
import io.rsocket.Payload;
|
||||
import io.rsocket.RSocket;
|
||||
import io.rsocket.RSocketFactory;
|
||||
import io.rsocket.transport.netty.client.TcpClientTransport;
|
||||
import io.rsocket.util.DefaultPayload;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class FireNForgetClient {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(FireNForgetClient.class);
|
||||
|
||||
private final RSocket socket;
|
||||
private final List<Float> data;
|
||||
|
||||
public FireNForgetClient() {
|
||||
this.socket = RSocketFactory.connect()
|
||||
.transport(TcpClientTransport.create("localhost", TCP_PORT))
|
||||
.start()
|
||||
.block();
|
||||
this.data = Collections.unmodifiableList(generateData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Send binary velocity (float) every 50ms
|
||||
*/
|
||||
public void sendData() {
|
||||
Flux.interval(Duration.ofMillis(50))
|
||||
.take(data.size())
|
||||
.map(this::createFloatPayload)
|
||||
.flatMap(socket::fireAndForget)
|
||||
.blockLast();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a binary payload containing a single float value
|
||||
*
|
||||
* @param index Index into the data list
|
||||
* @return Payload ready to send to the server
|
||||
*/
|
||||
private Payload createFloatPayload(Long index) {
|
||||
float velocity = data.get(index.intValue());
|
||||
ByteBuffer buffer = ByteBuffer.allocate(4).putFloat(velocity);
|
||||
buffer.rewind();
|
||||
return DefaultPayload.create(buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate sample data
|
||||
*
|
||||
* @return List of random floats
|
||||
*/
|
||||
private List<Float> generateData() {
|
||||
List<Float> dataList = new ArrayList<>(WIND_DATA_LENGTH);
|
||||
float velocity = 0;
|
||||
for (int i = 0; i < WIND_DATA_LENGTH; i++) {
|
||||
velocity += Math.random();
|
||||
dataList.add(velocity);
|
||||
}
|
||||
return dataList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the data used for this client.
|
||||
*
|
||||
* @return list of data values
|
||||
*/
|
||||
public List<Float> getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void dispose() {
|
||||
this.socket.dispose();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.rsocket;
|
||||
|
||||
import static com.baeldung.rsocket.support.Constants.*;
|
||||
import io.rsocket.Payload;
|
||||
import io.rsocket.RSocket;
|
||||
import io.rsocket.RSocketFactory;
|
||||
import io.rsocket.transport.netty.client.TcpClientTransport;
|
||||
import io.rsocket.util.DefaultPayload;
|
||||
|
||||
public class ReqResClient {
|
||||
|
||||
private final RSocket socket;
|
||||
|
||||
public ReqResClient() {
|
||||
this.socket = RSocketFactory.connect()
|
||||
.transport(TcpClientTransport.create("localhost", TCP_PORT))
|
||||
.start()
|
||||
.block();
|
||||
}
|
||||
|
||||
public String callBlocking(String string) {
|
||||
return socket
|
||||
.requestResponse(DefaultPayload.create(string))
|
||||
.map(Payload::getDataUtf8)
|
||||
.onErrorReturn(ERROR_MSG)
|
||||
.block();
|
||||
}
|
||||
|
||||
public void dispose() {
|
||||
this.socket.dispose();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.rsocket;
|
||||
|
||||
import static com.baeldung.rsocket.support.Constants.*;
|
||||
import io.rsocket.Payload;
|
||||
import io.rsocket.RSocket;
|
||||
import io.rsocket.RSocketFactory;
|
||||
import io.rsocket.transport.netty.client.TcpClientTransport;
|
||||
import io.rsocket.util.DefaultPayload;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class ReqStreamClient {
|
||||
|
||||
private final RSocket socket;
|
||||
|
||||
public ReqStreamClient() {
|
||||
this.socket = RSocketFactory.connect()
|
||||
.transport(TcpClientTransport.create("localhost", TCP_PORT))
|
||||
.start()
|
||||
.block();
|
||||
}
|
||||
|
||||
public Flux<Float> getDataStream() {
|
||||
return socket
|
||||
.requestStream(DefaultPayload.create(WIND_DATA_STREAM_NAME))
|
||||
.map(Payload::getData)
|
||||
.map(buf -> buf.getFloat())
|
||||
.onErrorReturn(null);
|
||||
}
|
||||
|
||||
public void dispose() {
|
||||
this.socket.dispose();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,107 @@
|
|||
package com.baeldung.rsocket;
|
||||
|
||||
import com.baeldung.rsocket.support.WindDataPublisher;
|
||||
import static com.baeldung.rsocket.support.Constants.*;
|
||||
import com.baeldung.rsocket.support.GameController;
|
||||
import io.rsocket.AbstractRSocket;
|
||||
import io.rsocket.Payload;
|
||||
import io.rsocket.RSocketFactory;
|
||||
import io.rsocket.transport.netty.server.TcpServerTransport;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.Disposable;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class Server {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(Server.class);
|
||||
|
||||
private final Disposable server;
|
||||
private final WindDataPublisher windDataPublisher = new WindDataPublisher();
|
||||
private final GameController gameController;
|
||||
|
||||
public Server() {
|
||||
this.server = RSocketFactory.receive()
|
||||
.acceptor((setupPayload, reactiveSocket) -> Mono.just(new RSocketImpl()))
|
||||
.transport(TcpServerTransport.create("localhost", TCP_PORT))
|
||||
.start()
|
||||
.doOnNext(x -> LOG.info("Server started"))
|
||||
.subscribe();
|
||||
|
||||
this.gameController = new GameController("Server Player");
|
||||
}
|
||||
|
||||
public void dispose() {
|
||||
windDataPublisher.complete();
|
||||
this.server.dispose();
|
||||
}
|
||||
|
||||
/**
|
||||
* RSocket implementation
|
||||
*/
|
||||
private class RSocketImpl extends AbstractRSocket {
|
||||
|
||||
/**
|
||||
* Handle Request/Response messages
|
||||
*
|
||||
* @param payload Message payload
|
||||
* @return payload response
|
||||
*/
|
||||
@Override
|
||||
public Mono<Payload> requestResponse(Payload payload) {
|
||||
try {
|
||||
return Mono.just(payload); // reflect the payload back to the sender
|
||||
} catch (Exception x) {
|
||||
return Mono.error(x);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle Fire-and-Forget messages
|
||||
*
|
||||
* @param payload Message payload
|
||||
* @return nothing
|
||||
*/
|
||||
@Override
|
||||
public Mono<Void> fireAndForget(Payload payload) {
|
||||
try {
|
||||
windDataPublisher.publish(payload); // forward the payload
|
||||
return Mono.empty();
|
||||
} catch (Exception x) {
|
||||
return Mono.error(x);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle Request/Stream messages. Each request returns a new stream.
|
||||
*
|
||||
* @param payload Payload that can be used to determine which stream to return
|
||||
* @return Flux stream containing simulated wind speed data
|
||||
*/
|
||||
@Override
|
||||
public Flux<Payload> requestStream(Payload payload) {
|
||||
String streamName = payload.getDataUtf8();
|
||||
if (WIND_DATA_STREAM_NAME.equals(streamName)) {
|
||||
return Flux.from(windDataPublisher);
|
||||
}
|
||||
return Flux.error(new IllegalArgumentException(streamName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle request for bidirectional channel
|
||||
*
|
||||
* @param payloads Stream of payloads delivered from the client
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public Flux<Payload> requestChannel(Publisher<Payload> payloads) {
|
||||
Flux.from(payloads)
|
||||
.subscribe(gameController::processPayload);
|
||||
Flux<Payload> channel = Flux.from(gameController);
|
||||
return channel;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.rsocket.support;
|
||||
|
||||
public interface Constants {
|
||||
|
||||
int TCP_PORT = 7101;
|
||||
String ERROR_MSG = "error";
|
||||
int WIND_DATA_LENGTH = 30;
|
||||
String WIND_DATA_STREAM_NAME = "wind-data";
|
||||
int SHOT_COUNT = 10;
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
package com.baeldung.rsocket.support;
|
||||
|
||||
import static com.baeldung.rsocket.support.Constants.*;
|
||||
import io.rsocket.Payload;
|
||||
import io.rsocket.util.DefaultPayload;
|
||||
import java.util.List;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.reactivestreams.Subscriber;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class GameController implements Publisher<Payload> {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(GameController.class);
|
||||
|
||||
private final String playerName;
|
||||
private final List<Long> shots;
|
||||
private Subscriber<? super Payload> subscriber;
|
||||
private boolean truce = false;
|
||||
|
||||
public GameController(String playerName) {
|
||||
this.playerName = playerName;
|
||||
this.shots = generateShotList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a random list of time intervals, 0-1000ms
|
||||
*
|
||||
* @return List of time intervals
|
||||
*/
|
||||
private List<Long> generateShotList() {
|
||||
return Flux.range(1, SHOT_COUNT)
|
||||
.map(x -> (long) Math.ceil(Math.random() * 1000))
|
||||
.collectList()
|
||||
.block();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(Subscriber<? super Payload> subscriber) {
|
||||
this.subscriber = subscriber;
|
||||
fireAtWill();
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish game events asynchronously
|
||||
*/
|
||||
private void fireAtWill() {
|
||||
new Thread(() -> {
|
||||
for (Long shotDelay : shots) {
|
||||
try { Thread.sleep(shotDelay); } catch (Exception x) {}
|
||||
if (truce) {
|
||||
break;
|
||||
}
|
||||
LOG.info("{}: bang!", playerName);
|
||||
subscriber.onNext(DefaultPayload.create("bang!"));
|
||||
}
|
||||
if (!truce) {
|
||||
LOG.info("{}: I give up!", playerName);
|
||||
subscriber.onNext(DefaultPayload.create("I give up"));
|
||||
}
|
||||
subscriber.onComplete();
|
||||
}).start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Process events from the opponent
|
||||
*
|
||||
* @param payload Payload received from the rSocket
|
||||
*/
|
||||
public void processPayload(Payload payload) {
|
||||
String message = payload.getDataUtf8();
|
||||
switch (message) {
|
||||
case "bang!":
|
||||
String result = Math.random() < 0.5 ? "Haha missed!" : "Ow!";
|
||||
LOG.info("{}: {}", playerName, result);
|
||||
break;
|
||||
case "I give up":
|
||||
truce = true;
|
||||
LOG.info("{}: OK, truce", playerName);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.rsocket.support;
|
||||
|
||||
import io.rsocket.Payload;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.reactivestreams.Subscriber;
|
||||
|
||||
/**
|
||||
* Simple PUblisher to provide async data to Flux stream
|
||||
*/
|
||||
public class WindDataPublisher implements Publisher<Payload> {
|
||||
|
||||
private Subscriber<? super Payload> subscriber;
|
||||
|
||||
@Override
|
||||
public void subscribe(Subscriber<? super Payload> subscriber) {
|
||||
this.subscriber = subscriber;
|
||||
}
|
||||
|
||||
public void publish(Payload payload) {
|
||||
if (subscriber != null) {
|
||||
subscriber.onNext(payload);
|
||||
}
|
||||
}
|
||||
|
||||
public void complete() {
|
||||
if (subscriber != null) {
|
||||
subscriber.onComplete();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
package com.baeldung.rsocket;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.Disposable;
|
||||
|
||||
public class RSocketIntegrationTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(RSocketIntegrationTest.class);
|
||||
|
||||
private static Server server;
|
||||
|
||||
public RSocketIntegrationTest() {
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpClass() {
|
||||
server = new Server();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownClass() {
|
||||
server.dispose();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendingAString_thenRevceiveTheSameString() {
|
||||
ReqResClient client = new ReqResClient();
|
||||
String string = "Hello RSocket";
|
||||
|
||||
assertEquals(string, client.callBlocking(string));
|
||||
|
||||
client.dispose();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendingStream_thenReceiveTheSameStream() {
|
||||
// create the client that pushes data to the server and start sending
|
||||
FireNForgetClient fnfClient = new FireNForgetClient();
|
||||
// create a client to read a stream from the server and subscribe to events
|
||||
ReqStreamClient streamClient = new ReqStreamClient();
|
||||
|
||||
// get the data that is used by the client
|
||||
List<Float> data = fnfClient.getData();
|
||||
// create a place to count the results
|
||||
List<Float> dataReceived = new ArrayList<>();
|
||||
|
||||
// assert that the data received is the same as the data sent
|
||||
Disposable subscription = streamClient.getDataStream()
|
||||
.index()
|
||||
.subscribe(
|
||||
tuple -> {
|
||||
assertEquals("Wrong value", data.get(tuple.getT1().intValue()), tuple.getT2());
|
||||
dataReceived.add(tuple.getT2());
|
||||
},
|
||||
err -> LOG.error(err.getMessage())
|
||||
);
|
||||
|
||||
// start sending the data
|
||||
fnfClient.sendData();
|
||||
|
||||
// wait a short time for the data to complete then dispose everything
|
||||
try { Thread.sleep(500); } catch (Exception x) {}
|
||||
subscription.dispose();
|
||||
fnfClient.dispose();
|
||||
|
||||
// verify the item count
|
||||
assertEquals("Wrong data count received", data.size(), dataReceived.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRunningChannelGame_thenLogTheResults() {
|
||||
ChannelClient client = new ChannelClient();
|
||||
client.playGame();
|
||||
client.dispose();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,45 +1,53 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>rxjava-2</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>rxjava-2</name>
|
||||
<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>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
<artifactId>rxjava-2</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.reactivex.rxjava2</groupId>
|
||||
<artifactId>rxjava</artifactId>
|
||||
<version>${rx.java2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${awaitility.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jakewharton.rxrelay2</groupId>
|
||||
<artifactId>rxrelay</artifactId>
|
||||
<version>${rxrelay.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.8.0</assertj.version>
|
||||
<rx.java2.version>2.2.2</rx.java2.version>
|
||||
<awaitility.version>1.7.0</awaitility.version>
|
||||
<rxrelay.version>2.0.0</rxrelay.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.reactivex.rxjava2</groupId>
|
||||
<artifactId>rxjava</artifactId>
|
||||
<version>${rx.java2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${awaitility.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jakewharton.rxrelay2</groupId>
|
||||
<artifactId>rxrelay</artifactId>
|
||||
<version>${rxrelay.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.github.akarnokd/rxjava2-extensions -->
|
||||
<dependency>
|
||||
<groupId>com.github.akarnokd</groupId>
|
||||
<artifactId>rxjava2-extensions</artifactId>
|
||||
<version>${rxjava2.ext.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.8.0</assertj.version>
|
||||
<rx.java2.version>2.2.2</rx.java2.version>
|
||||
<awaitility.version>1.7.0</awaitility.version>
|
||||
<rxrelay.version>2.0.0</rxrelay.version>
|
||||
<rxjava2.ext.version>0.20.4</rxjava2.ext.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,107 @@
|
|||
package com.baeldung.rxjava;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import hu.akarnokd.rxjava2.async.AsyncObservable;
|
||||
import io.reactivex.Observable;
|
||||
|
||||
public class AsyncAndSyncToObservableIntegrationTest {
|
||||
|
||||
AtomicInteger counter = new AtomicInteger();
|
||||
Callable<Integer> callable = () -> counter.incrementAndGet();
|
||||
|
||||
/* Method will execute every time it gets subscribed*/
|
||||
@Test
|
||||
public void givenSyncMethod_whenConvertedWithFromCallable_thenReturnObservable() {
|
||||
|
||||
Observable<Integer> source = Observable.fromCallable(callable);
|
||||
|
||||
for (int i = 1; i < 5; i++) {
|
||||
source.test()
|
||||
.awaitDone(5, TimeUnit.SECONDS)
|
||||
.assertResult(i);
|
||||
|
||||
assertEquals(i, counter.get());
|
||||
}
|
||||
}
|
||||
|
||||
/* Method will execute only once and cache its result.*/
|
||||
@Test
|
||||
public void givenSyncMethod_whenConvertedWithStart_thenReturnObservable() {
|
||||
|
||||
Observable<Integer> source = AsyncObservable.start(callable);
|
||||
|
||||
for (int i = 1; i < 5; i++) {
|
||||
source.test()
|
||||
.awaitDone(5, TimeUnit.SECONDS)
|
||||
.assertResult(1);
|
||||
|
||||
assertEquals(1, counter.get());
|
||||
}
|
||||
}
|
||||
|
||||
/* Method will execute only once and cache its result.*/
|
||||
@Test
|
||||
public void givenAsyncMethod_whenConvertedWithFromFuture_thenRetrunObservble() {
|
||||
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
Future<Integer> future = executor.submit(callable);
|
||||
Observable<Integer> source = Observable.fromFuture(future);
|
||||
|
||||
for (int i = 1; i < 5; i++) {
|
||||
source.test()
|
||||
.awaitDone(5, TimeUnit.SECONDS)
|
||||
.assertResult(1);
|
||||
|
||||
assertEquals(1, counter.get());
|
||||
}
|
||||
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
/* Method will execute every time it gets subscribed*/
|
||||
@Test
|
||||
public void givenAsyncMethod_whenConvertedWithStartFuture_thenRetrunObservble() {
|
||||
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
Observable<Integer> source = AsyncObservable.startFuture(() -> executor.submit(callable));
|
||||
|
||||
for (int i = 1; i < 5; i++) {
|
||||
source.test()
|
||||
.awaitDone(5, TimeUnit.SECONDS)
|
||||
.assertResult(i);
|
||||
|
||||
assertEquals(i, counter.get());
|
||||
}
|
||||
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
/*Method will execute only once and cache its result.*/
|
||||
@Test
|
||||
public void givenAsyncMethod_whenConvertedWithDeferFuture_thenRetrunObservble() {
|
||||
List<Integer> list = Arrays.asList(new Integer[] { counter.incrementAndGet(), counter.incrementAndGet(), counter.incrementAndGet() });
|
||||
ExecutorService exec = Executors.newSingleThreadExecutor();
|
||||
Callable<Observable<Integer>> callable = () -> Observable.fromIterable(list);
|
||||
Observable<Integer> source = AsyncObservable.deferFuture(() -> exec.submit(callable));
|
||||
for (int i = 1; i < 4; i++) {
|
||||
source.test()
|
||||
.awaitDone(5, TimeUnit.SECONDS)
|
||||
.assertResult(1, 2, 3);
|
||||
}
|
||||
|
||||
exec.shutdown();
|
||||
}
|
||||
|
||||
}
|
|
@ -2,8 +2,9 @@ package com.baeldung
|
|||
|
||||
import org.springframework.boot.SpringApplication
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration
|
||||
|
||||
@SpringBootApplication
|
||||
@SpringBootApplication(exclude = arrayOf(MongoReactiveDataAutoConfiguration::class))
|
||||
class Application
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
|
|
@ -4,10 +4,11 @@ import javax.servlet.Filter;
|
|||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||
import org.springframework.web.filter.DelegatingFilterProxy;
|
||||
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
||||
|
||||
@SpringBootApplication
|
||||
@SpringBootApplication( exclude = SecurityAutoConfiguration.class)
|
||||
public class Spring5Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue