Merge remote-tracking branch 'upstream/master'
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.java9;
|
||||
|
||||
public class Java9OptionalTest {
|
||||
@Test
|
||||
public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() {
|
||||
//given
|
||||
Optional<String> value = Optional.of("a");
|
||||
|
||||
//when
|
||||
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertThat(collect).hasSameElementsAs(List.of("A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() {
|
||||
//given
|
||||
Optional<String> value = Optional.empty();
|
||||
|
||||
//when
|
||||
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertThat(collect).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenPresent_thenShouldExecuteProperCallback() {
|
||||
//given
|
||||
Optional<String> value = Optional.of("properValue");
|
||||
AtomicInteger successCounter = new AtomicInteger(0);
|
||||
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
|
||||
|
||||
//when
|
||||
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
|
||||
|
||||
//then
|
||||
assertThat(successCounter.get()).isEqualTo(1);
|
||||
assertThat(onEmptyOptionalCounter.get()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() {
|
||||
//given
|
||||
Optional<String> value = Optional.empty();
|
||||
AtomicInteger successCounter = new AtomicInteger(0);
|
||||
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
|
||||
|
||||
//when
|
||||
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
|
||||
|
||||
//then
|
||||
assertThat(successCounter.get()).isEqualTo(0);
|
||||
assertThat(onEmptyOptionalCounter.get()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() {
|
||||
//given
|
||||
String expected = "properValue";
|
||||
Optional<String> value = Optional.of(expected);
|
||||
Optional<String> defaultValue = Optional.of("default");
|
||||
|
||||
//when
|
||||
Optional<String> result = value.or(() -> defaultValue);
|
||||
|
||||
//then
|
||||
assertThat(result.get()).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() {
|
||||
//given
|
||||
String defaultString = "default";
|
||||
Optional<String> value = Optional.empty();
|
||||
Optional<String> defaultValue = Optional.of(defaultString);
|
||||
|
||||
//when
|
||||
Optional<String> result = value.or(() -> defaultValue);
|
||||
|
||||
//then
|
||||
assertThat(result.get()).isEqualTo(defaultString);
|
||||
}
|
||||
}
|
||||
@@ -102,8 +102,10 @@
|
||||
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
|
||||
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
|
||||
- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
|
||||
- [Guide to UUID in JAVA] (http://www.baeldung.com/guide-to-uuid-in-java)
|
||||
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
|
||||
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
|
||||
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
|
||||
- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
|
||||
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
|
||||
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.concurrent.diningphilosophers;
|
||||
|
||||
public class DiningPhilosophers {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
Philosopher[] philosophers = new Philosopher[5];
|
||||
Object[] forks = new Object[philosophers.length];
|
||||
|
||||
for (int i = 0; i < forks.length; i++) {
|
||||
forks[i] = new Object();
|
||||
}
|
||||
|
||||
for (int i = 0; i < philosophers.length; i++) {
|
||||
|
||||
Object leftFork = forks[i];
|
||||
Object rightFork = forks[(i + 1) % forks.length];
|
||||
|
||||
if (i == philosophers.length - 1) {
|
||||
philosophers[i] = new Philosopher(rightFork, leftFork); // The last philosopher picks up the right fork first
|
||||
} else {
|
||||
philosophers[i] = new Philosopher(leftFork, rightFork);
|
||||
}
|
||||
|
||||
Thread t = new Thread(philosophers[i], "Philosopher " + (i + 1));
|
||||
t.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.concurrent.diningphilosophers;
|
||||
|
||||
public class Philosopher implements Runnable {
|
||||
|
||||
private final Object leftFork;
|
||||
private final Object rightFork;
|
||||
|
||||
public Philosopher(Object left, Object right) {
|
||||
this.leftFork = left;
|
||||
this.rightFork = right;
|
||||
}
|
||||
|
||||
private void doAction(String action) throws InterruptedException {
|
||||
System.out.println(Thread.currentThread().getName() + " " + action);
|
||||
Thread.sleep(((int) (Math.random() * 100)));
|
||||
}
|
||||
|
||||
@Override public void run() {
|
||||
try {
|
||||
while (true) {
|
||||
doAction(System.nanoTime() + ": Thinking"); // thinking
|
||||
synchronized (leftFork) {
|
||||
doAction(System.nanoTime() + ": Picked up left fork");
|
||||
synchronized (rightFork) {
|
||||
doAction(System.nanoTime() + ": Picked up right fork - eating"); // eating
|
||||
doAction(System.nanoTime() + ": Put down right fork");
|
||||
}
|
||||
doAction(System.nanoTime() + ": Put down left fork. Returning to thinking");
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.regexp;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class EscapingChars {
|
||||
public boolean isMatching(String input, String pattern) {
|
||||
return input.matches(pattern);
|
||||
}
|
||||
|
||||
public int splitAndCountWords(String input, String pattern) {
|
||||
return input.split(pattern).length;
|
||||
}
|
||||
|
||||
public int splitAndCountWordsUsingQuoteMethod(String input, String pattern) {
|
||||
return input.split(Pattern.quote(pattern)).length;
|
||||
}
|
||||
|
||||
public String changeCurrencySymbol(String input, String pattern,
|
||||
String correctStr) {
|
||||
Pattern p = Pattern.compile(pattern);
|
||||
Matcher m = p.matcher(input);
|
||||
return m.replaceAll(correctStr);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class StreamApi {
|
||||
|
||||
public String getLastElementUsingReduce(List<String> valueList) {
|
||||
Stream<String> stream = valueList.stream();
|
||||
return stream.reduce((first, second) -> second).orElse(null);
|
||||
}
|
||||
|
||||
public Integer getInfiniteStreamLastElementUsingReduce() {
|
||||
Stream<Integer> stream = Stream.iterate(0, i -> i + 1);
|
||||
return stream.limit(20).reduce((first, second) -> second).orElse(null);
|
||||
}
|
||||
|
||||
public String getLastElementUsingSkip(List<String> valueList) {
|
||||
long count = valueList.stream().count();
|
||||
Stream<String> stream = valueList.stream();
|
||||
return stream.skip(count - 1).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,23 +2,23 @@ package com.baeldung.string;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class StringHelper {
|
||||
public static String removeLastChar(String s) {
|
||||
class StringHelper {
|
||||
static String removeLastChar(String s) {
|
||||
return (s == null || s.length() == 0) ? s : (s.substring(0, s.length() - 1));
|
||||
}
|
||||
|
||||
public static String removeLastCharRegex(String s) {
|
||||
static String removeLastCharRegex(String s) {
|
||||
return (s == null) ? s : s.replaceAll(".$", "");
|
||||
}
|
||||
|
||||
public static String removeLastCharOptional(String s) {
|
||||
static String removeLastCharOptional(String s) {
|
||||
return Optional.ofNullable(s)
|
||||
.filter(str -> str.length() != 0)
|
||||
.map(str -> str.substring(0, str.length() - 1))
|
||||
.orElse(s);
|
||||
}
|
||||
|
||||
public static String removeLastCharRegexOptional(String s) {
|
||||
static String removeLastCharRegexOptional(String s) {
|
||||
return Optional.ofNullable(s)
|
||||
.map(str -> str.replaceAll(".$", ""))
|
||||
.orElse(s);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.uuid;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDGenerator {
|
||||
|
||||
/**
|
||||
* These are predefined UUID for name spaces
|
||||
*/
|
||||
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
|
||||
|
||||
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
System.out.println("Type 3 : " + generateType3UUID(NAMESPACE_DNS, "google.com"));
|
||||
System.out.println("Type 4 : " + generateType4UUID());
|
||||
System.out.println("Type 5 : " + generateType5UUID(NAMESPACE_URL, "google.com"));
|
||||
System.out.println("Unique key : " + generateUniqueKeysWithUUIDAndMessageDigest());
|
||||
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Type 4 UUID Generation
|
||||
*/
|
||||
public static UUID generateType4UUID() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type 3 UUID Generation
|
||||
*
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static UUID generateType3UUID(String namespace, String name) throws UnsupportedEncodingException {
|
||||
String source = namespace + name;
|
||||
byte[] bytes = source.getBytes("UTF-8");
|
||||
UUID uuid = UUID.nameUUIDFromBytes(bytes);
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type 5 UUID Generation
|
||||
*
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static UUID generateType5UUID(String namespace, String name) throws UnsupportedEncodingException {
|
||||
String source = namespace + name;
|
||||
byte[] bytes = source.getBytes("UTF-8");
|
||||
UUID uuid = type5UUIDFromBytes(bytes);
|
||||
return uuid;
|
||||
}
|
||||
|
||||
|
||||
public static UUID type5UUIDFromBytes(byte[] name) {
|
||||
MessageDigest md;
|
||||
try {
|
||||
md = MessageDigest.getInstance("SHA-1");
|
||||
} catch (NoSuchAlgorithmException nsae) {
|
||||
throw new InternalError("MD5 not supported", nsae);
|
||||
}
|
||||
byte[] bytes = md.digest(name);
|
||||
bytes[6] &= 0x0f; /* clear version */
|
||||
bytes[6] |= 0x50; /* set to version 5 */
|
||||
bytes[8] &= 0x3f; /* clear variant */
|
||||
bytes[8] |= 0x80; /* set to IETF variant */
|
||||
return constructType5UUID(bytes);
|
||||
}
|
||||
|
||||
private static UUID constructType5UUID(byte[] data) {
|
||||
long msb = 0;
|
||||
long lsb = 0;
|
||||
assert data.length == 16 : "data must be 16 bytes in length";
|
||||
|
||||
for (int i=0; i<8; i++)
|
||||
msb = (msb << 8) | (data[i] & 0xff);
|
||||
|
||||
for (int i=8; i<16; i++)
|
||||
lsb = (lsb << 8) | (data[i] & 0xff);
|
||||
return new UUID(msb, lsb);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Unique Keys Generation Using Message Digest and Type 4 UUID
|
||||
*
|
||||
* @throws NoSuchAlgorithmException
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static String generateUniqueKeysWithUUIDAndMessageDigest() throws NoSuchAlgorithmException, UnsupportedEncodingException {
|
||||
MessageDigest salt = MessageDigest.getInstance("SHA-256");
|
||||
salt.update(UUID.randomUUID()
|
||||
.toString()
|
||||
.getBytes("UTF-8"));
|
||||
String digest = bytesToHex(salt.digest());
|
||||
return digest;
|
||||
}
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
char[] hexChars = new char[bytes.length * 2];
|
||||
for (int j = 0; j < bytes.length; j++) {
|
||||
int v = bytes[j] & 0xFF;
|
||||
hexChars[j * 2] = hexArray[v >>> 4];
|
||||
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
|
||||
}
|
||||
return new String(hexChars);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package com.baeldung.regexp;
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -11,57 +13,59 @@ public class EscapingCharsTest {
|
||||
public void givenRegexWithDot_whenMatchingStr_thenMatches() {
|
||||
String strInput = "foof";
|
||||
String strRegex = "foo.";
|
||||
EscapingChars e = new EscapingChars();
|
||||
|
||||
assertEquals(true, e.isMatching(strInput, strRegex));
|
||||
|
||||
assertEquals(true, strInput.matches(strRegex));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDotEsc_whenMatchingStr_thenNotMatching() {
|
||||
String strInput = "foof";
|
||||
String strRegex = "foo\\.";
|
||||
EscapingChars e = new EscapingChars();
|
||||
|
||||
assertEquals(false, e.isMatching(strInput, strRegex));
|
||||
|
||||
assertEquals(false, strInput.matches(strRegex));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRegexWithPipeEscaped_whenSplitStr_thenSplits() {
|
||||
String strInput = "foo|bar|hello|world";
|
||||
String strRegex = "\\Q|\\E";
|
||||
EscapingChars e = new EscapingChars();
|
||||
|
||||
assertEquals(4, e.splitAndCountWords(strInput, strRegex));
|
||||
|
||||
assertEquals(4, strInput.split(strRegex).length);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRegexWithPipeEscQuoteMeth_whenSplitStr_thenSplits() {
|
||||
String strInput = "foo|bar|hello|world";
|
||||
String strRegex = "|";
|
||||
EscapingChars e = new EscapingChars();
|
||||
|
||||
assertEquals(4, e.splitAndCountWordsUsingQuoteMethod(strInput, strRegex));
|
||||
|
||||
assertEquals(4,strInput.split(Pattern.quote(strRegex)).length);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDollar_whenReplacing_thenNotReplace() {
|
||||
String strInput = "I gave $50 to my brother.He bought candy for $35. Now he has $15 left.";
|
||||
String strInput = "I gave $50 to my brother."
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
String strRegex = "$";
|
||||
String strReplacement = "�";
|
||||
String output = "I gave �50 to my brother.He bought candy for �35. Now he has �15 left.";
|
||||
EscapingChars e = new EscapingChars();
|
||||
|
||||
assertThat(output, not(equalTo(e.changeCurrencySymbol(strInput, strRegex, strReplacement))));
|
||||
String strReplacement = "£";
|
||||
String output = "I gave £50 to my brother."
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
Pattern p = Pattern.compile(strRegex);
|
||||
Matcher m = p.matcher(strInput);
|
||||
|
||||
assertThat(output, not(equalTo(m.replaceAll(strReplacement))));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDollarEsc_whenReplacing_thenReplace() {
|
||||
String strInput = "I gave $50 to my brother. He bought candy for $35. Now he has $15 left.";
|
||||
String strInput = "I gave $50 to my brother."
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
String strRegex = "\\$";
|
||||
String strReplacement = "�";
|
||||
String output = "I gave �50 to my brother. He bought candy for �35. Now he has �15 left.";
|
||||
EscapingChars e = new EscapingChars();
|
||||
|
||||
assertEquals(output, e.changeCurrencySymbol(strInput, strRegex, strReplacement));
|
||||
String strReplacement = "£";
|
||||
String output = "I gave £50 to my brother."
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
Pattern p = Pattern.compile(strRegex);
|
||||
Matcher m = p.matcher(strInput);
|
||||
|
||||
assertEquals(output,m.replaceAll(strReplacement));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamApiTest {
|
||||
private StreamApi streamApi = new StreamApi();
|
||||
|
||||
@Test
|
||||
public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() {
|
||||
List<String> valueList = new ArrayList<String>();
|
||||
valueList.add("Joe");
|
||||
valueList.add("John");
|
||||
valueList.add("Sean");
|
||||
|
||||
String last = streamApi.getLastElementUsingReduce(valueList);
|
||||
|
||||
assertEquals("Sean", last);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() {
|
||||
Integer last = streamApi.getInfiniteStreamLastElementUsingReduce();
|
||||
assertEquals(new Integer(19), last);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() {
|
||||
List<String> valueList = new ArrayList<String>();
|
||||
valueList.add("Joe");
|
||||
valueList.add("John");
|
||||
valueList.add("Sean");
|
||||
|
||||
String last = streamApi.getLastElementUsingSkip(valueList);
|
||||
|
||||
assertEquals("Sean", last);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -167,9 +167,11 @@ public class JavaRandomUnitTest {
|
||||
final int leftLimit = 97; // letter 'a'
|
||||
final int rightLimit = 122; // letter 'z'
|
||||
final int targetStringLength = 10;
|
||||
final Random random = new Random();
|
||||
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||
|
||||
for (int i = 0; i < targetStringLength; i++) {
|
||||
final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit + 1));
|
||||
final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
|
||||
buffer.append((char) randomLimitedInt);
|
||||
}
|
||||
final String generatedString = buffer.toString();
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<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.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>ejb-session-beans</artifactId>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<arquillian-bom.version>1.1.12.Final</arquillian-bom.version>
|
||||
<shrinkwrap-resolver-impl-maven.version>2.2.6</shrinkwrap-resolver-impl-maven.version>
|
||||
<arquillian-junit-container.version>1.1.12.Final</arquillian-junit-container.version>
|
||||
<arquillian-glassfish-embedded-3.1.version>1.0.0.Final</arquillian-glassfish-embedded-3.1.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<javaee-api.version>7.0</javaee-api.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jboss.arquillian</groupId>
|
||||
<artifactId>arquillian-bom</artifactId>
|
||||
<version>1.1.13.Final</version>
|
||||
<scope>import</scope>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>${javaee-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jboss.arquillian.junit</groupId>
|
||||
<artifactId>arquillian-junit-container</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>arquillian-glassfish-embedded</id>
|
||||
<activation>
|
||||
<activeByDefault>true</activeByDefault>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jboss.arquillian.container</groupId>
|
||||
<artifactId>arquillian-glassfish-embedded-3.1</artifactId>
|
||||
<version>1.0.0.CR4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.main.extras</groupId>
|
||||
<artifactId>glassfish-embedded-all</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.4</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.17</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.ejb.stateful;
|
||||
|
||||
import javax.ejb.EJB;
|
||||
|
||||
public class EJBClient1 {
|
||||
|
||||
@EJB
|
||||
public StatefulEJB statefulEJB;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.ejb.stateful;
|
||||
|
||||
import javax.ejb.EJB;
|
||||
|
||||
public class EJBClient2 {
|
||||
|
||||
@EJB
|
||||
public StatefulEJB statefulEJB;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.ejb.stateful;
|
||||
|
||||
import javax.ejb.Stateful;
|
||||
|
||||
@Stateful
|
||||
public class StatefulEJB {
|
||||
|
||||
public String name;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.ejb.stateless;
|
||||
|
||||
import javax.ejb.EJB;
|
||||
|
||||
public class EJBClient1 {
|
||||
|
||||
@EJB
|
||||
public StatelessEJB statelessEJB;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.ejb.stateless;
|
||||
|
||||
import javax.ejb.EJB;
|
||||
|
||||
public class EJBClient2 {
|
||||
|
||||
@EJB
|
||||
public StatelessEJB statelessEJB;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.ejb.stateless;
|
||||
|
||||
import javax.ejb.Stateless;
|
||||
|
||||
|
||||
@Stateless
|
||||
public class StatelessEJB {
|
||||
|
||||
public String name;
|
||||
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.ejb.test.stateful;
|
||||
|
||||
import org.jboss.arquillian.container.test.api.Deployment;
|
||||
import org.jboss.arquillian.junit.Arquillian;
|
||||
import org.jboss.shrinkwrap.api.ShrinkWrap;
|
||||
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
|
||||
import org.jboss.shrinkwrap.api.spec.JavaArchive;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import com.baeldung.ejb.stateful.EJBClient1;
|
||||
import com.baeldung.ejb.stateful.EJBClient2;
|
||||
import com.baeldung.ejb.stateful.StatefulEJB;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
|
||||
@RunWith(Arquillian.class)
|
||||
public class StatefulEJBTest {
|
||||
|
||||
@Inject
|
||||
private EJBClient1 ejbClient1;
|
||||
|
||||
@Inject
|
||||
private EJBClient2 ejbClient2;
|
||||
|
||||
@Test
|
||||
public void givenOneStatefulBean_whenTwoClientsSetValueOnBean_thenClientStateIsMaintained() {
|
||||
|
||||
// act
|
||||
ejbClient1.statefulEJB.name = "Client 1";
|
||||
ejbClient2.statefulEJB.name = "Client 2";
|
||||
|
||||
// assert
|
||||
Assert.assertNotEquals(ejbClient1.statefulEJB.name, ejbClient2.statefulEJB.name);
|
||||
Assert.assertEquals("Client 1", ejbClient1.statefulEJB.name);
|
||||
Assert.assertEquals("Client 2", ejbClient2.statefulEJB.name);
|
||||
|
||||
}
|
||||
|
||||
@Deployment
|
||||
public static JavaArchive createDeployment() {
|
||||
return ShrinkWrap.create(JavaArchive.class)
|
||||
.addClass(StatefulEJB.class)
|
||||
.addClass(EJBClient1.class)
|
||||
.addClass(EJBClient2.class)
|
||||
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
|
||||
}
|
||||
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.ejb.test.stateless;
|
||||
|
||||
import org.jboss.arquillian.container.test.api.Deployment;
|
||||
import org.jboss.arquillian.junit.Arquillian;
|
||||
import org.jboss.shrinkwrap.api.ShrinkWrap;
|
||||
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
|
||||
import org.jboss.shrinkwrap.api.spec.JavaArchive;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import com.baeldung.ejb.stateless.EJBClient1;
|
||||
import com.baeldung.ejb.stateless.EJBClient2;
|
||||
import com.baeldung.ejb.stateless.StatelessEJB;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
|
||||
@RunWith(Arquillian.class)
|
||||
public class StatelessEJBTest {
|
||||
|
||||
@Inject
|
||||
private EJBClient1 ejbClient1;
|
||||
|
||||
@Inject
|
||||
private EJBClient2 ejbClient2;
|
||||
|
||||
@Test
|
||||
public void givenOneStatelessBean_whenStateIsSetInOneBean_secondBeanShouldHaveSameState() {
|
||||
|
||||
// act
|
||||
ejbClient1.statelessEJB.name = "Client 1";
|
||||
|
||||
// assert
|
||||
Assert.assertEquals("Client 1", ejbClient1.statelessEJB.name);
|
||||
Assert.assertEquals("Client 1", ejbClient2.statelessEJB.name);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenOneStatelessBean_whenStateIsSetInBothBeans_secondBeanShouldHaveSecondBeanState() {
|
||||
|
||||
// act
|
||||
ejbClient1.statelessEJB.name = "Client 1";
|
||||
ejbClient2.statelessEJB.name = "Client 2";
|
||||
|
||||
// assert
|
||||
Assert.assertEquals("Client 2", ejbClient2.statelessEJB.name);
|
||||
|
||||
}
|
||||
|
||||
@Deployment
|
||||
public static JavaArchive createDeployment() {
|
||||
return ShrinkWrap.create(JavaArchive.class)
|
||||
.addClass(StatelessEJB.class)
|
||||
.addClass(EJBClient1.class)
|
||||
.addClass(EJBClient2.class)
|
||||
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
|
||||
}
|
||||
|
||||
}
|
||||
+8
-1
@@ -40,7 +40,12 @@
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<type>ejb</type>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb-session-beans</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<type>ejb</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
@@ -75,5 +80,7 @@
|
||||
<modules>
|
||||
<module>ejb-remote</module>
|
||||
<module>ejb-client</module>
|
||||
<module>ejb-session-beans</module>
|
||||
<module>ejb-session-beans-client</module>
|
||||
</modules>
|
||||
</project>
|
||||
@@ -15,6 +15,8 @@
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
@@ -22,6 +24,11 @@
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>5.2.9.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
@@ -37,6 +44,32 @@
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<forkCount>3</forkCount>
|
||||
<reuseForks>true</reuseForks>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package com.baeldung.hibernate;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
@@ -20,44 +24,56 @@ import com.baeldung.hibernate.pojo.Supplier;
|
||||
public class HibernateMultiTenantUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
private static Map<String, ConnectionProvider> connectionProviderMap = new HashMap<>();
|
||||
private static final String[] tenantDBNames = { "mydb1","mydb2"};
|
||||
private static final String[] tenantDBNames = { "mydb1", "mydb2" };
|
||||
|
||||
public static SessionFactory getSessionFactory() throws UnsupportedTenancyException {
|
||||
public static SessionFactory getSessionFactory() throws UnsupportedTenancyException, IOException {
|
||||
if (sessionFactory == null) {
|
||||
Configuration configuration = new Configuration().configure();
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry(configuration);
|
||||
sessionFactory = makeSessionFactory (serviceRegistry);
|
||||
// sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
|
||||
|
||||
// Configuration configuration = new Configuration().configure();
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = makeSessionFactory(serviceRegistry);
|
||||
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
|
||||
MetadataSources metadataSources = new MetadataSources( serviceRegistry );
|
||||
for(Class annotatedClasses : getAnnotatedClasses()) {
|
||||
metadataSources.addAnnotatedClass( annotatedClasses );
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
for (Class annotatedClasses : getAnnotatedClasses()) {
|
||||
metadataSources.addAnnotatedClass(annotatedClasses);
|
||||
}
|
||||
|
||||
Metadata metadata = metadataSources.buildMetadata();
|
||||
return metadata.getSessionFactoryBuilder().build();
|
||||
|
||||
return metadata.getSessionFactoryBuilder()
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
private static Class<?>[] getAnnotatedClasses() {
|
||||
return new Class<?>[] {
|
||||
Supplier.class
|
||||
};
|
||||
return new Class<?>[] { Supplier.class };
|
||||
}
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry(Configuration configuration) throws UnsupportedTenancyException {
|
||||
Properties properties = configuration.getProperties();
|
||||
private static ServiceRegistry configureServiceRegistry() throws UnsupportedTenancyException, IOException {
|
||||
|
||||
// Properties properties = configuration.getProperties();
|
||||
Properties properties = getProperties();
|
||||
|
||||
connectionProviderMap = setUpConnectionProviders(properties, tenantDBNames);
|
||||
properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, new ConfigurableMultiTenantConnectionProvider(connectionProviderMap));
|
||||
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties).build();
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("hibernate.properties");
|
||||
FileInputStream inputStream = new FileInputStream(propertiesURL.getFile());
|
||||
properties.load(inputStream);
|
||||
System.out.println("LOADED PROPERTIES FROM hibernate.properties");
|
||||
|
||||
return properties;
|
||||
}
|
||||
|
||||
private static Map<String, ConnectionProvider> setUpConnectionProviders(Properties properties, String[] tenantNames) throws UnsupportedTenancyException {
|
||||
@@ -66,23 +82,27 @@ public class HibernateMultiTenantUtil {
|
||||
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
|
||||
|
||||
String tenantStrategy = properties.getProperty("hibernate.multiTenancy");
|
||||
System.out.println("Strategy:"+tenantStrategy);
|
||||
System.out.println("Strategy:" + tenantStrategy);
|
||||
properties.put(Environment.URL, tenantUrl(properties.getProperty(Environment.URL), tenant, tenantStrategy));
|
||||
System.out.println("URL:"+properties.getProperty(Environment.URL));
|
||||
System.out.println("URL:" + properties.getProperty(Environment.URL));
|
||||
connectionProvider.configure(properties);
|
||||
System.out.println("Tenant:"+tenant);
|
||||
System.out.println("Tenant:" + tenant);
|
||||
providerMap.put(tenant, connectionProvider);
|
||||
|
||||
|
||||
}
|
||||
System.out.println("Added connections for:");
|
||||
providerMap.keySet().stream().forEach(System.out::println);
|
||||
providerMap.keySet()
|
||||
.stream()
|
||||
.forEach(System.out::println);
|
||||
return providerMap;
|
||||
}
|
||||
|
||||
private static Object tenantUrl(String originalUrl, String tenant, String tenantStrategy) throws UnsupportedTenancyException {
|
||||
if (tenantStrategy.toUpperCase().equals("DATABASE")) {
|
||||
if (tenantStrategy.toUpperCase()
|
||||
.equals("DATABASE")) {
|
||||
return originalUrl.replace(DEFAULT_DB_NAME, tenant);
|
||||
} else if (tenantStrategy.toUpperCase().equals("SCHEMA")) {
|
||||
} else if (tenantStrategy.toUpperCase()
|
||||
.equals("SCHEMA")) {
|
||||
return originalUrl + String.format(SCHEMA_TOKEN, tenant);
|
||||
} else {
|
||||
throw new UnsupportedTenancyException("Not yet supported");
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE hibernate-configuration PUBLIC
|
||||
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
|
||||
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
||||
<hibernate-configuration>
|
||||
<session-factory>
|
||||
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
|
||||
<property name="hibernate.connection.url">jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1</property>
|
||||
<property name="hibernate.connection.username">sa</property>
|
||||
<property name="connection.password"/>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
|
||||
<property name="hibernate.multiTenancy">DATABASE</property>
|
||||
</session-factory>
|
||||
</hibernate-configuration>
|
||||
@@ -0,0 +1,8 @@
|
||||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
|
||||
hibernate.connection.username=sa
|
||||
jdbc.password=
|
||||
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.multiTenancy=DATABASE
|
||||
+46
-40
@@ -1,65 +1,71 @@
|
||||
package com.baeldung.hibernate;
|
||||
import com.baeldung.hibernate.pojo.Supplier;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.pojo.Supplier;
|
||||
|
||||
public class MultiTenantHibernateIntegrationTest {
|
||||
@Test
|
||||
public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs () {
|
||||
SessionFactory sessionFactory;
|
||||
try {
|
||||
sessionFactory = HibernateMultiTenantUtil.getSessionFactory();
|
||||
|
||||
Session db1Session = sessionFactory
|
||||
.withOptions().tenantIdentifier("mydb1").openSession();
|
||||
|
||||
initDb1(db1Session);
|
||||
|
||||
Transaction transaction = db1Session.getTransaction();
|
||||
transaction.begin();
|
||||
Supplier supplierFromDB1 = (Supplier)db1Session.createCriteria(Supplier.class).list().get(0);
|
||||
transaction.commit();
|
||||
|
||||
Session db2Session = sessionFactory
|
||||
.withOptions().tenantIdentifier("mydb2").openSession();
|
||||
|
||||
initDb2(db2Session);
|
||||
db2Session.getTransaction().begin();
|
||||
Supplier supplierFromDB2 = (Supplier) db2Session.createCriteria(Supplier.class).list().get(0);
|
||||
db2Session.getTransaction().commit();
|
||||
|
||||
System.out.println(supplierFromDB1);
|
||||
System.out.println(supplierFromDB2);
|
||||
|
||||
assertNotEquals(supplierFromDB1, supplierFromDB2);
|
||||
} catch (UnsupportedTenancyException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs() throws UnsupportedTenancyException, IOException {
|
||||
SessionFactory sessionFactory = HibernateMultiTenantUtil.getSessionFactory();
|
||||
|
||||
Session db1Session = sessionFactory.withOptions().tenantIdentifier("mydb1").openSession();
|
||||
|
||||
initDb1(db1Session);
|
||||
|
||||
Transaction transaction = db1Session.getTransaction();
|
||||
transaction.begin();
|
||||
Supplier supplierFromDB1 = (Supplier) db1Session.createCriteria(Supplier.class).list().get(0);
|
||||
transaction.commit();
|
||||
|
||||
Session db2Session = sessionFactory.withOptions().tenantIdentifier("mydb2").openSession();
|
||||
|
||||
initDb2(db2Session);
|
||||
db2Session.getTransaction().begin();
|
||||
Supplier supplierFromDB2 = (Supplier) db2Session.createCriteria(Supplier.class).list().get(0);
|
||||
db2Session.getTransaction().commit();
|
||||
|
||||
System.out.println(supplierFromDB1);
|
||||
System.out.println(supplierFromDB2);
|
||||
|
||||
assertNotEquals(supplierFromDB1, supplierFromDB2);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void initDb1(Session db1Session) {
|
||||
System.out.println("Init DB1");
|
||||
Transaction transaction = db1Session.getTransaction();
|
||||
transaction.begin();
|
||||
db1Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate();
|
||||
db1Session.createSQLQuery("create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))").executeUpdate();
|
||||
db1Session
|
||||
.createSQLQuery(
|
||||
"create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))")
|
||||
.executeUpdate();
|
||||
db1Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'John', 'USA')").executeUpdate();
|
||||
transaction.commit();
|
||||
}
|
||||
|
||||
|
||||
private void initDb2(Session db2Session) {
|
||||
System.out.println("Init DB2");
|
||||
Transaction transaction = db2Session.getTransaction();
|
||||
transaction.begin();
|
||||
db2Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate();
|
||||
db2Session.createSQLQuery("create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))").executeUpdate();
|
||||
db2Session
|
||||
.createSQLQuery(
|
||||
"create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))")
|
||||
.executeUpdate();
|
||||
db2Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'Miller', 'UK')").executeUpdate();
|
||||
transaction.commit();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
|
||||
hibernate.connection.username=sa
|
||||
jdbc.password=
|
||||
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.multiTenancy=DATABASE
|
||||
@@ -3,7 +3,6 @@ package com.baeldung;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
@@ -56,32 +55,12 @@ public class DynamicTestsExample {
|
||||
|
||||
// sample input and output
|
||||
List<String> inputList =
|
||||
new ArrayList<>(Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"));
|
||||
Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
|
||||
List<String> outputList =
|
||||
new ArrayList<>(Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"));
|
||||
Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
|
||||
|
||||
// input generator that generates inputs using inputList
|
||||
Iterator<String> inputGenerator = new Iterator<String>() {
|
||||
|
||||
String current;
|
||||
int size = inputList.size();
|
||||
int index = 0;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
if(index == size) {
|
||||
return false;
|
||||
}
|
||||
current = inputList.get(index);
|
||||
index++;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String next() {
|
||||
return current;
|
||||
}
|
||||
};
|
||||
Iterator<String> inputGenerator = inputList.iterator();
|
||||
|
||||
// a display name generator that creates a different name based on the input
|
||||
Function<String, String> displayNameGenerator = (input) -> "Resolving: " + input;
|
||||
|
||||
@@ -276,6 +276,16 @@
|
||||
<version>2.3.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>0.6.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>jool</artifactId>
|
||||
<version>0.9.12</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<multiverse.version>0.7.0</multiverse.version>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.jooq.lambda.Seq;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class JoolMergeStreamsTest {
|
||||
@Test
|
||||
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
|
||||
Seq<Integer> seq1 = Seq.of(1, 3, 5);
|
||||
Seq<Integer> seq2 = Seq.of(2, 4, 6);
|
||||
|
||||
Seq<Integer> resultingSeq = seq1.append(seq2);
|
||||
|
||||
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6),
|
||||
resultingSeq.toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() {
|
||||
Seq<String> seq = Seq.of("foo", "bar");
|
||||
Seq<String> openingBracketSeq = Seq.of("[");
|
||||
Seq<String> closingBracketSeq = Seq.of("]");
|
||||
|
||||
Seq<String> resultingStream = seq.append(closingBracketSeq)
|
||||
.prepend(openingBracketSeq);
|
||||
|
||||
Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"),
|
||||
resultingStream.toList());
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user