[BAEL-16045] - Moved code to java-string-2

This commit is contained in:
amit2103
2019-10-27 19:47:01 +05:30
parent db85c8f275
commit 6bc2f22a9a
20514 changed files with 1642278 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
+15
View File
@@ -0,0 +1,15 @@
## Guava
This module contains articles a Google Guava
### Relevant Articles:
- [Guava Functional Cookbook](https://www.baeldung.com/guava-functions-predicates)
- [Guide to Guavas PreConditions](https://www.baeldung.com/guava-preconditions)
- [Introduction to Guava CacheLoader](https://www.baeldung.com/guava-cacheloader)
- [Introduction to Guava Memoizer](https://www.baeldung.com/guava-memoizer)
- [Guide to Guavas EventBus](https://www.baeldung.com/guava-eventbus)
- [Guide to Guavas Reflection Utilities](https://www.baeldung.com/guava-reflection)
- [Guide to Mathematical Utilities in Guava](https://www.baeldung.com/guava-math)
- [Bloom Filter in Java using Guava](https://www.baeldung.com/guava-bloom-filter)
- [Quick Guide to the Guava RateLimiter](https://www.baeldung.com/guava-rate-limiter)
+45
View File
@@ -0,0 +1,45 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>guava</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>guava</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>guava</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
</properties>
</project>
@@ -0,0 +1,17 @@
package org.baeldung.guava;
public class CustomEvent {
private String action;
CustomEvent(String action) {
this.action = action;
}
String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}
@@ -0,0 +1,38 @@
package org.baeldung.guava;
import com.google.common.eventbus.DeadEvent;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EventListener {
private static int eventsHandled;
private static final Logger LOG = LoggerFactory.getLogger(EventListener.class);
@Subscribe
public void stringEvent(String event) {
LOG.info("do event [" + event + "]");
eventsHandled++;
}
@Subscribe
public void someCustomEvent(CustomEvent customEvent) {
LOG.info("do event [" + customEvent.getAction() + "]");
eventsHandled++;
}
@Subscribe
public void handleDeadEvent(DeadEvent deadEvent) {
LOG.info("unhandled event [" + deadEvent.getEvent() + "]");
eventsHandled++;
}
int getEventsHandled() {
return eventsHandled;
}
void resetEventsHandled() {
eventsHandled = 0;
}
}
@@ -0,0 +1,17 @@
package org.baeldung.guava.memoizer;
import java.math.BigInteger;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class CostlySupplier {
public static BigInteger generateBigNumber() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
}
return new BigInteger("12345");
}
}
@@ -0,0 +1,22 @@
package org.baeldung.guava.memoizer;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.math.BigInteger;
public class Factorial {
private static LoadingCache<Integer, BigInteger> memo = CacheBuilder.newBuilder()
.build(CacheLoader.from(Factorial::getFactorial));
public static BigInteger getFactorial(int n) {
if (n == 0) {
return BigInteger.ONE;
} else {
return BigInteger.valueOf(n).multiply(memo.getUnchecked(n - 1));
}
}
}
@@ -0,0 +1,26 @@
package org.baeldung.guava.memoizer;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.math.BigInteger;
import java.util.concurrent.TimeUnit;
public class FibonacciSequence {
private static LoadingCache<Integer, BigInteger> memo = CacheBuilder.newBuilder()
.maximumSize(100)
.build(CacheLoader.from(FibonacciSequence::getFibonacciNumber));
public static BigInteger getFibonacciNumber(int n) {
if (n == 0) {
return BigInteger.ZERO;
} else if (n == 1) {
return BigInteger.ONE;
} else {
return memo.getUnchecked(n - 1).add(memo.getUnchecked(n - 2));
}
}
}
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,54 @@
package org.baeldung.guava;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.junit.Test;
import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
public class BloomFilterUnitTest {
@Test
public void givenBloomFilter_whenAddNStringsToIt_thenShouldNotReturnAnyFalsePositive() {
//when
BloomFilter<Integer> filter = BloomFilter.create(
Funnels.integerFunnel(),
500,
0.01);
//when
filter.put(1);
filter.put(2);
filter.put(3);
//then
// the probability that it returns true, but is actually false is 1%
assertThat(filter.mightContain(1)).isTrue();
assertThat(filter.mightContain(2)).isTrue();
assertThat(filter.mightContain(3)).isTrue();
assertThat(filter.mightContain(100)).isFalse();
}
@Test
public void givenBloomFilter_whenAddNStringsToItMoreThanDefinedExpectedInsertions_thenItWillReturnTrueForAlmostAllElements() {
//when
BloomFilter<Integer> filter = BloomFilter.create(
Funnels.integerFunnel(),
5,
0.01);
//when
IntStream.range(0, 100_000).forEach(filter::put);
//then
assertThat(filter.mightContain(1)).isTrue();
assertThat(filter.mightContain(2)).isTrue();
assertThat(filter.mightContain(3)).isTrue();
assertThat(filter.mightContain(1_000_000)).isTrue();
}
}
@@ -0,0 +1,112 @@
package org.baeldung.guava;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.math.BigInteger;
import java.math.RoundingMode;
import org.junit.Test;
import com.google.common.math.BigIntegerMath;
public class GuavaBigIntegerMathUnitTest {
@Test
public void whenPerformBinomialOnTwoIntValues_shouldReturnResult() {
BigInteger result = BigIntegerMath.binomial(6, 3);
assertEquals(new BigInteger("20"), result);
}
@Test
public void whenProformCeilPowOfTwoBigIntegerValues_shouldReturnResult() {
BigInteger result = BigIntegerMath.ceilingPowerOfTwo(new BigInteger("20"));
assertEquals(new BigInteger("32"), result);
}
@Test
public void whenDivideTwoBigIntegerValues_shouldDivideThemAndReturnTheResultForCeilingRounding() {
BigInteger result = BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.CEILING);
assertEquals(new BigInteger("4"), result);
}
@Test
public void whenDivideTwoBigIntegerValues_shouldDivideThemAndReturnTheResultForFloorRounding() {
BigInteger result = BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.FLOOR);
assertEquals(new BigInteger("3"), result);
}
@Test(expected = ArithmeticException.class)
public void whenDivideTwoBigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.UNNECESSARY);
}
@Test
public void whenFactorailInteger_shouldFactorialThemAndReturnTheResultIfInIntRange() {
BigInteger result = BigIntegerMath.factorial(5);
assertEquals(new BigInteger("120"), result);
}
@Test
public void whenFloorPowerOfInteger_shouldReturnValue() {
BigInteger result = BigIntegerMath.floorPowerOfTwo(new BigInteger("30"));
assertEquals(new BigInteger("16"), result);
}
@Test
public void whenIsPowOfInteger_shouldReturnTrueIfPowerOfTwo() {
boolean result = BigIntegerMath.isPowerOfTwo(new BigInteger("16"));
assertTrue(result);
}
@Test
public void whenLog10BigIntegerValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() {
int result = BigIntegerMath.log10(new BigInteger("30"), RoundingMode.CEILING);
assertEquals(2, result);
}
@Test
public void whenLog10BigIntegerValues_shouldog10ThemAndReturnTheResultForFloorRounding() {
int result = BigIntegerMath.log10(new BigInteger("30"), RoundingMode.FLOOR);
assertEquals(1, result);
}
@Test(expected = ArithmeticException.class)
public void whenLog10BigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
BigIntegerMath.log10(new BigInteger("30"), RoundingMode.UNNECESSARY);
}
@Test
public void whenLog2BigIntegerValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() {
int result = BigIntegerMath.log2(new BigInteger("30"), RoundingMode.CEILING);
assertEquals(5, result);
}
@Test
public void whenLog2BigIntegerValues_shouldog2ThemAndReturnTheResultForFloorRounding() {
int result = BigIntegerMath.log2(new BigInteger("30"), RoundingMode.FLOOR);
assertEquals(4, result);
}
@Test(expected = ArithmeticException.class)
public void whenLog2BigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
BigIntegerMath.log2(new BigInteger("30"), RoundingMode.UNNECESSARY);
}
@Test
public void whenSqrtBigIntegerValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() {
BigInteger result = BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.CEILING);
assertEquals(new BigInteger("6"), result);
}
@Test
public void whenSqrtBigIntegerValues_shouldSqrtThemAndReturnTheResultForFloorRounding() {
BigInteger result = BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.FLOOR);
assertEquals(new BigInteger("5"), result);
}
@Test(expected = ArithmeticException.class)
public void whenSqrtBigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.UNNECESSARY);
}
}
@@ -0,0 +1,71 @@
package org.baeldung.guava;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import static com.google.common.collect.Iterables.cycle;
import static com.google.common.collect.Maps.newHashMap;
import static org.assertj.core.api.Assertions.assertThat;
public class GuavaCacheLoaderUnitTest {
int callCount = 0;
@Test
public void givenAMap_whenAddingValues_thenCanTreatThemAsCache() {
Map<String, String> cache = newHashMap();
cache.put("foo", "cachedValueForFoo");
cache.put("bar", "cachedValueForBar");
assertThat(cache.get("foo")).isEqualTo("cachedValueForFoo");
assertThat(cache.get("bar")).isEqualTo("cachedValueForBar");
}
@Test
public void givenCacheLoader_whenGettingItemTwice_shouldOnlyCallOnce() throws ExecutionException {
final LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
.build(new CacheLoader<String, String>() {
@Override
public String load(final String s) throws Exception {
return slowMethod(s);
}
});
String value = loadingCache.get("key");
value = loadingCache.get("key");
assertThat(callCount).isEqualTo(1);
assertThat(value).isEqualTo("key");
}
@Test
public void givenCacheLoader_whenRefreshingItem_shouldCallAgain() throws ExecutionException {
final LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
.build(new CacheLoader<String, String>() {
@Override
public String load(final String s) throws Exception {
return slowMethod(s);
}
});
String value = loadingCache.get("key");
loadingCache.refresh("key");
assertThat(callCount).isEqualTo(2);
assertThat(value).isEqualTo("key");
}
private String slowMethod(final String s) {
callCount++;
return s;
}
}
@@ -0,0 +1,212 @@
package org.baeldung.guava;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalCause;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.common.cache.Weigher;
public class GuavaCacheUnitTest {
@Test
public void whenCacheMiss_thenAutoLoad() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().build(loader);
assertEquals(0, cache.size());
assertEquals("HELLO", cache.getUnchecked("hello"));
assertEquals(1, cache.size());
}
@Test
public void whenCacheReachMaxSize_thenEviction() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(3).build(loader);
cache.getUnchecked("first");
cache.getUnchecked("second");
cache.getUnchecked("third");
cache.getUnchecked("forth");
assertEquals(3, cache.size());
assertNull(cache.getIfPresent("first"));
assertEquals("FORTH", cache.getIfPresent("forth"));
}
@Test
public void whenCacheReachMaxWeight_thenEviction() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final Weigher<String, String> weighByLength = new Weigher<String, String>() {
@Override
public int weigh(final String key, final String value) {
return value.length();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumWeight(16).weigher(weighByLength).build(loader);
cache.getUnchecked("first");
cache.getUnchecked("second");
cache.getUnchecked("third");
cache.getUnchecked("last");
assertEquals(3, cache.size());
assertNull(cache.getIfPresent("first"));
assertEquals("LAST", cache.getIfPresent("last"));
}
@Test
public void whenEntryIdle_thenEviction() throws InterruptedException {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterAccess(2, TimeUnit.MILLISECONDS).build(loader);
cache.getUnchecked("hello");
assertEquals(1, cache.size());
cache.getUnchecked("hello");
Thread.sleep(3);
cache.getUnchecked("test");
assertEquals(1, cache.size());
assertNull(cache.getIfPresent("hello"));
}
@Test
public void whenEntryLiveTimeExpire_thenEviction() throws InterruptedException {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.MILLISECONDS).build(loader);
cache.getUnchecked("hello");
assertEquals(1, cache.size());
Thread.sleep(3);
cache.getUnchecked("test");
assertEquals(1, cache.size());
assertNull(cache.getIfPresent("hello"));
}
@Test
public void whenWeekKeyHasNoRef_thenRemoveFromCache() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().weakKeys().build(loader);
}
@Test
public void whenSoftValue_thenRemoveFromCache() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().softValues().build(loader);
}
@Test
public void whenNullValue_thenOptional() {
final CacheLoader<String, Optional<String>> loader = new CacheLoader<String, Optional<String>>() {
@Override
public final Optional<String> load(final String key) {
return Optional.fromNullable(getSuffix(key));
}
};
final LoadingCache<String, Optional<String>> cache = CacheBuilder.newBuilder().build(loader);
assertEquals("txt", cache.getUnchecked("text.txt").get());
assertFalse(cache.getUnchecked("hello").isPresent());
}
@Test
public void whenLiveTimeEnd_thenRefresh() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().refreshAfterWrite(1, TimeUnit.MINUTES).build(loader);
}
@Test
public void whenPreloadCache_thenUsePutAll() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().build(loader);
final Map<String, String> map = new HashMap<String, String>();
map.put("first", "FIRST");
map.put("second", "SECOND");
cache.putAll(map);
assertEquals(2, cache.size());
}
@Test
public void whenEntryRemovedFromCache_thenNotify() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final RemovalListener<String, String> listener = new RemovalListener<String, String>() {
@Override
public void onRemoval(final RemovalNotification<String, String> n) {
if (n.wasEvicted()) {
final String cause = n.getCause().name();
assertEquals(RemovalCause.SIZE.toString(), cause);
}
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(3).removalListener(listener).build(loader);
cache.getUnchecked("first");
cache.getUnchecked("second");
cache.getUnchecked("third");
cache.getUnchecked("last");
assertEquals(3, cache.size());
}
// UTIL
private String getSuffix(final String str) {
final int lastIndex = str.lastIndexOf('.');
if (lastIndex == -1) {
return null;
}
return str.substring(lastIndex + 1);
}
}
@@ -0,0 +1,98 @@
package org.baeldung.guava;
import static org.junit.Assert.*;
import java.math.RoundingMode;
import org.junit.Test;
import com.google.common.math.DoubleMath;
import com.google.common.math.IntMath;
public class GuavaDoubleMathUnitTest {
@Test
public void whenFactorailDouble_shouldFactorialThemAndReturnTheResultIfInDoubleRange() {
double result = DoubleMath.factorial(5);
assertEquals(120, result, 0);
}
@Test
public void whenFactorailDouble_shouldFactorialThemAndReturnDoubkeInfIfNotInDoubletRange() {
double result = DoubleMath.factorial(Integer.MAX_VALUE);
assertEquals(Double.POSITIVE_INFINITY, result, 0);
}
@Test
public void whenFuzzyCompareDouble_shouldReturnZeroIfInRange() {
int result = DoubleMath.fuzzyCompare(4, 4.05, 0.6);
assertEquals(0, result);
}
@Test
public void whenFuzzyCompareDouble_shouldReturnNonZeroIfNotInRange() {
int result = DoubleMath.fuzzyCompare(4, 5, 0.1);
assertEquals(-1, result);
}
@Test
public void whenFuzzyEqualDouble_shouldReturnZeroIfInRange() {
boolean result = DoubleMath.fuzzyEquals(4, 4.05, 0.6);
assertTrue(result);
}
@Test
public void whenFuzzyEqualDouble_shouldReturnNonZeroIfNotInRange() {
boolean result = DoubleMath.fuzzyEquals(4, 5, 0.1);
assertFalse(result);
}
@Test
public void whenMathematicalIntDouble_shouldReturnTrueIfInRange() {
boolean result = DoubleMath.isMathematicalInteger(5);
assertTrue(result);
}
@Test
public void whenMathematicalIntDouble_shouldReturnFalseIfNotInRange() {
boolean result = DoubleMath.isMathematicalInteger(5.2);
assertFalse(result);
}
@Test
public void whenIsPowerOfTwoDouble_shouldReturnTrueIfIsPowerOfTwo() {
boolean result = DoubleMath.isMathematicalInteger(4);
assertTrue(result);
}
@Test
public void whenIsPowerOfTwoDouble_shouldReturnFalseIsNotPowerOfTwoe() {
boolean result = DoubleMath.isMathematicalInteger(5.2);
assertFalse(result);
}
@Test
public void whenLog2Double_shouldReturnResult() {
double result = DoubleMath.log2(4);
assertEquals(2, result, 0);
}
@Test
public void whenLog2DoubleValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() {
int result = DoubleMath.log2(30, RoundingMode.CEILING);
assertEquals(5, result);
}
@Test
public void whenLog2DoubleValues_shouldog2ThemAndReturnTheResultForFloorRounding() {
int result = DoubleMath.log2(30, RoundingMode.FLOOR);
assertEquals(4, result);
}
@Test(expected = ArithmeticException.class)
public void whenLog2DoubleValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
DoubleMath.log2(30, RoundingMode.UNNECESSARY);
}
}
@@ -0,0 +1,54 @@
package org.baeldung.guava;
import com.google.common.eventbus.EventBus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class GuavaEventBusUnitTest {
private EventListener listener;
private EventBus eventBus;
@Before
public void setUp() {
eventBus = new EventBus();
listener = new EventListener();
eventBus.register(listener);
}
@After
public void tearDown() {
eventBus.unregister(listener);
}
@Test
public void givenStringEvent_whenEventHandled_thenSuccess() {
listener.resetEventsHandled();
eventBus.post("String Event");
assertEquals(1, listener.getEventsHandled());
}
@Test
public void givenCustomEvent_whenEventHandled_thenSuccess() {
listener.resetEventsHandled();
CustomEvent customEvent = new CustomEvent("Custom Event");
eventBus.post(customEvent);
assertEquals(1, listener.getEventsHandled());
}
@Test
public void givenUnSubscribedEvent_whenEventHandledByDeadEvent_thenSuccess() {
listener.resetEventsHandled();
eventBus.post(12345);
assertEquals(1, listener.getEventsHandled());
}
}
@@ -0,0 +1,186 @@
package org.baeldung.guava;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
public class GuavaFunctionalExamplesUnitTest {
// tests
// predicates - filtering
@Test
public final void whenFilteringNumbersAccordingToACondition_thenCorrectResults() {
final List<Integer> numbers = Lists.newArrayList(1, 2, 3, 6, 8, 10, 34, 57, 89);
final Predicate<Integer> acceptEvenNumber = new Predicate<Integer>() {
@Override
public final boolean apply(final Integer number) {
return (number % 2) == 0;
}
};
final List<Integer> evenNumbers = Lists.newArrayList(Collections2.filter(numbers, acceptEvenNumber));
final Integer found = Collections.binarySearch(evenNumbers, 57);
assertThat(found, lessThan(0));
}
@Test
public final void givenCollectionContainsNulls_whenNullsAreFilteredOut_thenResultingCollectionsHasNoNulls() {
final List<String> withNulls = Lists.newArrayList("a", "bc", null, "def");
final Iterable<String> withoutNuls = Iterables.filter(withNulls, Predicates.notNull());
assertTrue(Iterables.all(withoutNuls, Predicates.notNull()));
}
// predicates - checking
@Test
public final void givenEvenNumbers_whenCheckingIfAllSatisfyTheEvenPredicate_thenYes() {
final List<Integer> evenNumbers = Lists.newArrayList(2, 6, 8, 10, 34, 90);
final Predicate<Integer> acceptEvenNumber = new Predicate<Integer>() {
@Override
public final boolean apply(final Integer number) {
return (number % 2) == 0;
}
};
assertTrue(Iterables.all(evenNumbers, acceptEvenNumber));
}
// negating a predicate
@Test
public final void givenCollectionOfEvenNumbers_whenCheckingThatCollectionContainsNoOddNumber_thenTrue() {
final List<Integer> evenNumbers = Lists.newArrayList(2, 6, 8, 10, 34, 90);
final Predicate<Integer> acceptOddNumber = new Predicate<Integer>() {
@Override
public final boolean apply(final Integer number) {
return (number % 2) != 0;
}
};
assertTrue(Iterables.all(evenNumbers, Predicates.not(acceptOddNumber)));
}
// other predicates
@Test
public final void when_thenCorrect() {
// CharMatcher.forPredicate(predicate)
}
// functions
@Test
public final void whenApplyingSimpleFunctionToInputs_thenCorrectlyTransformed() {
final List<Integer> numbers = Lists.newArrayList(1, 2, 3);
final List<String> numbersAsStrings = Lists.transform(numbers, Functions.toStringFunction());
assertThat(numbersAsStrings, contains("1", "2", "3"));
}
@Test
public final void whenUsingAnIntermediaryFunctionToOrder_thenCorerctlyOrderedInAlphabeticalOrder() {
final List<Integer> numbersToSort = Arrays.asList(2, 1, 11, 100, 8, 14);
final Ordering<Object> ordering = Ordering.natural().onResultOf(Functions.toStringFunction());
final List<Integer> inAlphabeticalOrder = ordering.sortedCopy(numbersToSort);
final List<Integer> correctAlphabeticalOrder = Lists.newArrayList(1, 100, 11, 14, 2, 8);
assertThat(correctAlphabeticalOrder, equalTo(inAlphabeticalOrder));
}
@Test
public final void whenChainingPredicatesAndFunctions_thenCorrectResults() {
final List<Integer> numbers = Arrays.asList(2, 1, 11, 100, 8, 14);
final Predicate<Integer> acceptEvenNumber = new Predicate<Integer>() {
@Override
public final boolean apply(final Integer number) {
return (number % 2) == 0;
}
};
final Function<Integer, Integer> powerOfTwo = new Function<Integer, Integer>() {
@Override
public final Integer apply(final Integer input) {
return (int) Math.pow(input, 2);
}
};
final FluentIterable<Integer> powerOfTwoOnlyForEvenNumbers = FluentIterable.from(numbers).filter(acceptEvenNumber).transform(powerOfTwo);
assertThat(powerOfTwoOnlyForEvenNumbers, contains(4, 10000, 64, 196));
}
@Test
public final void whenUsingFunctionComposition_thenCorrectResults() {
final List<Integer> numbers = Arrays.asList(2, 3);
final Function<Integer, Integer> powerOfTwo = new Function<Integer, Integer>() {
@Override
public final Integer apply(final Integer input) {
return (int) Math.pow(input, 2);
}
};
final List<Integer> result = Lists.transform(numbers, Functions.compose(powerOfTwo, powerOfTwo));
assertThat(result, contains(16, 81));
}
// Set+Function => Map
/**
* - see: http://code.google.com/p/guava-libraries/issues/detail?id=56
*/
@Test
public final void whenMapIsBackedBySetAndFunction_thenCorrect() {
final Function<Integer, Integer> powerOfTwo = new Function<Integer, Integer>() {
@Override
public final Integer apply(final Integer input) {
return (int) Math.pow(input, 2);
}
};
final Set<Integer> lowNumbers = Sets.newHashSet(2, 3, 4);
final Map<Integer, Integer> numberToPowerOfTwoMuttable = Maps.asMap(lowNumbers, powerOfTwo);
final Map<Integer, Integer> numberToPowerOfTwoImuttable = Maps.toMap(lowNumbers, powerOfTwo);
assertThat(numberToPowerOfTwoMuttable.get(2), equalTo(4));
assertThat(numberToPowerOfTwoImuttable.get(2), equalTo(4));
}
// Predicate => Function
@Test
public final void whenConvertingPredicateToFunction_thenCorrect() {
final List<Integer> numbers = Lists.newArrayList(1, 2, 3, 6);
final Predicate<Integer> acceptEvenNumber = new Predicate<Integer>() {
@Override
public final boolean apply(final Integer number) {
return (number % 2) == 0;
}
};
final Function<Integer, Boolean> isEventNumberFunction = Functions.forPredicate(acceptEvenNumber);
final List<Boolean> areNumbersEven = Lists.transform(numbers, isEventNumberFunction);
assertThat(areNumbersEven, contains(false, true, false, true));
}
}
@@ -0,0 +1,274 @@
package org.baeldung.guava;
import static org.junit.Assert.*;
import java.math.RoundingMode;
import com.google.common.math.IntMath;
import org.junit.Test;
public class GuavaIntMathUnitTest {
@Test
public void whenPerformBinomialOnTwoIntegerValues_shouldReturnResultIfUnderInt() {
int result = IntMath.binomial(6, 3);
assertEquals(20, result);
}
@Test
public void whenPerformBinomialOnTwoIntegerValues_shouldReturnIntMaxIfUnderInt() {
int result = IntMath.binomial(Integer.MAX_VALUE, 3);
assertEquals(Integer.MAX_VALUE, result);
}
@Test
public void whenProformCeilPowOfTwoIntegerValues_shouldReturnResult() {
int result = IntMath.ceilingPowerOfTwo(20);
assertEquals(32, result);
}
@Test
public void whenCheckedAddTwoIntegerValues_shouldAddThemAndReturnTheSumIfNotOverflow() {
int result = IntMath.checkedAdd(1, 2);
assertEquals(3, result);
}
@Test(expected = ArithmeticException.class)
public void gwhenCheckedAddTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() {
IntMath.checkedAdd(Integer.MAX_VALUE, 100);
}
@Test
public void whenCheckedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnTheResultIfNotOverflow() {
int result = IntMath.checkedMultiply(1, 2);
assertEquals(2, result);
}
@Test(expected = ArithmeticException.class)
public void gwhenCheckedMultiplyTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() {
IntMath.checkedMultiply(Integer.MAX_VALUE, 100);
}
@Test
public void whenCheckedPowTwoIntegerValues_shouldPowThemAndReturnTheResultIfNotOverflow() {
int result = IntMath.checkedPow(2, 3);
assertEquals(8, result);
}
@Test(expected = ArithmeticException.class)
public void gwhenCheckedPowTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() {
IntMath.checkedPow(Integer.MAX_VALUE, 100);
}
@Test
public void whenCheckedSubstractTwoIntegerValues_shouldSubstractThemAndReturnTheResultIfNotOverflow() {
int result = IntMath.checkedSubtract(4, 1);
assertEquals(3, result);
}
@Test(expected = ArithmeticException.class)
public void gwhenCheckedSubstractTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() {
IntMath.checkedSubtract(Integer.MAX_VALUE, -100);
}
@Test
public void whenDivideTwoIntegerValues_shouldDivideThemAndReturnTheResultForCeilingRounding() {
int result = IntMath.divide(10, 3, RoundingMode.CEILING);
assertEquals(4, result);
}
@Test
public void whenDivideTwoIntegerValues_shouldDivideThemAndReturnTheResultForFloorRounding() {
int result = IntMath.divide(10, 3, RoundingMode.FLOOR);
assertEquals(3, result);
}
@Test(expected = ArithmeticException.class)
public void whenDivideTwoIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
IntMath.divide(10, 3, RoundingMode.UNNECESSARY);
}
@Test
public void whenFactorailInteger_shouldFactorialThemAndReturnTheResultIfInIntRange() {
int result = IntMath.factorial(5);
assertEquals(120, result);
}
@Test
public void whenFactorailInteger_shouldFactorialThemAndReturnIntMaxIfNotInIntRange() {
int result = IntMath.factorial(Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, result);
}
@Test
public void whenFloorPowerOfInteger_shouldReturnValue() {
int result = IntMath.floorPowerOfTwo(30);
assertEquals(16, result);
}
@Test
public void whenGcdOfTwoIntegers_shouldReturnValue() {
int result = IntMath.gcd(30, 40);
assertEquals(10, result);
}
@Test
public void whenIsPowOfInteger_shouldReturnTrueIfPowerOfTwo() {
boolean result = IntMath.isPowerOfTwo(16);
assertTrue(result);
}
@Test
public void whenIsPowOfInteger_shouldReturnFalseeIfNotPowerOfTwo() {
boolean result = IntMath.isPowerOfTwo(20);
assertFalse(result);
}
@Test
public void whenIsPrineOfInteger_shouldReturnFalseeIfNotPrime() {
boolean result = IntMath.isPrime(20);
assertFalse(result);
}
@Test
public void whenLog10IntegerValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() {
int result = IntMath.log10(30, RoundingMode.CEILING);
assertEquals(2, result);
}
@Test
public void whenLog10IntegerValues_shouldog10ThemAndReturnTheResultForFloorRounding() {
int result = IntMath.log10(30, RoundingMode.FLOOR);
assertEquals(1, result);
}
@Test(expected = ArithmeticException.class)
public void whenLog10IntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
IntMath.log10(30, RoundingMode.UNNECESSARY);
}
@Test
public void whenLog2IntegerValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() {
int result = IntMath.log2(30, RoundingMode.CEILING);
assertEquals(5, result);
}
@Test
public void whenLog2IntegerValues_shouldog2ThemAndReturnTheResultForFloorRounding() {
int result = IntMath.log2(30, RoundingMode.FLOOR);
assertEquals(4, result);
}
@Test(expected = ArithmeticException.class)
public void whenLog2IntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
IntMath.log2(30, RoundingMode.UNNECESSARY);
}
@Test
public void whenMeanTwoIntegerValues_shouldMeanThemAndReturnTheResult() {
int result = IntMath.mean(30, 20);
assertEquals(25, result);
}
@Test
public void whenModTwoIntegerValues_shouldModThemAndReturnTheResult() {
int result = IntMath.mod(30, 4);
assertEquals(2, result);
}
@Test
public void whenPowTwoIntegerValues_shouldPowThemAndReturnTheResult() {
int result = IntMath.pow(6, 4);
assertEquals(1296, result);
}
@Test
public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnTheResult() {
int result = IntMath.saturatedAdd(6, 4);
assertEquals(10, result);
}
@Test
public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnIntMaxIfOverflow() {
int result = IntMath.saturatedAdd(Integer.MAX_VALUE, 1000);
assertEquals(Integer.MAX_VALUE, result);
}
@Test
public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnIntMinIfUnderflow() {
int result = IntMath.saturatedAdd(Integer.MIN_VALUE, -1000);
assertEquals(Integer.MIN_VALUE, result);
}
@Test
public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnTheResult() {
int result = IntMath.saturatedMultiply(6, 4);
assertEquals(24, result);
}
@Test
public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnIntMaxIfOverflow() {
int result = IntMath.saturatedMultiply(Integer.MAX_VALUE, 1000);
assertEquals(Integer.MAX_VALUE, result);
}
@Test
public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnIntMinIfUnderflow() {
int result = IntMath.saturatedMultiply(Integer.MIN_VALUE, 1000);
assertEquals(Integer.MIN_VALUE, result);
}
@Test
public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnTheResult() {
int result = IntMath.saturatedPow(6, 2);
assertEquals(36, result);
}
@Test
public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnIntMaxIfOverflow() {
int result = IntMath.saturatedPow(Integer.MAX_VALUE, 2);
assertEquals(Integer.MAX_VALUE, result);
}
@Test
public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnIntMinIfUnderflow() {
int result = IntMath.saturatedPow(Integer.MIN_VALUE, 3);
assertEquals(Integer.MIN_VALUE, result);
}
@Test
public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractThemAndReturnTheResult() {
int result = IntMath.saturatedSubtract(6, 2);
assertEquals(4, result);
}
@Test
public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractwThemAndReturnIntMaxIfOverflow() {
int result = IntMath.saturatedSubtract(Integer.MAX_VALUE, -2);
assertEquals(Integer.MAX_VALUE, result);
}
@Test
public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractThemAndReturnIntMinIfUnderflow() {
int result = IntMath.saturatedSubtract(Integer.MIN_VALUE, 3);
assertEquals(Integer.MIN_VALUE, result);
}
@Test
public void whenSqrtIntegerValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() {
int result = IntMath.sqrt(30, RoundingMode.CEILING);
assertEquals(6, result);
}
@Test
public void whenSqrtIntegerValues_shouldSqrtThemAndReturnTheResultForFloorRounding() {
int result = IntMath.sqrt(30, RoundingMode.FLOOR);
assertEquals(5, result);
}
@Test(expected = ArithmeticException.class)
public void whenSqrtIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
IntMath.sqrt(30, RoundingMode.UNNECESSARY);
}
}
@@ -0,0 +1,268 @@
package org.baeldung.guava;
import static org.junit.Assert.*;
import java.math.RoundingMode;
import com.google.common.math.LongMath;
import org.junit.Test;
public class GuavaLongMathUnitTest {
@Test
public void whenPerformBinomialOnTwoLongValues_shouldReturnResultIfUnderLong() {
long result = LongMath.binomial(6, 3);
assertEquals(20L, result);
}
@Test
public void whenProformCeilPowOfTwoLongValues_shouldReturnResult() {
long result = LongMath.ceilingPowerOfTwo(20L);
assertEquals(32L, result);
}
@Test
public void whenCheckedAddTwoLongValues_shouldAddThemAndReturnTheSumIfNotOverflow() {
long result = LongMath.checkedAdd(1L, 2L);
assertEquals(3L, result);
}
@Test(expected = ArithmeticException.class)
public void whenCheckedAddTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() {
LongMath.checkedAdd(Long.MAX_VALUE, 100L);
}
@Test
public void whenCheckedMultiplyTwoLongValues_shouldMultiplyThemAndReturnTheResultIfNotOverflow() {
long result = LongMath.checkedMultiply(3L, 2L);
assertEquals(6L, result);
}
@Test(expected = ArithmeticException.class)
public void whenCheckedMultiplyTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() {
LongMath.checkedMultiply(Long.MAX_VALUE, 100L);
}
@Test
public void whenCheckedPowTwoLongValues_shouldPowThemAndReturnTheResultIfNotOverflow() {
long result = LongMath.checkedPow(2L, 3);
assertEquals(8L, result);
}
@Test(expected = ArithmeticException.class)
public void gwhenCheckedPowTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() {
LongMath.checkedPow(Long.MAX_VALUE, 100);
}
@Test
public void whenCheckedSubstractTwoLongValues_shouldSubstractThemAndReturnTheResultIfNotOverflow() {
long result = LongMath.checkedSubtract(4L, 1L);
assertEquals(3L, result);
}
@Test(expected = ArithmeticException.class)
public void gwhenCheckedSubstractTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() {
LongMath.checkedSubtract(Long.MAX_VALUE, -100);
}
@Test
public void whenDivideTwoLongValues_shouldDivideThemAndReturnTheResultForCeilingRounding() {
long result = LongMath.divide(10L, 3L, RoundingMode.CEILING);
assertEquals(4L, result);
}
@Test
public void whenDivideTwoLongValues_shouldDivideThemAndReturnTheResultForFloorRounding() {
long result = LongMath.divide(10L, 3L, RoundingMode.FLOOR);
assertEquals(3L, result);
}
@Test(expected = ArithmeticException.class)
public void whenDivideTwoLongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
LongMath.divide(10L, 3L, RoundingMode.UNNECESSARY);
}
@Test
public void whenFactorailLong_shouldFactorialThemAndReturnTheResultIfInIntRange() {
long result = LongMath.factorial(5);
assertEquals(120L, result);
}
@Test
public void whenFactorailLong_shouldFactorialThemAndReturnIntMaxIfNotInIntRange() {
long result = LongMath.factorial(Integer.MAX_VALUE);
assertEquals(Long.MAX_VALUE, result);
}
@Test
public void whenFloorPowerOfLong_shouldReturnValue() {
long result = LongMath.floorPowerOfTwo(30L);
assertEquals(16L, result);
}
@Test
public void whenGcdOfTwoLongs_shouldReturnValue() {
long result = LongMath.gcd(30L, 40L);
assertEquals(10L, result);
}
@Test
public void whenIsPowOfLong_shouldReturnTrueIfPowerOfTwo() {
boolean result = LongMath.isPowerOfTwo(16L);
assertTrue(result);
}
@Test
public void whenIsPowOfLong_shouldReturnFalseeIfNotPowerOfTwo() {
boolean result = LongMath.isPowerOfTwo(20L);
assertFalse(result);
}
@Test
public void whenIsPrineOfLong_shouldReturnFalseeIfNotPrime() {
boolean result = LongMath.isPrime(20L);
assertFalse(result);
}
@Test
public void whenLog10LongValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() {
int result = LongMath.log10(30L, RoundingMode.CEILING);
assertEquals(2, result);
}
@Test
public void whenLog10LongValues_shouldog10ThemAndReturnTheResultForFloorRounding() {
int result = LongMath.log10(30L, RoundingMode.FLOOR);
assertEquals(1, result);
}
@Test(expected = ArithmeticException.class)
public void whenLog10LongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
LongMath.log10(30L, RoundingMode.UNNECESSARY);
}
@Test
public void whenLog2LongValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() {
int result = LongMath.log2(30L, RoundingMode.CEILING);
assertEquals(5, result);
}
@Test
public void whenLog2LongValues_shouldog2ThemAndReturnTheResultForFloorRounding() {
int result = LongMath.log2(30L, RoundingMode.FLOOR);
assertEquals(4, result);
}
@Test(expected = ArithmeticException.class)
public void whenLog2LongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
LongMath.log2(30L, RoundingMode.UNNECESSARY);
}
@Test
public void whenMeanTwoLongValues_shouldMeanThemAndReturnTheResult() {
long result = LongMath.mean(30L, 20L);
assertEquals(25L, result);
}
@Test
public void whenModLongAndIntegerValues_shouldModThemAndReturnTheResult() {
int result = LongMath.mod(30L, 4);
assertEquals(2, result);
}
@Test
public void whenModTwoLongValues_shouldModThemAndReturnTheResult() {
long result = LongMath.mod(30L, 4L);
assertEquals(2L, result);
}
@Test
public void whenPowTwoLongValues_shouldPowThemAndReturnTheResult() {
long result = LongMath.pow(6L, 4);
assertEquals(1296L, result);
}
@Test
public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnTheResult() {
long result = LongMath.saturatedAdd(6L, 4L);
assertEquals(10L, result);
}
@Test
public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnIntMaxIfOverflow() {
long result = LongMath.saturatedAdd(Long.MAX_VALUE, 1000L);
assertEquals(Long.MAX_VALUE, result);
}
@Test
public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnIntMinIfUnderflow() {
long result = LongMath.saturatedAdd(Long.MIN_VALUE, -1000);
assertEquals(Long.MIN_VALUE, result);
}
@Test
public void whenSaturatedMultiplyTwoLongValues_shouldMultiplyThemAndReturnTheResult() {
long result = LongMath.saturatedMultiply(6L, 4L);
assertEquals(24L, result);
}
@Test
public void whenSaturatedMultiplyTwoLongValues_shouldMultiplyThemAndReturnIntMaxIfOverflow() {
long result = LongMath.saturatedMultiply(Long.MAX_VALUE, 1000L);
assertEquals(Long.MAX_VALUE, result);
}
@Test
public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnTheResult() {
long result = LongMath.saturatedPow(6L, 2);
assertEquals(36L, result);
}
@Test
public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnIntMaxIfOverflow() {
long result = LongMath.saturatedPow(Long.MAX_VALUE, 2);
assertEquals(Long.MAX_VALUE, result);
}
@Test
public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnIntMinIfUnderflow() {
long result = LongMath.saturatedPow(Long.MIN_VALUE, 3);
assertEquals(Long.MIN_VALUE, result);
}
@Test
public void whenSaturatedSubstractTwoLongValues_shouldSubstractThemAndReturnTheResult() {
long result = LongMath.saturatedSubtract(6L, 2L);
assertEquals(4L, result);
}
@Test
public void whenSaturatedSubstractTwoLongValues_shouldSubstractwThemAndReturnIntMaxIfOverflow() {
long result = LongMath.saturatedSubtract(Long.MAX_VALUE, -2L);
assertEquals(Long.MAX_VALUE, result);
}
@Test
public void whenSaturatedSubstractTwoLongValues_shouldSubstractThemAndReturnIntMinIfUnderflow() {
long result = LongMath.saturatedSubtract(Long.MIN_VALUE, 3L);
assertEquals(Long.MIN_VALUE, result);
}
@Test
public void whenSqrtLongValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() {
long result = LongMath.sqrt(30L, RoundingMode.CEILING);
assertEquals(6L, result);
}
@Test
public void whenSqrtLongValues_shouldSqrtThemAndReturnTheResultForFloorRounding() {
long result = LongMath.sqrt(30L, RoundingMode.FLOOR);
assertEquals(5L, result);
}
@Test(expected = ArithmeticException.class)
public void whenSqrtLongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
LongMath.sqrt(30L, RoundingMode.UNNECESSARY);
}
}
@@ -0,0 +1,220 @@
package org.baeldung.guava;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.*;
import java.math.BigInteger;
import java.math.RoundingMode;
import org.junit.Test;
import com.google.common.math.DoubleMath;
import com.google.common.math.IntMath;
public class GuavaMathUnitTest {
@Test(expected = ArithmeticException.class)
public void whenSumOverflow_thenThrowException() {
IntMath.checkedAdd(Integer.MAX_VALUE, 1);
}
@Test(expected = ArithmeticException.class)
public void whenSumUnderflow_thenThrowException() {
IntMath.checkedAdd(Integer.MIN_VALUE, -1);
}
@Test
public void should_calculate_sum() {
int result = IntMath.checkedAdd(2, 1);
assertThat(result, equalTo(3));
}
@Test
public void whenSumOverflow_thenReturnMaxInteger() {
int result = IntMath.saturatedAdd(Integer.MAX_VALUE, 100);
assertThat(result, equalTo(Integer.MAX_VALUE));
}
@Test
public void whenSumUnderflow_thenReturnMinInteger() {
int result = IntMath.saturatedAdd(Integer.MIN_VALUE, -100);
assertThat(result, equalTo(Integer.MIN_VALUE));
}
@Test(expected = ArithmeticException.class)
public void whenDifferenceOverflow_thenThrowException() {
IntMath.checkedSubtract(Integer.MAX_VALUE, -1);
}
@Test(expected = ArithmeticException.class)
public void whenDifferenceUnderflow_thenThrowException() {
IntMath.checkedSubtract(Integer.MIN_VALUE, 1);
}
@Test
public void should_calculate_difference() {
int result = IntMath.checkedSubtract(200, 100);
assertThat(result, equalTo(100));
}
@Test
public void whenDifferenceOverflow_thenReturnMaxInteger() {
int result = IntMath.saturatedSubtract(Integer.MAX_VALUE, -1);
assertThat(result, equalTo(Integer.MAX_VALUE));
}
@Test
public void whenDifferenceUnderflow_thenReturnMinInteger() {
int result = IntMath.saturatedSubtract(Integer.MIN_VALUE, 1);
assertThat(result, equalTo(Integer.MIN_VALUE));
}
@Test(expected = ArithmeticException.class)
public void whenProductOverflow_thenThrowException() {
IntMath.checkedMultiply(Integer.MAX_VALUE, 2);
}
@Test(expected = ArithmeticException.class)
public void whenProductUnderflow_thenThrowException() {
IntMath.checkedMultiply(Integer.MIN_VALUE, 2);
}
@Test
public void should_calculate_product() {
int result = IntMath.checkedMultiply(21, 3);
assertThat(result, equalTo(63));
}
@Test
public void whenProductOverflow_thenReturnMaxInteger() {
int result = IntMath.saturatedMultiply(Integer.MAX_VALUE, 2);
assertThat(result, equalTo(Integer.MAX_VALUE));
}
@Test
public void whenProductUnderflow_thenReturnMinInteger() {
int result = IntMath.saturatedMultiply(Integer.MIN_VALUE, 2);
assertThat(result, equalTo(Integer.MIN_VALUE));
}
@Test(expected = ArithmeticException.class)
public void whenPowerOverflow_thenThrowException() {
IntMath.checkedPow(Integer.MAX_VALUE, 2);
}
@Test(expected = ArithmeticException.class)
public void whenPowerUnderflow_thenThrowException() {
IntMath.checkedPow(Integer.MIN_VALUE, 3);
}
@Test
public void should_calculate_power() {
int result = IntMath.saturatedPow(3, 3);
assertThat(result, equalTo(27));
}
@Test
public void whenPowerOverflow_thenReturnMaxInteger() {
int result = IntMath.saturatedPow(Integer.MAX_VALUE, 2);
assertThat(result, equalTo(Integer.MAX_VALUE));
}
@Test
public void whenPowerUnderflow_thenReturnMinInteger() {
int result = IntMath.saturatedPow(Integer.MIN_VALUE, 3);
assertThat(result, equalTo(Integer.MIN_VALUE));
}
@Test
public void should_round_divide_result() {
int result1 = IntMath.divide(3, 2, RoundingMode.DOWN);
assertThat(result1, equalTo(1));
int result2 = IntMath.divide(3, 2, RoundingMode.UP);
assertThat(result2, equalTo(2));
}
@Test
public void should_round_log2_result() {
int result1 = IntMath.log2(5, RoundingMode.FLOOR);
assertThat(result1, equalTo(2));
int result2 = IntMath.log2(5, RoundingMode.CEILING);
assertThat(result2, equalTo(3));
}
@Test
public void should_round_log10_result() {
int result = IntMath.log10(11, RoundingMode.HALF_UP);
assertThat(result, equalTo(1));
}
@Test
public void should_round_sqrt_result() {
int result = IntMath.sqrt(4, RoundingMode.UNNECESSARY);
assertThat(result, equalTo(2));
}
@Test(expected = ArithmeticException.class)
public void whenNeedRounding_thenThrowException() {
IntMath.sqrt(5, RoundingMode.UNNECESSARY);
}
@Test
public void should_calculate_gcd() {
int result = IntMath.gcd(15, 20);
assertThat(result, equalTo(5));
}
@Test
public void should_calculate_mod() {
int result = IntMath.mod(8, 3);
assertThat(result, equalTo(2));
}
@Test
public void should_test_if_is_power_of_two() {
boolean result1 = IntMath.isPowerOfTwo(8);
assertTrue(result1);
boolean result2 = IntMath.isPowerOfTwo(9);
assertFalse(result2);
}
@Test
public void should_calculate_factorial() {
int result = IntMath.factorial(4);
assertThat(result, equalTo(24));
}
@Test
public void should_calculate_binomial() {
int result = IntMath.binomial(7, 3);
assertThat(result, equalTo(35));
}
@Test
public void should_detect_integer() {
boolean result1 = DoubleMath.isMathematicalInteger(2.0);
assertThat(result1, equalTo(true));
boolean result2 = DoubleMath.isMathematicalInteger(2.1);
assertThat(result2, equalTo(false));
}
@Test
public void should_round_to_integer_types() {
int result3 = DoubleMath.roundToInt(2.5, RoundingMode.DOWN);
assertThat(result3, equalTo(2));
long result4 = DoubleMath.roundToLong(2.5, RoundingMode.HALF_UP);
assertThat(result4, equalTo(3L));
BigInteger result5 = DoubleMath.roundToBigInteger(2.5, RoundingMode.UP);
assertThat(result5, equalTo(new BigInteger("3")));
}
@Test
public void should_calculate_log_2() {
int result6 = DoubleMath.log2(10, RoundingMode.UP);
assertThat(result6, equalTo(4));
}
}
@@ -0,0 +1,92 @@
package org.baeldung.guava;
import com.google.common.base.Suppliers;
import org.baeldung.guava.memoizer.CostlySupplier;
import org.baeldung.guava.memoizer.Factorial;
import org.baeldung.guava.memoizer.FibonacciSequence;
import org.junit.Test;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.number.IsCloseTo.closeTo;
import static org.junit.Assert.assertThat;
public class GuavaMemoizerUnitTest {
@Test
public void givenInteger_whenGetFibonacciNumber_thenShouldCalculateFibonacciNumber() {
// given
int n = 95;
// when
BigInteger fibonacciNumber = FibonacciSequence.getFibonacciNumber(n);
// then
BigInteger expectedFibonacciNumber = new BigInteger("31940434634990099905");
assertThat(fibonacciNumber, is(equalTo(expectedFibonacciNumber)));
}
@Test
public void givenInteger_whenGetFactorial_thenShouldCalculateFactorial() {
// given
int n = 95;
// when
BigInteger factorial = Factorial.getFactorial(n);
// then
BigInteger expectedFactorial = new BigInteger("10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000");
assertThat(factorial, is(equalTo(expectedFactorial)));
}
@Test
public void givenMemoizedSupplier_whenGet_thenSubsequentGetsAreFast() {
// given
Supplier<BigInteger> memoizedSupplier;
memoizedSupplier = Suppliers.memoize(CostlySupplier::generateBigNumber);
// when
BigInteger expectedValue = new BigInteger("12345");
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 2000D);
// then
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 0D);
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 0D);
}
@Test
public void givenMemoizedSupplierWithExpiration_whenGet_thenSubsequentGetsBeforeExpiredAreFast() throws InterruptedException {
// given
Supplier<BigInteger> memoizedSupplier;
memoizedSupplier = Suppliers.memoizeWithExpiration(CostlySupplier::generateBigNumber, 3, TimeUnit.SECONDS);
// when
BigInteger expectedValue = new BigInteger("12345");
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 2000D);
// then
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 0D);
// add one more second until memoized Supplier is evicted from memory
TimeUnit.SECONDS.sleep(3);
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 2000D);
}
private <T> void assertSupplierGetExecutionResultAndDuration(Supplier<T> supplier,
T expectedValue,
double expectedDurationInMs) {
Instant start = Instant.now();
T value = supplier.get();
Long durationInMs = Duration.between(start, Instant.now()).toMillis();
double marginOfErrorInMs = 100D;
assertThat(value, is(equalTo(expectedValue)));
assertThat(durationInMs.doubleValue(), is(closeTo(expectedDurationInMs, marginOfErrorInMs)));
}
}
@@ -0,0 +1,104 @@
package org.baeldung.guava;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Arrays;
import org.junit.Test;
import com.google.common.base.*;
public class GuavaPreConditionsUnitTest {
@Test
public void whenCheckArgumentEvaluatesFalse_throwsException() {
int age = -18;
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0)).isInstanceOf(IllegalArgumentException.class).hasMessage(null).hasNoCause();
}
@Test
public void givenErrorMessage_whenCheckArgumentEvaluatesFalse_throwsException() {
final int age = -18;
final String message = "Age can't be zero or less than zero";
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message)).isInstanceOf(IllegalArgumentException.class).hasMessage(message).hasNoCause();
}
@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.";
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message, age)).isInstanceOf(IllegalArgumentException.class).hasMessage(message, age).hasNoCause();
}
@Test
public void givenArrayOfIntegers_whenCheckElementIndexEvaluatesFalse_throwsException() {
final int[] numbers = { 1, 2, 3, 4, 5 };
assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
}
@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";
assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause();
}
@Test
public void givenNullString_whenCheckNotNullCalledWithMessage_throwsException() {
final String nullObject = null;
final String message = "Please check the Object supplied, its null!";
assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message)).isInstanceOf(NullPointerException.class).hasMessage(message).hasNoCause();
}
@Test
public void givenNullString_whenCheckNotNullCalledWithTemplatedMessage_throwsException() {
final String nullObject = null;
final String message = "Please check the Object supplied, its %s!";
assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message, new Object[] { null })).isInstanceOf(NullPointerException.class).hasMessage(message, nullObject).hasNoCause();
}
@Test
public void givenArrayOfIntegers_whenCheckPositionIndexEvaluatesFalse_throwsException() {
final int[] numbers = { 1, 2, 3, 4, 5 };
assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
}
@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";
assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause();
}
@Test
public void givenArrayOfIntegers_whenCheckPositionIndexesEvaluatesFalse_throwsException() {
final int[] numbers = { 1, 2, 3, 4, 5 };
assertThatThrownBy(() -> Preconditions.checkPositionIndexes(6, 0, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
}
@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";
assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message)).isInstanceOf(IllegalStateException.class).hasMessageStartingWith(message).hasNoCause();
}
@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.";
assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates))).isInstanceOf(IllegalStateException.class)
.hasMessage(message, givenState, Arrays.toString(validStates)).hasNoCause();
}
}
@@ -0,0 +1,150 @@
package org.baeldung.guava;
import com.google.common.collect.Lists;
import com.google.common.reflect.Invokable;
import com.google.common.reflect.TypeToken;
import org.junit.Test;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class GuavaReflectionUtilsUnitTest {
@Test
public void givenTwoGenericList_whenCheckIsAssignableFrom_thenReturnTrueDueToTypeErasure() {
//given
ArrayList<String> stringList = Lists.newArrayList();
ArrayList<Integer> intList = Lists.newArrayList();
//when
boolean result = stringList.getClass().isAssignableFrom(intList.getClass());
//then
assertTrue(result);
}
@Test
public void givenTypeToken_whenResolveType_thenShouldResolveProperType() {
//given
TypeToken<List<String>> stringListToken = new TypeToken<List<String>>() {
};
TypeToken<List<Integer>> integerListToken = new TypeToken<List<Integer>>() {
};
TypeToken<List<? extends Number>> numberTypeToken = new TypeToken<List<? extends Number>>() {
};
//then
assertFalse(stringListToken.isSubtypeOf(integerListToken));
assertFalse(numberTypeToken.isSubtypeOf(integerListToken));
assertTrue(integerListToken.isSubtypeOf(numberTypeToken));
}
@Test
public void givenCustomClass_whenCaptureGeneric_thenReturnTypeAtRuntime() {
//given
ParametrizedClass<String> parametrizedClass = new ParametrizedClass<String>() {
};
//then
assertEquals(parametrizedClass.type, TypeToken.of(String.class));
}
@Test
public void givenComplexType_whenGetTypeArgument_thenShouldReturnTypeAtRuntime() {
//given
TypeToken<Function<Integer, String>> funToken = new TypeToken<Function<Integer, String>>() {
};
//when
TypeToken<?> funResultToken = funToken.resolveType(Function.class.getTypeParameters()[1]);
//then
assertEquals(funResultToken, TypeToken.of(String.class));
}
@Test
public void givenMapType_whenGetTypeArgumentOfEntry_thenShouldReturnTypeAtRuntime() throws NoSuchMethodException {
//given
TypeToken<Map<String, Integer>> mapToken = new TypeToken<Map<String, Integer>>() {
};
//when
TypeToken<?> entrySetToken = mapToken.resolveType(Map.class.getMethod("entrySet").getGenericReturnType());
//then
assertEquals(entrySetToken, new TypeToken<Set<Map.Entry<String, Integer>>>() {
});
}
@Test
public void givenInvokable_whenCheckPublicMethod_shouldReturnTrue() throws NoSuchMethodException {
//given
Method method = CustomClass.class.getMethod("somePublicMethod");
Invokable<CustomClass, ?> invokable = new TypeToken<CustomClass>() {
}.method(method);
//when
boolean isPublicStandradJava = Modifier.isPublic(method.getModifiers());
boolean isPublicGuava = invokable.isPublic();
//then
assertTrue(isPublicStandradJava);
assertTrue(isPublicGuava);
}
@Test
public void givenInvokable_whenCheckFinalMethod_shouldReturnFalseForIsOverridable() throws NoSuchMethodException {
//given
Method method = CustomClass.class.getMethod("notOverridablePublicMethod");
Invokable<CustomClass, ?> invokable = new TypeToken<CustomClass>() {
}.method(method);
//when
boolean isOverridableStandardJava = (!(Modifier.isFinal(method.getModifiers()) || Modifier.isPrivate(method.getModifiers())
|| Modifier.isStatic(method.getModifiers())
|| Modifier.isFinal(method.getDeclaringClass().getModifiers())));
boolean isOverridableFinalGauava = invokable.isOverridable();
//then
assertFalse(isOverridableStandardJava);
assertFalse(isOverridableFinalGauava);
}
@Test
public void givenListOfType_whenGetReturnRype_shouldCaptureTypeAtRuntime() throws NoSuchMethodException {
//given
Method getMethod = List.class.getMethod("get", int.class);
//when
Invokable<List<Integer>, ?> invokable = new TypeToken<List<Integer>>() {
}.method(getMethod);
//then
assertEquals(TypeToken.of(Integer.class), invokable.getReturnType()); // Not Object.class!
}
abstract class ParametrizedClass<T> {
TypeToken<T> type = new TypeToken<T>(getClass()) {
};
}
class CustomClass {
public void somePublicMethod() {
}
public final void notOverridablePublicMethod() {
}
}
}
@@ -0,0 +1,82 @@
package org.baeldung.guava;
import com.google.common.util.concurrent.RateLimiter;
import org.junit.Test;
import java.time.ZonedDateTime;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
public class RateLimiterLongRunningUnitTest {
@Test
public void givenLimitedResource_whenUseRateLimiter_thenShouldLimitPermits() {
//given
RateLimiter rateLimiter = RateLimiter.create(100);
//when
long startTime = ZonedDateTime.now().getSecond();
IntStream.range(0, 1000).forEach(i -> {
rateLimiter.acquire();
doSomeLimitedOperation();
});
long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime;
//then
assertThat(elapsedTimeSeconds >= 10);
}
@Test
public void givenLimitedResource_whenRequestTwice_thenShouldPermitWithoutBlocking() {
//given
RateLimiter rateLimiter = RateLimiter.create(2);
//when
long startTime = ZonedDateTime.now().getSecond();
rateLimiter.acquire(1);
doSomeLimitedOperation();
rateLimiter.acquire(1);
doSomeLimitedOperation();
long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime;
//then
assertThat(elapsedTimeSeconds <= 1);
}
@Test
public void givenLimitedResource_whenRequestOnce_thenShouldPermitWithoutBlocking() {
//given
RateLimiter rateLimiter = RateLimiter.create(100);
//when
long startTime = ZonedDateTime.now().getSecond();
rateLimiter.acquire(100);
doSomeLimitedOperation();
long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime;
//then
assertThat(elapsedTimeSeconds <= 1);
}
@Test
public void givenLimitedResource_whenTryAcquire_shouldNotBlockIndefinitely() {
//given
RateLimiter rateLimiter = RateLimiter.create(1);
//when
rateLimiter.acquire();
boolean result = rateLimiter.tryAcquire(2, 10, TimeUnit.MILLISECONDS);
//then
assertThat(result).isFalse();
}
private void doSomeLimitedOperation() {
//some computing
}
}
+13
View File
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
+1
View File
@@ -0,0 +1 @@
John Jane Adam Tom
+1
View File
@@ -0,0 +1 @@
Hello world
+1
View File
@@ -0,0 +1 @@
Test
+4
View File
@@ -0,0 +1,4 @@
John
Jane
Adam
Tom
+1
View File
@@ -0,0 +1 @@
Hello world
Binary file not shown.