Merge branch 'master' into master

This commit is contained in:
Ahmed Tawila
2017-07-30 04:07:28 +03:00
committed by GitHub
335 changed files with 20462 additions and 1744 deletions
@@ -3,7 +3,6 @@ package com.baeldung.awaitility;
import org.awaitility.Awaitility;
import org.awaitility.Duration;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.concurrent.Callable;
@@ -0,0 +1,89 @@
package com.baeldung.bytebuddy;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import org.junit.Test;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import static net.bytebuddy.matcher.ElementMatchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class ByteBuddyUnitTest {
@Test
public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException {
DynamicType.Unloaded unloadedType = new ByteBuddy()
.subclass(Object.class)
.method(ElementMatchers.isToString())
.intercept(FixedValue.value("Hello World ByteBuddy!"))
.make();
Class<?> dynamicType = unloadedType.load(getClass().getClassLoader())
.getLoaded();
assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!");
}
@Test
public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception {
ByteBuddyAgent.install();
new ByteBuddy()
.redefine(Foo.class)
.method(named("sayHelloFoo"))
.intercept(FixedValue.value("Hello Foo Redefined"))
.make()
.load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Foo f = new Foo();
assertEquals(f.sayHelloFoo(), "Hello Foo Redefined");
}
@Test
public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException {
String r = new ByteBuddy()
.subclass(Foo.class)
.method(
named("sayHelloFoo")
.and(isDeclaredBy(Foo.class)
.and(returns(String.class)))
)
.intercept(MethodDelegation.to(Bar.class))
.make()
.load(getClass().getClassLoader())
.getLoaded()
.newInstance()
.sayHelloFoo();
assertEquals(r, Bar.sayHelloBar());
}
@Test
public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception {
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.name("MyClassName")
.defineMethod("custom", String.class, Modifier.PUBLIC)
.intercept(MethodDelegation.to(Bar.class))
.defineField("x", String.class, Modifier.PUBLIC)
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
Method m = type.getDeclaredMethod("custom", null);
assertEquals(m.invoke(type.newInstance()), Bar.sayHelloBar());
assertNotNull(type.getDeclaredField("x"));
}
}
@@ -19,14 +19,14 @@ public class BeanGeneratorIntegrationTest {
beanGenerator.addProperty("name", String.class);
Object myBean = beanGenerator.create();
Method setter = myBean
.getClass()
.getMethod("setName", String.class);
.getClass()
.getMethod("setName", String.class);
setter.invoke(myBean, "some string value set by a cglib");
//then
Method getter = myBean
.getClass()
.getMethod("getName");
.getClass()
.getMethod("getName");
assertEquals("some string value set by a cglib", getter.invoke(myBean));
}
}
@@ -1,6 +1,10 @@
package com.baeldung.cglib.proxy;
import com.baeldung.cglib.mixin.*;
import com.baeldung.cglib.mixin.Class1;
import com.baeldung.cglib.mixin.Class2;
import com.baeldung.cglib.mixin.Interface1;
import com.baeldung.cglib.mixin.Interface2;
import com.baeldung.cglib.mixin.MixinInterface;
import net.sf.cglib.proxy.Mixin;
import org.junit.Test;
@@ -12,8 +16,8 @@ public class MixinUnitTest {
public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception {
//when
Mixin mixin = Mixin.create(
new Class[]{Interface1.class, Interface2.class, MixinInterface.class},
new Object[]{new Class1(), new Class2()}
new Class[]{Interface1.class, Interface2.class, MixinInterface.class},
new Object[]{new Class1(), new Class2()}
);
MixinInterface mixinDelegate = (MixinInterface) mixin;
@@ -0,0 +1,43 @@
package com.baeldung.chronicle.queue;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.junit.Test;
import net.openhft.chronicle.Chronicle;
import net.openhft.chronicle.ChronicleQueueBuilder;
import net.openhft.chronicle.ExcerptTailer;
import net.openhft.chronicle.tools.ChronicleTools;
public class ChronicleQueueTest {
@Test
public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException {
File queueDir = Files.createTempDirectory("chronicle-queue").toFile();
ChronicleTools.deleteOnExit(queueDir.getPath());
Chronicle chronicle = ChronicleQueueBuilder.indexed(queueDir).build();
String stringVal = "Hello World";
int intVal = 101;
long longVal = System.currentTimeMillis();
double doubleVal = 90.00192091d;
ChronicleQueue.writeToQueue(chronicle, stringVal, intVal, longVal, doubleVal);
ExcerptTailer tailer = chronicle.createTailer();
while (tailer.nextIndex()) {
assertEquals(stringVal, tailer.readUTF());
assertEquals(intVal, tailer.readInt());
assertEquals(longVal, tailer.readLong());
assertEquals((Double) doubleVal, (Double) tailer.readDouble());
}
tailer.finish();
tailer.close();
chronicle.close();
}
}
@@ -0,0 +1,159 @@
package com.baeldung.circularfifoqueue;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.junit.Assert;
import org.junit.Test;
public class CircularFifoQueueTest {
private static final int DEFAULT_SIZE = 32;
private static final int FIXED_SIZE = 5;
private static final int COLLECTION_SIZE = 7;
private static final String TEST_COLOR = "Red";
private static final String TEST_COLOR_BY_INDEX = "Blue";
@Test
public void whenUsingDefualtConstructor_correctSizeQueue() {
CircularFifoQueue<String> bits = new CircularFifoQueue<>();
Assert.assertEquals(DEFAULT_SIZE, bits.maxSize());
}
@Test
public void givenAddElements_whenUsingIntConstructor_correctSizeQueue() {
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.offer("White");
colors.offer("Black");
Assert.assertEquals(FIXED_SIZE, colors.maxSize());
}
@Test
public void whenUsingCollectionConstructor_correctSizeQueue() {
List<String> days = new ArrayList<>();
days.add("Monday");
days.add("Tuesday");
days.add("Wednesday");
days.add("Thursday");
days.add("Friday");
days.add("Saturday");
days.add("Sunday");
CircularFifoQueue<String> daysOfWeek = new CircularFifoQueue<>(days);
Assert.assertEquals(COLLECTION_SIZE, daysOfWeek.maxSize());
}
@Test
public void givenAddElements_whenGetElement_correctElement() {
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.offer("White");
colors.offer("Black");
Assert.assertEquals(TEST_COLOR_BY_INDEX, colors.get(1));
}
@Test
public void givenAddElements_whenPollElement_correctElement() {
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.offer("White");
colors.offer("Black");
Assert.assertEquals(TEST_COLOR, colors.poll());
}
@Test
public void givenAddElements_whenPeekQueue_correctElement() {
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.offer("White");
colors.offer("Black");
Assert.assertEquals(TEST_COLOR, colors.peek());
}
@Test
public void givenAddElements_whenElementQueue_correctElement() {
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.offer("White");
colors.offer("Black");
Assert.assertEquals(TEST_COLOR, colors.element());
}
@Test
public void givenAddElements_whenRemoveElement_correctElement() {
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.offer("White");
colors.offer("Black");
Assert.assertEquals(TEST_COLOR, colors.remove());
}
@Test
public void givenFullQueue_whenClearQueue_getIsEmpty() {
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.offer("White");
colors.offer("Black");
colors.clear();
Assert.assertEquals(true, colors.isEmpty());
}
@Test
public void givenFullQueue_whenCheckFull_getIsFull() {
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.offer("White");
colors.offer("Black");
Assert.assertEquals(false, colors.isFull());
}
@Test
public void givenFullQueue_whenAddMoreElements_getIsAtFullCapacity() {
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.offer("White");
colors.offer("Black");
colors.add("Orange");
colors.add("Violet");
colors.add("Pink");
Assert.assertEquals(true, colors.isAtFullCapacity());
}
}
@@ -0,0 +1,37 @@
package com.baeldung.commons.chain;
import org.apache.commons.chain.Catalog;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.junit.Assert;
import org.junit.Test;
import static com.baeldung.commons.chain.AtmConstants.*;
public class AtmChainTest {
public static final int EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN = 460;
public static final int EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN = 0;
public static final int EXPECTED_NO_OF_HUNDREDS_DISPENSED = 4;
public static final int EXPECTED_NO_OF_FIFTIES_DISPENSED = 1;
public static final int EXPECTED_NO_OF_TENS_DISPENSED = 1;
@Test
public void givenInputsToContext_whenAppliedChain_thenExpectedContext() {
Context context = new AtmRequestContext();
context.put(TOTAL_AMOUNT_TO_BE_WITHDRAWN, 460);
context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, 460);
Catalog catalog = new AtmCatalog();
Command atmWithdrawalChain = catalog.getCommand(ATM_WITHDRAWAL_CHAIN);
try {
atmWithdrawalChain.execute(context);
} catch (Exception e) {
e.printStackTrace();
}
Assert.assertEquals(EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN, (int) context.get(TOTAL_AMOUNT_TO_BE_WITHDRAWN));
Assert.assertEquals(EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN, (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN));
Assert.assertEquals(EXPECTED_NO_OF_HUNDREDS_DISPENSED, (int) context.get(NO_OF_HUNDREDS_DISPENSED));
Assert.assertEquals(EXPECTED_NO_OF_FIFTIES_DISPENSED, (int) context.get(NO_OF_FIFTIES_DISPENSED));
Assert.assertEquals(EXPECTED_NO_OF_TENS_DISPENSED, (int) context.get(NO_OF_TENS_DISPENSED));
}
}
@@ -2,16 +2,12 @@ package com.baeldung.commons.collections;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
import org.apache.commons.collections4.bidimap.DualLinkedHashBidiMap;
import org.apache.commons.collections4.bidimap.DualTreeBidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Created by smatt on 03/07/2017.
*/
public class BidiMapUnitTest {
@Test
@@ -3,14 +3,17 @@ package com.baeldung.commons.collections;
import com.baeldung.commons.collectionutil.Address;
import com.baeldung.commons.collectionutil.Customer;
import org.apache.commons.collections4.Closure;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.Transformer;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -36,13 +39,13 @@ public class CollectionUtilsGuideTest {
linkedList1 = new LinkedList<>(list1);
}
@Test
public void givenList_whenAddIgnoreNull_thenNoNullAdded() {
CollectionUtils.addIgnoreNull(list1, null);
assertFalse(list1.contains(null));
}
@Test
public void givenTwoSortedLists_whenCollated_thenSorted() {
List<Customer> sortedList = CollectionUtils.collate(list1, list2);
@@ -51,7 +54,7 @@ public class CollectionUtilsGuideTest {
assertTrue(sortedList.get(0).getName().equals("Bob"));
assertTrue(sortedList.get(2).getName().equals("Daniel"));
}
@Test
public void givenListOfCustomers_whenTransformed_thenListOfAddress() {
Collection<Address> addressCol = CollectionUtils.collect(list1, new Transformer<Customer, Address>() {
@@ -59,61 +62,61 @@ public class CollectionUtilsGuideTest {
return new Address(customer.getLocality(), customer.getCity(), customer.getZip());
}
});
List<Address> addressList = new ArrayList<>(addressCol);
assertTrue(addressList.size() == 3);
assertTrue(addressList.get(0).getLocality().equals("locality1"));
}
@Test
public void givenCustomerList_whenFiltered_thenCorrectSize() {
boolean isModified = CollectionUtils.filter(linkedList1, new Predicate<Customer>() {
public boolean evaluate(Customer customer) {
return Arrays.asList("Daniel","Kyle").contains(customer.getName());
return Arrays.asList("Daniel", "Kyle").contains(customer.getName());
}
});
//filterInverse does the opposite. It removes the element from the list if the Predicate returns true
//select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection
assertTrue(isModified && linkedList1.size() == 2);
}
@Test
public void givenNonEmptyList_whenCheckedIsNotEmpty_thenTrue() {
List<Customer> emptyList = new ArrayList<>();
List<Customer> nullList = null;
//Very handy at times where we want to check if a collection is not null and not empty too.
//isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading
assertTrue(CollectionUtils.isNotEmpty(list1));
assertTrue(CollectionUtils.isEmpty(nullList));
assertTrue(CollectionUtils.isEmpty(emptyList));
}
@Test
public void givenCustomerListAndASubcollection_whenChecked_thenTrue() {
assertTrue(CollectionUtils.isSubCollection(list3, list1));
}
@Test
public void givenTwoLists_whenIntersected_thenCheckSize() {
Collection<Customer> intersection = CollectionUtils.intersection(list1, list3);
assertTrue(intersection.size() == 2);
}
@Test
public void givenTwoLists_whenSubtracted_thenCheckElementNotPresentInA() {
Collection<Customer> result = CollectionUtils.subtract(list1, list3);
assertFalse(result.contains(customer1));
}
@Test
public void givenTwoLists_whenUnioned_thenCheckElementPresentInResult() {
Collection<Customer> union = CollectionUtils.union(list1, list2);
assertTrue(union.contains(customer1));
assertTrue(union.contains(customer4));
}
}
@@ -0,0 +1,132 @@
package com.baeldung.commons.collections;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.collections4.PredicateUtils;
import org.apache.commons.collections4.TransformerUtils;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
import static org.hamcrest.collection.IsMapWithSize.anEmptyMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class MapUtilsTest {
private String[][] color2DArray = new String[][]{
{"RED", "#FF0000"},
{"GREEN", "#00FF00"},
{"BLUE", "#0000FF"}
};
private String[] color1DArray = new String[]{
"RED", "#FF0000",
"GREEN", "#00FF00",
"BLUE", "#0000FF"
};
private Map<String, String> colorMap;
@Before
public void createMap() {
this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color2DArray);
}
@Test
public void whenCreateMapFrom2DArray_theMapIsCreated() {
this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color2DArray);
assertThat(this.colorMap, is(aMapWithSize(this.color2DArray.length)));
assertThat(this.colorMap, hasEntry("RED", "#FF0000"));
assertThat(this.colorMap, hasEntry("GREEN", "#00FF00"));
assertThat(this.colorMap, hasEntry("BLUE", "#0000FF"));
}
@Test
public void whenCreateMapFrom1DArray_theMapIsCreated() {
this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color1DArray);
assertThat(this.colorMap, is(aMapWithSize(this.color1DArray.length / 2)));
assertThat(this.colorMap, hasEntry("RED", "#FF0000"));
assertThat(this.colorMap, hasEntry("GREEN", "#00FF00"));
assertThat(this.colorMap, hasEntry("BLUE", "#0000FF"));
}
@Test
public void whenVerbosePrintMap_thenMustPrintFormattedMap() {
MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap);
}
@Test
public void whenGetKeyNotPresent_thenMustReturnDefaultValue() {
String defaultColorStr = "COLOR_NOT_FOUND";
String color = MapUtils.getString(this.colorMap, "BLACK", defaultColorStr);
assertEquals(color, defaultColorStr);
}
@Test
public void whenGetOnNullMap_thenMustReturnDefaultValue() {
String defaultColorStr = "COLOR_NOT_FOUND";
String color = MapUtils.getString(null, "RED", defaultColorStr);
assertEquals(color, defaultColorStr);
}
@Test
public void whenInvertMap_thenMustReturnInvertedMap() {
Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap);
int size = invColorMap.size();
Assertions.assertThat(invColorMap)
.hasSameSizeAs(colorMap)
.containsKeys(this.colorMap.values().toArray(new String[size]))
.containsValues(this.colorMap.keySet().toArray(new String[size]));
}
@Test(expected = IllegalArgumentException.class)
public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() {
Map<String, String> rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(
new HashMap<String, String>(),
this.color1DArray));
rgbMap.put("ORANGE", "#FFA500");
}
@Test(expected = IllegalArgumentException.class)
public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() {
Map<String, String> uniqValuesMap
= MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate());
uniqValuesMap.put("NEW_RED", "#FF0000");
}
@Test
public void whenCreateLazyMap_theMapIsCreated() {
Map<Integer, String> intStrMap = MapUtils.lazyMap(
new HashMap<Integer, String>(),
TransformerUtils.stringValueTransformer());
assertThat(intStrMap, is(anEmptyMap()));
intStrMap.get(1);
intStrMap.get(2);
intStrMap.get(3);
assertThat(intStrMap, is(aMapWithSize(3)));
}
}
@@ -11,9 +11,6 @@ import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by smatt on 21/06/2017.
*/
public class SetUtilsUnitTest {
@Test(expected = IllegalArgumentException.class)
@@ -27,33 +24,33 @@ public class SetUtilsUnitTest {
@Test
public void givenTwoSets_whenDifference_thenSetView() {
Set<Integer> a = new HashSet<>(Arrays.asList(1,2,5));
Set<Integer> b = new HashSet<>(Arrays.asList(1,2));
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2));
SetUtils.SetView<Integer> result = SetUtils.difference(a, b);
assertTrue(result.size() == 1 && result.contains(5));
}
@Test
public void givenTwoSets_whenUnion_thenUnionResult() {
Set<Integer> a = new HashSet<>(Arrays.asList(1,2,5));
Set<Integer> b = new HashSet<>(Arrays.asList(1,2));
Set<Integer> expected = new HashSet<>(Arrays.asList(1,2,5));
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2));
Set<Integer> expected = new HashSet<>(Arrays.asList(1, 2, 5));
SetUtils.SetView<Integer> union = SetUtils.union(a, b);
assertTrue(SetUtils.isEqualSet(expected, union));
}
@Test
public void givenTwoSets_whenIntersection_thenIntersectionResult() {
Set<Integer> a = new HashSet<>(Arrays.asList(1,2,5));
Set<Integer> b = new HashSet<>(Arrays.asList(1,2));
Set<Integer> expected = new HashSet<>(Arrays.asList(1,2));
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2));
Set<Integer> expected = new HashSet<>(Arrays.asList(1, 2));
SetUtils.SetView<Integer> intersect = SetUtils.intersection(a, b);
assertTrue(SetUtils.isEqualSet(expected, intersect));
}
@Test
public void givenSet_whenTransformedSet_thenTransformedResult() {
Set<Integer> a = SetUtils.transformedSet(new HashSet<>(), (e) -> e * 2 );
Set<Integer> a = SetUtils.transformedSet(new HashSet<>(), (e) -> e * 2);
a.add(2);
assertEquals(a.toArray()[0], 4);
@@ -65,19 +62,19 @@ public class SetUtilsUnitTest {
@Test
public void givenTwoSet_whenDisjunction_thenDisjunctionSet() {
Set<Integer> a = new HashSet<>(Arrays.asList(1,2,5));
Set<Integer> b = new HashSet<>(Arrays.asList(1,2,3));
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2, 3));
SetUtils.SetView<Integer> result = SetUtils.disjunction(a, b);
assertTrue(result.toSet().contains(5) && result.toSet().contains(3));
}
@Test
public void givenSet_when_OrderedSet_thenMaintainElementOrder() {
Set<Integer> set = new HashSet<>(Arrays.asList(10,1,5));
Set<Integer> set = new HashSet<>(Arrays.asList(10, 1, 5));
System.out.println("unordered set: " + set);
Set<Integer> orderedSet = SetUtils.orderedSet(new HashSet<>());
orderedSet.addAll(Arrays.asList(10,1,5));
orderedSet.addAll(Arrays.asList(10, 1, 5));
System.out.println("ordered set = " + orderedSet);
}
}
@@ -1,10 +1,5 @@
package com.baeldung.commons.collections.orderedmap;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.OrderedMap;
import org.apache.commons.collections4.OrderedMapIterator;
import org.apache.commons.collections4.map.LinkedMap;
@@ -12,6 +7,11 @@ import org.apache.commons.collections4.map.ListOrderedMap;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class OrderedMapUnitTest {
private String[] names = {"Emily", "Mathew", "Rose", "John", "Anna"};
@@ -0,0 +1,163 @@
package com.baeldung.commons.dbutils;
import org.apache.commons.dbutils.AsyncQueryRunner;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class DbUtilsUnitTest {
private Connection connection;
@Before
public void setupDB() throws Exception {
Class.forName("org.h2.Driver");
String db = "jdbc:h2:mem:;INIT=runscript from 'classpath:/employees.sql'";
connection = DriverManager.getConnection(db);
}
@After
public void closeBD() {
DbUtils.closeQuietly(connection);
}
@Test
public void givenResultHandler_whenExecutingQuery_thenExpectedList() throws SQLException {
MapListHandler beanListHandler = new MapListHandler();
QueryRunner runner = new QueryRunner();
List<Map<String, Object>> list = runner.query(connection, "SELECT * FROM employee", beanListHandler);
assertEquals(list.size(), 5);
assertEquals(list.get(0)
.get("firstname"), "John");
assertEquals(list.get(4)
.get("firstname"), "Christian");
}
@Test
public void givenResultHandler_whenExecutingQuery_thenEmployeeList() throws SQLException {
BeanListHandler<Employee> beanListHandler = new BeanListHandler<>(Employee.class);
QueryRunner runner = new QueryRunner();
List<Employee> employeeList = runner.query(connection, "SELECT * FROM employee", beanListHandler);
assertEquals(employeeList.size(), 5);
assertEquals(employeeList.get(0)
.getFirstName(), "John");
assertEquals(employeeList.get(4)
.getFirstName(), "Christian");
}
@Test
public void givenResultHandler_whenExecutingQuery_thenExpectedScalar() throws SQLException {
ScalarHandler<Long> scalarHandler = new ScalarHandler<>();
QueryRunner runner = new QueryRunner();
String query = "SELECT COUNT(*) FROM employee";
long count = runner.query(connection, query, scalarHandler);
assertEquals(count, 5);
}
@Test
public void givenResultHandler_whenExecutingQuery_thenEmailsSetted() throws SQLException {
EmployeeHandler employeeHandler = new EmployeeHandler(connection);
QueryRunner runner = new QueryRunner();
List<Employee> employees = runner.query(connection, "SELECT * FROM employee", employeeHandler);
assertEquals(employees.get(0)
.getEmails()
.size(), 2);
assertEquals(employees.get(2)
.getEmails()
.size(), 3);
assertNotNull(employees.get(0).getEmails().get(0).getEmployeeId());
}
@Test
public void givenResultHandler_whenExecutingQuery_thenAllPropertiesSetted() throws SQLException {
EmployeeHandler employeeHandler = new EmployeeHandler(connection);
QueryRunner runner = new QueryRunner();
String query = "SELECT * FROM employee_legacy";
List<Employee> employees = runner.query(connection, query, employeeHandler);
assertEquals((int) employees.get(0).getId(), 1);
assertEquals(employees.get(0).getFirstName(), "John");
}
@Test
public void whenInserting_thenInserted() throws SQLException {
QueryRunner runner = new QueryRunner();
String insertSQL = "INSERT INTO employee (firstname,lastname,salary, hireddate) VALUES (?, ?, ?, ?)";
int numRowsInserted = runner.update(connection, insertSQL, "Leia", "Kane", 60000.60, new Date());
assertEquals(numRowsInserted, 1);
}
@Test
public void givenHandler_whenInserting_thenExpectedId() throws SQLException {
ScalarHandler<Integer> scalarHandler = new ScalarHandler<>();
QueryRunner runner = new QueryRunner();
String insertSQL = "INSERT INTO employee (firstname,lastname,salary, hireddate) VALUES (?, ?, ?, ?)";
int newId = runner.insert(connection, insertSQL, scalarHandler, "Jenny", "Medici", 60000.60, new Date());
assertEquals(newId, 6);
}
@Test
public void givenSalary_whenUpdating_thenUpdated() throws SQLException {
double salary = 35000;
QueryRunner runner = new QueryRunner();
String updateSQL = "UPDATE employee SET salary = salary * 1.1 WHERE salary <= ?";
int numRowsUpdated = runner.update(connection, updateSQL, salary);
assertEquals(numRowsUpdated, 3);
}
@Test
public void whenDeletingRecord_thenDeleted() throws SQLException {
QueryRunner runner = new QueryRunner();
String deleteSQL = "DELETE FROM employee WHERE id = ?";
int numRowsDeleted = runner.update(connection, deleteSQL, 3);
assertEquals(numRowsDeleted, 1);
}
@Test
public void givenAsyncRunner_whenExecutingQuery_thenExpectedList() throws Exception {
AsyncQueryRunner runner = new AsyncQueryRunner(Executors.newCachedThreadPool());
EmployeeHandler employeeHandler = new EmployeeHandler(connection);
String query = "SELECT * FROM employee";
Future<List<Employee>> future = runner.query(connection, query, employeeHandler);
List<Employee> employeeList = future.get(10, TimeUnit.SECONDS);
assertEquals(employeeList.size(), 5);
}
}
@@ -2,9 +2,10 @@ package com.baeldung.commons.lang3;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class StringUtilsUnitTest {
@Test
@@ -6,7 +6,7 @@ import java.util.List;
import static org.junit.Assert.assertEquals;
public class HikariCPUnitTest {
public class HikariCPIntegrationTest {
@Test
public void givenConnection_thenFetchDbData() {
@@ -0,0 +1,63 @@
package com.baeldung.hll;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import net.agkn.hll.HLL;
import org.assertj.core.data.Offset;
import org.junit.Test;
import java.util.stream.LongStream;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
public class HLLUnitTest {
@Test
public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() {
//given
long numberOfElements = 100_000_000;
long toleratedDifference = 1_000_000;
HashFunction hashFunction = Hashing.murmur3_128();
HLL hll = new HLL(14, 5);
//when
LongStream.range(0, numberOfElements).forEach(element -> {
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
hll.addRaw(hashedValue);
}
);
//then
long cardinality = hll.cardinality();
assertThat(cardinality).isCloseTo(numberOfElements, Offset.offset(toleratedDifference));
}
@Test
public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinalityForUnionOfHLLs() {
//given
long numberOfElements = 100_000_000;
long toleratedDifference = 1_000_000;
HashFunction hashFunction = Hashing.murmur3_128();
HLL firstHll = new HLL(15, 5);
HLL secondHLL = new HLL(15, 5);
//when
LongStream.range(0, numberOfElements).forEach(element -> {
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
firstHll.addRaw(hashedValue);
}
);
LongStream.range(numberOfElements, numberOfElements * 2).forEach(element -> {
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
secondHLL.addRaw(hashedValue);
}
);
//then
firstHll.union(secondHLL);
long cardinality = firstHll.cardinality();
assertThat(cardinality).isCloseTo(numberOfElements * 2, Offset.offset(toleratedDifference * 2));
}
}
@@ -8,7 +8,9 @@ import org.jasypt.util.text.BasicTextEncryptor;
import org.junit.Ignore;
import org.junit.Test;
import static junit.framework.Assert.*;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotSame;
import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertEquals;
public class JasyptUnitTest {
@@ -30,7 +32,7 @@ public class JasyptUnitTest {
}
@Test
public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldBeSame(){
public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldBeSame() {
String password = "secret-pass";
BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
String encryptedPassword = passwordEncryptor.encryptPassword(password);
@@ -43,7 +45,7 @@ public class JasyptUnitTest {
}
@Test
public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldNotBeSame(){
public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldNotBeSame() {
String password = "secret-pass";
BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
String encryptedPassword = passwordEncryptor.encryptPassword(password);
@@ -56,7 +58,6 @@ public class JasyptUnitTest {
}
@Test
@Ignore("should have installed local_policy.jar")
public void givenTextPrivateData_whenDecrypt_thenCompareToEncryptedWithCustomAlgorithm() {
@@ -77,7 +78,7 @@ public class JasyptUnitTest {
@Test
@Ignore("should have installed local_policy.jar")
public void givenTextPrivateData_whenDecryptOnHighPerformance_thenDecrypt(){
public void givenTextPrivateData_whenDecryptOnHighPerformance_thenDecrypt() {
//given
String privateData = "secret-data";
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
@@ -8,7 +8,6 @@ import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.assertEquals;
@@ -0,0 +1,50 @@
package com.baeldung.neuroph;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.neuroph.core.NeuralNetwork;
import static org.junit.Assert.*;
public class XORTest {
private NeuralNetwork ann = null;
@Before
public void annInit() {
ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork());
}
@Test
public void leftDisjunctTest() {
ann.setInput(0, 1);
ann.calculate();
assertEquals(ann.getOutput()[0], 1.0,0.0);
}
@Test
public void rightDisjunctTest() {
ann.setInput(1, 0);
ann.calculate();
assertEquals(ann.getOutput()[0], 1.0,0.0);
}
@Test
public void bothFalseConjunctTest() {
ann.setInput(0, 0);
ann.calculate();
assertEquals(ann.getOutput()[0], 0.0,0.0);
}
@Test
public void bothTrueConjunctTest() {
ann.setInput(1, 1);
ann.calculate();
assertEquals(ann.getOutput()[0], 0.0,0.0);
}
@After
public void annClose() {
ann = null;
}
}
@@ -8,7 +8,11 @@ import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.RequestResponsePact;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.http.*;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
@@ -20,7 +24,7 @@ public class PactConsumerDrivenContractUnitTest {
@Rule
public PactProviderRuleMk2 mockProvider
= new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
= new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
@Pact(consumer = "test_consumer")
public RequestResponsePact createPact(PactDslWithProvider builder) {
@@ -28,25 +32,25 @@ public class PactConsumerDrivenContractUnitTest {
headers.put("Content-Type", "application/json");
return builder
.given("test GET ")
.uponReceiving("GET REQUEST")
.path("/")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body("{\"condition\": true, \"name\": \"tom\"}")
.given("test POST")
.uponReceiving("POST REQUEST")
.method("POST")
.headers(headers)
.body("{\"name\": \"Michael\"}")
.path("/create")
.willRespondWith()
.status(201)
.headers(headers)
.body("")
.toPact();
.given("test GET ")
.uponReceiving("GET REQUEST")
.path("/")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body("{\"condition\": true, \"name\": \"tom\"}")
.given("test POST")
.uponReceiving("POST REQUEST")
.method("POST")
.headers(headers)
.body("{\"name\": \"Michael\"}")
.path("/create")
.willRespondWith()
.status(201)
.headers(headers)
.body("")
.toPact();
}
@@ -55,7 +59,7 @@ public class PactConsumerDrivenContractUnitTest {
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
//when
ResponseEntity<String> response
= new RestTemplate().getForEntity(mockProvider.getUrl(), String.class);
= new RestTemplate().getForEntity(mockProvider.getUrl(), String.class);
//then
assertThat(response.getStatusCode().value()).isEqualTo(200);
@@ -69,10 +73,10 @@ public class PactConsumerDrivenContractUnitTest {
//when
ResponseEntity<String> postResponse = new RestTemplate().exchange(
mockProvider.getUrl() + "/create",
HttpMethod.POST,
new HttpEntity<>(jsonBody, httpHeaders),
String.class
mockProvider.getUrl() + "/create",
HttpMethod.POST,
new HttpEntity<>(jsonBody, httpHeaders),
String.class
);
//then
@@ -0,0 +1,90 @@
package com.baeldung.pcollections;
import org.junit.Test;
import org.pcollections.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PCollectionsUnitTest {
@Test
public void whenEmpty_thenCreateEmptyHashPMap() {
HashPMap<String, String> pmap = HashTreePMap.empty();
assertEquals(pmap.size(), 0);
}
@Test
public void givenKeyValue_whenSingleton_thenCreateNonEmptyHashPMap() {
HashPMap<String, String> pmap1 = HashTreePMap.singleton("key1", "value1");
assertEquals(pmap1.size(), 1);
}
@Test
public void givenExistingHashMap_whenFrom_thenCreateHashPMap() {
Map map = new HashMap();
map.put("mkey1", "mval1");
map.put("mkey2", "mval2");
HashPMap<String, String> pmap2 = HashTreePMap.from(map);
assertEquals(pmap2.size(), 2);
}
@Test
public void whenHashPMapMethods_thenPerformOperations() {
HashPMap<String, String> pmap = HashTreePMap.empty();
HashPMap<String, String> pmap0 = pmap.plus("key1", "value1");
Map map = new HashMap();
map.put("key2", "val2");
map.put("key3", "val3");
HashPMap<String, String> pmap1 = pmap0.plusAll(map);
HashPMap<String, String> pmap2 = pmap1.minus("key1");
HashPMap<String, String> pmap3 = pmap2.minusAll(map.keySet());
assertEquals(pmap0.size(), 1);
assertEquals(pmap1.size(), 3);
assertFalse(pmap2.containsKey("key1"));
assertEquals(pmap3.size(), 0);
}
@Test
public void whenTreePVectorMethods_thenPerformOperations() {
TreePVector pVector = TreePVector.empty();
TreePVector pV1 = pVector.plus("e1");
TreePVector pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4"));
assertEquals(1, pV1.size());
assertEquals(4, pV2.size());
TreePVector pV3 = pV2.minus("e1");
TreePVector pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4"));
assertEquals(pV3.size(), 3);
assertEquals(pV4.size(), 0);
TreePVector pSub = pV2.subList(0, 2);
assertTrue(pSub.contains("e1") && pSub.contains("e2"));
TreePVector pVW = (TreePVector) pV2.with(0, "e10");
assertEquals(pVW.get(0), "e10");
}
@Test
public void whenMapPSetMethods_thenPerformOperations() {
MapPSet pSet = HashTreePSet.empty()
.plusAll(Arrays.asList("e1","e2","e3","e4"));
assertEquals(pSet.size(), 4);
MapPSet pSet1 = pSet.minus("e4");
assertFalse(pSet1.contains("e4"));
}
}
@@ -13,11 +13,11 @@ public class WordUtilsTest {
Assert.assertEquals("To Be Capitalized!", result);
}
@Test
public void whenContainsWords_thenCorrect() {
boolean containsWords = WordUtils.containsAllWords("String to search", "to", "search");
Assert.assertTrue(containsWords);
}
}
@@ -1,85 +0,0 @@
package com.baeldung.zip;
import com.google.common.collect.Streams;
import org.jooq.lambda.Seq;
import org.jooq.lambda.tuple.Tuple2;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
public class ZipCollectionTest {
List<String> names;
List<Integer> ages;
List<String> expectedOutput;
@Before
public void setUp() throws Exception {
names = Arrays.asList("John", "Jane", "Jack", "Dennis");
ages = Arrays.asList(24, 25, 27);
expectedOutput = Arrays.asList("John:24", "Jane:25", "Jack:27");
}
@Test
public void zipCollectionUsingGuava21() {
List<String> output = Streams
.zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age)
.collect(Collectors.toList());
assertEquals(output, expectedOutput);
}
@Test
public void zipCollectionUsingIntStream() {
List<String> output = IntStream
.range(0, Math.min(names.size(), ages.size()))
.mapToObj(i -> names.get(i) + ":" + ages.get(i))
.collect(Collectors.toList());
assertEquals(output, expectedOutput);
}
@Test
public void zipCollectionUsingJool() {
Seq<String> output = Seq
.of("John", "Jane", "Jack")
.zip(Seq.of(24, 25, 27), (x, y) -> x + ":" + y);
assertEquals(output.toList(), expectedOutput);
}
@Test
public void zipCollectionUsingJoolTuple() {
Seq<Tuple2<String, Integer>> output = Seq
.of("John", "Jane", "Dennis")
.zip(Seq.of(24, 25, 27));
Tuple2<String, Integer> element1 = new Tuple2<String, Integer>("John", 24);
Tuple2<String, Integer> element2 = new Tuple2<String, Integer>("Jane", 25);
Tuple2<String, Integer> element3 = new Tuple2<String, Integer>("Dennis", 27);
List<Tuple2> expectedOutput = Arrays.asList(element1, element2, element3);
assertEquals(output.collect(Collectors.toList()), expectedOutput);
}
@Test
public void zipCollectionUsingJoolWithIndex() {
Seq<Tuple2<String, Long>> output = Seq
.of("John", "Jane", "Dennis")
.zipWithIndex();
Tuple2<String, Long> element1 = new Tuple2<>("John", 0L);
Tuple2<String, Long> element2 = new Tuple2<>("Jane", 1L);
Tuple2<String, Long> element3 = new Tuple2<>("Dennis", 2L);
List<Tuple2> expectedOutput = Arrays.asList(element1, element2, element3);
assertEquals(output.collect(Collectors.toList()), expectedOutput);
}
}