This commit is contained in:
Ahmed Tawila 2017-10-22 10:49:08 +02:00
commit 7120a2f1e3
72 changed files with 921 additions and 434 deletions

View File

@ -0,0 +1 @@
## Relevant articles:

1
apache-cayenne/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
asm/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -1,19 +1,32 @@
package com.baeldung.examples.asm.instrumentation; package com.baeldung.examples.asm.instrumentation;
import com.baeldung.examples.asm.CustomClassWriter; import com.baeldung.examples.asm.CustomClassWriter;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation; import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
/**
*
* @author baeldung
*/
public class Premain { public class Premain {
public static void premain(String agentArgs, Instrumentation inst) { public static void premain(String agentArgs, Instrumentation inst) {
inst.addTransformer((l, name, c, d, b) -> { inst.addTransformer(new ClassFileTransformer() {
if (name.equals("java/lang/Integer")) { @Override
CustomClassWriter cr = new CustomClassWriter(b); public byte[] transform(ClassLoader l, String name, Class c,
return cr.addField(); ProtectionDomain d, byte[] b)
throws IllegalClassFormatException {
if (name.equals("java/lang/Integer")) {
CustomClassWriter cr = new CustomClassWriter(b);
return cr.addField();
}
return b;
} }
return b;
}); });
} }
} }

