Merge remote-tracking branch 'origin/master' into bael-835-gc-limit-exceed

This commit is contained in:
slavisa-baeldung 2017-06-30 15:30:32 +01:00
commit 2e2bfeca39
8 changed files with 324 additions and 44 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<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">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
@ -13,6 +13,15 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>central</id>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
@ -31,6 +40,11 @@
<version>${kotlin-reflect.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core</artifactId>
<version>${kotlinx.version}</version>
</dependency>
</dependencies>
@ -104,10 +118,11 @@
</build>
<properties>
<kotlin-maven-plugin.version>1.1.1</kotlin-maven-plugin.version>
<kotlin-test-junit.version>1.1.1</kotlin-test-junit.version>
<kotlin-stdlib.version>1.1.1</kotlin-stdlib.version>
<kotlin-reflect.version>1.1.1</kotlin-reflect.version>
<kotlin-maven-plugin.version>1.1.2</kotlin-maven-plugin.version>
<kotlin-test-junit.version>1.1.2</kotlin-test-junit.version>
<kotlin-stdlib.version>1.1.2</kotlin-stdlib.version>
<kotlin-reflect.version>1.1.2</kotlin-reflect.version>
<kotlinx.version>0.15</kotlinx.version>
</properties>
</project>

View File

@ -0,0 +1,179 @@
package com.baeldung.kotlin
import kotlinx.coroutines.experimental.*
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
import kotlin.coroutines.experimental.buildSequence
import kotlin.system.measureTimeMillis
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class CoroutinesTest {
@Test
fun givenBuildSequence_whenTakeNElements_thenShouldReturnItInALazyWay() {
//given
val fibonacciSeq = buildSequence {
var a = 0
var b = 1
yield(1)
while (true) {
yield(a + b)
val tmp = a + b
a = b
b = tmp
}
}
//when
val res = fibonacciSeq.take(5).toList()
//then
assertEquals(res, listOf(1, 1, 2, 3, 5))
}
@Test
fun givenLazySeq_whenTakeNElements_thenShouldReturnAllElements() {
//given
val lazySeq = buildSequence {
print("START ")
for (i in 1..5) {
yield(i)
print("STEP ")
}
print("END")
}
//when
val res = lazySeq.take(10).toList()
//then
assertEquals(res, listOf(1, 2, 3, 4, 5))
}
@Test
fun givenAsyncCoroutine_whenStartIt_thenShouldExecuteItInTheAsyncWay() {
//given
val res = mutableListOf<String>()
//when
runBlocking<Unit> {
val promise = launch(CommonPool) { expensiveComputation(res) }
res.add("Hello,")
promise.join()
}
//then
assertEquals(res, listOf("Hello,", "word!"))
}
suspend fun expensiveComputation(res: MutableList<String>) {
delay(1000L)
res.add("word!")
}
@Test
fun givenHugeAmountOfCoroutines_whenStartIt_thenShouldExecuteItWithoutOutOfMemory() {
runBlocking<Unit> {
//given
val counter = AtomicInteger(0)
val numberOfCoroutines = 100_000
//when
val jobs = List(numberOfCoroutines) {
launch(CommonPool) {
delay(1L)
counter.incrementAndGet()
}
}
jobs.forEach { it.join() }
//then
assertEquals(counter.get(), numberOfCoroutines)
}
}
@Test
fun givenCancellableJob_whenRequestForCancel_thenShouldQuit() {
runBlocking<Unit> {
//given
val job = launch(CommonPool) {
while (isActive) {
println("is working")
}
}
delay(1300L)
//when
job.cancel()
//then cancel successfully
}
}
@Test(expected = CancellationException::class)
fun givenAsyncAction_whenDeclareTimeout_thenShouldFinishWhenTimedOut() {
runBlocking<Unit> {
withTimeout(1300L) {
repeat(1000) { i ->
println("Some expensive computation $i ...")
delay(500L)
}
}
}
}
@Test
fun givenHaveTwoExpensiveAction_whenExecuteThemAsync_thenTheyShouldRunConcurrently() {
runBlocking<Unit> {
val delay = 1000L
val time = measureTimeMillis {
//given
val one = async(CommonPool) { someExpensiveComputation(delay) }
val two = async(CommonPool) { someExpensiveComputation(delay) }
//when
runBlocking {
one.await()
two.await()
}
}
//then
assertTrue(time < delay * 2)
}
}
@Test
fun givenTwoExpensiveAction_whenExecuteThemLazy_thenTheyShouldNotConcurrently() {
runBlocking<Unit> {
val delay = 1000L
val time = measureTimeMillis {
//given
val one = async(CommonPool, CoroutineStart.LAZY) { someExpensiveComputation(delay) }
val two = async(CommonPool, CoroutineStart.LAZY) { someExpensiveComputation(delay) }
//when
runBlocking {
one.await()
two.await()
}
}
//then
assertTrue(time > delay * 2)
}
}
suspend fun someExpensiveComputation(delayInMilliseconds: Long) {
delay(delayInMilliseconds)
}
}

View File

@ -350,6 +350,17 @@
<artifactId>java-lsh</artifactId>
<version>${java-lsh.version}</version>
</dependency>
<dependency>
<groupId>au.com.dius</groupId>
<artifactId>pact-jvm-consumer-junit_2.11</artifactId>
<version>${pact.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.10</version>
</dependency>
</dependencies>
<properties>
<multiverse.version>0.7.0</multiverse.version>
@ -379,6 +390,7 @@
<commons.collections.version>4.1</commons.collections.version>
<junit.version>4.12</junit.version>
<java-lsh.version>0.10</java-lsh.version>
<pact.version>3.5.0</pact.version>
</properties>
</project>

View File

@ -0,0 +1,82 @@
package com.baeldung.pact;
import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRuleMk2;
import au.com.dius.pact.consumer.PactVerification;
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.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class PactConsumerDrivenContractUnitTest {
@Rule
public PactProviderRuleMk2 mockProvider
= new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
@Pact(consumer = "test_consumer")
public RequestResponsePact createPact(PactDslWithProvider builder) {
Map<String, String> headers = new HashMap<String, String>();
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();
}
@Test
@PactVerification()
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
//when
ResponseEntity<String> response
= new RestTemplate().getForEntity(mockProvider.getUrl(), String.class);
//then
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThat(response.getHeaders().get("Content-Type").contains("application/json")).isTrue();
assertThat(response.getBody()).contains("condition", "true", "name", "tom");
//and
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
String jsonBody = "{\"name\": \"Michael\"}";
//when
ResponseEntity<String> postResponse = new RestTemplate().exchange(
mockProvider.getUrl() + "/create",
HttpMethod.POST,
new HttpEntity<>(jsonBody, httpHeaders),
String.class
);
//then
assertThat(postResponse.getStatusCode().value()).isEqualTo(201);
}
}

View File

@ -88,8 +88,6 @@
<module>junit5</module>
<module>jws</module>
<module>kotlin</module>
<module>libraries</module>
<module>log-mdc</module>
<module>log4j</module>

View File

@ -4,12 +4,10 @@ public class Fare {
private Long nightSurcharge;
private Long rideFare;
private Long totalFare;
public Fare() {
nightSurcharge = 0L;
rideFare = 0L;
totalFare = 0L;
}
public Long getNightSurcharge() {
@ -31,9 +29,4 @@ public class Fare {
public Long getTotalFare() {
return nightSurcharge + rideFare;
}
public void setTotalFare(Long totalFare) {
this.totalFare = totalFare;
}
}

View File

@ -13,7 +13,7 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class TaxiFareConfiguration {
public static final String drlFile = "TAXI_FARE_RULE.drl";
private static final String drlFile = "TAXI_FARE_RULE.drl";
@Bean
public KieContainer kieContainer() {
@ -25,14 +25,11 @@ public class TaxiFareConfiguration {
kieBuilder.buildAll();
KieModule kieModule = kieBuilder.getKieModule();
KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId());
return kContainer;
return kieServices.newKieContainer(kieModule.getReleaseId());
}
@Bean
public TaxiFareCalculatorService taxiFareCalculatorService() {
TaxiFareCalculatorService taxiFareCalculatorService = new TaxiFareCalculatorService();
return taxiFareCalculatorService;
return new TaxiFareCalculatorService();
}
}

View File

@ -1,25 +1,23 @@
package com.baeldung.spring.drools.service;
import com.baeldung.spring.drools.model.Fare;
import com.baeldung.spring.drools.model.TaxiRide;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.spring.drools.model.TaxiRide;
import com.baeldung.spring.drools.model.Fare;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TaxiFareConfiguration.class)
public class TaxiFareCalculatorServiceTest {
@Autowired
TaxiFareCalculatorService taxiFareCalculatorService;
private TaxiFareCalculatorService taxiFareCalculatorService;
@Test
public void testCalculateFareScenario1() {
@ -28,10 +26,11 @@ public class TaxiFareCalculatorServiceTest {
taxiRide.setDistanceInMile(9L);
Fare rideFare = new Fare();
Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare);
Assert.assertNotNull(totalCharge);
Assert.assertEquals(Long.valueOf(70), totalCharge);
assertNotNull(totalCharge);
assertEquals(Long.valueOf(70), totalCharge);
}
@Test
public void testCalculateFareScenario2() {
TaxiRide taxiRide = new TaxiRide();
@ -39,8 +38,9 @@ public class TaxiFareCalculatorServiceTest {
taxiRide.setDistanceInMile(5L);
Fare rideFare = new Fare();
Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare);
Assert.assertNotNull(totalCharge);
Assert.assertEquals(Long.valueOf(100), totalCharge);
assertNotNull(totalCharge);
assertEquals(Long.valueOf(100), totalCharge);
}
@Test
@ -50,10 +50,11 @@ public class TaxiFareCalculatorServiceTest {
taxiRide.setDistanceInMile(50L);
Fare rideFare = new Fare();
Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare);
Assert.assertNotNull(totalCharge);
Assert.assertEquals(Long.valueOf(170), totalCharge);
assertNotNull(totalCharge);
assertEquals(Long.valueOf(170), totalCharge);
}
@Test
public void testCalculateFareScenario4() {
TaxiRide taxiRide = new TaxiRide();
@ -61,10 +62,11 @@ public class TaxiFareCalculatorServiceTest {
taxiRide.setDistanceInMile(50L);
Fare rideFare = new Fare();
Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare);
Assert.assertNotNull(totalCharge);
Assert.assertEquals(Long.valueOf(250), totalCharge);
assertNotNull(totalCharge);
assertEquals(Long.valueOf(250), totalCharge);
}
@Test
public void testCalculateFareScenario5() {
TaxiRide taxiRide = new TaxiRide();
@ -72,10 +74,11 @@ public class TaxiFareCalculatorServiceTest {
taxiRide.setDistanceInMile(100L);
Fare rideFare = new Fare();
Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare);
Assert.assertNotNull(totalCharge);
Assert.assertEquals(Long.valueOf(220), totalCharge);
assertNotNull(totalCharge);
assertEquals(Long.valueOf(220), totalCharge);
}
@Test
public void testCalculateFareScenario6() {
TaxiRide taxiRide = new TaxiRide();
@ -83,8 +86,9 @@ public class TaxiFareCalculatorServiceTest {
taxiRide.setDistanceInMile(100L);
Fare rideFare = new Fare();
Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare);
Assert.assertNotNull(totalCharge);
Assert.assertEquals(Long.valueOf(350), totalCharge);
assertNotNull(totalCharge);
assertEquals(Long.valueOf(350), totalCharge);
}
}