This commit is contained in:
Karan Khanna 2018-05-20 16:52:43 +02:00
commit da80e9e2c5
625 changed files with 8738 additions and 2379 deletions

View File

@ -0,0 +1,28 @@
package com.baeldung.hashtable;
public class Word {
private String name;
public Word(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Word))
return false;
Word word = (Word) o;
return word.getName().equals(this.name) ? true : false;
}
public int hashCode() {
return name.hashCode();
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.optional;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OrElseAndOrElseGet {
public static List<String> names = Arrays.asList("John", "Jones", "Kelly", "Cristina", "Raven");
private static final Logger LOG = LoggerFactory.getLogger(OrElseAndOrElseGet.class);
public String getRandomName() {
LOG.info("getRandomName() method - start");
Random random = new Random();
int index = random.nextInt(5);
LOG.info("getRandomName() method - end");
return names.get(index);
}
public String getNameUsingOrElse(String name) {
return Optional.ofNullable(name)
.orElse(getRandomName());
}
public String getNameUsingOrElseGet(String name) {
return Optional.ofNullable(name)
.orElseGet(() -> getRandomName());
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.optional;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.RunnerException;
@Fork(1)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class OrElseAndOrElseGetBenchmarkRunner {
private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet();
public static void main(String[] args) throws RunnerException, IOException {
org.openjdk.jmh.Main.main(args);
}
@Benchmark
public String orElseBenchmark() {
return orElsevsOrElseGet.getNameUsingOrElse("baeldung");
}
@Benchmark
public String orElseGetBenchmark() {
return orElsevsOrElseGet.getNameUsingOrElseGet("baeldung");
}
}

View File

@ -0,0 +1,274 @@
package com.baeldung.hashtable;
import java.util.ConcurrentModificationException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import org.junit.Test;
public class HashtableUnitTest {
@Test
public void whenPutAndGet_thenReturnsValue() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
Word word = new Word("cat");
table.put(word, "an animal");
String definition = table.get(word);
assertEquals("an animal", definition);
definition = table.remove(word);
assertEquals("an animal", definition);
}
@Test
public void whenThesameInstanceOfKey_thenReturnsValue() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
Word word = new Word("cat");
table.put(word, "an animal");
String extracted = table.get(word);
assertEquals("an animal", extracted);
}
@Test
public void whenEqualsOverridden_thenReturnsValue() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
Word word = new Word("cat");
table.put(word, "an animal");
String extracted = table.get(new Word("cat"));
assertEquals("an animal", extracted);
}
@Test(expected = NullPointerException.class)
public void whenNullKey_thenException() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(null, "an animal");
}
@Test(expected = ConcurrentModificationException.class)
public void whenIterate_thenFailFast() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "an animal");
table.put(new Word("dog"), "another animal");
Iterator<Word> it = table.keySet().iterator();
System.out.println("iterator created");
table.remove(new Word("dog"));
System.out.println("element removed");
while (it.hasNext()) {
Word key = it.next();
System.out.println(table.get(key));
}
}
@Test
public void whenEnumerate_thenNotFailFast() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("1"), "one");
table.put(new Word("2"), "two");
table.put(new Word("3"), "three");
table.put(new Word("4"), "four");
table.put(new Word("5"), "five");
table.put(new Word("6"), "six");
table.put(new Word("7"), "seven");
table.put(new Word("8"), "eight");
Enumeration<Word> enumKey = table.keys();
System.out.println("Enumeration created");
table.remove(new Word("1"));
System.out.println("element removed");
while (enumKey.hasMoreElements()) {
Word key = enumKey.nextElement();
System.out.println(table.get(key));
}
}
@Test
public void whenAddElements_thenIterationOrderUnpredicable() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("1"), "one");
table.put(new Word("2"), "two");
table.put(new Word("3"), "three");
table.put(new Word("4"), "four");
table.put(new Word("5"), "five");
table.put(new Word("6"), "six");
table.put(new Word("7"), "seven");
table.put(new Word("8"), "eight");
Iterator<Map.Entry<Word, String>> it = table.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Word, String> entry = it.next();
System.out.println(entry.getValue());
}
}
@Test
public void whenGetOrDefault_thenDefaultGot() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
Word key = new Word("dog");
String definition;
// old way
/* if (table.containsKey(key)) {
definition = table.get(key);
} else {
definition = "not found";
}*/
// new way
definition = table.getOrDefault(key, "not found");
assertThat(definition, is("not found"));
}
@Test
public void whenPutifAbsent_thenNotRewritten() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
String definition = "an animal";
// old way
/* if (!table.containsKey(new Word("cat"))) {
table.put(new Word("cat"), definition);
}*/
// new way
table.putIfAbsent(new Word("cat"), definition);
assertThat(table.get(new Word("cat")), is("a small domesticated carnivorous mammal"));
}
@Test
public void whenRemovePair_thenCheckKeyAndValue() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
// old way
/* if (table.get(new Word("cat")).equals("an animal")) {
table.remove(new Word("cat"));
}*/
// new way
boolean result = table.remove(new Word("cat"), "an animal");
assertThat(result, is(false));
}
@Test
public void whenReplacePair_thenValueChecked() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
String definition = "an animal";
// old way
/* if (table.containsKey(new Word("cat")) && table.get(new Word("cat")).equals("a small domesticated carnivorous mammal")) {
table.put(new Word("cat"), definition);
}*/
// new way
table.replace(new Word("cat"), "a small domesticated carnivorous mammal", definition);
assertThat(table.get(new Word("cat")), is("an animal"));
}
@Test
public void whenKeyIsAbsent_thenNotRewritten() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
// old way
/* if (!table.containsKey(cat)) {
String definition = "an animal";// calculate
table.put(new Word("cat"), definition);
}
*/
// new way
table.computeIfAbsent(new Word("cat"), key -> "an animal");
assertThat(table.get(new Word("cat")), is("a small domesticated carnivorous mammal"));
}
@Test
public void whenKeyIsPresent_thenComputeIfPresent() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
Word cat = new Word("cat");
// old way
/* if (table.containsKey(cat)) {
String concatination = cat.getName() + " - " + table.get(cat);
table.put(cat, concatination);
}*/
// new way
table.computeIfPresent(cat, (key, value) -> key.getName() + " - " + value);
assertThat(table.get(cat), is("cat - a small domesticated carnivorous mammal"));
}
@Test
public void whenCompute_thenForAllKeys() {
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" };
for (String animal : animals) {
table.compute(animal, (key, value) -> (value == null ? Integer.valueOf(1) : Integer.valueOf(value) + 1));
}
assertThat(table.values(), hasItems(2, 2, 2, 1));
}
@Test
public void whenInsteadOfCompute_thenMerge() {
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" };
for (String animal : animals) {
table.merge(animal, 1, (oldValue, value) -> (oldValue + value));
}
assertThat(table.values(), hasItems(2, 2, 2, 1));
}
@Test
public void whenForeach_thenIterate() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
table.put(new Word("dog"), "another animal");
table.forEach((k, v) -> System.out.println(k.getName() + " - " + v)
);
}
@Test
public void whenReplaceall_thenNoIterationNeeded() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
table.put(new Word("dog"), "another animal");
table.replaceAll((k, v) -> k.getName() + " - " + v);
assertThat(table.values(), hasItems("cat - a small domesticated carnivorous mammal", "dog - another animal"));
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.java8.optional;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;
import com.baeldung.optional.OrElseAndOrElseGet;
public class OrElseAndOrElseGetTest {
private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet();
private static final Logger LOG = LoggerFactory.getLogger(OrElseAndOrElseGetTest.class);
@Test
public void givenNonEmptyOptional_whenOrElseUsed_thenGivenStringReturned() {
LOG.info("In givenNonEmptyOptional_whenOrElseUsed_thenGivenStringReturned()");
String name = orElsevsOrElseGet.getNameUsingOrElse("baeldung");
assertEquals(name, "baeldung");
}
@Test
public void givenEmptyOptional_whenOrElseUsed_thenRandomStringReturned() {
LOG.info("In givenEmptyOptional_whenOrElseUsed_thenRandomStringReturned()");
String name = orElsevsOrElseGet.getNameUsingOrElse(null);
assertTrue(orElsevsOrElseGet.names.contains(name));
}
@Test
public void givenNonEmptyOptional_whenOrElseGetUsed_thenGivenStringReturned() {
LOG.info("In givenNonEmptyOptional_whenOrElseGetUsed_thenGivenStringReturned()");
String name = orElsevsOrElseGet.getNameUsingOrElseGet("baeldung");
assertEquals(name, "baeldung");
}
@Test
public void givenEmptyOptional_whenOrElseGetUsed_thenRandomStringReturned() {
LOG.info("In givenEmptyOptional_whenOrElseGetUsed_thenRandomStringReturned()");
String name = orElsevsOrElseGet.getNameUsingOrElseGet(null);
assertTrue(orElsevsOrElseGet.names.contains(name));
}
}