1
atomix/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -0,0 +1,48 @@
package com.baeldung.staticdemo;
/**
* This class demonstrates the use of static fields and static methods
* the instance variables engine and displacement are distinct for
* each and every object whereas static/class variable numberOfCars
* is unique and is shared across all objects of this class.
*
* @author baeldung
*
*/
public class Car {
private String name;
private String engine;
public static int numberOfCars;
public Car(String name, String engine) {
this.name = name;
this.engine = engine;
numberOfCars++;
}
//getters and setters
public static int getNumberOfCars() {
return numberOfCars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEngine() {
return engine;
}
public void setEngine(String engine) {
this.engine = engine;
}
public static void setNumberOfCars(int numberOfCars) {
Car.numberOfCars = numberOfCars;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.staticdemo;
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.staticdemo;
import java.util.LinkedList;
import java.util.List;
public class StaticBlock {
private static List<String> ranks = new LinkedList<>();
static {
ranks.add("Lieutenant");
ranks.add("Captain");
ranks.add("Major");
}
static {
ranks.add("Colonel");
ranks.add("General");
}
//getters and setters
public static List<String> getRanks() {
return ranks;
}
public static void setRanks(List<String> ranks) {
StaticBlock.ranks = ranks;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.staticdemo;
import static org.junit.Assert.*;
import org.junit.Test;
public class CarIntegrationTest {
@Test
public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() {
new Car("Jaguar", "V8");
new Car("Bugatti", "W16");
assertEquals(2, Car.numberOfCars);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.staticdemo;
import org.junit.Assert;
import org.junit.Test;
public class SingletonIntegrationTest {
@Test
public void givenStaticInnerClass_whenMultipleTimesInstanceCalled_thenOnlyOneTimeInitialized() {
Singleton object1 = Singleton.getInstance();
Singleton object2 = Singleton.getInstance();
Assert.assertSame(object1, object2);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.staticdemo;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.Test;
public class StaticBlockIntegrationTest {
@Test
public void whenAddedListElementsThroughStaticBlock_thenEnsureCorrectOrder() {
List<String> actualList = StaticBlock.getRanks();
assertThat(actualList, contains("Lieutenant", "Captain", "Major", "Colonel", "General"));
}
}

1
deltaspike/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -0,0 +1,38 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<artifactId>drools-backward-chaining</artifactId>
<version>1.0</version>
<name>drools-backward-chaining</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<runtime.version>6.4.0.Final</runtime.version>
</properties>
<dependencies>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-api</artifactId>
<version>${runtime.version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>${runtime.version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<version>${runtime.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,28 @@
package com.baeldung;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import com.baeldung.model.Beatle;
public class BackwardChainingBeatles {
public static void main(String[] args) {
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-backward-chaining");
// drools session base on the xml configuration (<strong>kmodule.xml</strong>)
// graph population
kSession.insert(new Beatle("Starr", "drums"));
kSession.insert(new Beatle("McCartney", "bass"));
kSession.insert(new Beatle("Lennon", "guitar"));
kSession.insert(new Beatle("Harrison", "guitar"));
kSession.insert("Ringo"); // invoke the rule that calls the query implentation of backward chaining
kSession.fireAllRules(); // invoke all the rules
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.model;
import org.kie.api.definition.type.Position;
public class Beatle {
@Position(0)
private String lastName;
@Position(1)
private String instrument;
public Beatle(String lastName, String instrument) {
this.lastName = lastName;
this.instrument = instrument;
}
public String getInstrument() {
return instrument;
}
public void setInstrument(String instrument) {
this.instrument = instrument;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule">
<kbase name="backward_chaining" packages="backward_chaining">
<ksession name="ksession-backward-chaining"/>
</kbase>
</kmodule>

View File

@ -0,0 +1,44 @@
package com.baeldung
import com.baeldung.model.Beatle;
query whichBeatle(String lastName, String instrument)
Beatle(lastName, instrument;)
or
(Beatle(lastName, null;)
and
whichBeatle(null, instrument;)) //recursive call to the function that allows to search in a derivation tree structure
end
rule "Ringo"
when
String(this == "Ringo")
whichBeatle("Starr", "drums";)
then
System.out.println("The beatle is Ringo Starr");
end
rule "Paul"
when
String(this == "Paul")
whichBeatle("McCartney", "bass";)
then
System.out.println("The beatle is Paul McCartney");
end
rule "John"
when
String(this == "John")
whichBeatle("Lennon", "guitar";)
then
System.out.println("The beatle is John Lennon");
end
rule "George"
when
String(this == "George")
whichBeatle("Harrison", "guitar";)
then
System.out.println("The beatle is George Harrison");
end

1
eclipse/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -0,0 +1 @@
## Relevant articles:

1
events/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
gradle/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -0,0 +1 @@
## Relevant articles:

1
guest/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

59
guest/spring-mvc/pom.xml Normal file
View File

@ -0,0 +1,59 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.forketyfork.guest</groupId>
<artifactId>spring-mvc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-mvc</name>
<description>Spring MVC sample project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
</project>

View File

@ -0,0 +1,15 @@
package com.forketyfork.guest.springmvc;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.boot.SpringApplication;
@SpringBootApplication
@ComponentScan(basePackages = {"com.forketyfork.guest.springmvc"})
public class Spring5Application {
public static void main(String[] args) {
SpringApplication.run(Spring5Application.class, args);
}
}

View File

@ -0,0 +1,27 @@
package com.forketyfork.guest.springmvc.model;
public class LoginData {
private String login;
private String password;
public LoginData() {
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -0,0 +1,31 @@
package com.forketyfork.guest.springmvc.web;
import com.forketyfork.guest.springmvc.model.LoginData;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.Collections;
@Controller
public class InternalsController {
private static final String LOGIN = "jack";
private static final String PASSWORD = "halloween";
@GetMapping("/")
public String hello() {
return "login";
}
@PostMapping("/login")
public ModelAndView login(LoginData loginData) {
if (LOGIN.equals(loginData.getLogin()) && PASSWORD.equals(loginData.getPassword())) {
return new ModelAndView("success", Collections.singletonMap("login", loginData.getLogin()));
} else {
return new ModelAndView("failure", Collections.singletonMap("login", loginData.getLogin()));
}
}
}

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login Failure</title>
</head>
<p>
User with login <span th:text="${login}"></span> not found, please <a href="/">try again</a>.
</p>
</html>

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Login Form</title></head>
<body>
<form method="post" action="/login">
<input type="text" placeholder="Login" name="login"/>
<input type="password" placeholder="Password" name="password"/>
<button type="submit">Submit</button>
</form>
</body>
</html>

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login Success</title>
</head>
<p>
Hello, <span th:text="${login}"></span>!
</p>
</html>

1
hibernate5/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -2,7 +2,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>hystrix</artifactId> <artifactId>hystrix</artifactId>
<version>1.0</version> <version>1.0</version>
<name>hystrix</name> <name>hystrix</name>

View File

@ -10,53 +10,53 @@ import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
public class HystrixTimeoutIntegrationTest { public class HystrixTimeoutManualTest {
@Test @Test
public void givenInputBobAndDefaultSettings_whenCommandExecuted_thenReturnHelloBob(){ public void givenInputBobAndDefaultSettings_whenCommandExecuted_thenReturnHelloBob() {
assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!")); assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!"));
} }
@Test @Test
public void givenSvcTimeoutOf100AndDefaultSettings_whenRemoteSvcExecuted_thenReturnSuccess() public void givenSvcTimeoutOf100AndDefaultSettings_whenRemoteSvcExecuted_thenReturnSuccess()
throws InterruptedException { throws InterruptedException {
HystrixCommand.Setter config = HystrixCommand HystrixCommand.Setter config = HystrixCommand
.Setter .Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup2")); .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup2"));
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(), assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(),
equalTo("Success")); equalTo("Success"));
} }
@Test(expected = HystrixRuntimeException.class) @Test(expected = HystrixRuntimeException.class)
public void givenSvcTimeoutOf10000AndDefaultSettings__whenRemoteSvcExecuted_thenExpectHRE() throws InterruptedException { public void givenSvcTimeoutOf10000AndDefaultSettings__whenRemoteSvcExecuted_thenExpectHRE() throws InterruptedException {
HystrixCommand.Setter config = HystrixCommand HystrixCommand.Setter config = HystrixCommand
.Setter .Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest3")); .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest3"));
new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute(); new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute();
} }
@Test @Test
public void givenSvcTimeoutOf5000AndExecTimeoutOf10000_whenRemoteSvcExecuted_thenReturnSuccess() public void givenSvcTimeoutOf5000AndExecTimeoutOf10000_whenRemoteSvcExecuted_thenReturnSuccess()
throws InterruptedException { throws InterruptedException {
HystrixCommand.Setter config = HystrixCommand HystrixCommand.Setter config = HystrixCommand
.Setter .Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest4")); .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest4"));
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
commandProperties.withExecutionTimeoutInMilliseconds(10_000); commandProperties.withExecutionTimeoutInMilliseconds(10_000);
config.andCommandPropertiesDefaults(commandProperties); config.andCommandPropertiesDefaults(commandProperties);
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
equalTo("Success")); equalTo("Success"));
} }
@Test(expected = HystrixRuntimeException.class) @Test(expected = HystrixRuntimeException.class)
public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE() public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE()
throws InterruptedException { throws InterruptedException {
HystrixCommand.Setter config = HystrixCommand HystrixCommand.Setter config = HystrixCommand
.Setter .Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest5")); .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest5"));
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
commandProperties.withExecutionTimeoutInMilliseconds(5_000); commandProperties.withExecutionTimeoutInMilliseconds(5_000);
config.andCommandPropertiesDefaults(commandProperties); config.andCommandPropertiesDefaults(commandProperties);
@ -65,45 +65,45 @@ public class HystrixTimeoutIntegrationTest {
@Test @Test
public void givenSvcTimeoutOf500AndExecTimeoutOf10000AndThreadPool__whenExecuted_thenReturnSuccess() public void givenSvcTimeoutOf500AndExecTimeoutOf10000AndThreadPool__whenExecuted_thenReturnSuccess()
throws InterruptedException { throws InterruptedException {
HystrixCommand.Setter config = HystrixCommand HystrixCommand.Setter config = HystrixCommand
.Setter .Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupThreadPool")); .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupThreadPool"));
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
commandProperties.withExecutionTimeoutInMilliseconds(10_000); commandProperties.withExecutionTimeoutInMilliseconds(10_000);
config.andCommandPropertiesDefaults(commandProperties); config.andCommandPropertiesDefaults(commandProperties);
config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
.withMaxQueueSize(10) .withMaxQueueSize(10)
.withCoreSize(3) .withCoreSize(3)
.withQueueSizeRejectionThreshold(10)); .withQueueSizeRejectionThreshold(10));
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
equalTo("Success")); equalTo("Success"));
} }
@Test @Test
public void givenCircuitBreakerSetup__whenRemoteSvcCmdExecuted_thenReturnSuccess() public void givenCircuitBreakerSetup__whenRemoteSvcCmdExecuted_thenReturnSuccess()
throws InterruptedException { throws InterruptedException {
HystrixCommand.Setter config = HystrixCommand HystrixCommand.Setter config = HystrixCommand
.Setter .Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupCircuitBreaker")); .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupCircuitBreaker"));
HystrixCommandProperties.Setter properties = HystrixCommandProperties.Setter(); HystrixCommandProperties.Setter properties = HystrixCommandProperties.Setter();
properties.withExecutionTimeoutInMilliseconds(1000); properties.withExecutionTimeoutInMilliseconds(1000);
properties.withCircuitBreakerSleepWindowInMilliseconds(4000); properties.withCircuitBreakerSleepWindowInMilliseconds(4000);
properties.withExecutionIsolationStrategy( properties.withExecutionIsolationStrategy(
HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);
properties.withCircuitBreakerEnabled(true); properties.withCircuitBreakerEnabled(true);
properties.withCircuitBreakerRequestVolumeThreshold(1); properties.withCircuitBreakerRequestVolumeThreshold(1);
config.andCommandPropertiesDefaults(properties); config.andCommandPropertiesDefaults(properties);
config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
.withMaxQueueSize(1) .withMaxQueueSize(1)
.withCoreSize(1) .withCoreSize(1)
.withQueueSizeRejectionThreshold(1)); .withQueueSizeRejectionThreshold(1));
assertThat(this.invokeRemoteService(config, 10_000), equalTo(null)); assertThat(this.invokeRemoteService(config, 10_000), equalTo(null));
assertThat(this.invokeRemoteService(config, 10_000), equalTo(null)); assertThat(this.invokeRemoteService(config, 10_000), equalTo(null));
@ -111,19 +111,19 @@ public class HystrixTimeoutIntegrationTest {
Thread.sleep(5000); Thread.sleep(5000);
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
equalTo("Success")); equalTo("Success"));
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
equalTo("Success")); equalTo("Success"));
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
equalTo("Success")); equalTo("Success"));
} }
public String invokeRemoteService(HystrixCommand.Setter config, int timeout) public String invokeRemoteService(HystrixCommand.Setter config, int timeout)
throws InterruptedException { throws InterruptedException {
String response = null; String response = null;
try { try {
response = new RemoteServiceTestCommand(config, response = new RemoteServiceTestCommand(config,
new RemoteServiceTestSimulator(timeout)).execute(); new RemoteServiceTestSimulator(timeout)).execute();
} catch (HystrixRuntimeException ex) { } catch (HystrixRuntimeException ex) {
System.out.println("ex = " + ex); System.out.println("ex = " + ex);
} }

1
intelliJ/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
jhipster/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
jmh/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
jooby/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
json-path/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
linkrest/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -16,7 +16,7 @@
<dep.ver.metrics>3.1.2</dep.ver.metrics> <dep.ver.metrics>3.1.2</dep.ver.metrics>
<dep.ver.servlet>3.1.0</dep.ver.servlet> <dep.ver.servlet>3.1.0</dep.ver.servlet>
<netflix.servo.ver>0.12.17</netflix.servo.ver> <netflix.servo.ver>0.12.17</netflix.servo.ver>
<micrometer.ver>1.0.0-rc.2</micrometer.ver> <micrometer.ver>0.12.0.RELEASE</micrometer.ver>
<spring.boot.ver>2.0.0.M5</spring.boot.ver> <spring.boot.ver>2.0.0.M5</spring.boot.ver>
</properties> </properties>

View File

@ -16,6 +16,7 @@ import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static io.micrometer.core.instrument.Meter.Type;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.hamcrest.core.IsCollectionContaining.hasItems;
@ -27,7 +28,7 @@ import static org.junit.Assert.assertTrue;
*/ */
public class MicrometerAtlasTest { public class MicrometerAtlasTest {
AtlasConfig atlasConfig; private AtlasConfig atlasConfig;
@Before @Before
public void init() { public void init() {
@ -208,32 +209,27 @@ public class MicrometerAtlasTest {
timer.record(8, TimeUnit.SECONDS); timer.record(8, TimeUnit.SECONDS);
timer.record(13, TimeUnit.SECONDS); timer.record(13, TimeUnit.SECONDS);
List<Gauge> quantileGauges = registry Map<String, Integer> quantileMap = extractTagValueMap(registry, Type.Gauge, 1e9);
assertThat(quantileMap, allOf(hasEntry("quantile=0.3", 2), hasEntry("quantile=0.5", 3), hasEntry("quantile=0.95", 8)));
}
private Map<String, Integer> extractTagValueMap(MeterRegistry registry, Type meterType, double valueDivisor) {
return registry
.getMeters() .getMeters()
.stream() .stream()
.filter(meter -> meter .filter(meter -> meter.getType() == meterType)
.getType() .collect(Collectors.toMap(meter -> {
.name() Tag tag = meter
.equals("Gauge"))
.map(meter -> (Gauge) meter)
.collect(Collectors.toList());
assert (3 == quantileGauges.size());
Map<String, Integer> quantileMap = quantileGauges
.stream()
.collect(Collectors.toMap(gauge -> {
Tag tag = gauge
.getId() .getId()
.getTags() .getTags()
.iterator() .iterator()
.next(); .next();
return tag.getKey() + "=" + tag.getValue(); return tag.getKey() + "=" + tag.getValue();
}, gauge -> (int) (gauge.value() / 1e9))); }, meter -> (int) (meter
.measure()
assertThat(quantileMap.keySet(), hasItems("quantile=0.3", "quantile=0.5", "quantile=0.95")); .iterator()
assertThat(quantileMap.get("quantile=0.3"), is(2)); .next()
assertThat(quantileMap.get("quantile=0.5"), is(3)); .getValue() / valueDivisor)));
assertThat(quantileMap.get("quantile=0.95"), is(8));
} }
@Test @Test
@ -243,6 +239,7 @@ public class MicrometerAtlasTest {
.builder("summary") .builder("summary")
.histogram(Histogram.linear(0, 10, 5)) .histogram(Histogram.linear(0, 10, 5))
.register(registry); .register(registry);
hist.record(3); hist.record(3);
hist.record(8); hist.record(8);
hist.record(20); hist.record(20);
@ -250,22 +247,7 @@ public class MicrometerAtlasTest {
hist.record(13); hist.record(13);
hist.record(26); hist.record(26);
Map<String, Integer> histograms = registry Map<String, Integer> histograms = extractTagValueMap(registry, Type.Counter, 1.0);
.getMeters()
.stream()
.filter(meter -> meter.getType() == Meter.Type.Counter)
.collect(Collectors.toMap(counter -> {
Tag tag = counter
.getId()
.getTags()
.iterator()
.next();
return tag.getKey() + "=" + tag.getValue();
}, counter -> (int) counter
.measure()
.iterator()
.next()
.getValue()));
assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=10.0", 2), hasEntry("bucket=20.0", 2), hasEntry("bucket=30.0", 1), hasEntry("bucket=40.0", 1), hasEntry("bucket=Infinity", 0))); assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=10.0", 2), hasEntry("bucket=20.0", 2), hasEntry("bucket=30.0", 1), hasEntry("bucket=40.0", 1), hasEntry("bucket=Infinity", 0)));
} }
@ -284,22 +266,7 @@ public class MicrometerAtlasTest {
timer.record(341, TimeUnit.MILLISECONDS); timer.record(341, TimeUnit.MILLISECONDS);
timer.record(500, TimeUnit.MILLISECONDS); timer.record(500, TimeUnit.MILLISECONDS);
Map<String, Integer> histograms = registry Map<String, Integer> histograms = extractTagValueMap(registry, Type.Counter, 1.0);
.getMeters()
.stream()
.filter(meter -> meter.getType() == Meter.Type.Counter)
.collect(Collectors.toMap(counter -> {
Tag tag = counter
.getId()
.getTags()
.iterator()
.next();
return tag.getKey() + "=" + tag.getValue();
}, counter -> (int) counter
.measure()
.iterator()
.next()
.getValue()));
assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=2.0E8", 1), hasEntry("bucket=4.0E8", 1), hasEntry("bucket=Infinity", 3))); assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=2.0E8", 1), hasEntry("bucket=4.0E8", 1), hasEntry("bucket=Infinity", 3)));

