Merge branch 'master' into BAEL-614

This commit is contained in:
Tomasz Lelek 2017-01-29 11:43:17 +01:00 committed by GitHub
commit afa9292544
43 changed files with 31140 additions and 55 deletions

1
.gitignore vendored
View File

@ -27,3 +27,4 @@ target/
spring-openid/src/main/resources/application.properties
.recommenders/
/spring-hibernate4/nbproject/

View File

@ -9,30 +9,8 @@ import java.util.function.Function;
import static org.junit.Assert.assertEquals;
public class CollectorImprovementTest {
private static class Blog {
private String authorName;
private List<String> comments;
public Blog(String authorName) {
this.authorName = authorName;
this.comments = new LinkedList<String>();
}
public String getAuthorName() {
return this.authorName;
}
public List<String> getComments() {
return new LinkedList<String>(this.comments);
}
public void addComment(String comment) {
this.comments.add(comment);
}
}
@Test
public void testFiltering() {
@Test
public void givenList_whenSatifyPredicate_thenMapValueWithOccurences() {
List<Integer> numbers = List.of(1, 2, 3, 5, 5);
Map<Integer, Long> result = numbers.stream()
@ -49,14 +27,9 @@ public class CollectorImprovementTest {
}
@Test
public void testFlatMapping() {
Blog blog1 = new CollectorImprovementTest.Blog("1");
blog1.addComment("Nice");
blog1.addComment("Very Nice");
Blog blog2 = new CollectorImprovementTest.Blog("2");
blog2.addComment("Disappointing");
blog2.addComment("Ok");
blog2.addComment("Could be better");
public void givenListOfBlogs_whenAuthorName_thenMapAuthorWithComments() {
Blog blog1 = new Blog("1", "Nice", "Very Nice");
Blog blog2 = new Blog("2", "Disappointing", "Ok", "Could be better");
List<Blog> blogs = List.of(blog1, blog2);
Map<String, List<List<String>>> authorComments1 =
@ -79,3 +52,21 @@ public class CollectorImprovementTest {
assertEquals(3, authorComments2.get("2").size());
}
}
class Blog {
private String authorName;
private List<String> comments;
public Blog(String authorName, String... comments) {
this.authorName = authorName;
this.comments = List.of(comments);
}
public String getAuthorName() {
return this.authorName;
}
public List<String> getComments() {
return this.comments;
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.concurrent.blockingqueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
@ -12,7 +11,6 @@ public class BlockingQueueUsage {
int poisonPill = Integer.MAX_VALUE;
int poisonPillPerProducer = N_CONSUMERS / N_PRODUCERS;
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(BOUND);
for (int i = 0; i < N_PRODUCERS; i++) {

View File

@ -1,9 +1,8 @@
package com.baeldung.concurrent.blockingqueue;
import java.util.concurrent.BlockingQueue;
class NumbersConsumer implements Runnable {
public class NumbersConsumer implements Runnable {
private final BlockingQueue<Integer> queue;
private final int poisonPill;
@ -21,7 +20,6 @@ class NumbersConsumer implements Runnable {
}
String result = number.toString();
System.out.println(Thread.currentThread().getName() + " result: " + result);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();

View File

@ -1,23 +1,22 @@
package com.baeldung.concurrent.blockingqueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadLocalRandom;
public class NumbersProducer implements Runnable {
class NumbersProducer implements Runnable {
private final BlockingQueue<Integer> numbersQueue;
private final int poisonPill;
private final int poisonPillPerProducer;
public NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
this.numbersQueue = numbersQueue;
this.poisonPill = poisonPill;
this.poisonPillPerProducer = poisonPillPerProducer;
}
public void run() {
try {
generateNumbers();

View File

@ -16,7 +16,7 @@ public class Worker implements Runnable {
public void run() {
// Do some work
System.out.println("Doing some logic");
countDownLatch.countDown();
outputScraper.add("Counted down");
countDownLatch.countDown();
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.concurrent.future;
import java.util.concurrent.RecursiveTask;
public class FactorialSquareCalculator extends RecursiveTask<Integer> {
private static final long serialVersionUID = 1L;
final private Integer n;
public FactorialSquareCalculator(Integer n) {
this.n = n;
}
@Override
protected Integer compute() {
if (n <= 1) {
return n;
}
FactorialSquareCalculator calculator = new FactorialSquareCalculator(n - 1);
calculator.fork();
return n * n + calculator.join();
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.concurrent.future;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class SquareCalculator {
private final ExecutorService executor;
public SquareCalculator(ExecutorService executor) {
this.executor = executor;
}
public Future<Integer> calculate(Integer input) {
return executor.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(1000);
return input * input;
}
});
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.concurrent.future;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ForkJoinPool;
import org.junit.Test;
public class FactorialSquareCalculatorUnitTest {
@Test
public void whenCalculatesFactorialSquare_thenReturnCorrectValue() {
ForkJoinPool forkJoinPool = new ForkJoinPool();
FactorialSquareCalculator calculator = new FactorialSquareCalculator(10);
forkJoinPool.execute(calculator);
assertEquals("The sum of the squares from 1 to 10 is 385", 385, calculator.join().intValue());
}
}

View File

@ -0,0 +1,94 @@
package com.baeldung.concurrent.future;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
public class SquareCalculatorUnitTest {
@Rule
public TestName name = new TestName();
private long start;
private SquareCalculator squareCalculator;
@Test
public void givenExecutorIsSingleThreaded_whenTwoExecutionsAreTriggered_thenRunInSequence() throws InterruptedException, ExecutionException {
squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor());
Future<Integer> result1 = squareCalculator.calculate(4);
Future<Integer> result2 = squareCalculator.calculate(1000);
while (!result1.isDone() || !result2.isDone()) {
System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done"));
Thread.sleep(300);
}
assertEquals(16, result1.get().intValue());
assertEquals(1000000, result2.get().intValue());
}
@Test(expected = TimeoutException.class)
public void whenGetWithTimeoutLowerThanExecutionTime_thenThrowException() throws InterruptedException, ExecutionException, TimeoutException {
squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor());
Future<Integer> result = squareCalculator.calculate(4);
result.get(500, TimeUnit.MILLISECONDS);
}
@Test
public void givenExecutorIsMultiThreaded_whenTwoExecutionsAreTriggered_thenRunInParallel() throws InterruptedException, ExecutionException {
squareCalculator = new SquareCalculator(Executors.newFixedThreadPool(2));
Future<Integer> result1 = squareCalculator.calculate(4);
Future<Integer> result2 = squareCalculator.calculate(1000);
while (!result1.isDone() || !result2.isDone()) {
System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done"));
Thread.sleep(300);
}
assertEquals(16, result1.get().intValue());
assertEquals(1000000, result2.get().intValue());
}
@Test(expected = CancellationException.class)
public void whenCancelFutureAndCallGet_thenThrowException() throws InterruptedException, ExecutionException, TimeoutException {
squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor());
Future<Integer> result = squareCalculator.calculate(4);
boolean canceled = result.cancel(true);
assertTrue("Future was canceled", canceled);
assertTrue("Future was canceled", result.isCancelled());
result.get();
}
@Before
public void start() {
start = System.currentTimeMillis();
}
@After
public void end() {
System.out.println(String.format("Test %s took %s ms \n", name.getMethodName(), System.currentTimeMillis() - start));
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.java.concurrentmap;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class ConcurrentMapAggregateStatusTest {
private ExecutorService executorService;
private Map<String, Integer> concurrentMap;
private List<Integer> mapSizes;
private int MAX_SIZE = 100000;
@Before
public void init() {
executorService = Executors.newFixedThreadPool(2);
concurrentMap = new ConcurrentHashMap<>();
mapSizes = new ArrayList<>(MAX_SIZE);
}
@Test
public void givenConcurrentMap_whenSizeWithoutConcurrentUpdates_thenCorrect() throws InterruptedException {
Runnable collectMapSizes = () -> {
for (int i = 0; i < MAX_SIZE; i++) {
concurrentMap.put(String.valueOf(i), i);
mapSizes.add(concurrentMap.size());
}
};
Runnable retrieveMapData = () -> {
for (int i = 0; i < MAX_SIZE; i++) {
concurrentMap.get(String.valueOf(i));
}
};
executorService.execute(retrieveMapData);
executorService.execute(collectMapSizes);
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
for (int i = 1; i <= MAX_SIZE; i++) {
assertEquals("map size should be consistently reliable", i, mapSizes
.get(i - 1)
.intValue());
}
assertEquals(MAX_SIZE, concurrentMap.size());
}
@Test
public void givenConcurrentMap_whenUpdatingAndGetSize_thenError() throws InterruptedException {
Runnable collectMapSizes = () -> {
for (int i = 0; i < MAX_SIZE; i++) {
mapSizes.add(concurrentMap.size());
}
};
Runnable updateMapData = () -> {
for (int i = 0; i < MAX_SIZE; i++) {
concurrentMap.put(String.valueOf(i), i);
}
};
executorService.execute(updateMapData);
executorService.execute(collectMapSizes);
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes
.get(MAX_SIZE - 1)
.intValue());
assertEquals(MAX_SIZE, concurrentMap.size());
}
}

View File

@ -0,0 +1,160 @@
package com.baeldung.java.concurrentmap;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.junit.Assert.assertNull;
public class ConcurrentMapNullKeyValueTest {
ConcurrentMap<String, Object> concurrentMap;
@Before
public void setup() {
concurrentMap = new ConcurrentHashMap<>();
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenGetWithNullKey_thenThrowsNPE() {
concurrentMap.get(null);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenGetOrDefaultWithNullKey_thenThrowsNPE() {
concurrentMap.getOrDefault(null, new Object());
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenPutWithNullKey_thenThrowsNPE() {
concurrentMap.put(null, new Object());
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenPutNullValue_thenThrowsNPE() {
concurrentMap.put("test", null);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMapAndKeyAbsent_whenPutWithNullKey_thenThrowsNPE() {
concurrentMap.putIfAbsent(null, new Object());
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMapAndMapWithNullKey_whenPutNullKeyMap_thenThrowsNPE() {
Map<String, Object> nullKeyMap = new HashMap<>();
nullKeyMap.put(null, new Object());
concurrentMap.putAll(nullKeyMap);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMapAndMapWithNullValue_whenPutNullValueMap_thenThrowsNPE() {
Map<String, Object> nullValueMap = new HashMap<>();
nullValueMap.put("test", null);
concurrentMap.putAll(nullValueMap);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenReplaceNullKeyWithValues_thenThrowsNPE() {
concurrentMap.replace(null, new Object(), new Object());
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenReplaceWithNullNewValue_thenThrowsNPE() {
Object o = new Object();
concurrentMap.replace("test", o, null);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenReplaceOldNullValue_thenThrowsNPE() {
Object o = new Object();
concurrentMap.replace("test", null, o);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenReplaceWithNullValue_thenThrowsNPE() {
concurrentMap.replace("test", null);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenReplaceNullKey_thenThrowsNPE() {
concurrentMap.replace(null, "test");
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenReplaceAllMappingNull_thenThrowsNPE() {
concurrentMap.put("test", new Object());
concurrentMap.replaceAll((s, o) -> null);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenRemoveNullKey_thenThrowsNPE() {
concurrentMap.remove(null);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenRemoveNullKeyWithValue_thenThrowsNPE() {
concurrentMap.remove(null, new Object());
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenMergeNullKeyWithValue_thenThrowsNPE() {
concurrentMap.merge(null, new Object(), (o, o2) -> o2);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenMergeKeyWithNullValue_thenThrowsNPE() {
concurrentMap.put("test", new Object());
concurrentMap.merge("test", null, (o, o2) -> o2);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMapAndAssumeKeyAbsent_whenComputeWithNullKey_thenThrowsNPE() {
concurrentMap.computeIfAbsent(null, s -> s);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMapAndAssumeKeyPresent_whenComputeWithNullKey_thenThrowsNPE() {
concurrentMap.computeIfPresent(null, (s, o) -> o);
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHashMap_whenComputeWithNullKey_thenThrowsNPE() {
concurrentMap.compute(null, (s, o) -> o);
}
@Test
public void givenConcurrentHashMap_whenMergeKeyRemappingNull_thenRemovesMapping() {
Object oldValue = new Object();
concurrentMap.put("test", oldValue);
concurrentMap.merge("test", new Object(), (o, o2) -> null);
assertNull(concurrentMap.get("test"));
}
@Test
public void givenConcurrentHashMapAndKeyAbsent_whenComputeWithKeyRemappingNull_thenRemainsAbsent() {
concurrentMap.computeIfPresent("test", (s, o) -> null);
assertNull(concurrentMap.get("test"));
}
@Test
public void givenKeyPresent_whenComputeIfPresentRemappingNull_thenMappingRemoved() {
Object oldValue = new Object();
concurrentMap.put("test", oldValue);
concurrentMap.computeIfPresent("test", (s, o) -> null);
assertNull(concurrentMap.get("test"));
}
@Test
public void givenKeyPresent_whenComputeRemappingNull_thenMappingRemoved() {
Object oldValue = new Object();
concurrentMap.put("test", oldValue);
concurrentMap.compute("test", (s, o) -> null);
assertNull(concurrentMap.get("test"));
}
}

View File

@ -0,0 +1,98 @@
package com.baeldung.java.concurrentmap;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class ConcurrentMapPerformanceTest {
@Test
public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception {
Map<String, Object> hashtable = new Hashtable<>();
Map<String, Object> synchronizedHashMap = Collections.synchronizedMap(new HashMap<>());
Map<String, Object> concurrentHashMap = new ConcurrentHashMap<>();
long hashtableAvgRuntime = timeElapseForGetPut(hashtable);
long syncHashMapAvgRuntime = timeElapseForGetPut(synchronizedHashMap);
long concurrentHashMapAvgRuntime = timeElapseForGetPut(concurrentHashMap);
assertTrue(hashtableAvgRuntime > concurrentHashMapAvgRuntime);
assertTrue(syncHashMapAvgRuntime > concurrentHashMapAvgRuntime);
System.out.println(String.format("Hashtable: %s, syncHashMap: %s, ConcurrentHashMap: %s", hashtableAvgRuntime, syncHashMapAvgRuntime, concurrentHashMapAvgRuntime));
}
private long timeElapseForGetPut(Map<String, Object> map) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(4);
long startTime = System.nanoTime();
for (int i = 0; i < 4; i++) {
executorService.execute(() -> {
for (int j = 0; j < 500_000; j++) {
int value = ThreadLocalRandom
.current()
.nextInt(10000);
String key = String.valueOf(value);
map.put(key, value);
map.get(key);
}
});
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
return (System.nanoTime() - startTime) / 500_000;
}
@Test
public void givenConcurrentMap_whenKeyWithSameHashCode_thenPerformanceDegrades() throws InterruptedException {
class SameHash {
@Override
public int hashCode() {
return 1;
}
}
int executeTimes = 5000;
Map<SameHash, Integer> mapOfSameHash = new ConcurrentHashMap<>();
ExecutorService executorService = Executors.newFixedThreadPool(2);
long sameHashStartTime = System.currentTimeMillis();
for (int i = 0; i < 2; i++) {
executorService.execute(() -> {
for (int j = 0; j < executeTimes; j++) {
mapOfSameHash.put(new SameHash(), 1);
}
});
}
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);
long mapOfSameHashDuration = System.currentTimeMillis() - sameHashStartTime;
Map<Object, Integer> mapOfDefaultHash = new ConcurrentHashMap<>();
executorService = Executors.newFixedThreadPool(2);
long defaultHashStartTime = System.currentTimeMillis();
for (int i = 0; i < 2; i++) {
executorService.execute(() -> {
for (int j = 0; j < executeTimes; j++) {
mapOfDefaultHash.put(new Object(), 1);
}
});
}
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);
long mapOfDefaultHashDuration = System.currentTimeMillis() - defaultHashStartTime;
assertEquals(executeTimes * 2, mapOfDefaultHash.size());
assertNotEquals(executeTimes * 2, mapOfSameHash.size());
System.out.println(String.format("same-hash: %s, default-hash: %s", mapOfSameHashDuration, mapOfDefaultHashDuration));
assertTrue("same hashCode() should greatly degrade performance", mapOfSameHashDuration > mapOfDefaultHashDuration * 10);
}
}

View File

@ -0,0 +1,78 @@
package com.baeldung.java.concurrentmap;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class ConcurretMapMemoryConsistencyTest {
@Test
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
Map<String, Integer> map = new ConcurrentHashMap<>();
List<Integer> sumList = parallelSum100(map, 1000);
assertEquals(1, sumList
.stream()
.distinct()
.count());
long wrongResultCount = sumList
.stream()
.filter(num -> num != 100)
.count();
assertEquals(0, wrongResultCount);
}
@Test
public void givenHashtable_whenSumParallel_thenCorrect() throws Exception {
Map<String, Integer> map = new Hashtable<>();
List<Integer> sumList = parallelSum100(map, 1000);
assertEquals(1, sumList
.stream()
.distinct()
.count());
long wrongResultCount = sumList
.stream()
.filter(num -> num != 100)
.count();
assertEquals(0, wrongResultCount);
}
@Test
public void givenHashMap_whenSumParallel_thenError() throws Exception {
Map<String, Integer> map = new HashMap<>();
List<Integer> sumList = parallelSum100(map, 100);
assertNotEquals(1, sumList
.stream()
.distinct()
.count());
long wrongResultCount = sumList
.stream()
.filter(num -> num != 100)
.count();
assertTrue(wrongResultCount > 0);
}
private List<Integer> parallelSum100(Map<String, Integer> map, int executionTimes) throws InterruptedException {
List<Integer> sumList = new ArrayList<>(1000);
for (int i = 0; i < executionTimes; i++) {
map.put("test", 0);
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int j = 0; j < 10; j++) {
executorService.execute(() -> {
for (int k = 0; k < 10; k++)
map.computeIfPresent("test", (key, value) -> value + 1);
});
}
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);
sumList.add(map.get("test"));
}
return sumList;
}
}

View File

@ -0,0 +1,141 @@
package org.baeldung.guava;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import org.junit.Test;
import static com.google.common.base.Preconditions.*;
public class GuavaPreConditionsTest {
@Test(expected = IllegalArgumentException.class)
public void whenCheckArgumentEvaluatesFalse_throwsException() {
int age = -18;
checkArgument(age > 0);
}
@Test
public void givenErrorMessage_whenCheckArgumentEvaluatesFalse_throwsException() {
final int age = -18;
final String message = "Age can't be zero or less than zero";
try {
checkArgument(age > 0, message);
} catch (IllegalArgumentException illegalArgumentException) {
assertEquals(message, illegalArgumentException.getMessage());
}
}
@Test
public void givenTemplatedErrorMessage_whenCheckArgumentEvaluatesFalse_throwsException() {
final int age = -18;
final String message = "Age can't be zero or less than zero, you supplied %s.";
try {
checkArgument(age > 0, message, age);
} catch (IllegalArgumentException illegalArgumentException) {
final String formattedMessage = String.format(message, age);
assertEquals(formattedMessage, illegalArgumentException.getMessage());
}
}
@Test(expected = IndexOutOfBoundsException.class)
public void givenArrayOfIntegers_whenCheckElementIndexEvaluatesFalse_throwsException() {
final int[] numbers = { 1, 2, 3, 4, 5 };
checkElementIndex(6, numbers.length - 1);
}
@Test
public void givenArrayOfIntegersAndMessage_whenCheckElementIndexEvaluatesFalse_throwsException() {
final int[] numbers = { 1, 2, 3, 4, 5 };
final String message = "Please check the bound of an array and retry";
try {
checkElementIndex(6, numbers.length - 1, message);
} catch (IndexOutOfBoundsException indexOutOfBoundsException) {
assertTrue(indexOutOfBoundsException.getMessage().startsWith(message));
}
}
@Test(expected = NullPointerException.class)
public void givenNullString_whenCheckNotNullCalled_throwsException() {
final String nullObject = null;
checkNotNull(nullObject);
}
@Test
public void givenNullString_whenCheckNotNullCalledWithMessage_throwsException() {
final String nullObject = null;
final String message = "Please check the Object supplied, its null!";
try {
checkNotNull(nullObject, message);
} catch (NullPointerException nullPointerException) {
assertEquals(message, nullPointerException.getMessage());
}
}
@Test
public void givenNullString_whenCheckNotNullCalledWithTemplatedMessage_throwsException() {
final String nullObject = null;
final String message = "Please check the Object supplied, its %s!";
try {
checkNotNull(nullObject, message, nullObject);
} catch (NullPointerException nullPointerException) {
final String formattedMessage = String.format(message, nullObject);
assertEquals(formattedMessage, nullPointerException.getMessage());
}
}
@Test(expected = IndexOutOfBoundsException.class)
public void givenArrayOfIntegers_whenCheckPositionIndexEvaluatesFalse_throwsException() {
final int[] numbers = { 1, 2, 3, 4, 5 };
checkPositionIndex(6, numbers.length - 1);
}
@Test
public void givenArrayOfIntegersAndMessage_whenCheckPositionIndexEvaluatesFalse_throwsException() {
final int[] numbers = { 1, 2, 3, 4, 5 };
final String message = "Please check the bound of an array and retry";
try {
checkPositionIndex(6, numbers.length - 1, message);
} catch (IndexOutOfBoundsException indexOutOfBoundsException) {
assertTrue(indexOutOfBoundsException.getMessage().startsWith(message));
}
}
@Test(expected = IndexOutOfBoundsException.class)
public void givenArrayOfIntegers_whenCheckPositionIndexesEvaluatesFalse_throwsException() {
final int[] numbers = { 1, 2, 3, 4, 5 };
checkPositionIndexes(6, 0, numbers.length - 1);
}
@Test(expected = IllegalStateException.class)
public void givenValidStates_whenCheckStateEvaluatesFalse_throwsException() {
final int[] validStates = { -1, 0, 1 };
final int givenState = 10;
checkState(Arrays.binarySearch(validStates, givenState) > 0);
}
@Test
public void givenValidStatesAndMessage_whenCheckStateEvaluatesFalse_throwsException() {
final int[] validStates = { -1, 0, 1 };
final int givenState = 10;
final String message = "You have entered an invalid state";
try {
checkState(Arrays.binarySearch(validStates, givenState) < 0, message);
} catch (IllegalStateException IllegalStateException) {
assertEquals(message, IllegalStateException.getMessage());
}
}
@Test
public void givenValidStatesAndTemplatedMessage_whenCheckStateEvaluatesFalse_throwsException() {
final int[] validStates = { -1, 0, 1 };
final int givenState = 10;
final String message = "State can't be %s, It can be one of %s.";
try {
checkState(Arrays.binarySearch(validStates, givenState) < 0, message, givenState, Arrays.toString(validStates));
} catch (IllegalStateException IllegalStateException) {
final String formattedMessage = String.format(message, givenState, Arrays.toString(validStates));
assertEquals(formattedMessage, IllegalStateException.getMessage());
}
}
}

View File

@ -38,6 +38,12 @@
<version>${kotlin-maven-plugin.version}</version>
<executions>
<execution>
<configuration>
<sourceDirs>
<source>src/main/java</source>
<source>src/main/kotlin</source>
</sourceDirs>
</configuration>
<id>compile</id>
<goals>
<goal>compile</goal>
@ -45,6 +51,12 @@
</execution>
<execution>
<configuration>
<sourceDirs>
<source>src/test/java</source>
<source>src/test/kotlin</source>
</sourceDirs>
</configuration>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>

View File

@ -0,0 +1,7 @@
package com.baeldung.java;
public class StringUtils {
public static String toUpperCase(String name) {
return name.toUpperCase();
}
}

View File

@ -24,29 +24,41 @@ class ItemManager(val categoryId: String, val dbConnection: String) {
fun makeAnalyisOfCategory(catId: String): Unit {
val result = if (catId == "100") "Yes" else "No"
println(result)
`object`()
}
fun sum(a: Int, b: Int): Int {
return a + b
}
fun `object`(): String {
return "this is object"
}
}
fun main(args: Array<String>) {
val numbers = arrayOf("first", "second", "third", "fourth")
var concat = ""
for (n in numbers) {
concat += n
println(n)
}
var sum = 0
for (i in 2..9) {
sum += i
for (i in 2..9 step 2) {
println(i)
}
val res = 1.rangeTo(10).map { it * 2 }
println(res)
val firstName = "Tom"
val secondName = "Mary"
val concatOfNames = "$firstName + $secondName"
println("Names: $concatOfNames")
val sum = "four: ${2 + 2}"
val itemManager = ItemManager("cat_id", "db://connection")
ItemManager(categoryId = "catId", dbConnection = "db://Connection")
val result = "function result: ${itemManager.isFromSpecificCategory("1")}"
println(result)
@ -63,4 +75,9 @@ fun main(args: Array<String>) {
"Alice" -> println("Hi lady")
}
val items = listOf(1, 2, 3, 4)
val rwList = mutableListOf(1, 2, 3)
rwList.add(5)
}

View File

@ -0,0 +1,7 @@
package com.baeldung.kotlin
class MathematicsOperations {
fun addTwoNumbers(a: Int, b: Int): Int {
return a + b
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.kotlin;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class JavaCallToKotlinTest {
@Test
public void givenKotlinClass_whenCallFromJava_shouldProduceResults() {
//when
int res = new MathematicsOperations().addTwoNumbers(2, 4);
//then
assertEquals(6, res);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.kotlin
import com.baeldung.java.StringUtils
import org.junit.Test
import kotlin.test.assertEquals
class KotlinScalaInteroperabilityTest {
@Test
fun givenLowercaseString_whenExecuteMethodFromJavaStringUtils_shouldReturnStringUppercase() {
//given
val name = "tom"
//when
val res = StringUtils.toUpperCase(name)
//then
assertEquals(res, "TOM")
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.kotlin
import org.junit.Test
import kotlin.test.assertEquals
class LambdaTest {
@Test
fun givenListOfNumber_whenDoingOperationsUsingLambda_shouldReturnProperResult() {
//given
val listOfNumbers = listOf(1, 2, 3)
//when
val sum = listOfNumbers.reduce { a, b -> a + b }
//then
assertEquals(6, sum)
}
}

View File

@ -75,12 +75,12 @@
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-mongodb</artifactId>
<version>${querydsl.version}</version>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
</dependency>
@ -167,12 +167,12 @@
<org.springframework.version>4.3.4.RELEASE</org.springframework.version>
<org.springframework.data.version>1.8.6.RELEASE</org.springframework.data.version>
<org.springframework.data.version>1.9.6.RELEASE</org.springframework.data.version>
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<rest-assured.version>2.9.0</rest-assured.version>
<querydsl.version>3.7.4</querydsl.version>
<querydsl.version>4.1.4</querydsl.version>
<mysema.maven.version>1.1.3</mysema.maven.version>
<org.slf4j.version>1.7.21</org.slf4j.version>

View File

@ -13,7 +13,7 @@ import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import com.mysema.query.annotations.QueryEntity;
import com.querydsl.core.annotations.QueryEntity;
@QueryEntity
@Document
@ -37,6 +37,11 @@ public class User {
public User() {
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
@PersistenceConstructor
public User(final String name, @Value("#root.age ?: 0") final Integer age, final EmailAddress emailAddress) {

View File

@ -26,4 +26,10 @@ public interface UserRepository extends MongoRepository<User, String>, QueryDslP
List<User> findByNameStartingWith(String regexp);
List<User> findByNameEndingWith(String regexp);
@Query(value="{}", fields="{name : 1}")
List<User> findNameAndId();
@Query(value="{}", fields="{_id : 0}")
List<User> findNameAndAgeExcludeId();
}

View File

@ -0,0 +1,147 @@
package org.baeldung.aggregation;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.baeldung.aggregation.model.StatePopulation;
import org.baeldung.config.MongoConfig;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.aggregation.LimitOperation;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.aggregation.ProjectionOperation;
import org.springframework.data.mongodb.core.aggregation.SortOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class ZipsAggregationLiveTest {
private static MongoClient client;
@Autowired
private MongoTemplate mongoTemplate;
@BeforeClass
public static void setupTests() throws Exception {
client = new MongoClient();
DB testDB = client.getDB("test");
DBCollection zipsCollection = testDB.getCollection("zips");
zipsCollection.drop();
InputStream zipsJsonStream = ZipsAggregationLiveTest.class.getResourceAsStream("/zips.json");
BufferedReader reader = new BufferedReader(new InputStreamReader(zipsJsonStream));
reader.lines()
.forEach(line -> zipsCollection.insert((DBObject) JSON.parse(line)));
reader.close();
}
@AfterClass
public static void tearDown() throws Exception {
client = new MongoClient();
DB testDB = client.getDB("test");
DBCollection zipsCollection = testDB.getCollection("zips");
zipsCollection.drop();
client.close();
}
@Test
public void whenStatesHavePopGrtrThan10MillionAndSorted_thenSuccess() {
GroupOperation groupByStateAndSumPop = group("state").sum("pop").as("statePop");
MatchOperation filterStates = match(new Criteria("statePop").gt(10000000));
SortOperation sortByPopDesc = sort(new Sort(Direction.DESC, "statePop"));
Aggregation aggregation = newAggregation(groupByStateAndSumPop, filterStates, sortByPopDesc);
AggregationResults<StatePopulation> result = mongoTemplate.aggregate(aggregation, "zips", StatePopulation.class);
/*
* Assert that all states have population
* greater than 10000000
*/
result.forEach(statePop -> {
assertTrue(statePop.getStatePop() > 10000000);
});
/*
* Assert that states fetched are in sorted by
* decreasing population
*/
List<StatePopulation> actualList = StreamSupport.stream(result.spliterator(), false)
.collect(Collectors.toList());
List<StatePopulation> expectedList = new ArrayList<>(actualList);
Collections.sort(expectedList, (sp1, sp2) -> sp2.getStatePop() - sp1.getStatePop());
assertEquals(expectedList, actualList);
}
@Test
public void whenStateWithLowestAvgCityPopIsND_theSuccess() {
GroupOperation sumTotalCityPop = group("state", "city").sum("pop").as("cityPop");
GroupOperation averageStatePop = group("_id.state").avg("cityPop").as("avgCityPop");
SortOperation sortByAvgPopAsc = sort(new Sort(Direction.ASC, "avgCityPop"));
ProjectionOperation projectToMatchModel = project().andExpression("_id").as("state")
.andExpression("avgCityPop").as("statePop");
LimitOperation limitToOnlyFirstDoc = limit(1);
Aggregation aggregation = newAggregation(sumTotalCityPop, averageStatePop, sortByAvgPopAsc, limitToOnlyFirstDoc, projectToMatchModel);
AggregationResults<StatePopulation> result = mongoTemplate.aggregate(aggregation, "zips", StatePopulation.class);
StatePopulation smallestState = result.getUniqueMappedResult();
assertEquals("ND", smallestState.getState());
assertTrue(smallestState.getStatePop()
.equals(1645));
}
@Test
public void whenMaxTXAndMinDC_theSuccess() {
GroupOperation sumZips = group("state").count().as("zipCount");
SortOperation sortByCount = sort(Direction.ASC, "zipCount");
GroupOperation groupFirstAndLast = group().first("_id").as("minZipState")
.first("zipCount").as("minZipCount").last("_id").as("maxZipState")
.last("zipCount").as("maxZipCount");
Aggregation aggregation = newAggregation(sumZips, sortByCount, groupFirstAndLast);
AggregationResults<DBObject> result = mongoTemplate.aggregate(aggregation, "zips", DBObject.class);
DBObject dbObject = result.getUniqueMappedResult();
assertEquals("DC", dbObject.get("minZipState"));
assertEquals(24, dbObject.get("minZipCount"));
assertEquals("TX", dbObject.get("maxZipState"));
assertEquals(1671, dbObject.get("maxZipCount"));
}
}

View File

@ -0,0 +1,38 @@
package org.baeldung.aggregation.model;
import org.springframework.data.annotation.Id;
public class StatePopulation {
@Id
private String state;
private Integer statePop;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Integer getStatePop() {
return statePop;
}
public void setStatePop(Integer statePop) {
this.statePop = statePop;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("StatePopulation [state=");
builder.append(state);
builder.append(", statePop=");
builder.append(statePop);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,70 @@
package org.baeldung.mongotemplate;
import static org.junit.Assert.*;
import org.baeldung.config.MongoConfig;
import org.baeldung.model.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class MongoTemplateProjectionLiveTest {
@Autowired
private MongoTemplate mongoTemplate;
@Before
public void testSetup() {
if (!mongoTemplate.collectionExists(User.class)) {
mongoTemplate.createCollection(User.class);
}
}
@After
public void tearDown() {
mongoTemplate.dropCollection(User.class);
}
@Test
public void givenUserExists_whenAgeZero_thenSuccess() {
mongoTemplate.insert(new User("John", 30));
mongoTemplate.insert(new User("Ringo", 35));
Query query = new Query();
query.fields()
.include("name");
mongoTemplate.find(query, User.class)
.forEach(user -> {
assertNotNull(user.getName());
assertTrue(user.getAge()
.equals(0));
});
}
@Test
public void givenUserExists_whenIdNull_thenSuccess() {
mongoTemplate.insert(new User("John", 30));
mongoTemplate.insert(new User("Ringo", 35));
Query query = new Query();
query.fields()
.exclude("_id");
mongoTemplate.find(query, User.class)
.forEach(user -> {
assertNull(user.getId());
assertNotNull(user.getAge());
});
}
}

View File

@ -13,7 +13,9 @@ import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mysema.query.types.Predicate;
import com.querydsl.core.types.Predicate;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)

View File

@ -0,0 +1,62 @@
package org.baeldung.repository;
import static org.junit.Assert.*;
import org.baeldung.config.MongoConfig;
import org.baeldung.model.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class UserRepositoryProjectionLiveTest {
@Autowired
private UserRepository userRepository;
@Autowired
private MongoOperations mongoOps;
@Before
public void testSetup() {
if (!mongoOps.collectionExists(User.class)) {
mongoOps.createCollection(User.class);
}
}
@After
public void tearDown() {
mongoOps.dropCollection(User.class);
}
@Test
public void givenUserExists_whenAgeZero_thenSuccess() {
mongoOps.insert(new User("John", 30));
mongoOps.insert(new User("Ringo", 35));
userRepository.findNameAndId()
.forEach(user -> {
assertNotNull(user.getName());
assertTrue(user.getAge().equals(0));
});
}
@Test
public void givenUserExists_whenIdNull_thenSuccess() {
mongoOps.insert(new User("John", 30));
mongoOps.insert(new User("Ringo", 35));
userRepository.findNameAndAgeExcludeId()
.forEach(user -> {
assertNull(user.getId());
assertNotNull(user.getAge());
});
}
}

File diff suppressed because it is too large Load Diff

View File

@ -105,7 +105,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<version>4.12</version>
<scope>test</scope>
</dependency>
@ -119,7 +119,7 @@
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<version>1.3</version>
<scope>test</scope>
</dependency>

View File

@ -0,0 +1,38 @@
package com.baeldung.hibernate.oneToMany.config;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateAnnotationUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate-annotation.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.hibernate.oneToMany.main;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.baeldung.hibernate.model.Cart;
import com.baeldung.hibernate.model.Items;
import com.baeldung.hibernate.config.HibernateAnnotationUtil;
public class HibernateOneToManyAnnotationMain {
public static void main(String[] args) {
Cart cart = new Cart();
cart.setName("MyCart");
Items item1 = new Items("I10", 10, 1, cart);
Items item2 = new Items("I20", 20, 2, cart);
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1); itemsSet.add(item2);
cart.setItems(itemsSet);
cart.setTotal(10*1 + 20*2);
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try{
//Get Session
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
System.out.println("Session created");
//start transaction
tx = session.beginTransaction();
//Save the Model object
session.save(cart);
session.save(item1);
session.save(item2);
//Commit transaction
tx.commit();
System.out.println("Cart ID="+cart.getId());
System.out.println("item1 ID="+item1.getId()+", Foreign Key Cart ID="+item1.getCart().getId());
System.out.println("item2 ID="+item2.getId()+", Foreign Key Cart ID="+item1.getCart().getId());
}catch(Exception e){
System.out.println("Exception occured. "+e.getMessage());
e.printStackTrace();
}finally{
if(!sessionFactory.isClosed()){
System.out.println("Closing SessionFactory");
sessionFactory.close();
}
}
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.hibernate.oneToMany.model;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="CART")
public class Cart {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="cart_id")
private long id;
@Column(name="total")
private double total;
@Column(name="name")
private String name;
@OneToMany(mappedBy="cart")
private Set<Items> items;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.hibernate.oneToMany.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="ITEMS")
public class Items {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private long id;
@Column(name="item_id")
private String itemId;
@Column(name="item_total")
private double itemTotal;
@Column(name="quantity")
private int quantity;
@ManyToOne
@JoinColumn(name="cart_id", nullable=false)
private Cart cart;
//Hibernate requires no-args constructor
public Items(){}
public Items(String itemId, double total, int qty, Cart c){
this.itemId=itemId;
this.itemTotal=total;
this.quantity=qty;
this.cart=c;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public double getItemTotal() {
return itemTotal;
}
public void setItemTotal(double itemTotal) {
this.itemTotal = itemTotal;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">bastard5</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/setup</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<mapping class="com.baeldung.hibernate.model.Cart"/>
<mapping class="com.baeldung.hibernate.model.Items"/>
</session-factory>
</hibernate-configuration>

View File

@ -0,0 +1,17 @@
CREATE TABLE `Cart` (
`cart_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`total` decimal(10,0) NOT NULL,
`name` varchar(10) DEFAULT NULL,
PRIMARY KEY (`cart_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
CREATE TABLE `Items` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`cart_id` int(11) unsigned NOT NULL,
`item_id` varchar(10) NOT NULL,
`item_total` decimal(10,0) NOT NULL,
`quantity` int(3) NOT NULL,
PRIMARY KEY (`id`),
KEY `cart_id` (`cart_id`),
CONSTRAINT `items_ibfk_1` FOREIGN KEY (`cart_id`) REFERENCES `Cart` (`cart_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

View File

@ -0,0 +1,43 @@
package com.baeldung.hibernate.oneToMany.config;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class HibernateAnnotationUtilTest {
public HibernateAnnotationUtilTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testGetSessionFactory() {
System.out.println("getSessionFactory");
SessionFactory expResult = null;
SessionFactory result = HibernateAnnotationUtil.getSessionFactory();
assertEquals(expResult, result);
fail("The test failed.");
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.hibernate.oneToMany.main;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class HibernateOneToManyAnnotationMainTest {
public HibernateOneToManyAnnotationMainTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testMain() {
System.out.println("main");
String[] args = null;
HibernateOneToManyAnnotationMain.main(args);
fail("The test failed.");
}
}

View File

@ -0,0 +1,111 @@
package com.baeldung.hibernate.oneToMany.model;
import java.util.Set;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class CartTest {
public CartTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testGetId() {
System.out.println("getId");
Cart instance = new Cart();
long expResult = 0L;
long result = instance.getId();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetId() {
System.out.println("setId");
long id = 0L;
Cart instance = new Cart();
instance.setId(id);
fail("The test failed.");
}
@Test
public void testGetTotal() {
System.out.println("getTotal");
Cart instance = new Cart();
double expResult = 0.0;
double result = instance.getTotal();
assertEquals(expResult, result, 0.0);
fail("The test failed.");
}
@Test
public void testSetTotal() {
System.out.println("setTotal");
double total = 0.0;
Cart instance = new Cart();
instance.setTotal(total);
fail("The test failed.");
}
@Test
public void testGetName() {
System.out.println("getName");
Cart instance = new Cart();
String expResult = "";
String result = instance.getName();
assertEquals(expResult, result);
fail("The test failed");
}
@Test
public void testSetName() {
System.out.println("setName");
String name = "";
Cart instance = new Cart();
instance.setName(name);
fail("The test failed.");
}
@Test
public void testGetItems() {
System.out.println("getItems");
Cart instance = new Cart();
Set<Items> expResult = null;
Set<Items> result = instance.getItems();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetItems() {
System.out.println("setItems");
Set<Items> items = null;
Cart instance = new Cart();
instance.setItems(items);
fail("The test case failed");
}
}

View File

@ -0,0 +1,131 @@
package com.baeldung.hibernate.oneToMany.model;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class ItemsTest {
public ItemsTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testGetItemId() {
System.out.println("getItemId");
Items instance = new Items();
String expResult = "";
String result = instance.getItemId();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetItemId() {
System.out.println("setItemId");
String itemId = "";
Items instance = new Items();
instance.setItemId(itemId);
fail("The test failed.");
}
@Test
public void testGetItemTotal() {
System.out.println("getItemTotal");
Items instance = new Items();
double expResult = 0.0;
double result = instance.getItemTotal();
assertEquals(expResult, result, 0.0);
fail("The test failed.");
}
@Test
public void testSetItemTotal() {
System.out.println("setItemTotal");
double itemTotal = 0.0;
Items instance = new Items();
instance.setItemTotal(itemTotal);
fail("The test failed.");
}
@Test
public void testGetQuantity() {
System.out.println("getQuantity");
Items instance = new Items();
int expResult = 0;
int result = instance.getQuantity();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetQuantity() {
System.out.println("setQuantity");
int quantity = 0;
Items instance = new Items();
instance.setQuantity(quantity);
fail("The test failed.");
}
@Test
public void testGetCart() {
System.out.println("getCart");
Items instance = new Items();
Cart expResult = null;
Cart result = instance.getCart();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetCart() {
System.out.println("setCart");
Cart cart = null;
Items instance = new Items();
instance.setCart1(cart);
fail("The test failed.");
}
@Test
public void testGetId() {
System.out.println("getId");
Items instance = new Items();
long expResult = 0L;
long result = instance.getId();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetId() {
System.out.println("setId");
long id = 0L;
Items instance = new Items();
instance.setId(id);
fail("The test failed.");
}
}
}

View File

@ -0,0 +1,4 @@
## Spring MVC Forms Tutorials
### Relevant Articles
- [MaxUploadSizeExceededException in Spring](http://www.baeldung.com/spring-maxuploadsizeexceeded)