Merge remote-tracking branch 'upstream/master'

This commit is contained in:
gschambial 2017-11-14 10:20:12 +05:30
commit 5b8fb97494
25 changed files with 317 additions and 362 deletions

View File

@ -1,24 +1,21 @@
package com.baeldung.concurrent.runnable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.commons.lang3.RandomUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RunnableVsThreadTest {
public class RunnableVsThreadLiveTest {
private static Logger log =
LoggerFactory.getLogger(RunnableVsThreadTest.class);
LoggerFactory.getLogger(RunnableVsThreadLiveTest.class);
private static ExecutorService executorService;
@ -77,9 +74,7 @@ public class RunnableVsThreadTest {
public void givenACallableAsLambda_whenSubmitToES_thenResult()
throws Exception {
Future<Integer> future = executorService.submit(() -> {
return RandomUtils.nextInt(0, 100);
});
Future<Integer> future = executorService.submit(() -> RandomUtils.nextInt(0, 100));
log.info("Result from callable: {}", future.get());
}
@ -99,7 +94,7 @@ class SimpleThread extends Thread{
private String message;
public SimpleThread(String message) {
SimpleThread(String message) {
this.message = message;
}
@ -116,7 +111,7 @@ class SimpleRunnable implements Runnable {
private String message;
public SimpleRunnable(String message) {
SimpleRunnable(String message) {
this.message = message;
}

View File

@ -1,35 +0,0 @@
<?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>
<version>${runtime.version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<version>${runtime.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -1,28 +0,0 @@
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

@ -1,33 +0,0 @@
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

@ -1,6 +0,0 @@
<?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

@ -1,3 +0,0 @@
groupId=com.baeldung.drools
artifactId=DroosBackwardChaining
version=1.0.0-SNAPSHOT

View File

@ -1,44 +0,0 @@
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

View File

@ -1,34 +0,0 @@
package com.baeldung
import com.baeldung.drools.model.Fact;
global com.baeldung.drools.model.Result result;
dialect "mvel"
query belongsTo(String x, String y)
Fact(x, y;)
or
(Fact(z, y;) and belongsTo(x, z;))
end
rule "Great Wall of China BELONGS TO Planet Earth"
when
belongsTo("Great Wall of China", "Planet Earth";)
then
result.setValue("Decision one taken: Great Wall of China BELONGS TO Planet Earth");
end
rule "Great Wall of China DOES NOT BELONG TO of Planet Earth"
when
not belongsTo("Great Wall of China", "Planet Earth";)
then
result.setValue("Decision two taken: Great Wall of China DOES NOT BELONG TO Planet Earth");
end
rule "print all facts"
when
belongsTo(element, place;)
then
result.addFact(element + " IS ELEMENT OF " + place);
end

View File

@ -1,54 +0,0 @@
package com.baeldung.test;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import com.baeldung.drools.model.Fact;
import com.baeldung.drools.model.Result;
import static junit.framework.TestCase.assertEquals;
public class BackwardChainingTest {
private Result result;
private KieServices ks;
private KieContainer kContainer;
private KieSession ksession;
@Before
public void before() {
result = new Result();
ks = KieServices.Factory.get();
kContainer = ks.getKieClasspathContainer();
ksession = kContainer.newKieSession("ksession-backward-chaining");
ksession.setGlobal("result", result);
}
@Test
public void whenWallOfChinaIsGiven_ThenItBelongsToPlanetEarth() {
ksession.setGlobal("result", result);
ksession.insert(new Fact("Asia", "Planet Earth"));
ksession.insert(new Fact("China", "Asia"));
ksession.insert(new Fact("Great Wall of China", "China"));
ksession.fireAllRules();
// Assert Decision one
assertEquals(result.getValue(), "Decision one taken: Great Wall of China BELONGS TO Planet Earth");
}
@Test
public void whenChinaIsNotGiven_ThenWallOfChinaDoesNotBelongToPlanetEarth() {
ksession.insert(new Fact("Asia", "Planet Earth"));
// ksession.insert(new Location("China", "Asia")); // not provided to force Decision two
ksession.insert(new Fact("Great Wall of China", "China"));
ksession.fireAllRules();
// Assert Decision two
assertEquals(result.getValue(), "Decision two taken: Great Wall of China DOES NOT BELONG TO Planet Earth");
}
}

View File

@ -1,73 +1,68 @@
<?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>
<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.baeldung</groupId>
<artifactId>drools</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>drools</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<http-component-version>4.4.6</http-component-version>
<drools-version>7.1.0.Beta2</drools-version>
<apache-poi-version>3.13</apache-poi-version>
</properties>
<properties>
<http-component-version>4.4.6</http-component-version>
<drools-version>7.1.0.Beta2</drools-version>
<apache-poi-version>3.13</apache-poi-version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${http-component-version}</version>
</dependency>
<!-- ... -->
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-ci</artifactId>
<version>${drools-version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<version>${drools-version}</version>
</dependency>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${http-component-version}</version>
</dependency>
<!-- ... -->
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-ci</artifactId>
<version>${drools-version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<version>${drools-version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>${drools-version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>${drools-version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${apache-poi-version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>${drools-version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>${drools-version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${apache-poi-version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${apache-poi-version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${apache-poi-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
</dependencies>
</dependencies>
</project>

View File

@ -1,9 +1,8 @@
package com.baeldung.drools;
package com.baeldung.drools.backward_chaining;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import com.baeldung.drools.config.DroolsBeanFactory;
import com.baeldung.drools.model.Fact;
import com.baeldung.drools.model.Result;
@ -11,17 +10,17 @@ public class BackwardChaining {
public static void main(String[] args) {
Result result = new BackwardChaining().backwardChaining();
System.out.println(result.getValue());
result.getFacts().stream().forEach(System.out::println);
result.getFacts()
.stream()
.forEach(System.out::println);
}
public Result backwardChaining() {
Result result = new Result();
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession ksession = kContainer.newKieSession("ksession-backward-chaining");
KieSession ksession = new DroolsBeanFactory().getKieSession();
ksession.setGlobal("result", result);
ksession.insert(new Fact("Asia", "Planet Earth"));
// ksession.insert(new Fact("China", "Asia"));
ksession.insert(new Fact("China", "Asia"));
ksession.insert(new Fact("Great Wall of China", "China"));
ksession.fireAllRules();

View File

@ -3,7 +3,6 @@ package com.baeldung.drools.config;
import org.drools.decisiontable.DecisionTableProviderImpl;
import org.kie.api.KieServices;
import org.kie.api.builder.*;
import org.kie.api.io.KieResources;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
@ -22,7 +21,7 @@ public class DroolsBeanFactory {
private KieFileSystem getKieFileSystem() throws IOException{
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
List<String> rules=Arrays.asList("SuggestApplicant.drl","Product_rules.xls");
List<String> rules=Arrays.asList("BackwardChaining.drl","SuggestApplicant.drl","Product_rules.xls");
for(String rule:rules){
kieFileSystem.write(ResourceFactory.newClassPathResource(rule));
}
@ -56,9 +55,11 @@ public class DroolsBeanFactory {
getKieRepository();
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/BackwardChaining.drl"));
kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/SuggestApplicant.drl"));
kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Product_rules.xls"));
KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
kb.buildAll();
KieModule kieModule = kb.getKieModule();

View File

@ -1,4 +1,4 @@
package com.baeldung
package com.baeldung.drools.rules
import com.baeldung.drools.model.Fact;

View File

@ -0,0 +1,36 @@
package com.baeldung.drools.backward_chaining;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.runtime.KieSession;
import com.baeldung.drools.config.DroolsBeanFactory;
import com.baeldung.drools.model.Fact;
import com.baeldung.drools.model.Result;
import static junit.framework.TestCase.assertEquals;
public class BackwardChainingTest {
private Result result;
private KieSession ksession;
@Before
public void before() {
result = new Result();
ksession = new DroolsBeanFactory().getKieSession();
}
@Test
public void whenWallOfChinaIsGiven_ThenItBelongsToPlanetEarth() {
ksession.setGlobal("result", result);
ksession.insert(new Fact("Asia", "Planet Earth"));
ksession.insert(new Fact("China", "Asia"));
ksession.insert(new Fact("Great Wall of China", "China"));
ksession.fireAllRules();
// Assert Decision one
assertEquals(result.getValue(), "Decision one taken: Great Wall of China BELONGS TO Planet Earth");
}
}

View File

@ -622,6 +622,21 @@
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.58</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client</artifactId>
<version>${googleclient.version}</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>${googleclient.version}</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId>
<version>${googleclient.version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
@ -639,6 +654,7 @@
</repository>
</repositories>
<properties>
<googleclient.version>1.23.0</googleclient.version>
<crdt.version>0.1.0</crdt.version>
<multiverse.version>0.7.0</multiverse.version>
<cglib.version>3.2.4</cglib.version>

View File

@ -0,0 +1,65 @@
package com.baeldung.googlehttpclientguide;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.apache.ApacheHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.ExponentialBackOff;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class GitHubExample {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
//static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
//static final JsonFactory JSON_FACTORY = new GsonFactory();
private static void run() throws Exception {
HttpRequestFactory requestFactory
= HTTP_TRANSPORT.createRequestFactory(
(HttpRequest request) -> {
request.setParser(new JsonObjectParser(JSON_FACTORY));
});
GitHubUrl url = new GitHubUrl("https://api.github.com/users");
url.per_page = 10;
url.page = 1;
HttpRequest request = requestFactory.buildGetRequest(url);
ExponentialBackOff backoff = new ExponentialBackOff.Builder()
.setInitialIntervalMillis(500)
.setMaxElapsedTimeMillis(900000)
.setMaxIntervalMillis(6000)
.setMultiplier(1.5)
.setRandomizationFactor(0.5)
.build();
request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
Type type = new TypeToken<List<User>>() {}.getType();
List<User> users = (List<User>)request.execute().parseAs(type);
System.out.println(users);
url.appendRawPath("/eugenp");
request = requestFactory.buildGetRequest(url);
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<HttpResponse> responseFuture = request.executeAsync(executor);
User eugen = responseFuture.get().parseAs(User.class);
System.out.println(eugen);
executor.shutdown();
}
public static void main(String[] args) {
try {
run();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.googlehttpclientguide;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key;
public class GitHubUrl extends GenericUrl{
public GitHubUrl(String encodedUrl) {
super(encodedUrl);
}
@Key
public int per_page;
@Key
public int page;
}

View File

@ -0,0 +1,77 @@
package com.baeldung.googlehttpclientguide;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
public class User extends GenericJson {
@Key
private String login;
@Key
private long id;
@Key
private String url;
@Key
private String company;
@Key
private String blog;
@Key
private String email;
@Key("subscriptions_url")
private String subscriptionsUrl;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getBlog() {
return blog;
}
public void setBlog(String blog) {
this.blog = blog;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
}
}

View File

@ -0,0 +1,10 @@
# Properties file which configures the operation of the JDK logging facility.
# The system will look for this config file to be specified as a system property:
# -Djava.util.logging.config.file=${project_loc:dailymotion-simple-cmdline-sample}/logging.properties
# Set up the console handler (uncomment "level" to show more fine-grained messages)
handlers = java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level = ALL
# Set up logging of HTTP requests and responses (uncomment "level" to show)
com.google.api.client.http.level = ALL

View File

@ -2,4 +2,4 @@
- [A Guide to Activiti with Java](http://www.baeldung.com/java-activiti)
- [Introduction to Activiti with Spring](http://www.baeldung.com/spring-activiti)
- [Activiti with Spring Security](http://www.baeldung.com/activiti-spring-security)

View File

@ -2,6 +2,6 @@ package org.baeldung.dsrouting;
public enum ClientDatabase {
ACME_WIDGETS, WIDGETS_ARE_US, WIDGET_DEPOT
CLIENT_A, CLIENT_B
}

View File

@ -22,41 +22,30 @@ public class DataSourceRoutingTestConfiguration {
@Bean
public DataSource clientDatasource() {
Map<Object, Object> targetDataSources = new HashMap<>();
DataSource acmeWidgetsDatasource = acmeWidgetsDatasource();
DataSource widgetsAreUsDatasource = widgetsAreUsDatasource();
DataSource widgetsDepotDatasource = widgetsDepotDatasource();
targetDataSources.put(ClientDatabase.ACME_WIDGETS, acmeWidgetsDatasource);
targetDataSources.put(ClientDatabase.WIDGETS_ARE_US, widgetsAreUsDatasource);
targetDataSources.put(ClientDatabase.WIDGET_DEPOT, widgetsDepotDatasource);
DataSource clientADatasource = clientADatasource();
DataSource clientBDatasource = clientBDatasource();
targetDataSources.put(ClientDatabase.CLIENT_A, clientADatasource);
targetDataSources.put(ClientDatabase.CLIENT_B, clientBDatasource);
ClientDataSourceRouter clientRoutingDatasource = new ClientDataSourceRouter();
clientRoutingDatasource.setTargetDataSources(targetDataSources);
clientRoutingDatasource.setDefaultTargetDataSource(acmeWidgetsDatasource);
clientRoutingDatasource.setDefaultTargetDataSource(clientADatasource);
return clientRoutingDatasource;
}
private DataSource acmeWidgetsDatasource() {
private DataSource clientADatasource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase embeddedDb = dbBuilder.setType(EmbeddedDatabaseType.H2)
.setName("ACMEWIDGETS")
.setName("CLIENT_A")
.addScript("classpath:dsrouting-db.sql")
.build();
return embeddedDb;
}
private DataSource widgetsAreUsDatasource() {
private DataSource clientBDatasource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase embeddedDb = dbBuilder.setType(EmbeddedDatabaseType.H2)
.setName("WIDGETSAREUS")
.addScript("classpath:dsrouting-db.sql")
.build();
return embeddedDb;
}
private DataSource widgetsDepotDatasource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase embeddedDb = dbBuilder.setType(EmbeddedDatabaseType.H2)
.setName("WIDGETDEPOT")
.setName("CLIENT_B")
.addScript("classpath:dsrouting-db.sql")
.build();
return embeddedDb;

View File

@ -24,23 +24,18 @@ public class DataSourceRoutingTests {
@Before
public void setup() {
final String SQL_ACME_WIDGETS = "insert into client (id, name) values (1, 'ACME WIDGETS')";
final String SQL_WIDGETS_ARE_US = "insert into client (id, name) values (2, 'WIDGETS ARE US')";
final String SQL_WIDGET_DEPOT = "insert into client (id, name) values (3, 'WIDGET DEPOT')";
final String SQL_CLIENT_A = "insert into client (id, name) values (1, 'CLIENT A')";
final String SQL_CLIENT_B = "insert into client (id, name) values (2, 'CLIENT B')";
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(routingDatasource);
ClientDatabaseContextHolder.set(ClientDatabase.ACME_WIDGETS);
jdbcTemplate.execute(SQL_ACME_WIDGETS);
ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_A);
jdbcTemplate.execute(SQL_CLIENT_A);
ClientDatabaseContextHolder.clear();
ClientDatabaseContextHolder.set(ClientDatabase.WIDGETS_ARE_US);
jdbcTemplate.execute(SQL_WIDGETS_ARE_US);
ClientDatabaseContextHolder.clear();
ClientDatabaseContextHolder.set(ClientDatabase.WIDGET_DEPOT);
jdbcTemplate.execute(SQL_WIDGET_DEPOT);
ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_B);
jdbcTemplate.execute(SQL_CLIENT_B);
ClientDatabaseContextHolder.clear();
}
@ -48,15 +43,11 @@ public class DataSourceRoutingTests {
public void givenClientDbs_whenContextsSwitch_thenRouteToCorrectDatabase() throws Exception {
// test ACME WIDGETS
String clientName = clientService.getClientName(ClientDatabase.ACME_WIDGETS);
assertEquals(clientName, "ACME WIDGETS");
String clientName = clientService.getClientName(ClientDatabase.CLIENT_A);
assertEquals(clientName, "CLIENT A");
// test WIDGETS_ARE_US
clientName = clientService.getClientName(ClientDatabase.WIDGETS_ARE_US);
assertEquals(clientName, "WIDGETS ARE US");
// test WIDGET_DEPOT
clientName = clientService.getClientName(ClientDatabase.WIDGET_DEPOT);
assertEquals(clientName, "WIDGET DEPOT");
clientName = clientService.getClientName(ClientDatabase.CLIENT_B);
assertEquals(clientName, "CLIENT B");
}
}