View File

@ -0,0 +1,28 @@
package com.baeldung.powermockito.introduction;
class LuckyNumberGenerator {
public int getLuckyNumber(String name) {
saveIntoDatabase(name);
if (name == null) {
return getDefaultLuckyNumber();
}
return getComputedLuckyNumber(name.length());
}
private void saveIntoDatabase(String name) {
// Save the name into the database
}
private int getDefaultLuckyNumber() {
return 100;
}
private int getComputedLuckyNumber(int length) {
return length < 5 ? 5 : 10000;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.powermockito.introduction;
import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.LuckyNumberGenerator")
public class LuckyNumberGeneratorTest {
@Test
public final void givenPrivateMethodWithReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
when(mock, "getDefaultLuckyNumber").thenReturn(300);
int result = mock.getLuckyNumber(null);
assertEquals(300, result);
}
@Test
public final void givenPrivateMethodWithArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
doReturn(1).when(mock, "getComputedLuckyNumber", ArgumentMatchers.anyInt());
int result = mock.getLuckyNumber("Jack");
assertEquals(1, result);
}
@Test
public final void givenPrivateMethodWithNoArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
int result = mock.getLuckyNumber("Tyranosorous");
verifyPrivate(mock).invoke("saveIntoDatabase", ArgumentMatchers.anyString());
assertEquals(10000, result);
}
}

