Merge branch 'master' into master

This commit is contained in:
Ahmed Tawila 2017-07-08 23:31:51 +03:00 committed by GitHub
commit 54debec690
13 changed files with 328 additions and 42 deletions

View File

@ -1,11 +1,15 @@
package com.baeldung.temporaladjusters; package com.baeldung.temporaladjusters;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek; import java.time.DayOfWeek;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.Period; import java.time.Period;
import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters; import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;

View File

@ -4,9 +4,15 @@ import java.time.DayOfWeek;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters; import java.time.temporal.TemporalAdjusters;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import com.baeldung.temporaladjuster.TemporalAdjusterUtil;
public class TemporalAdjustersTest { public class TemporalAdjustersTest {
@Test @Test

View File

@ -3,11 +3,11 @@ package org.baeldung.guava;
public class CustomEvent { public class CustomEvent {
private String action; private String action;
public CustomEvent(String action) { CustomEvent(String action) {
this.action = action; this.action = action;
} }
public String getAction() { String getAction() {
return action; return action;
} }

View File

@ -28,11 +28,11 @@ public class EventListener {
eventsHandled++; eventsHandled++;
} }
public int getEventsHandled() { int getEventsHandled() {
return eventsHandled; return eventsHandled;
} }
public void resetEventsHandled() { void resetEventsHandled() {
eventsHandled = 0; eventsHandled = 0;
} }
} }

View File

@ -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 BloomFilterTest {
@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();
}
}

View File

@ -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
}
}

View File

@ -349,6 +349,12 @@
<artifactId>java-lsh</artifactId> <artifactId>java-lsh</artifactId>
<version>${java-lsh.version}</version> <version>${java-lsh.version}</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
<dependency> <dependency>
<groupId>au.com.dius</groupId> <groupId>au.com.dius</groupId>
<artifactId>pact-jvm-consumer-junit_2.11</artifactId> <artifactId>pact-jvm-consumer-junit_2.11</artifactId>

View File

@ -8,25 +8,23 @@ public class AsyncService {
private final int DELAY = 1000; private final int DELAY = 1000;
private final int INIT_DELAY = 2000; private final int INIT_DELAY = 2000;
private AtomicLong value = new AtomicLong(0); private final AtomicLong value = new AtomicLong(0);
private Executor executor = Executors.newFixedThreadPool(4); private final Executor executor = Executors.newFixedThreadPool(4);
private volatile boolean initialized = false; private volatile boolean initialized = false;
public void initialize() { void initialize() {
executor.execute(() -> { executor.execute(() -> {
sleep(INIT_DELAY); sleep(INIT_DELAY);
initialized = true; initialized = true;
}); });
} }
public boolean isInitialized() { boolean isInitialized() {
return initialized; return initialized;
} }
public void addValue(long val) { void addValue(long val) {
if (!isInitialized()) { throwIfNotInitialized();
throw new IllegalStateException("Service is not initialized");
}
executor.execute(() -> { executor.execute(() -> {
sleep(DELAY); sleep(DELAY);
value.addAndGet(val); value.addAndGet(val);
@ -34,9 +32,7 @@ public class AsyncService {
} }
public long getValue() { public long getValue() {
if (!isInitialized()) { throwIfNotInitialized();
throw new IllegalStateException("Service is not initialized");
}
return value.longValue(); return value.longValue();
} }
@ -47,4 +43,10 @@ public class AsyncService {
e.printStackTrace(); e.printStackTrace();
} }
} }
private void throwIfNotInitialized() {
if (!initialized) {
throw new IllegalStateException("Service is not initialized");
}
}
} }

View File

@ -0,0 +1,40 @@
package com.baeldung.zip;
import com.google.common.collect.Streams;
import org.jooq.lambda.Seq;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
public class ZipCollectionExample {
static List<String> names = Arrays.asList("John", "Jane", "Jack", "Dennis");
static List<Integer> ages = Arrays.asList(24, 25, 27);
public static void main(String[] args) {
// Using Streams API from Guava 21
Streams
.zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age)
.forEach(System.out::println);
// Using native Java 8 Int Stream
IntStream
.range(0, Math.min(names.size(), ages.size()))
.mapToObj(i -> names.get(i) + ":" + ages.get(i))
.forEach(System.out::println);
// Using jOOL
Seq
.of("John", "Jane", "Dennis")
.zip(Seq.of(24, 25, 27));
Seq
.of("John", "Jane", "Dennis")
.zip(Seq.of(24, 25, 27), (x, y) -> x + ":" + y);
Seq
.of("a", "b", "c")
.zipWithIndex();
}
}

View File