View File

@ -74,17 +74,14 @@
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
- [Singletons in Java](http://www.baeldung.com/java-singleton)
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
- [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int)
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
@ -116,8 +113,6 @@
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern)
- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
@ -136,7 +131,6 @@
- [Class Loaders in Java](http://www.baeldung.com/java-classloaders)
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern)
- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
- [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger)
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
@ -145,4 +139,5 @@
- [Sending Emails with Java](http://www.baeldung.com/java-email)
- [Introduction to SSL in Java](http://www.baeldung.com/java-ssl)
- [Java KeyStore API](http://www.baeldung.com/java-keystore)
- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking)
- [Using Java Assertions](http://www.baeldung.com/java-assert)
- [Guide to Java Clock Class](http://www.baeldung.com/java-clock)

View File

@ -1,5 +0,0 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public interface Color {
String getColor();
}

View File

@ -1,5 +0,0 @@
package com.baeldung.designpatterns.creational.factory;
public interface Polygon {
String getType();
}

View File

@ -0,0 +1,81 @@
package com.baeldung.nan;
/**
* Sample usage of NaN.
*
*/
public class NaNExample {
public static void main(String[] args) {
NaNExample naNExample = new NaNExample();
naNExample.demo();
}
void demo() {
undefined_operations_produce_NaN();
operations_with_no_real_results_produce_NaN();
operations_with_NaN_produce_NaN();
comparison_with_NaN();
check_if_a_value_is_NaN();
assign_NaN_to_missing_values();
}
void undefined_operations_produce_NaN() {
System.out.println("Undefined Operations Produce NaN");
final double ZERO = 0;
System.out.println("ZERO / ZERO = " + (ZERO / ZERO));
System.out.println("INFINITY - INFINITY = " + (Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY));
System.out.println("INFINITY * ZERO = " + (Double.POSITIVE_INFINITY * ZERO));
System.out.println();
}
void operations_with_no_real_results_produce_NaN() {
System.out.println("Operations with no real results produce NaN");
System.out.println("SQUARE ROOT OF -1 = " + Math.sqrt(-1));
System.out.println("LOG OF -1 = " + Math.log(-1));
System.out.println();
}
void operations_with_NaN_produce_NaN() {
System.out.println("Operations with NaN produce NaN");
System.out.println("2 + NaN = " + (2 + Double.NaN));
System.out.println("2 - NaN = " + (2 - Double.NaN));
System.out.println("2 * NaN = " + (2 * Double.NaN));
System.out.println("2 / NaN = " + (2 / Double.NaN));
System.out.println();
}
void assign_NaN_to_missing_values() {
System.out.println("Assign NaN to Missing values");
double salaryRequired = Double.NaN;
System.out.println(salaryRequired);
System.out.println();
}
void comparison_with_NaN() {
System.out.println("Comparison with NaN");
final double NAN = Double.NaN;
System.out.println("NaN == 1 = " + (NAN == 1));
System.out.println("NaN > 1 = " + (NAN > 1));
System.out.println("NaN < 1 = " + (NAN < 1));
System.out.println("NaN != 1 = " + (NAN != 1));
System.out.println("NaN == NaN = " + (NAN == NAN));
System.out.println("NaN > NaN = " + (NAN > NAN));
System.out.println("NaN < NaN = " + (NAN < NAN));
System.out.println("NaN != NaN = " + (NAN != NAN));
System.out.println();
}
void check_if_a_value_is_NaN() {
System.out.println("Check if a value is NaN");
double x = 1;
System.out.println(x + " is NaN = " + (x != x));
System.out.println(x + " is NaN = " + (Double.isNaN(x)));
x = Double.NaN;
System.out.println(x + " is NaN = " + (x != x));
System.out.println(x + " is NaN = " + (Double.isNaN(x)));
System.out.println();
}
}

View File

@ -1,10 +1,12 @@
package com.baeldung.numberofdigits;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
import org.apache.log4j.Logger;
public class NumberOfDigitsDriver {
private static NumberOfDigits numberOfDigits;
private static Logger LOG = Logger.getLogger(NumberOfDigitsDriver.class);
static {
numberOfDigits = new NumberOfDigits();
}

View File

@ -0,0 +1,9 @@
package com.baeldung.scope.method;
public class BaseMethodClass {
public static void printMessage() {
System.out.println("base static method");
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.scope.method;
public class ChildMethodClass extends BaseMethodClass {
public static void printMessage() {
System.out.println("child static method");
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.scope.method;
public class MethodHidingDemo {
public static void main(String[] args) {
ChildMethodClass.printMessage();
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.scope.variable;
/**
* Created by Gebruiker on 5/7/2018.
*/
public class ChildVariable extends ParentVariable {
String instanceVariable = "child variable";
public void printInstanceVariable() {
System.out.println(instanceVariable);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.scope.variable;
/**
* Created by Gebruiker on 5/6/2018.
*/
public class HideVariable {
private String message = "this is instance variable";
HideVariable() {
String message = "constructor local variable";
System.out.println(message);
}
public void printLocalVariable() {
String message = "method local variable";
System.out.println(message);
}
public void printInstanceVariable() {
System.out.println(this.message);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.scope.variable;
/**
* Created by Gebruiker on 5/7/2018.
*/
public class ParentVariable {
String instanceVariable = "parent variable";
public void printInstanceVariable() {
System.out.println(instanceVariable);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.scope.variable;
/**
* Created by Gebruiker on 5/6/2018.
*/
public class VariableHidingDemo {
public static void main(String[] args) {
HideVariable variable = new HideVariable();
variable.printLocalVariable();
variable.printInstanceVariable();
ParentVariable parentVariable = new ParentVariable();
ParentVariable childVariable = new ChildVariable();
parentVariable.printInstanceVariable();
childVariable.printInstanceVariable();
}
}

View File

@ -0,0 +1,75 @@
package com.baeldung.stringisnumeric;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class Benchmarking {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(Benchmarking.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
@State(Scope.Thread)
public static class ExecutionPlan {
public String number = Integer.toString(Integer.MAX_VALUE);
public boolean isNumber = false;
public IsNumeric isNumeric= new IsNumeric();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingCoreJava(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingCoreJava(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingRegularExpressions(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingRegularExpressions(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingNumberUtils_isCreatable(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isParsable(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingNumberUtils_isParsable(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumeric(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingStringUtils_isNumeric(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingStringUtils_isNumericSpace(plan.number);
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.stringisnumeric;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
public class IsNumeric {
public boolean usingCoreJava(String strNum) {
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}
public boolean usingRegularExpressions(String strNum) {
return strNum.matches("-?\\d+(\\.\\d+)?");
}
public boolean usingNumberUtils_isCreatable(String strNum) {
return NumberUtils.isCreatable(strNum);
}
public boolean usingNumberUtils_isParsable(String strNum) {
return NumberUtils.isParsable(strNum);
}
public boolean usingStringUtils_isNumeric(String strNum) {
return StringUtils.isNumeric(strNum);
}
public boolean usingStringUtils_isNumericSpace(String strNum) {
return StringUtils.isNumericSpace(strNum);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.stringisnumeric;
import org.apache.log4j.Logger;
public class IsNumericDriver {
private static IsNumeric isNumeric;
private static Logger LOG = Logger.getLogger(IsNumericDriver.class);
static {
isNumeric =new IsNumeric();
}
public static void main(String[] args) {
LOG.info("Testing all methods...");
boolean res = isNumeric.usingCoreJava("1001");
LOG.info("Using Core Java : " + res);
res = isNumeric.usingRegularExpressions("1001");
LOG.info("Using Regular Expressions : " + res);
res =isNumeric.usingNumberUtils_isCreatable("1001");
LOG.info("Using NumberUtils.isCreatable : " + res);
res =isNumeric.usingNumberUtils_isParsable("1001");
LOG.info("Using NumberUtils.isParsable : " + res);
res =isNumeric.usingStringUtils_isNumeric("1001");
LOG.info("Using StringUtils.isNumeric : " + res);
res =isNumeric.usingStringUtils_isNumericSpace("1001");
LOG.info("Using StringUtils.isNumericSpace : " + res);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class CoreJavaIsNumericUnitTest {
public static boolean isNumeric(String strNum) {
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}
@Test
public void whenUsingCoreJava_thenTrue() {
// Valid Numbers
assertThat(isNumeric("22")).isTrue();
assertThat(isNumeric("5.05")).isTrue();
assertThat(isNumeric("-200")).isTrue();
assertThat(isNumeric("10.0d")).isTrue();
assertThat(isNumeric(" 22 ")).isTrue();
// Invalid Numbers
assertThat(isNumeric(null)).isFalse();
assertThat(isNumeric("")).isFalse();
assertThat(isNumeric("abc")).isFalse();
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.Test;
public class NumberUtilsIsCreatableUnitTest {
@Test
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
// Valid Numbers
assertThat(NumberUtils.isCreatable("22")).isTrue();
assertThat(NumberUtils.isCreatable("5.05")).isTrue();
assertThat(NumberUtils.isCreatable("-200")).isTrue();
assertThat(NumberUtils.isCreatable("10.0d")).isTrue();
assertThat(NumberUtils.isCreatable("1000L")).isTrue();
assertThat(NumberUtils.isCreatable("0xFF")).isTrue();
assertThat(NumberUtils.isCreatable("07")).isTrue();
assertThat(NumberUtils.isCreatable("2.99e+8")).isTrue();
// Invalid Numbers
assertThat(NumberUtils.isCreatable(null)).isFalse();
assertThat(NumberUtils.isCreatable("")).isFalse();
assertThat(NumberUtils.isCreatable("abc")).isFalse();
assertThat(NumberUtils.isCreatable(" 22 ")).isFalse();
assertThat(NumberUtils.isCreatable("09")).isFalse();
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.Test;
public class NumberUtilsIsParsableUnitTest {
@Test
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
// Valid Numbers
assertThat(NumberUtils.isParsable("22")).isTrue();
assertThat(NumberUtils.isParsable("-23")).isTrue();
assertThat(NumberUtils.isParsable("2.2")).isTrue();
assertThat(NumberUtils.isParsable("09")).isTrue();
// Invalid Numbers
assertThat(NumberUtils.isParsable(null)).isFalse();
assertThat(NumberUtils.isParsable("")).isFalse();
assertThat(NumberUtils.isParsable("6.2f")).isFalse();
assertThat(NumberUtils.isParsable("9.8d")).isFalse();
assertThat(NumberUtils.isParsable("22L")).isFalse();
assertThat(NumberUtils.isParsable("0xFF")).isFalse();
assertThat(NumberUtils.isParsable("2.99e+8")).isFalse();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class RegularExpressionsUnitTest {
public static boolean isNumeric(String strNum) {
return strNum.matches("-?\\d+(\\.\\d+)?");
}
@Test
public void whenUsingRegularExpressions_thenTrue() {
// Valid Numbers
assertThat(isNumeric("22")).isTrue();
assertThat(isNumeric("5.05")).isTrue();
assertThat(isNumeric("-200")).isTrue();
// Invalid Numbers
assertThat(isNumeric("abc")).isFalse();
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.stringisnumeric;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StringUtilsIsNumericSpaceUnitTest {
@Test
public void givenApacheCommons_whenUsingIsNumericSpace_thenTrue() {
// Valid Numbers
assertThat(StringUtils.isNumericSpace("123")).isTrue();
assertThat(StringUtils.isNumericSpace("١٢٣")).isTrue();
assertThat(StringUtils.isNumericSpace("")).isTrue();
assertThat(StringUtils.isNumericSpace(" ")).isTrue();
assertThat(StringUtils.isNumericSpace("12 3")).isTrue();
// Invalid Numbers
assertThat(StringUtils.isNumericSpace(null)).isFalse();
assertThat(StringUtils.isNumericSpace("ab2c")).isFalse();
assertThat(StringUtils.isNumericSpace("12.3")).isFalse();
assertThat(StringUtils.isNumericSpace("-123")).isFalse();
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.stringisnumeric;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StringUtilsIsNumericUnitTest {
@Test
public void givenApacheCommons_whenUsingIsNumeric_thenTrue() {
// Valid Numbers
assertThat(StringUtils.isNumeric("123")).isTrue();
assertThat(StringUtils.isNumeric("١٢٣")).isTrue();
assertThat(StringUtils.isNumeric("१२३")).isTrue();
// Invalid Numbers
assertThat(StringUtils.isNumeric(null)).isFalse();
assertThat(StringUtils.isNumeric("")).isFalse();
assertThat(StringUtils.isNumeric(" ")).isFalse();
assertThat(StringUtils.isNumeric("12 3")).isFalse();
assertThat(StringUtils.isNumeric("ab2c")).isFalse();
assertThat(StringUtils.isNumeric("12.3")).isFalse();
assertThat(StringUtils.isNumeric("-123")).isFalse();
}
}

View File

@ -63,6 +63,24 @@
<artifactId>kotlinx-coroutines-core</artifactId>
<version>${kotlinx.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-api</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-subject-extension</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-junit-platform-engine</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.nhaarman</groupId>
<artifactId>mockito-kotlin</artifactId>

View File

@ -0,0 +1,19 @@
package com.baeldung.kotlin.spek
import com.baeldung.kotlin.junit5.Calculator
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.subject.SubjectSpek
import org.junit.jupiter.api.Assertions.assertEquals
class CalculatorSubjectTest5 : SubjectSpek<Calculator>({
subject { Calculator() }
describe("A calculator") {
describe("Addition") {
val result = subject.add(3, 5)
it("Produces the correct answer") {
assertEquals(8, result)
}
}
}
})

View File

@ -0,0 +1,32 @@
package com.baeldung.kotlin.spek
import com.baeldung.kotlin.junit5.Calculator
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.junit.jupiter.api.Assertions.assertEquals
class CalculatorTest5 : Spek({
given("A calculator") {
val calculator = Calculator()
on("Adding 3 and 5") {
val result = calculator.add(3, 5)
it("Produces 8") {
assertEquals(8, result)
}
}
}
describe("A calculator") {
val calculator = Calculator()
describe("Addition") {
val result = calculator.add(3, 5)
it("Produces the correct answer") {
assertEquals(8, result)
}
}
}
})

View File

@ -0,0 +1,21 @@
package com.baeldung.kotlin.spek
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.jupiter.api.Assertions
class DataDrivenTest5 : Spek({
describe("A data driven test") {
mapOf(
"hello" to "HELLO",
"world" to "WORLD"
).forEach { input, expected ->
describe("Capitalising $input") {
it("Correctly returns $expected") {
Assertions.assertEquals(expected, input.toUpperCase())
}
}
}
}
})

View File

@ -0,0 +1,62 @@
package com.baeldung.kotlin.spek
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
class GroupTest5 : Spek({
describe("Outer group") {
beforeEachTest {
System.out.println("BeforeEachTest 0")
}
beforeGroup {
System.out.println("BeforeGroup 0")
}
afterEachTest {
System.out.println("AfterEachTest 0")
}
afterGroup {
System.out.println("AfterGroup 0")
}
describe("Inner group 1") {
beforeEachTest {
System.out.println("BeforeEachTest 1")
}
beforeGroup {
System.out.println("BeforeGroup 1")
}
afterEachTest {
System.out.println("AfterEachTest 1")
}
afterGroup {
System.out.println("AfterGroup 1")
}
it("Test 1") {
System.out.println("Test 1")
}
it("Test 2") {
System.out.println("Test 2")
}
}
describe("Inner group 2") {
beforeEachTest {
System.out.println("BeforeEachTest 2")
}
beforeGroup {
System.out.println("BeforeGroup 2")
}
afterEachTest {
System.out.println("AfterEachTest 2")
}
afterGroup {
System.out.println("AfterGroup 2")
}
it("Test 3") {
System.out.println("Test 3")
}
it("Test 4") {
System.out.println("Test 4")
}
}
}
})

View File

@ -1,11 +1,12 @@
package com.baeldung.flips.model;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@Data
@RequiredArgsConstructor
public class Foo {
private final String name;
private final int id;
@NonNull private final String name;
@NonNull private final int id;
}

View File

@ -20,7 +20,7 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
"first.active.after=2999-03-15T00:00:00Z",
"logging.level.org.flips=info"
})
}, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
@ActiveProfiles("dev")
public class FlipControllerTest {

View File

@ -32,6 +32,14 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>${java-hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -52,6 +60,7 @@
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
</properties>
</project>

View File

@ -12,6 +12,7 @@ import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.emptyIterable;
import java.util.Collections;
import java.util.List;
@ -57,6 +58,12 @@ public class HamcrestExamplesUnitTest {
final List<String> collection = Lists.newArrayList();
assertThat(collection, empty());
}
@Test
public final void givenIterableIsEmpty_whenChecking_thenEmpty() {
final Iterable<String> collection = Lists.newArrayList();
assertThat(collection, emptyIterable());
}
@Test
public final void givenCollectionIsNotEmpty_whenChecking_thenNotEmpty() {

View File

@ -1,30 +1,12 @@
package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.Employee;
import com.baeldung.hibernate.pojo.EntityDescription;
import com.baeldung.hibernate.pojo.OrderEntry;
import com.baeldung.hibernate.pojo.OrderEntryIdClass;
import com.baeldung.hibernate.pojo.OrderEntryPK;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.PolygonEntity;
import com.baeldung.hibernate.pojo.Product;
import com.baeldung.hibernate.pojo.Phone;
import com.baeldung.hibernate.pojo.TemporalValues;
import com.baeldung.hibernate.pojo.Course;
import com.baeldung.hibernate.pojo.Student;
import com.baeldung.hibernate.pojo.User;
import com.baeldung.hibernate.pojo.UserProfile;
import com.baeldung.hibernate.pojo.inheritance.Animal;
import com.baeldung.hibernate.pojo.inheritance.Bag;
import com.baeldung.hibernate.pojo.inheritance.Book;
import com.baeldung.hibernate.pojo.inheritance.Car;
import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
import com.baeldung.hibernate.pojo.inheritance.MyProduct;
import com.baeldung.hibernate.pojo.inheritance.Pen;
import com.baeldung.hibernate.pojo.inheritance.Person;
import com.baeldung.hibernate.pojo.inheritance.Pet;
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
import com.baeldung.hibernate.pessimisticlocking.Individual;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent;
import com.baeldung.hibernate.pojo.*;
import com.baeldung.hibernate.pojo.Person;
import com.baeldung.hibernate.pojo.inheritance.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
@ -82,6 +64,12 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(PointEntity.class);
metadataSources.addAnnotatedClass(PolygonEntity.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class);
metadataSources.addAnnotatedClass(Individual.class);
metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class);
metadataSources.addAnnotatedClass(PessimisticLockingStudent.class);
metadataSources.addAnnotatedClass(PessimisticLockingCourse.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()

View File

@ -0,0 +1,34 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.Embeddable;
@Embeddable
public class Address {
private String country;
private String city;
public Address(String country, String city) {
this.country = country;
this.city = city;
}
public Address() {
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.*;
import java.util.List;
@Entity
public class Customer {
@Id
private Long customerId;
private String name;
private String lastName;
@ElementCollection
@CollectionTable(name = "customer_address")
private List<Address> addressList;
public Customer() {
}
public Customer(Long customerId, String name, String lastName, List<Address> addressList) {
this.customerId = customerId;
this.name = name;
this.lastName = lastName;
this.addressList = addressList;
}
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<Address> getAddressList() {
return addressList;
}
public void setAddressList(List<Address> addressList) {
this.addressList = addressList;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Individual {
@Id
private Long id;
private String name;
private String lastName;
public Individual(Long id, String name, String lastName) {
this.id = id;
this.name = name;
this.lastName = lastName;
}
public Individual() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.*;
@Entity
public class PessimisticLockingCourse {
@Id
private Long courseId;
private String name;
@ManyToOne
@JoinTable(name = "student_course")
private PessimisticLockingStudent student;
public PessimisticLockingCourse(Long courseId, String name, PessimisticLockingStudent student) {
this.courseId = courseId;
this.name = name;
this.student = student;
}
public PessimisticLockingCourse() {
}
public Long getCourseId() {
return courseId;
}
public void setCourseId(Long courseId) {
this.courseId = courseId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PessimisticLockingStudent getStudent() {
return student;
}
public void setStudent(PessimisticLockingStudent students) {
this.student = students;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.Entity;
import java.math.BigDecimal;
@Entity
public class PessimisticLockingEmployee extends Individual {
private BigDecimal salary;
public PessimisticLockingEmployee(Long id, String name, String lastName, BigDecimal salary) {
super(id, name, lastName);
this.salary = salary;
}
public PessimisticLockingEmployee() {
super();
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal average) {
this.salary = average;
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.*;
import java.util.List;
@Entity
public class PessimisticLockingStudent {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "student")
private List<PessimisticLockingCourse> courses;
public PessimisticLockingStudent(Long id, String name) {
this.id = id;
this.name = name;
}
public PessimisticLockingStudent() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<PessimisticLockingCourse> getCourses() {
return courses;
}
public void setCourses(List<PessimisticLockingCourse> courses) {
this.courses = courses;
}
}

View File

@ -0,0 +1,151 @@
package com.baeldung.hibernate.pessimisticlocking;
import com.baeldung.hibernate.HibernateUtil;
import com.vividsolutions.jts.util.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.*;
import java.io.IOException;
import java.util.Arrays;
public class BasicPessimisticLockingIntegrationTest {
@BeforeClass
public static void setUp() throws IOException {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOHN");
PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "MATH", student);
student.setCourses(Arrays.asList(course));
entityManager.persist(course);
entityManager.persist(student);
entityManager.getTransaction()
.commit();
entityManager.close();
}
@Test
public void givenFoundRecordWithPessimisticRead_whenFindingNewOne_PessimisticLockExceptionThrown() {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
entityManager.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ);
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ);
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
@Test
public void givenRecordWithPessimisticReadQuery_whenQueryingNewOne_PessimisticLockExceptionThrown() throws IOException {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
Query query = entityManager.createQuery("from Student where studentId = :studentId");
query.setParameter("studentId", 1L);
query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
query.getResultList();
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
Query query2 = entityManager2.createQuery("from Student where studentId = :studentId");
query2.setParameter("studentId", 1L);
query2.setLockMode(LockModeType.PESSIMISTIC_READ);
query2.getResultList();
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
@Test
public void givenRecordWithPessimisticReadLock_whenFindingNewOne_PessimisticLockExceptionThrown() {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
entityManager.lock(resultStudent, LockModeType.PESSIMISTIC_READ);
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_FORCE_INCREMENT);
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
@Test
public void givenRecordAndRefreshWithPessimisticRead_whenFindingWithPessimisticWrite_PessimisticLockExceptionThrown() {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_FORCE_INCREMENT);
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_WRITE);
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
@Test
public void givenRecordWithPessimisticRead_whenUpdatingRecord_PessimisticLockExceptionThrown() {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_READ);
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L);
resultStudent2.setName("Change");
entityManager2.persist(resultStudent2);
entityManager2.getTransaction()
.commit();
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
@Test
public void givenRecordWithPessimisticWrite_whenUpdatingRecord_PessimisticLockExceptionThrown() {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_WRITE);
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L);
resultStudent2.setName("Change");
entityManager2.persist(resultStudent2);
entityManager2.getTransaction()
.commit();
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
String propertyFileName = "hibernate-pessimistic-locking.properties";
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
.openSession();
entityManager.getTransaction()
.begin();
return entityManager;
}
}

View File

@ -0,0 +1,115 @@
package com.baeldung.hibernate.pessimisticlocking;
import com.baeldung.hibernate.HibernateUtil;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.PessimisticLockScope;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class PessimisticLockScopesIntegrationTest {
@Test
public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
PessimisticLockingEmployee employee = new PessimisticLockingEmployee(1L, "JOHN", "SMITH", new BigDecimal(4.5));
em.persist(employee);
em.getTransaction()
.commit();
em.close();
// NORMAL SCOPE
EntityManager em2 = getEntityManagerWithOpenTransaction();
PessimisticLockingEmployee foundEmployee = em2.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE);
em2.getTransaction()
.rollback();
// EXTENDED SCOPE
Map<String, Object> map = new HashMap<>();
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundEmployee = em3.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
em3.getTransaction()
.rollback();
em2.close();
em3.close();
}
@Test
public void givenEntityWithElementCollection_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
Address address = new Address("Poland", "Warsaw");
Customer customer = new Customer(1L, "JOE", "DOE", Arrays.asList(address));
em.persist(customer);
em.getTransaction()
.commit();
em.close();
// NORMAL SCOPE
EntityManager em2 = getEntityManagerWithOpenTransaction();
Customer foundCustomer = em2.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE);
em2.getTransaction()
.rollback();
// EXTENDED SCOPE
Map<String, Object> map = new HashMap<>();
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundCustomer = em3.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
em2.getTransaction()
.rollback();
em2.close();
em3.close();
}
@Test
public void givenEntityWithOneToMany_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOE");
PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "COURSE", student);
student.setCourses(Arrays.asList(course));
em.persist(course);
em.persist(student);
em.getTransaction()
.commit();
em.close();
// NORMAL SCOPE
EntityManager em2 = getEntityManagerWithOpenTransaction();
PessimisticLockingCourse foundCourse = em2.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE);
em2.getTransaction()
.rollback();
// EXTENDED SCOPE
Map<String, Object> map = new HashMap<>();
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundCourse = em3.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
em3.getTransaction()
.rollback();
em2.close();
em3.close();
}
protected EntityManager getEntityManagerWithOpenTransaction() throws IOException {
String propertyFileName = "hibernate-pessimistic-locking.properties";
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
.openSession();
entityManager.getTransaction()
.begin();
return entityManager;
}
}

View File

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

View File

@ -24,6 +24,7 @@ import org.junit.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
@ -89,7 +90,7 @@ public class HttpClientAuthLiveTest {
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException {
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
final String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
final String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
@ -129,7 +130,7 @@ public class HttpClientAuthLiveTest {
private String authorizationHeader(final String username, final String password) {
final String auth = username + ":" + password;
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
return "Basic " + new String(encodedAuth);
}

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<<<<<<< HEAD
<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>
@ -75,5 +76,79 @@
<org.apache.httpcomponents.version>4.5.3</org.apache.httpcomponents.version>
<spring-test.version>5.0.5.RELEASE</spring-test.version>
</properties>
=======
<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>javax-servlets</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- File Uploading -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${org.apache.httpcomponents.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-test.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<org.apache.httpcomponents.version>4.5.3</org.apache.httpcomponents.version>
<spring-test.version>5.0.5.RELEASE</spring-test.version>
</properties>
>>>>>>> c2590b9d7ed2068984a248e213046f0cf34bdc30
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung;
public class Constants {
public static final String UPLOAD_DIRECTORY = "upload";
public static final String DEFAULT_FILENAME = "default.file";
public static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
public static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
public static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
}

View File

@ -0,0 +1,54 @@
package com.baeldung.servlets;
import com.baeldung.Constants;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import static com.baeldung.Constants.UPLOAD_DIRECTORY;
@WebServlet(
name = "MultiPartServlet",
urlPatterns = {"/multiPartServlet"}
)
@MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
public class MultipartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename"))
return content.substring(content.indexOf("=") + 2, content.length() - 1);
}
return Constants.DEFAULT_FILENAME;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists())
uploadDir.mkdir();
try {
String fileName = "";
for (Part part : request.getParts()) {
fileName = getFileName(part);
part.write(uploadPath + File.separator + fileName);
}
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
} catch (FileNotFoundException fne) {
request.setAttribute("message", "There was an error: " + fne.getMessage());
}
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.servlets;
import javax.servlet.annotation.WebServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import static com.baeldung.Constants.*;
@WebServlet(
name = "UploadServlet",
urlPatterns = {"/uploadFile"}
)
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
}
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "UploadWelcomeServlet", urlPatterns = "/uploadwelcome")
public class UploadWelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/upload.jsp").forward(request, response);
}
}

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
</web-app>

View File

@ -0,0 +1,13 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Result</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>

View File

@ -0,0 +1,23 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Demo</title>
</head>
<body>
<div>Apache FileUpload</div>
<form method="post" action="uploadFile" enctype="multipart/form-data">
Choose a file: <input type="file" name="uploadFile"/><input type="submit" value="Upload"/>
</form>
</br>
<div>Servlet Multipart</div>
<form method="post" action="multiPartServlet" enctype="multipart/form-data">
Choose a file: <input type="file" name="multiPartServlet"/><input type="submit" value="Upload"/>
</form>
</body>
</html>

Binary file not shown.

BIN
jni/native/macos/libnative.dylib Executable file

Binary file not shown.

BIN
jni/native/win32/native.dll Normal file

Binary file not shown.

15
jni/pom.xml Normal file
View File

@ -0,0 +1,15 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>jni</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,48 @@
#include "com_baeldung_jni_ExampleObjectsJNI.h"
#include <iostream>
/*
* Class: com_baeldung_jni_ExampleObjectsJNI
* Method: createUser
* Signature: (Ljava/lang/String;D)Lcom/baeldung/jni/UserData;
*/
JNIEXPORT jobject JNICALL Java_com_baeldung_jni_ExampleObjectsJNI_createUser
(JNIEnv *env, jobject thisObject, jstring name, jdouble balance){
// Create the object of the class UserData
jclass userDataClass = env->FindClass("com/baeldung/jni/UserData");
jobject newUserData = env->AllocObject(userDataClass);
// Get UserData fields to set
jfieldID nameField = env->GetFieldID(userDataClass , "name", "Ljava/lang/String;");
jfieldID balanceField = env->GetFieldID(userDataClass , "balance", "D");
// Set the values of the new object
env->SetObjectField(newUserData, nameField, name);
env->SetDoubleField(newUserData, balanceField, balance);
// Return the created object
return newUserData;
}
/*
* Class: com_baeldung_jni_ExampleObjectsJNI
* Method: printUserData
* Signature: (Lcom/baeldung/jni/UserData;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_baeldung_jni_ExampleObjectsJNI_printUserData
(JNIEnv *env, jobject thisObject, jobject userData){
// Find the class method id
jclass userDataClass = env->GetObjectClass(userData);
jmethodID methodId = env->GetMethodID(userDataClass, "getUserInfo", "()Ljava/lang/String;");
// Call the object method and get the result
jstring result = (jstring)env->CallObjectMethod(userData, methodId);
// Print the result
std::cout << "C++: User data is: " << env->GetStringUTFChars(result, NULL) << std::endl;
return result;
}

View File

@ -0,0 +1,29 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_baeldung_jni_ExampleObjectsJNI */
#ifndef _Included_com_baeldung_jni_ExampleObjectsJNI
#define _Included_com_baeldung_jni_ExampleObjectsJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_baeldung_jni_ExampleObjectsJNI
* Method: createUser
* Signature: (Ljava/lang/String;D)Lcom/baeldung/jni/UserData;
*/
JNIEXPORT jobject JNICALL Java_com_baeldung_jni_ExampleObjectsJNI_createUser
(JNIEnv *, jobject, jstring, jdouble);
/*
* Class: com_baeldung_jni_ExampleObjectsJNI
* Method: printUserData
* Signature: (Lcom/baeldung/jni/UserData;)V
*/
JNIEXPORT jstring JNICALL Java_com_baeldung_jni_ExampleObjectsJNI_printUserData
(JNIEnv *, jobject, jobject);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,34 @@
#include "com_baeldung_jni_ExampleParametersJNI.h"
#include <iostream>
#include <string>
/*
* Class: com_baeldung_jni_ExampleParametersJNI
* Method: sumIntegers
* Signature: (II)J
*/
JNIEXPORT jlong JNICALL Java_com_baeldung_jni_ExampleParametersJNI_sumIntegers (JNIEnv* env, jobject thisObject, jint first, jint second){
std::cout << "C++: The numbers received are : " << first << " and " << second << std::endl;
return (long)first + (long)second;
}
/*
* Class: com_baeldung_jni_ExampleParametersJNI
* Method: sayHelloToMe
* Signature: (Ljava/lang/String;Z)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_baeldung_jni_ExampleParametersJNI_sayHelloToMe (JNIEnv* env, jobject thisObject, jstring name, jboolean isFemale){
const char* nameCharPointer = env->GetStringUTFChars(name, NULL);
std::cout << "C++: The string received is: " << nameCharPointer << std::endl;
std::string title;
if(isFemale){
title = "Ms. ";
}
else{
title = "Mr. ";
}
std::string fullName = title + nameCharPointer;
return env->NewStringUTF(fullName.c_str());
}

View File

@ -0,0 +1,29 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_baeldung_jni_ExampleParametersJNI */
#ifndef _Included_com_baeldung_jni_ExampleParametersJNI
#define _Included_com_baeldung_jni_ExampleParametersJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_baeldung_jni_ExampleParametersJNI
* Method: sumIntegers
* Signature: (II)J
*/
JNIEXPORT jlong JNICALL Java_com_baeldung_jni_ExampleParametersJNI_sumIntegers
(JNIEnv*, jobject, jint, jint);
/*
* Class: com_baeldung_jni_ExampleParametersJNI
* Method: sayHelloToMe
* Signature: (Ljava/lang/String;Z)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_baeldung_jni_ExampleParametersJNI_sayHelloToMe
(JNIEnv*, jobject, jstring, jboolean);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,13 @@
#include "com_baeldung_jni_HelloWorldJNI.h"
#include <iostream>
/*
* Class: com_baeldung_jni_HelloWorldJNI
* Method: sayHello
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_baeldung_jni_HelloWorldJNI_sayHello (JNIEnv* env, jobject thisObject) {
std::string hello = "Hello from C++ !!";
std::cout << hello << std::endl;
return env->NewStringUTF(hello.c_str());
}

View File

@ -0,0 +1,21 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_baeldung_jni_HelloWorldJNI */
#ifndef _Included_com_baeldung_jni_HelloWorldJNI
#define _Included_com_baeldung_jni_HelloWorldJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_baeldung_jni_HelloWorldJNI
* Method: sayHello
* Signature: ()V
*/
JNIEXPORT jstring JNICALL Java_com_baeldung_jni_HelloWorldJNI_sayHello
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,6 @@
REM Create the header with javac -h . ClassName.java
REM Remember to set your JAVA_HOME env var
g++ -c -I%JAVA_HOME%\include -I%JAVA_HOME%\include\win32 com_baeldung_jni_HelloWorldJNI.cpp -o com_baeldung_jni_HelloWorldJNI.o
g++ -c -I%JAVA_HOME%\include -I%JAVA_HOME%\include\win32 com_baeldung_jni_ExampleParametersJNI.cpp -o com_baeldung_jni_ExampleParametersJNI.o
g++ -c -I%JAVA_HOME%\include -I%JAVA_HOME%\include\win32 com_baeldung_jni_ExampleObjectsJNI.cpp -o com_baeldung_jni_ExampleObjectsJNI.o
g++ -shared -o ..\..\..\native\win32\native.dll com_baeldung_jni_HelloWorldJNI.o com_baeldung_jni_ExampleParametersJNI.o com_baeldung_jni_ExampleObjectsJNI.o -Wl,--add-stdcall-alias

View File

@ -0,0 +1,7 @@
# Create the header with javac -h . ClassName.java
# Remember to set your JAVA_HOME env var
g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux com_baeldung_jni_HelloWorldJNI.cpp -o com_baeldung_jni_HelloWorldJNI.o
g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux com_baeldung_jni_ExampleParametersJNI.cpp -o com_baeldung_jni_ExampleParametersJNI.o
g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux com_baeldung_jni_ExampleObjectsJNI.cpp -o com_baeldung_jni_ExampleObjectsJNI.o
g++ -shared -fPIC -o ../../../native/linux_x86_64/libnative.so com_baeldung_jni_HelloWorldJNI.o com_baeldung_jni_ExampleParametersJNI.o com_baeldung_jni_ExampleObjectsJNI.o -lc
# Don't forget to set java.library.path to point to the folder where you have the libnative you're loading.

View File

@ -0,0 +1,6 @@
# Create the header with javac -h . ClassName.java
# Remember to set your JAVA_HOME env var
g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_HelloWorldJNI.cpp -o com_baeldung_jni_HelloWorldJNI.o
g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_ExampleParametersJNI.cpp -o com_baeldung_jni_ExampleParametersJNI.o
g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_ExampleObjectsJNI.cpp -o com_baeldung_jni_ExampleObjectsJNI.o
g++ -dynamiclib -o ../../../native/macos/libnative.dylib com_baeldung_jni_HelloWorldJNI.o com_baeldung_jni_ExampleParametersJNI.o com_baeldung_jni_ExampleObjectsJNI.o -lc

View File

@ -0,0 +1,19 @@
package com.baeldung.jni;
public class ExampleObjectsJNI {
static {
System.loadLibrary("native");
}
public static void main(String[] args) {
ExampleObjectsJNI instance = new ExampleObjectsJNI();
UserData newUser = instance.createUser("John Doe", 450.67);
instance.printUserData(newUser);
}
public native UserData createUser(String name, double balance);
public native String printUserData(UserData user);
}

View File

@ -0,0 +1,20 @@
package com.baeldung.jni;
public class ExampleParametersJNI {
static {
System.loadLibrary("native");
}
public static void main(String[] args) {
System.out.println("Java: My full name: " + new ExampleParametersJNI().sayHelloToMe("Martin", false));
long sumFromNative = new ExampleParametersJNI().sumIntegers(456, 44);
System.out.println("Java: The sum coming from native code is: " + sumFromNative);
}
// Declare another method sumIntegers that receives two integers and return a long with the sum
public native long sumIntegers(int first, int second);
// Declare another method sayHelloToMe that receives the name and gender and returns the proper salutation
public native String sayHelloToMe(String name, boolean isFemale);
}

View File

@ -0,0 +1,15 @@
package com.baeldung.jni;
public class HelloWorldJNI {
static {
System.loadLibrary("native");
}
public static void main(String[] args) {
new HelloWorldJNI().sayHello();
}
// Declare a native method sayHello() that receives no arguments and returns void
public native String sayHello();
}

View File

@ -0,0 +1,11 @@
package com.baeldung.jni;
public class UserData {
public String name;
public double balance;
public String getUserInfo() {
return "[name]=" + name + ", [balance]=" + balance;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.jni;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class JNINativeTests {
@Before
public void setup() {
System.loadLibrary("native");
}
@Test
public void whenNativeHelloWorld_thenOutputIsAsExpected() {
HelloWorldJNI helloWorld = new HelloWorldJNI();
String helloFromNative = helloWorld.sayHello();
assertTrue(!helloFromNative.isEmpty() && helloFromNative.equals("Hello from C++ !!"));
}
@Test
public void whenSumNative_thenResultIsArithmeticallyCorrect() {
ExampleParametersJNI parametersNativeMethods = new ExampleParametersJNI();
assertTrue(parametersNativeMethods.sumIntegers(200, 400) == 600L);
}
@Test
public void whenSayingNativeHelloToMe_thenResultIsAsExpected() {
ExampleParametersJNI parametersNativeMethods = new ExampleParametersJNI();
assertEquals(parametersNativeMethods.sayHelloToMe("Orange", true), "Ms. Orange");
}
@Test
public void whenCreatingNativeObject_thenObjectIsNotNullAndHasCorrectData() {
String name = "Iker Casillas";
double balance = 2378.78;
ExampleObjectsJNI objectsNativeMethods = new ExampleObjectsJNI();
UserData userFromNative = objectsNativeMethods.createUser(name, balance);
assertNotNull(userFromNative);
assertEquals(userFromNative.name, name);
assertTrue(userFromNative.balance == balance);
}
@Test
public void whenNativeCallingObjectMethod_thenResultIsAsExpected() {
String name = "Sergio Ramos";
double balance = 666.77;
ExampleObjectsJNI objectsNativeMethods = new ExampleObjectsJNI();
UserData userData = new UserData();
userData.name = name;
userData.balance = balance;
assertEquals(objectsNativeMethods.printUserData(userData), "[name]=" + name + ", [balance]=" + balance);
}
}

View File

@ -3,5 +3,9 @@
- [Introduction to ORMLite](http://www.baeldung.com/ormlite)
- [Introduction To Kryo](http://www.baeldung.com/kryo)
- [Introduction to KafkaStreams in Java](http://www.baeldung.com/java-kafka-streams)
- [Guide to Java Data Objects](http://www.baeldung.com/jdo)
- [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries)
- [Introduction to HikariCP](http://www.baeldung.com/hikaricp)
- [Introduction to JCache](http://www.baeldung.com/jcache)
- [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite)
- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data)
- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data)

View File

@ -0,0 +1 @@
log4j.rootLogger=INFO, stdout

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?><root>
</root>

View File

@ -87,6 +87,60 @@
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- Hikari CP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.7.2</version>
<scope>compile</scope>
</dependency>
<!-- JDO -->
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>javax.jdo</artifactId>
<version>3.2.0-m7</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>5.1.1</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-api-jdo</artifactId>
<version>5.1.1</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-rdbms</artifactId>
<version>5.1.1</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-maven-plugin</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-xml</artifactId>
<version>5.0.0-release</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-jdo-query</artifactId>
<version>5.0.4</version>
</dependency>
<!-- Jcache -->
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>${cache.version}</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>${hazelcast.version}</version>
</dependency>
</dependencies>
<build>
@ -176,6 +230,29 @@
</plugin>
<!-- /Reladomo -->
<!-- JDO Plugin -->
<plugin>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-maven-plugin</artifactId>
<version>5.0.2</version>
<configuration>
<api>JDO</api>
<props>${basedir}/datanucleus.properties</props>
<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
<verbose>true</verbose>
<fork>false</fork>
<!-- Solve windows line too long error -->
</configuration>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
@ -196,8 +273,10 @@
<kafka.version>1.0.0</kafka.version>
<ignite.version>2.4.0</ignite.version>
<gson.version>2.8.2</gson.version>
<cache.version>1.1.0</cache.version>
<hazelcast.version>3.8.4</hazelcast.version>
<maven-antrun-plugin.version>1.8</maven-antrun-plugin.version>
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
</properties>
</project>
</project>

View File

@ -1,96 +1,96 @@
package com.baeldung.jdo.query;
import java.util.List;
import javax.jdo.JDOQLTypedQuery;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
import org.datanucleus.metadata.PersistenceUnitMetaData;
public class MyApp {
private static PersistenceManagerFactory pmf;
private static PersistenceManager pm;
public static void main(String[] args) {
defineDynamicPersistentUnit();
createTestData();
queryUsingJDOQL();
queryUsingTypedJDOQL();
queryUsingSQL();
queryUsingJPQL();
}
public static void createTestData() {
ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut", 5);
ProductItem item2 = new ProductItem("pro2", "price less than 10", "InStock", 8);
ProductItem item3 = new ProductItem("pro3", "price more than 10", "SoldOut", 15);
if (pm != null) {
pm.makePersistent(item1);
pm.makePersistent(item2);
pm.makePersistent(item3);
}
}
public static void defineDynamicPersistentUnit() {
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db");
pumd.addProperty("javax.jdo.option.ConnectionUserName", "root");
pumd.addProperty("javax.jdo.option.ConnectionPassword", "admin");
pumd.addProperty("javax.jdo.option.ConnectionDriverName", "com.mysql.jdbc.Driver");
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
pmf = new JDOPersistenceManagerFactory(pumd, null);
pm = pmf.getPersistenceManager();
}
public static void queryUsingJDOQL() {
Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold");
List<ProductItem> explicitParamResults = (List<ProductItem>) query.execute(10);
query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
query.setParameters("double threshold");
List<ProductItem> explicitParamResults2 = (List<ProductItem>) query.execute(10);
query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
List<ProductItem> implicitParamResults = (List<ProductItem>) query.execute(10);
}
public static void queryUsingTypedJDOQL() {
JDOQLTypedQuery<ProductItem> tq = pm.newJDOQLTypedQuery(ProductItem.class);
QProductItem cand = QProductItem.candidate();
tq = tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro")));
List<ProductItem> results = tq.executeList();
}
public static void queryUsingSQL() {
Query query = pm.newQuery("javax.jdo.query.SQL", "select * from " + "product_item where price < ? and status = ?");
query.setClass(ProductItem.class);
query.setParameters(10, "InStock");
List<ProductItem> results = query.executeList();
}
public static void queryUsingJPQL() {
Query query = pm.newQuery("JPQL", "select i from " + "com.baeldung.jdo.query.ProductItem i where i.price < 10" + " and i.status = 'InStock'");
List<ProductItem> results = (List<ProductItem>) query.execute();
}
public static void namedQuery() {
Query<ProductItem> query = pm.newNamedQuery(ProductItem.class, "PriceBelow10");
List<ProductItem> results = query.executeList();
}
}
package com.baeldung.jdo.query;
import java.util.List;
import javax.jdo.JDOQLTypedQuery;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
import org.datanucleus.metadata.PersistenceUnitMetaData;
public class MyApp {
private static PersistenceManagerFactory pmf;
private static PersistenceManager pm;
public static void main(String[] args) {
defineDynamicPersistentUnit();
createTestData();
queryUsingJDOQL();
queryUsingTypedJDOQL();
queryUsingSQL();
queryUsingJPQL();
}
public static void createTestData() {
ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut", 5);
ProductItem item2 = new ProductItem("pro2", "price less than 10", "InStock", 8);
ProductItem item3 = new ProductItem("pro3", "price more than 10", "SoldOut", 15);
if (pm != null) {
pm.makePersistent(item1);
pm.makePersistent(item2);
pm.makePersistent(item3);
}
}
public static void defineDynamicPersistentUnit() {
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db");
pumd.addProperty("javax.jdo.option.ConnectionUserName", "root");
pumd.addProperty("javax.jdo.option.ConnectionPassword", "admin");
pumd.addProperty("javax.jdo.option.ConnectionDriverName", "com.mysql.jdbc.Driver");
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
pmf = new JDOPersistenceManagerFactory(pumd, null);
pm = pmf.getPersistenceManager();
}
public static void queryUsingJDOQL() {
Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold");
List<ProductItem> explicitParamResults = (List<ProductItem>) query.execute(10);
query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
query.setParameters("double threshold");
List<ProductItem> explicitParamResults2 = (List<ProductItem>) query.execute(10);
query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
List<ProductItem> implicitParamResults = (List<ProductItem>) query.execute(10);
}
public static void queryUsingTypedJDOQL() {
JDOQLTypedQuery<ProductItem> tq = pm.newJDOQLTypedQuery(ProductItem.class);
QProductItem cand = QProductItem.candidate();
tq = tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro")));
List<ProductItem> results = tq.executeList();
}
public static void queryUsingSQL() {
Query query = pm.newQuery("javax.jdo.query.SQL", "select * from " + "product_item where price < ? and status = ?");
query.setClass(ProductItem.class);
query.setParameters(10, "InStock");
List<ProductItem> results = query.executeList();
}
public static void queryUsingJPQL() {
Query query = pm.newQuery("JPQL", "select i from " + "com.baeldung.jdo.query.ProductItem i where i.price < 10" + " and i.status = 'InStock'");
List<ProductItem> results = (List<ProductItem>) query.execute();
}
public static void namedQuery() {
Query<ProductItem> query = pm.newNamedQuery(ProductItem.class, "PriceBelow10");
List<ProductItem> results = query.executeList();
}
}

View File

@ -1,70 +1,70 @@
package com.baeldung.jdo.query;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
@PersistenceCapable(table = "product_item")
public class ProductItem {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT)
int id;
String name;
String description;
String status;
double price;
public ProductItem() {
}
public ProductItem(String name, String description, String status, double price) {
this.name = name;
this.description = description;
this.status = status;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
package com.baeldung.jdo.query;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
@PersistenceCapable(table = "product_item")
public class ProductItem {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT)
int id;
String name;
String description;
String status;
double price;
public ProductItem() {
}
public ProductItem(String name, String description, String status, double price) {
this.name = name;
this.description = description;
this.status = status;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}

View File

@ -1,66 +1,66 @@
package com.baeldung.jdo.xml;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.annotations.Element;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
@PersistenceCapable(schema = "/myproduct/people", table = "person")
public class AnnotadedPerson {
@XmlAttribute
private long personNum;
@PrimaryKey
private String firstName;
private String lastName;
@XmlElementWrapper(name = "phone-numbers")
@XmlElement(name = "phone-number")
@Element(types = String.class)
private List phoneNumbers = new ArrayList();
public AnnotadedPerson(long personNum, String firstName, String lastName) {
super();
this.personNum = personNum;
this.firstName = firstName;
this.lastName = lastName;
}
public long getPersonNum() {
return personNum;
}
public void setPersonNum(long personNum) {
this.personNum = personNum;
}
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 List getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}
package com.baeldung.jdo.xml;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.annotations.Element;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
@PersistenceCapable(schema = "/myproduct/people", table = "person")
public class AnnotadedPerson {
@XmlAttribute
private long personNum;
@PrimaryKey
private String firstName;
private String lastName;
@XmlElementWrapper(name = "phone-numbers")
@XmlElement(name = "phone-number")
@Element(types = String.class)
private List phoneNumbers = new ArrayList();
public AnnotadedPerson(long personNum, String firstName, String lastName) {
super();
this.personNum = personNum;
this.firstName = firstName;
this.lastName = lastName;
}
public long getPersonNum() {
return personNum;
}
public void setPersonNum(long personNum) {
this.personNum = personNum;
}
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 List getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}

View File

@ -1,105 +1,105 @@
package com.baeldung.jdo.xml;
import java.util.List;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
import org.datanucleus.metadata.PersistenceUnitMetaData;
public class MyApp {
private static PersistenceUnitMetaData pumd;
private static PersistenceManagerFactory pmf;
private static PersistenceManager pm;
public static void main(String[] args) {
// persist product object using dynamic persistence unit
defineDynamicPersistentUnit();
Product product = new Product("id1", "Sony Discman", "A standard discman from Sony", 49.99);
persistObject(product);
closePersistenceManager();
// persist AnnotatedPerson object using named pmf
defineNamedPersistenceManagerFactory("XmlDatastore");
AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320, "annotated", "person");
annotatedPerson.getPhoneNumbers().add("999999999");
annotatedPerson.getPhoneNumbers().add("000000000");
persistObject(annotatedPerson);
queryAnnotatedPersonsInXML();
closePersistenceManager();
// persist Person object using PMF created by properties file
definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties");
Person person = new Person(654321, "bealdung", "author");
person.getPhoneNumbers().add("123456789");
person.getPhoneNumbers().add("987654321");
persistObject(person);
queryPersonsInXML();
closePersistenceManager();
}
public static void defineDynamicPersistentUnit() {
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml");
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
pumd.addProperty("datanucleus.xml.indentSize", "4");
pmf = new JDOPersistenceManagerFactory(pumd, null);
pm = pmf.getPersistenceManager();
}
public static void defineNamedPersistenceManagerFactory(String pmfName) {
pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore");
pm = pmf.getPersistenceManager();
}
public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath) {
pmf = JDOHelper.getPersistenceManagerFactory(filePath);
pm = pmf.getPersistenceManager();
}
public static void closePersistenceManager() {
if (pm != null && !pm.isClosed()) {
pm.close();
}
}
public static void persistObject(Object obj) {
Transaction tx = pm.currentTransaction();
try {
tx.begin();
pm.makePersistent(obj);
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
public static void queryPersonsInXML() {
Query<Person> query = pm.newQuery(Person.class);
List<Person> result = query.executeList();
System.out.println("name: " + result.get(0).getFirstName());
}
public static void queryAnnotatedPersonsInXML() {
Query<AnnotadedPerson> query = pm.newQuery(AnnotadedPerson.class);
List<AnnotadedPerson> result = query.executeList();
System.out.println("name: " + result.get(0).getFirstName());
}
}
package com.baeldung.jdo.xml;
import java.util.List;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
import org.datanucleus.metadata.PersistenceUnitMetaData;
public class MyApp {
private static PersistenceUnitMetaData pumd;
private static PersistenceManagerFactory pmf;
private static PersistenceManager pm;
public static void main(String[] args) {
// persist product object using dynamic persistence unit
defineDynamicPersistentUnit();
Product product = new Product("id1", "Sony Discman", "A standard discman from Sony", 49.99);
persistObject(product);
closePersistenceManager();
// persist AnnotatedPerson object using named pmf
defineNamedPersistenceManagerFactory("XmlDatastore");
AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320, "annotated", "person");
annotatedPerson.getPhoneNumbers().add("999999999");
annotatedPerson.getPhoneNumbers().add("000000000");
persistObject(annotatedPerson);
queryAnnotatedPersonsInXML();
closePersistenceManager();
// persist Person object using PMF created by properties file
definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties");
Person person = new Person(654321, "bealdung", "author");
person.getPhoneNumbers().add("123456789");
person.getPhoneNumbers().add("987654321");
persistObject(person);
queryPersonsInXML();
closePersistenceManager();
}
public static void defineDynamicPersistentUnit() {
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml");
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
pumd.addProperty("datanucleus.xml.indentSize", "4");
pmf = new JDOPersistenceManagerFactory(pumd, null);
pm = pmf.getPersistenceManager();
}
public static void defineNamedPersistenceManagerFactory(String pmfName) {
pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore");
pm = pmf.getPersistenceManager();
}
public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath) {
pmf = JDOHelper.getPersistenceManagerFactory(filePath);
pm = pmf.getPersistenceManager();
}
public static void closePersistenceManager() {
if (pm != null && !pm.isClosed()) {
pm.close();
}
}
public static void persistObject(Object obj) {
Transaction tx = pm.currentTransaction();
try {
tx.begin();
pm.makePersistent(obj);
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
public static void queryPersonsInXML() {
Query<Person> query = pm.newQuery(Person.class);
List<Person> result = query.executeList();
System.out.println("name: " + result.get(0).getFirstName());
}
public static void queryAnnotatedPersonsInXML() {
Query<AnnotadedPerson> query = pm.newQuery(AnnotadedPerson.class);
List<AnnotadedPerson> result = query.executeList();
System.out.println("name: " + result.get(0).getFirstName());
}
}

View File

@ -1,58 +1,58 @@
package com.baeldung.jdo.xml;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
@PersistenceCapable
public class Person {
private long personNum;
@PrimaryKey
private String firstName;
private String lastName;
private List phoneNumbers = new ArrayList();
public Person(long personNum, String firstName, String lastName) {
super();
this.personNum = personNum;
this.firstName = firstName;
this.lastName = lastName;
}
public long getPersonNum() {
return personNum;
}
public void setPersonNum(long personNum) {
this.personNum = personNum;
}
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 List getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}
package com.baeldung.jdo.xml;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
@PersistenceCapable
public class Person {
private long personNum;
@PrimaryKey
private String firstName;
private String lastName;
private List phoneNumbers = new ArrayList();
public Person(long personNum, String firstName, String lastName) {
super();
this.personNum = personNum;
this.firstName = firstName;
this.lastName = lastName;
}
public long getPersonNum() {
return personNum;
}
public void setPersonNum(long personNum) {
this.personNum = personNum;
}
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 List getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}

View File

@ -1,58 +1,58 @@
package com.baeldung.jdo.xml;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
@PersistenceCapable
public class Product {
@PrimaryKey
String id;
String name;
String description;
double price;
public Product() {
}
public Product(String id, String name, String description, double price) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
package com.baeldung.jdo.xml;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
@PersistenceCapable
public class Product {
@PrimaryKey
String id;
String name;
String description;
double price;
public Product() {
}
public Product(String id, String name, String description, double price) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}

View File

@ -0,0 +1,4 @@
javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.api.jdo.JDOPersistenceManagerFactory
javax.jdo.option.ConnectionURL= xml:file:myfile-ds.xml
datanucleus.xml.indentSize=6
datanucleus.schema.autoCreateAll=true

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<jdoconfig xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig
http://xmlns.jcp.org/xml/ns/jdo/jdoconfig_3_2.xsd"
version="3.2">
<!-- Datastore Txn PMF -->
<persistence-manager-factory name="XmlDatastore">
<property name="javax.jdo.PersistenceManagerFactoryClass"
value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory" />
<property name="javax.jdo.option.ConnectionURL" value="xml:file:namedPMF-ds.xml" />
<property name="datanucleus.xml.indentSize" value="6" />
<property name="datanucleus.schema.autoCreateAll"
value="true" />
</persistence-manager-factory>
<?xml version="1.0" encoding="UTF-8"?>
<jdoconfig xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdoconfig
http://xmlns.jcp.org/xml/ns/jdo/jdoconfig_3_2.xsd"
version="3.2">
<!-- Datastore Txn PMF -->
<persistence-manager-factory name="XmlDatastore">
<property name="javax.jdo.PersistenceManagerFactoryClass"
value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory" />
<property name="javax.jdo.option.ConnectionURL" value="xml:file:namedPMF-ds.xml" />
<property name="datanucleus.xml.indentSize" value="6" />
<property name="datanucleus.schema.autoCreateAll"
value="true" />
</persistence-manager-factory>
</jdoconfig>

View File

@ -1,29 +1,29 @@
<jdo xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdo http://xmlns.jcp.org/xml/ns/jdo/jdo_3_1.xsd"
version="3.1">
<package name="com.baeldung.jdo.xml">
<class name="Person" detachable="true" schema="/myproduct/people"
table="person">
<field name="personNum">
<extension vendor-name="datanucleus" key="XmlAttribute"
value="true" />
</field>
<field name="firstName" primary-key="true" /> <!-- PK since JAXB requires String -->
<field name="lastName" />
<field name="phoneNumbers">
<collection element-type="java.lang.String" />
<element column="phoneNumber" />
</field>
</class>
</package>
<package name="com.baeldung.jdo.query">
<class name="ProductItem" detachable="true" table="product_item">
<query name="PriceBelow10" language="javax.jdo.query.SQL">
<![CDATA[SELECT * FROM PRODUCT_ITEM WHERE PRICE < 10
]]></query>
</class>
</package>
<jdo xmlns="http://xmlns.jcp.org/xml/ns/jdo/jdo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jdo/jdo http://xmlns.jcp.org/xml/ns/jdo/jdo_3_1.xsd"
version="3.1">
<package name="com.baeldung.jdo.xml">
<class name="Person" detachable="true" schema="/myproduct/people"
table="person">
<field name="personNum">
<extension vendor-name="datanucleus" key="XmlAttribute"
value="true" />
</field>
<field name="firstName" primary-key="true" /> <!-- PK since JAXB requires String -->
<field name="lastName" />
<field name="phoneNumbers">
<collection element-type="java.lang.String" />
<element column="phoneNumber" />
</field>
</class>
</package>
<package name="com.baeldung.jdo.query">
<class name="ProductItem" detachable="true" table="product_item">
<query name="PriceBelow10" language="javax.jdo.query.SQL">
<![CDATA[SELECT * FROM PRODUCT_ITEM WHERE PRICE < 10
]]></query>
</class>
</package>
</jdo>

View File

@ -21,7 +21,8 @@ public class CacheLoaderTest {
@Before
public void setup() {
CachingProvider cachingProvider = Caching.getCachingProvider();
// Adding fully qualified class name because of multiple Cache Provider (Ignite and Hazelcast)
CachingProvider cachingProvider = Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider");
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration<Integer, String> config = new MutableConfiguration<Integer, String>().setReadThrough(true).setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader()));
this.cache = cacheManager.createCache("SimpleCache", config);
@ -29,7 +30,7 @@ public class CacheLoaderTest {
@After
public void tearDown() {
Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME);
Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider").getCacheManager().destroyCache(CACHE_NAME);
}
@Test
@ -39,4 +40,4 @@ public class CacheLoaderTest {
assertEquals("fromCache" + i, value);
}
}
}
}

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