1
mocks/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
mockserver/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
parent-boot-4/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
parent-boot-5/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -1,55 +1,53 @@
package com.baeldung.restassured; package com.baeldung.restassured;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.get;
import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasItems;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static io.restassured.RestAssured.get;
import com.github.tomakehurst.wiremock.WireMockServer;
public class RestAssured2IntegrationTest { public class RestAssured2IntegrationTest {
private WireMockServer wireMockServer = new WireMockServer(); private static final int PORT = 8084;
private static WireMockServer wireMockServer = new WireMockServer(PORT);
private static final String EVENTS_PATH = "/odds"; private static final String EVENTS_PATH = "/odds";
private static final String APPLICATION_JSON = "application/json"; private static final String APPLICATION_JSON = "application/json";
private static final String ODDS = getJson(); private static final String ODDS = getJson();
@Before @BeforeClass
public void before() throws Exception { public static void before() throws Exception {
System.out.println("Setting up!"); System.out.println("Setting up!");
wireMockServer.start(); wireMockServer.start();
configureFor("localhost", 8080); configureFor("localhost", PORT);
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( RestAssured.port = PORT;
aResponse().withStatus(200) stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
.withHeader("Content-Type", APPLICATION_JSON) aResponse().withStatus(200)
.withBody(ODDS))); .withHeader("Content-Type", APPLICATION_JSON)
} .withBody(ODDS)));
}
@Test @Test
public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() { public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() {
get("/odds").then().body("odds.findAll { it.status > 0 }.price", get("/odds").then().body("odds.findAll { it.status > 0 }.price",
hasItems(5.25f, 1.2f)); hasItems(5.25f, 1.2f));
} }
private static String getJson() { private static String getJson() {
return Util.inputStreamToString(RestAssured2IntegrationTest.class
return Util.inputStreamToString(new RestAssured2IntegrationTest().getClass() .getResourceAsStream("/odds.json"));
.getResourceAsStream("/odds.json")); }
}
@After
public void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
@AfterClass
public static void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
} }