@ -1,19 +1,20 @@
package com.baeldung.awaitility; 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;
import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.await; import static org.awaitility.Awaitility.await;
import static org.awaitility.Awaitility.fieldIn; import static org.awaitility.Awaitility.fieldIn;
import static org.awaitility.Awaitility.given; import static org.awaitility.Awaitility.given;
import static org.awaitility.proxy.AwaitilityClassProxy.to; import static org.awaitility.proxy.AwaitilityClassProxy.to;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import org.awaitility.Awaitility;
import org.awaitility.Duration;
import org.junit.Before;
import org.junit.Test;
public class AsyncServiceUnitTest { public class AsyncServiceUnitTest {
private AsyncService asyncService; private AsyncService asyncService;
@ -25,18 +26,18 @@ public class AsyncServiceUnitTest {
@Test @Test
public void givenAsyncService_whenInitialize_thenInitOccurs1() { public void givenAsyncService_whenInitialize_thenInitOccurs1() {
asyncService.initialize(); asyncService.initialize();
Callable<Boolean> isInitialized = () -> asyncService.isInitialized(); Callable<Boolean> isInitialized = asyncService::isInitialized;
await().until(isInitialized); await().until(isInitialized);
} }
@Test @Test
public void givenAsyncService_whenInitialize_thenInitOccurs2() { public void givenAsyncService_whenInitialize_thenInitOccurs2() {
asyncService.initialize(); asyncService.initialize();
Callable<Boolean> isInitialized = () -> asyncService.isInitialized(); Callable<Boolean> isInitialized = asyncService::isInitialized;
await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS) await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS)
.atMost(Duration.FIVE_SECONDS) .atMost(Duration.FIVE_SECONDS)
.with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS) .with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS)
.until(isInitialized); .until(isInitialized);
} }
@Test @Test
@ -46,7 +47,7 @@ public class AsyncServiceUnitTest {
Awaitility.setDefaultTimeout(Duration.ONE_MINUTE); Awaitility.setDefaultTimeout(Duration.ONE_MINUTE);
asyncService.initialize(); asyncService.initialize();
await().until(() -> asyncService.isInitialized()); await().until(asyncService::isInitialized);
} }
@Test @Test
@ -59,14 +60,14 @@ public class AsyncServiceUnitTest {
public void givenAsyncService_whenInitialize_thenInitOccurs3() { public void givenAsyncService_whenInitialize_thenInitOccurs3() {
asyncService.initialize(); asyncService.initialize();
await().until(fieldIn(asyncService) await().until(fieldIn(asyncService)
.ofType(boolean.class) .ofType(boolean.class)
.andWithName("initialized"), equalTo(true)); .andWithName("initialized"), equalTo(true));
} }
@Test @Test
public void givenValue_whenAddValue_thenValueAdded() { public void givenValue_whenAddValue_thenValueAdded() {
asyncService.initialize(); asyncService.initialize();
await().until(() -> asyncService.isInitialized()); await().until(asyncService::isInitialized);
long value = 5; long value = 5;
asyncService.addValue(value); asyncService.addValue(value);
await().until(asyncService::getValue, equalTo(value)); await().until(asyncService::getValue, equalTo(value));
@ -76,9 +77,9 @@ public class AsyncServiceUnitTest {
public void givenAsyncService_whenGetValue_thenExceptionIgnored() { public void givenAsyncService_whenGetValue_thenExceptionIgnored() {
asyncService.initialize(); asyncService.initialize();
given().ignoreException(IllegalStateException.class) given().ignoreException(IllegalStateException.class)
.await() .await()
.atMost(Duration.FIVE_SECONDS) .atMost(Duration.FIVE_SECONDS)
.atLeast(Duration.FIVE_HUNDRED_MILLISECONDS) .atLeast(Duration.FIVE_HUNDRED_MILLISECONDS)
.until(asyncService::getValue, equalTo(0L)); .until(asyncService::getValue, equalTo(0L));
} }
} }

View File

@ -54,8 +54,10 @@ public class CollectionUtilsGuideTest {
@Test @Test
public void givenListOfCustomers_whenTransformed_thenListOfAddress() { public void givenListOfCustomers_whenTransformed_thenListOfAddress() {
Collection<Address> addressCol = CollectionUtils.collect(list1, customer -> { Collection<Address> addressCol = CollectionUtils.collect(list1, new Transformer<Customer, Address>() {
return new Address(customer.getLocality(), customer.getCity(), customer.getZip()); public Address transform(Customer customer) {
return new Address(customer.getLocality(), customer.getCity(), customer.getZip());
}
}); });
List<Address> addressList = new ArrayList<>(addressCol); List<Address> addressList = new ArrayList<>(addressCol);
@ -66,7 +68,11 @@ public class CollectionUtilsGuideTest {
@Test @Test
public void givenCustomerList_whenFiltered_thenCorrectSize() { public void givenCustomerList_whenFiltered_thenCorrectSize() {
boolean isModified = CollectionUtils.filter(linkedList1, customer -> Arrays.asList("Daniel","Kyle").contains(customer.getName())); boolean isModified = CollectionUtils.filter(linkedList1, new Predicate<Customer>() {
public boolean evaluate(Customer customer) {
return Arrays.asList("Daniel","Kyle").contains(customer.getName());
}
});
//filterInverse does the opposite. It removes the element from the list if the Predicate returns true //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 //select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection

View File

@ -0,0 +1,85 @@
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);
}
}