Skip to content

Commit 5a09cee

Browse files
authored
Merge pull request eugenp#5114 from neerajnyd/bael-1168
Bael 1168 Ratpack HTTP Client
2 parents 3df9e64 + 6c1629d commit 5a09cee

9 files changed

Lines changed: 277 additions & 85 deletions

File tree

‎ratpack/build.gradle‎

Lines changed: 35 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,35 @@
1-
buildscript {
2-
repositories {
3-
jcenter()
4-
}
5-
dependencies {
6-
classpath "io.ratpack:ratpack-gradle:1.4.5"
7-
classpath "com.h2database:h2:1.4.193"
8-
}
9-
}
10-
11-
if (!JavaVersion.current().java8Compatible) {
12-
throw new IllegalStateException("Must be built with Java 8 or higher")
13-
}
14-
15-
apply plugin: "io.ratpack.ratpack-java"
16-
apply plugin: 'java'
17-
18-
repositories {
19-
jcenter()
20-
}
21-
22-
dependencies {
23-
compile ratpack.dependency('hikari')
24-
compile 'com.h2database:h2:1.4.193'
25-
testCompile 'junit:junit:4.11'
26-
runtime "org.slf4j:slf4j-simple:1.7.21"
27-
}
28-
29-
test {
30-
testLogging {
31-
events 'started', 'passed'
32-
}
33-
}
34-
35-
mainClassName = "com.baeldung.Application"
1+
buildscript {
2+
repositories {
3+
jcenter()
4+
}
5+
dependencies {
6+
classpath "io.ratpack:ratpack-gradle:1.5.4"
7+
classpath "com.h2database:h2:1.4.193"
8+
}
9+
}
10+
11+
if (!JavaVersion.current().java8Compatible) {
12+
throw new IllegalStateException("Must be built with Java 8 or higher")
13+
}
14+
15+
apply plugin: "io.ratpack.ratpack-java"
16+
apply plugin: 'java'
17+
18+
repositories {
19+
jcenter()
20+
}
21+
22+
dependencies {
23+
compile ratpack.dependency('hikari')
24+
compile 'com.h2database:h2:1.4.193'
25+
testCompile 'junit:junit:4.11'
26+
runtime "org.slf4j:slf4j-simple:1.7.21"
27+
}
28+
29+
test {
30+
testLogging {
31+
events 'started', 'passed'
32+
}
33+
}
34+
35+
mainClassName = "com.baeldung.Application"

‎ratpack/pom.xml‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@
3535
<groupId>io.ratpack</groupId>
3636
<artifactId>ratpack-hystrix</artifactId>
3737
<version>${ratpack.version}</version>
38+
<exclusions>
39+
<exclusion>
40+
<groupId>com.netflix.hystrix</groupId>
41+
<artifactId>hystrix-core</artifactId>
42+
</exclusion>
43+
</exclusions>
44+
</dependency>
45+
<dependency>
46+
<groupId>com.netflix.hystrix</groupId>
47+
<artifactId>hystrix-core</artifactId>
48+
<version>${hystrix.version}</version>
3849
</dependency>
3950
<dependency>
4051
<groupId>io.ratpack</groupId>
@@ -76,10 +87,11 @@
7687
<properties>
7788
<maven.compiler.source>1.8</maven.compiler.source>
7889
<maven.compiler.target>1.8</maven.compiler.target>
79-
<ratpack.version>1.4.6</ratpack.version>
90+
<ratpack.version>1.5.4</ratpack.version>
8091
<httpclient.version>4.5.3</httpclient.version>
8192
<httpcore.version>4.4.6</httpcore.version>
8293
<h2database.version>1.4.193</h2database.version>
94+
<hystrix.version>1.5.12</hystrix.version>
8395
</properties>
8496