View File

@ -1,5 +1,14 @@
package com.baeldung.restassured; package com.baeldung.restassured;
import com.github.fge.jsonschema.SchemaVersion;
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.get;
@ -11,96 +20,86 @@ import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasItems;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.fge.jsonschema.SchemaVersion;
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.tomakehurst.wiremock.WireMockServer;
public class RestAssuredIntegrationTest { public class RestAssuredIntegrationTest {
private static final int PORT = 8083;
private static WireMockServer wireMockServer = new WireMockServer(PORT);
private WireMockServer wireMockServer = new WireMockServer(); private static final String EVENTS_PATH = "/events?id=390";
private static final String EVENTS_PATH = "/events?id=390"; private static final String APPLICATION_JSON = "application/json";
private static final String APPLICATION_JSON = "application/json"; private static final String GAME_ODDS = getEventJson();
private static final String GAME_ODDS = getEventJson();
@Before @BeforeClass
public void before() throws Exception { public static void before() throws Exception {
System.out.println("Setting up!"); System.out.println("Setting up!");
wireMockServer.start(); wireMockServer.start();
configureFor("localhost", 8080); RestAssured.port = PORT;
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( configureFor("localhost", PORT);
aResponse().withStatus(200) stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
.withHeader("Content-Type", APPLICATION_JSON) aResponse().withStatus(200)
.withBody(GAME_ODDS))); .withHeader("Content-Type", APPLICATION_JSON)
} .withBody(GAME_ODDS)));
}
@Test @Test
public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() { public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() {
get("/events?id=390").then().assertThat() get("/events?id=390").then().assertThat()
.body("odd.ck", equalTo(12.2f)); .body("odd.ck", equalTo(12.2f));
} }
@Test @Test
public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() { public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() {
get("/events?id=390").then().statusCode(200).assertThat() get("/events?id=390").then().statusCode(200).assertThat()
.body("id", equalTo("390")); .body("id", equalTo("390"));
}
} @Test
public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() {
get("/events?id=390").then().assertThat()
.body("odds.price", hasItems("1.30", "5.25", "2.70", "1.20"));
}
@Test @Test
public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() { public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() {
get("/events?id=390").then().assertThat()
.body("odds.price", hasItems("1.30", "5.25", "2.70", "1.20"));
}
@Test get("/events?id=390").then().assertThat()
public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() { .body(matchesJsonSchemaInClasspath("event_0.json"));
}
get("/events?id=390").then().assertThat() @Test
.body(matchesJsonSchemaInClasspath("event_0.json")); public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() {
} JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory
.newBuilder()
.setValidationConfiguration(
ValidationConfiguration.newBuilder()
.setDefaultVersion(SchemaVersion.DRAFTV4)
.freeze()).freeze();
@Test get("/events?id=390")
public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() { .then()
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory .assertThat()
.newBuilder() .body(matchesJsonSchemaInClasspath("event_0.json").using(
.setValidationConfiguration( jsonSchemaFactory));
ValidationConfiguration.newBuilder() }
.setDefaultVersion(SchemaVersion.DRAFTV4)
.freeze()).freeze();
get("/events?id=390") @Test
.then() public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() {
.assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json").using(
jsonSchemaFactory));
} get("/events?id=390")
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json").using(
settings().with().checkedValidation(false)));
}
@Test @AfterClass
public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() { public static void after() throws Exception {
System.out.println("Running: tearDown");
get("/events?id=390") wireMockServer.stop();
.then() }
.assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json").using(
settings().with().checkedValidation(false)));
}
@After
public void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
private static String getEventJson() {
return Util.inputStreamToString(RestAssuredIntegrationTest.class
.getResourceAsStream("/event_0.json"));
}
private static String getEventJson() {
return Util.inputStreamToString(RestAssuredIntegrationTest.class
.getResourceAsStream("/event_0.json"));
}
} }

