Ratpack HTTP Client

This commit is contained in:
Neeraj Yadav
2018-08-30 02:56:21 +05:30
parent 9e1d35c42d
commit aacb654119
9 changed files with 270 additions and 85 deletions
@@ -1,49 +1,81 @@
package com.baeldung;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.filter.RequestValidatorFilter;
import com.baeldung.model.Employee;
import ratpack.guice.Guice;
import ratpack.hikari.HikariModule;
import ratpack.http.MutableHeaders;
import ratpack.jackson.Jackson;
import ratpack.http.MutableHeaders;
import ratpack.server.RatpackServer;
public class Application {
public static void main(String[] args) throws Exception {
List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee(1L, "Mr", "John Doe"));
employees.add(new Employee(2L, "Mr", "White Snow"));
RatpackServer.start(
server -> server.registry(Guice.registry(bindings -> bindings.module(HikariModule.class, config -> {
config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
config.addDataSourceProperty("URL",
"jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'");
}))).handlers(chain -> chain
.all(
// ctx -> {
// MutableHeaders headers =
// ctx.getResponse().getHeaders();
// headers.set("Access-Control-Allow-Origin","*");
// headers.set("Accept-Language", "en-us");
// headers.set("Accept-Charset", "UTF-8");
// ctx.next();
// }
new RequestValidatorFilter())
.get(ctx -> ctx.render("Welcome to baeldung ratpack!!!"))
.get("data/employees", ctx -> ctx.render(Jackson.json(employees)))
.get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens().get("name") + "!!!"))
.post(":amount", ctx -> ctx
.render(" Amount $" + ctx.getPathTokens().get("amount") + " added successfully !!!"))));
}
}
package com.baeldung;
import com.baeldung.filter.RequestValidatorFilter;
import com.baeldung.handler.EmployeeHandler;
import com.baeldung.handler.RedirectHandler;
import com.baeldung.model.Employee;
import com.baeldung.repository.EmployeeRepository;
import com.baeldung.repository.EmployeeRepositoryImpl;
import com.zaxxer.hikari.HikariConfig;
import io.netty.buffer.PooledByteBufAllocator;
import ratpack.func.Action;
import ratpack.func.Function;
import ratpack.guice.BindingsSpec;
import ratpack.guice.Guice;
import ratpack.handling.Chain;
import ratpack.hikari.HikariModule;
import ratpack.http.client.HttpClient;
import ratpack.jackson.Jackson;
import ratpack.registry.Registry;
import ratpack.server.RatpackServer;
import ratpack.server.RatpackServerSpec;
import ratpack.server.ServerConfig;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
public class Application {
public static void main(String[] args) throws Exception {
final Action<HikariConfig> hikariConfigAction = hikariConfig -> {
hikariConfig.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
hikariConfig.addDataSourceProperty("URL", "jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'");
};
final Action<BindingsSpec> bindingsSpecAction = bindings -> bindings.module(HikariModule.class, hikariConfigAction);
final HttpClient httpClient = HttpClient.of(httpClientSpec -> {
httpClientSpec.poolSize(10)
.connectTimeout(Duration.of(60, ChronoUnit.SECONDS))
.maxContentLength(ServerConfig.DEFAULT_MAX_CONTENT_LENGTH)
.responseMaxChunkSize(16384)
.readTimeout(Duration.of(60, ChronoUnit.SECONDS))
.byteBufAllocator(PooledByteBufAllocator.DEFAULT);
});
final Function<Registry, Registry> registryFunction = Guice.registry(bindingsSpecAction);
final Action<Chain> chainAction = chain -> chain.all(new RequestValidatorFilter())
.get(ctx -> ctx.render("Welcome to baeldung ratpack!!!"))
.get("data/employees", ctx -> ctx.render(Jackson.json(createEmpList())))
.get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens()
.get("name") + "!!!"))
.post(":amount", ctx -> ctx.render(" Amount $" + ctx.getPathTokens()
.get("amount") + " added successfully !!!"));
final Action<Chain> routerChainAction = routerChain -> {
routerChain.path("redirect", new RedirectHandler())
.prefix("employee", empChain -> {
empChain.get(":id", new EmployeeHandler());
});
};
final Action<RatpackServerSpec> ratpackServerSpecAction = serverSpec -> serverSpec.registry(registryFunction)
.registryOf(registrySpec -> {
registrySpec.add(EmployeeRepository.class, new EmployeeRepositoryImpl());
registrySpec.add(HttpClient.class, httpClient);
})
.handlers(chain -> chain.insert(routerChainAction)
.insert(chainAction));
RatpackServer.start(ratpackServerSpecAction);
}
private static List<Employee> createEmpList() {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1L, "Mr", "John Doe"));
employees.add(new Employee(2L, "Mr", "White Snow"));
return employees;
}
}
@@ -0,0 +1,20 @@
package com.baeldung.handler;
import com.baeldung.repository.EmployeeRepository;
import com.baeldung.model.Employee;
import ratpack.exec.Promise;
import ratpack.handling.Context;
import ratpack.handling.Handler;
public class EmployeeHandler implements Handler {
@Override
public void handle(Context ctx) throws Exception {
EmployeeRepository repository = ctx.get(EmployeeRepository.class);
Long id = Long.valueOf(ctx.getPathTokens()
.get("id"));
Promise<Employee> employeePromise = repository.findEmployeeById(id);
employeePromise.map(employee -> employee.getName())
.then(name -> ctx.getResponse()
.send(name));
}
}
@@ -0,0 +1,12 @@
package com.baeldung.handler;
import ratpack.handling.Context;
import ratpack.handling.Handler;
public class FooHandler implements Handler {
@Override
public void handle(Context ctx) throws Exception {
ctx.getResponse()
.send("Hello Foo!");
}
}
@@ -0,0 +1,23 @@
package com.baeldung.handler;
import ratpack.exec.Promise;
import ratpack.handling.Context;
import ratpack.handling.Handler;
import ratpack.http.client.HttpClient;
import ratpack.http.client.ReceivedResponse;
import java.net.URI;
public class RedirectHandler implements Handler {
@Override
public void handle(Context ctx) throws Exception {
HttpClient client = ctx.get(HttpClient.class);
URI uri = URI.create("http://localhost:5050/employee/1");
Promise<ReceivedResponse> responsePromise = client.get(uri);
responsePromise.map(response -> response.getBody()
.getText()
.toUpperCase())
.then(responseText -> ctx.getResponse()
.send(responseText));
}
}
@@ -0,0 +1,10 @@
package com.baeldung.repository;
import com.baeldung.model.Employee;
import ratpack.exec.Promise;
public interface EmployeeRepository {
Promise<Employee> findEmployeeById(Long id) throws Exception;
}
@@ -0,0 +1,25 @@
package com.baeldung.repository;
import com.baeldung.model.Employee;
import ratpack.exec.Promise;
import java.util.HashMap;
import java.util.Map;
public class EmployeeRepositoryImpl implements EmployeeRepository {
private static final Map<Long, Employee> EMPLOYEE_MAP = new HashMap<>();
public EmployeeRepositoryImpl() {
EMPLOYEE_MAP.put(1L, new Employee(1L, "Ms", "Jane Doe"));
EMPLOYEE_MAP.put(2L, new Employee(2L, "Mr", "NY"));
}
@Override
public Promise<Employee> findEmployeeById(Long id) throws Exception {
return Promise.async(downstream -> {
Thread.sleep(500);
downstream.success(EMPLOYEE_MAP.get(id));
});
}
}