8597
</project>
Lines changed: 81 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,81 @@
1-
package com.baeldung;
2-
3-
import java.util.ArrayList;
4-
import java.util.List;
5-
6-
import com.baeldung.filter.RequestValidatorFilter;
7-
import com.baeldung.model.Employee;
8-
9-
import ratpack.guice.Guice;
10-
import ratpack.hikari.HikariModule;
11-
import ratpack.http.MutableHeaders;
12-
import ratpack.jackson.Jackson;
13-
import ratpack.http.MutableHeaders;
14-
import ratpack.server.RatpackServer;
15-
16-
public class Application {
17-
18-
public static void main(String[] args) throws Exception {
19-
20-
List<Employee> employees = new ArrayList<Employee>();
21-
employees.add(new Employee(1L, "Mr", "John Doe"));
22-
employees.add(new Employee(2L, "Mr", "White Snow"));
23-
24-
25-
RatpackServer.start(
26-
server -> server.registry(Guice.registry(bindings -> bindings.module(HikariModule.class, config -> {
27-
config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
28-
config.addDataSourceProperty("URL",
29-
"jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'");
30-
}))).handlers(chain -> chain
31-
.all(
32-
// ctx -> {
33-
// MutableHeaders headers =
34-
// ctx.getResponse().getHeaders();
35-
// headers.set("Access-Control-Allow-Origin","*");
36-
// headers.set("Accept-Language", "en-us");
37-
// headers.set("Accept-Charset", "UTF-8");
38-
// ctx.next();
39-
// }
40-
new RequestValidatorFilter())
41-
.get(ctx -> ctx.render("Welcome to baeldung ratpack!!!"))
42-
.get("data/employees", ctx -> ctx.render(Jackson.json(employees)))
43-
.get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens().get("name") + "!!!"))
44-
.post(":amount", ctx -> ctx
45-
.render(" Amount $" + ctx.getPathTokens().get("amount") + " added successfully !!!"))));
46-
}
47-
48-
}
49-
1+
package com.baeldung;
2+
3+
import com.baeldung.filter.RequestValidatorFilter;
4+
import com.baeldung.handler.EmployeeHandler;
5+
import com.baeldung.handler.RedirectHandler;
6+
import com.baeldung.model.Employee;
7+
import com.baeldung.repository.EmployeeRepository;
8+
import com.baeldung.repository.EmployeeRepositoryImpl;
9+
import com.zaxxer.hikari.HikariConfig;
10+
import io.netty.buffer.PooledByteBufAllocator;
11+
import ratpack.func.Action;
12+
import ratpack.func.Function;
13+
import ratpack.guice.BindingsSpec;
14+
import ratpack.guice.Guice;
15+
import ratpack.handling.Chain;
16+
import ratpack.hikari.HikariModule;
17+
import ratpack.http.client.HttpClient;
18+
import ratpack.jackson.Jackson;
19+
import ratpack.registry.Registry;
20+
import ratpack.server.RatpackServer;
21+
import ratpack.server.RatpackServerSpec;
22+
import ratpack.server.ServerConfig;
23+
24+
import java.time.Duration;
25+
import java.time.temporal.ChronoUnit;
26+
import java.util.ArrayList;
27+
import java.util.List;
28+
29+
public class Application {
30+
31+
public static void main(String[] args) throws Exception {
32+
33+
final Action<HikariConfig> hikariConfigAction = hikariConfig -> {
34+
hikariConfig.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
35+
hikariConfig.addDataSourceProperty("URL", "jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'");
36+
};
37+
38+
final Action<BindingsSpec> bindingsSpecAction = bindings -> bindings.module(HikariModule.class, hikariConfigAction);
39+
final HttpClient httpClient = HttpClient.of(httpClientSpec -> {
40+
httpClientSpec.poolSize(10)
41+
.connectTimeout(Duration.of(60, ChronoUnit.SECONDS))
42+
.maxContentLength(ServerConfig.DEFAULT_MAX_CONTENT_LENGTH)
43+
.responseMaxChunkSize(16384)
44+
.readTimeout(Duration.of(60, ChronoUnit.SECONDS))
45+
.byteBufAllocator(PooledByteBufAllocator.DEFAULT);
46+
});
47+
final Function<Registry, Registry> registryFunction = Guice.registry(bindingsSpecAction);
48+
49+
final Action<Chain> chainAction = chain -> chain.all(new RequestValidatorFilter())
50+
.get(ctx -> ctx.render("Welcome to baeldung ratpack!!!"))
51+
.get("data/employees", ctx -> ctx.render(Jackson.json(createEmpList())))
52+
.get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens()
53+
.get("name") + "!!!"))
54+
.post(":amount", ctx -> ctx.render(" Amount $" + ctx.getPathTokens()
55+
.get("amount") + " added successfully !!!"));
56+
57+
final Action<Chain> routerChainAction = routerChain -> {
58+
routerChain.path("redirect", new RedirectHandler())
59+
.prefix("employee", empChain -> {
60+
empChain.get(":id", new EmployeeHandler());
61+
});
62+
};
63+
final Action<RatpackServerSpec> ratpackServerSpecAction = serverSpec -> serverSpec.registry(registryFunction)
64+
.registryOf(registrySpec -> {
65+
registrySpec.add(EmployeeRepository.class, new EmployeeRepositoryImpl());
66+
registrySpec.add(HttpClient.class, httpClient);
67+
})
68+
.handlers(chain -> chain.insert(routerChainAction)
69+
.insert(chainAction));
70+
71+
RatpackServer.start(ratpackServerSpecAction);
72+
}
73+
74+
private static List<Employee> createEmpList() {
75+
List<Employee> employees = new ArrayList<>();
76+
employees.add(new Employee(1L, "Mr", "John Doe"));
77+
employees.add(new Employee(2L, "Mr", "White Snow"));
78+
return employees;
79+
}
80+
81+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.handler;
2+
3+
import com.baeldung.repository.EmployeeRepository;
4+
import com.baeldung.model.Employee;
5+
import ratpack.exec.Promise;
6+
import ratpack.handling.Context;
7+
import ratpack.handling.Handler;
8+
9+
public class EmployeeHandler implements Handler {
10+
@Override
11+
public void handle(Context ctx) throws Exception {
12+
EmployeeRepository repository = ctx.get(EmployeeRepository.class);
13+
Long id = Long.valueOf(ctx.getPathTokens()
14+
.get("id"));
15+
Promise<Employee> employeePromise = repository.findEmployeeById(id);
16+
employeePromise.map(employee -> employee.getName())
17+
.then(name -> ctx.getResponse()
18+
.send(name));
19+
}
20+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.baeldung.handler;
2+
3+
import ratpack.handling.Context;
4+
import ratpack.handling.Handler;
5+
6+
public class FooHandler implements Handler {
7+
@Override
8+
public void handle(Context ctx) throws Exception {
9+
ctx.getResponse()
10+
.send("Hello Foo!");
11+
}
12+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.handler;
2+
3+
import ratpack.exec.Promise;
4+
import ratpack.handling.Context;
5+
import ratpack.handling.Handler;
6+
import ratpack.http.client.HttpClient;
7+
import ratpack.http.client.ReceivedResponse;
8+
9+
import java.net.URI;
10+
11+
public class RedirectHandler implements Handler {
12+
@Override
13+
public void handle(Context ctx) throws Exception {
14+
HttpClient client = ctx.get(HttpClient.class);
15+
URI uri = URI.create("http://localhost:5050/employee/1");
16+
Promise<ReceivedResponse> responsePromise = client.get(uri);
17+
responsePromise.map(response -> response.getBody()
18+
.getText()
19+
.toUpperCase())
20+
.then(responseText -> ctx.getResponse()
21+
.send(responseText));
22+
}
23+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.baeldung.repository;
2+
3+
import com.baeldung.model.Employee;
4+
import ratpack.exec.Promise;
5+
6+
public interface EmployeeRepository {
7+
8+
Promise<Employee> findEmployeeById(Long id) throws Exception;
9+
10+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.repository;
2+
3+
import com.baeldung.model.Employee;
4+
import ratpack.exec.Promise;
5+
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
9+
public class EmployeeRepositoryImpl implements EmployeeRepository {
10+
11+
private static final Map<Long, Employee> EMPLOYEE_MAP = new HashMap<>();
12+
13+
public EmployeeRepositoryImpl() {
14+
EMPLOYEE_MAP.put(1L, new Employee(1L, "Ms", "Jane Doe"));
15+
EMPLOYEE_MAP.put(2L, new Employee(2L, "Mr", "NY"));
16+
}
17+
18+
@Override
19+
public Promise<Employee> findEmployeeById(Long id) throws Exception {
20+
return Promise.async(downstream -> {
21+
Thread.sleep(500);
22+
downstream.success(EMPLOYEE_MAP.get(id));
23+
});
24+
}
25+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.baeldung;
2+
3+
import com.baeldung.model.Employee;
4+
import org.junit.Test;
5+
import ratpack.exec.Promise;
6+
import ratpack.func.Action;
7+
import ratpack.handling.Chain;
8+
import ratpack.handling.Handler;
9+
import ratpack.registry.Registry;
10+
import ratpack.test.embed.EmbeddedApp;
11+
import ratpack.test.exec.ExecHarness;
12+
13+
import static org.junit.Assert.assertEquals;
14+
15+
public class AppHttpUnitTest {
16+
17+
@Test
18+
public void givenAnyUri_GetEmployeeFromSameRegistry() throws Exception {
19+
Handler allHandler = ctx -> {
20+
Long id = Long.valueOf(ctx.getPathTokens()
21+
.get("id"));
22+
Employee employee = new Employee(id, "Mr", "NY");
23+
ctx.next(Registry.single(Employee.class, employee));
24+
};
25+
Handler empNameHandler = ctx -> {
26+
Employee employee = ctx.get(Employee.class);
27+
ctx.getResponse()
28+
.send("Name of employee with ID " + employee.getId() + " is " + employee.getName());
29+
};
30+
Handler empTitleHandler = ctx -> {
31+
Employee employee = ctx.get(Employee.class);
32+
ctx.getResponse()
33+
.send("Title of employee with ID " + employee.getId() + " is " + employee.getTitle());
34+
};
35+
36+
Action<Chain> chainAction = chain -> chain.prefix("employee/:id", empChain -> {
37+
empChain.all(allHandler)
38+
.get("name", empNameHandler)
39+
.get("title", empTitleHandler);
40+
});
41+
EmbeddedApp.fromHandlers(chainAction)
42+
.test(testHttpClient -> {
43+
assertEquals("Name of employee with ID 1 is NY", testHttpClient.get("employee/1/name")
44+
.getBody()
45+
.getText());
46+
assertEquals("Title of employee with ID 1 is Mr", testHttpClient.get("employee/1/title")
47+
.getBody()
48+
.getText());
49+
});
50+
}
51+
52+
@Test
53+
public void givenSyncDataSource_GetDataFromPromise() throws Exception {
54+
String value = ExecHarness.yieldSingle(execution -> Promise.sync(() -> "Foo"))
55+
.getValueOrThrow();
56+
assertEquals("Foo", value);
57+
}
58+
}

0 commit comments

Comments
 (0)