View File

@ -1,54 +1,55 @@
package com.baeldung.restassured; package com.baeldung.restassured;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.get;
import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasItems;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static io.restassured.RestAssured.get;
import com.github.tomakehurst.wiremock.WireMockServer;
public class RestAssuredXML2IntegrationTest { public class RestAssuredXML2IntegrationTest {
private WireMockServer wireMockServer = new WireMockServer(); private static final int PORT = 8082;
private static WireMockServer wireMockServer = new WireMockServer(PORT);
private static final String EVENTS_PATH = "/teachers"; private static final String EVENTS_PATH = "/teachers";
private static final String APPLICATION_XML = "application/xml"; private static final String APPLICATION_XML = "application/xml";
private static final String TEACHERS = getXml(); private static final String TEACHERS = getXml();
@Before @BeforeClass
public void before() throws Exception { public static void before() throws Exception {
System.out.println("Setting up!"); System.out.println("Setting up!");
wireMockServer.start(); wireMockServer.start();
configureFor("localhost", 8080); RestAssured.port = PORT;
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( configureFor("localhost", PORT);
aResponse().withStatus(200) stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
.withHeader("Content-Type", APPLICATION_XML) aResponse().withStatus(200)
.withBody(TEACHERS))); .withHeader("Content-Type", APPLICATION_XML)
} .withBody(TEACHERS)));
@Test }
public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() {
get("/teachers")
.then()
.body("teachers.teacher.find { it.@department == 'science' }.subject",
hasItems("math", "physics"));
}
private static String getXml() {
return Util
.inputStreamToString(new RestAssuredXML2IntegrationTest().getClass().getResourceAsStream("/teachers.xml"));
}
@After
public void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
@Test
public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() {
get("/teachers")
.then()
.body("teachers.teacher.find { it.@department == 'science' }.subject",
hasItems("math", "physics"));
}
private static String getXml() {
return Util.inputStreamToString(RestAssuredXML2IntegrationTest.class
.getResourceAsStream("/teachers.xml"));
}
@AfterClass
public static void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
} }

View File

@ -1,99 +1,90 @@
package com.baeldung.restassured; package com.baeldung.restassured;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.post; import static io.restassured.RestAssured.post;
import static io.restassured.RestAssured.get;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.xml.HasXPath.hasXPath; import static org.hamcrest.xml.HasXPath.hasXPath;
import java.io.FileNotFoundException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.fge.jsonschema.SchemaVersion;
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.tomakehurst.wiremock.WireMockServer;
public class RestAssuredXMLIntegrationTest { public class RestAssuredXMLIntegrationTest {
private WireMockServer wireMockServer = new WireMockServer(); private static final int PORT = 8081;
private static final String EVENTS_PATH = "/employees"; private static WireMockServer wireMockServer = new WireMockServer(PORT);
private static final String APPLICATION_XML = "application/xml";
private static final String EMPLOYEES = getXml();
@Before private static final String EVENTS_PATH = "/employees";
public void before() throws Exception { private static final String APPLICATION_XML = "application/xml";
System.out.println("Setting up!"); private static final String EMPLOYEES = getXml();
wireMockServer.start();
configureFor("localhost", 8080);
stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_XML)
.withBody(EMPLOYEES)));
}
@Test
public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() {
post("/employees").then().assertThat()
.body("employees.employee.first-name", equalTo("Jane"));
}
@Test @BeforeClass
public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() { public static void before() throws Exception {
post("/employees").then().assertThat() System.out.println("Setting up!");
.body("employees.employee.first-name", equalTo("Jane")) wireMockServer.start();
.body("employees.employee.last-name", equalTo("Daisy")) configureFor("localhost", PORT);
.body("employees.employee.sex", equalTo("f")); RestAssured.port = PORT;
} stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_XML)
.withBody(EMPLOYEES)));
}
@Test @Test
public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() { public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() {
post("/employees") post("/employees").then().assertThat()
.then() .body("employees.employee.first-name", equalTo("Jane"));
.assertThat() }
.body("employees.employee.first-name", equalTo("Jane"),
"employees.employee.last-name", equalTo("Daisy"),
"employees.employee.sex", equalTo("f"));
}
@Test @Test
public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() { public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() {
post("/employees") post("/employees").then().assertThat()
.then() .body("employees.employee.first-name", equalTo("Jane"))
.assertThat() .body("employees.employee.last-name", equalTo("Daisy"))
.body(hasXPath("/employees/employee/first-name", .body("employees.employee.sex", equalTo("f"));
containsString("Ja"))); }
} @Test
public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() {
post("/employees")
.then()
.assertThat()
.body("employees.employee.first-name", equalTo("Jane"),
"employees.employee.last-name", equalTo("Daisy"),
"employees.employee.sex", equalTo("f"));
}
@Test @Test
public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() { public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() {
post("/employees") post("/employees")
.then() .then()
.assertThat() .assertThat()
.body(hasXPath("/employees/employee/first-name[text()='Jane']")); .body(hasXPath("/employees/employee/first-name",
containsString("Ja")));
}
} @Test
public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() {
post("/employees")
.then()
.assertThat()
.body(hasXPath("/employees/employee/first-name[text()='Jane']"));
}
private static String getXml() {
return Util
.inputStreamToString(RestAssuredXMLIntegrationTest.class.getResourceAsStream("/employees.xml"));
}
private static String getXml() { @AfterClass
public static void after() throws Exception {
return Util System.out.println("Running: tearDown");
.inputStreamToString(new RestAssuredXMLIntegrationTest().getClass().getResourceAsStream("/employees.xml")); wireMockServer.stop();
}
}
@After
public void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
} }

View File

@ -1,36 +1,15 @@
package com.baeldung.restassured; package com.baeldung.restassured;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.util.Scanner;
public class Util { final class Util {
public static String inputStreamToString(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line; private Util() {
try { }
br = new BufferedReader(new InputStreamReader(is)); static String inputStreamToString(InputStream is) {
while ((line = br.readLine()) != null) { Scanner s = new Scanner(is).useDelimiter("\\A");
sb.append(line); return s.hasNext() ? s.next() : "";
} }
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
} }

View File

@ -0,0 +1 @@
## Relevant articles:

1
rmi/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
rule-engines/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
saas/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -1,22 +1,21 @@
package com.baeldung; package com.baeldung;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
@RestController @RestController
public class BaeldungController { public class BaeldungController {
@RequestMapping(method = { RequestMethod.GET }, value = { "/hello" }) @GetMapping("/hello")
public String sayHello(HttpServletResponse response) { public String sayHello(HttpServletResponse response) {
return "hello"; return "hello";
} }
@RequestMapping(method = { RequestMethod.POST }, value = { "/baeldung" }) @PostMapping("/baeldung")
public String sayHelloPost(HttpServletResponse response) { public String sayHelloPost(HttpServletResponse response) {
return "hello"; return "hello";
} }
} }

View File

@ -2,23 +2,16 @@ package com.baeldung;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
@SpringBootApplication @SpringBootApplication
public class SpringDemoApplication extends SpringBootServletInitializer { public class SpringDemoApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(SpringDemoApplication.class, args); SpringApplication.run(SpringDemoApplication.class, args);
} }
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringDemoApplication.class);
}
@Bean @Bean
public RestTemplate getRestTemplate() { public RestTemplate getRestTemplate() {
return new RestTemplate(); return new RestTemplate();

View File

@ -0,0 +1 @@
server.port=8082

View File

@ -1,16 +0,0 @@
package com.baeldung;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
public class OtherDefsIntegrationTest extends SpringIntegrationTest {
@When("^the client calls /baeldung$")
public void the_client_issues_POST_hello() throws Throwable {
executePost("http://localhost:8080/baeldung");
}
@Given("^the client calls /hello$")
public void the_client_issues_GET_hello() throws Throwable {
executeGet("http://localhost:8080/hello");
}
}

View File

@ -11,23 +11,19 @@ public class ResponseResults {
private final ClientHttpResponse theResponse; private final ClientHttpResponse theResponse;
private final String body; private final String body;
protected ResponseResults(final ClientHttpResponse response) throws IOException { ResponseResults(final ClientHttpResponse response) throws IOException {
this.theResponse = response; this.theResponse = response;
final InputStream bodyInputStream = response.getBody(); final InputStream bodyInputStream = response.getBody();
if (null == bodyInputStream) { final StringWriter stringWriter = new StringWriter();
this.body = "{}"; IOUtils.copy(bodyInputStream, stringWriter);
} else { this.body = stringWriter.toString();
final StringWriter stringWriter = new StringWriter();
IOUtils.copy(bodyInputStream, stringWriter);
this.body = stringWriter.toString();
}
} }
protected ClientHttpResponse getTheResponse() { ClientHttpResponse getTheResponse() {
return theResponse; return theResponse;
} }
protected String getBody() { String getBody() {
return body; return body;
} }
} }

View File

@ -1,9 +1,5 @@
package com.baeldung; package com.baeldung;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationContextLoader; import org.springframework.boot.test.SpringApplicationContextLoader;
@ -12,40 +8,39 @@ import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
//@RunWith(SpringJUnit4ClassRunner.class) //@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringDemoApplication.class, loader = SpringApplicationContextLoader.class) @ContextConfiguration(classes = SpringDemoApplication.class, loader = SpringApplicationContextLoader.class)
@WebAppConfiguration @WebAppConfiguration
@IntegrationTest @IntegrationTest
public class SpringIntegrationTest { public class SpringIntegrationTest {
protected static ResponseResults latestResponse = null; static ResponseResults latestResponse = null;
@Autowired @Autowired
protected RestTemplate restTemplate; protected RestTemplate restTemplate;
protected void executeGet(String url) throws IOException { void executeGet(String url) throws IOException {
final Map<String, String> headers = new HashMap<>(); final Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json"); headers.put("Accept", "application/json");
final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers); final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers);
final ResponseResultErrorHandler errorHandler = new ResponseResultErrorHandler(); final ResponseResultErrorHandler errorHandler = new ResponseResultErrorHandler();
restTemplate.setErrorHandler(errorHandler); restTemplate.setErrorHandler(errorHandler);
latestResponse = restTemplate.execute(url, HttpMethod.GET, requestCallback, new ResponseExtractor<ResponseResults>() { latestResponse = restTemplate.execute(url, HttpMethod.GET, requestCallback, response -> {
@Override if (errorHandler.hadError) {
public ResponseResults extractData(ClientHttpResponse response) throws IOException { return (errorHandler.getResults());
if (errorHandler.hadError) { } else {
return (errorHandler.getResults()); return (new ResponseResults(response));
} else {
return (new ResponseResults(response));
}
} }
}); });
} }
protected void executePost(String url) throws IOException { void executePost() throws IOException {
final Map<String, String> headers = new HashMap<>(); final Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json"); headers.put("Accept", "application/json");
final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers); final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers);
@ -56,17 +51,14 @@ public class SpringIntegrationTest {
} }
restTemplate.setErrorHandler(errorHandler); restTemplate.setErrorHandler(errorHandler);
latestResponse = restTemplate.execute(url, HttpMethod.POST, requestCallback, new ResponseExtractor<ResponseResults>() { latestResponse = restTemplate
@Override .execute("http://localhost:8082/baeldung", HttpMethod.POST, requestCallback, response -> {
public ResponseResults extractData(ClientHttpResponse response) throws IOException { if (errorHandler.hadError) {
if (errorHandler.hadError) { return (errorHandler.getResults());
return (errorHandler.getResults()); } else {
} else { return (new ResponseResults(response));
return (new ResponseResults(response)); }
} });
}
});
} }
private class ResponseResultErrorHandler implements ResponseErrorHandler { private class ResponseResultErrorHandler implements ResponseErrorHandler {

View File

@ -3,6 +3,7 @@ package com.baeldung;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import cucumber.api.java.en.Given;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import cucumber.api.java.en.And; import cucumber.api.java.en.And;
@ -11,9 +12,19 @@ import cucumber.api.java.en.When;
public class StepDefsIntegrationTest extends SpringIntegrationTest { public class StepDefsIntegrationTest extends SpringIntegrationTest {
@When("^the client calls /baeldung$")
public void the_client_issues_POST_hello() throws Throwable {
executePost();
}
@Given("^the client calls /hello$")
public void the_client_issues_GET_hello() throws Throwable {
executeGet("http://localhost:8082/hello");
}
@When("^the client calls /version$") @When("^the client calls /version$")
public void the_client_issues_GET_version() throws Throwable { public void the_client_issues_GET_version() throws Throwable {
executeGet("http://localhost:8080/version"); executeGet("http://localhost:8082/version");
} }
@Then("^the client receives status code of (\\d+)$") @Then("^the client receives status code of (\\d+)$")

1
spring-drools/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

1
spring-groovy/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -23,11 +23,8 @@ public class HibernateImmutableIntegrationTest {
@Before @Before
public void before() { public void before() {
session = HibernateUtil.getSessionFactory().getCurrentSession(); session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); session.beginTransaction();
createEvent();
createEventGenerated();
session.setCacheMode(CacheMode.REFRESH);
} }
@BeforeClass @BeforeClass
@ -40,8 +37,6 @@ public class HibernateImmutableIntegrationTest {
HibernateUtil.getSessionFactory().close(); HibernateUtil.getSessionFactory().close();
} }
//
@Test @Test
public void addEvent() { public void addEvent() {
Event event = new Event(); Event event = new Event();
@ -49,15 +44,18 @@ public class HibernateImmutableIntegrationTest {
event.setTitle("Public Event"); event.setTitle("Public Event");
session.save(event); session.save(event);
session.getTransaction().commit(); session.getTransaction().commit();
session.close();
} }
@Test @Test
public void updateEvent() { public void updateEvent() {
createEvent();
Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0); Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0);
event.setTitle("Private Event"); event.setTitle("Private Event");
session.update(event); session.update(event);
session.flush(); session.flush();
session.refresh(event); session.refresh(event);
session.close();
assertThat(event.getTitle(), equalTo("New Event")); assertThat(event.getTitle(), equalTo("New Event"));
assertThat(event.getId(), equalTo(5L)); assertThat(event.getId(), equalTo(5L));
@ -65,13 +63,16 @@ public class HibernateImmutableIntegrationTest {
@Test @Test
public void deleteEvent() { public void deleteEvent() {
createEvent();
Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0); Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0);
session.delete(event); session.delete(event);
session.getTransaction().commit(); session.getTransaction().commit();
session.close();
} }
@Test @Test
public void addGuest() { public void addGuest() {
createEvent();
Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0); Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0);
String newGuest = "Sara"; String newGuest = "Sara";
event.getGuestList().add(newGuest); event.getGuestList().add(newGuest);
@ -79,6 +80,7 @@ public class HibernateImmutableIntegrationTest {
exception.expect(PersistenceException.class); exception.expect(PersistenceException.class);
session.save(event); session.save(event);
session.getTransaction().commit(); session.getTransaction().commit();
session.close();
} }
@Test @Test
@ -94,18 +96,18 @@ public class HibernateImmutableIntegrationTest {
@Test @Test
public void updateEventGenerated() { public void updateEventGenerated() {
createEventGenerated();
EventGeneratedId eventGeneratedId = (EventGeneratedId) session.createQuery("FROM EventGeneratedId WHERE name LIKE '%John%'").list().get(0); EventGeneratedId eventGeneratedId = (EventGeneratedId) session.createQuery("FROM EventGeneratedId WHERE name LIKE '%John%'").list().get(0);
eventGeneratedId.setName("Mike"); eventGeneratedId.setName("Mike");
session.update(eventGeneratedId); session.update(eventGeneratedId);
session.flush(); session.flush();
session.refresh(eventGeneratedId); session.refresh(eventGeneratedId);
session.close();
assertThat(eventGeneratedId.getName(), equalTo("John")); assertThat(eventGeneratedId.getName(), equalTo("John"));
assertThat(eventGeneratedId.getId(), equalTo(1L)); assertThat(eventGeneratedId.getId(), equalTo(1L));
} }
//
private static void createEvent() { private static void createEvent() {
Event event = new Event(5L, "New Event", Sets.newHashSet("guest")); Event event = new Event(5L, "New Event", Sets.newHashSet("guest"));
session.save(event); session.save(event);

View File

@ -0,0 +1 @@
## Relevant articles:

1
spring-mybatis/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -0,0 +1 @@
## Relevant articles:

1
vaadin/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -0,0 +1 @@
## Relevant articles: