diff --git a/ratpack/build.gradle b/ratpack/build.gradle index aeddd5f9f9..25af3ddb51 100644 --- a/ratpack/build.gradle +++ b/ratpack/build.gradle @@ -1,35 +1,35 @@ -buildscript { - repositories { - jcenter() - } - dependencies { - classpath "io.ratpack:ratpack-gradle:1.4.5" - classpath "com.h2database:h2:1.4.193" - } -} - -if (!JavaVersion.current().java8Compatible) { - throw new IllegalStateException("Must be built with Java 8 or higher") -} - -apply plugin: "io.ratpack.ratpack-java" -apply plugin: 'java' - -repositories { - jcenter() -} - -dependencies { - compile ratpack.dependency('hikari') - compile 'com.h2database:h2:1.4.193' - testCompile 'junit:junit:4.11' - runtime "org.slf4j:slf4j-simple:1.7.21" -} - -test { - testLogging { - events 'started', 'passed' - } -} - -mainClassName = "com.baeldung.Application" +buildscript { + repositories { + jcenter() + } + dependencies { + classpath "io.ratpack:ratpack-gradle:1.5.4" + classpath "com.h2database:h2:1.4.193" + } +} + +if (!JavaVersion.current().java8Compatible) { + throw new IllegalStateException("Must be built with Java 8 or higher") +} + +apply plugin: "io.ratpack.ratpack-java" +apply plugin: 'java' + +repositories { + jcenter() +} + +dependencies { + compile ratpack.dependency('hikari') + compile 'com.h2database:h2:1.4.193' + testCompile 'junit:junit:4.11' + runtime "org.slf4j:slf4j-simple:1.7.21" +} + +test { + testLogging { + events 'started', 'passed' + } +} + +mainClassName = "com.baeldung.Application" diff --git a/ratpack/pom.xml b/ratpack/pom.xml index bbde3d1cd7..7de11e6955 100644 --- a/ratpack/pom.xml +++ b/ratpack/pom.xml @@ -35,6 +35,17 @@ io.ratpack ratpack-hystrix ${ratpack.version} + + + com.netflix.hystrix + hystrix-core + + + + + com.netflix.hystrix + hystrix-core + ${hystrix.version} io.ratpack @@ -76,10 +87,11 @@ 1.8 1.8 - 1.4.6 + 1.5.4 4.5.3 4.4.6 1.4.193 + 1.5.12 diff --git a/ratpack/src/main/java/com/baeldung/Application.java b/ratpack/src/main/java/com/baeldung/Application.java index 7f46b241ea..4a391d04a1 100644 --- a/ratpack/src/main/java/com/baeldung/Application.java +++ b/ratpack/src/main/java/com/baeldung/Application.java @@ -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 employees = new ArrayList(); - 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 hikariConfigAction = hikariConfig -> { + hikariConfig.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource"); + hikariConfig.addDataSourceProperty("URL", "jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'"); + }; + + final Action 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 registryFunction = Guice.registry(bindingsSpecAction); + + final Action 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 routerChainAction = routerChain -> { + routerChain.path("redirect", new RedirectHandler()) + .prefix("employee", empChain -> { + empChain.get(":id", new EmployeeHandler()); + }); + }; + final Action 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 createEmpList() { + List employees = new ArrayList<>(); + employees.add(new Employee(1L, "Mr", "John Doe")); + employees.add(new Employee(2L, "Mr", "White Snow")); + return employees; + } + +} diff --git a/ratpack/src/main/java/com/baeldung/handler/EmployeeHandler.java b/ratpack/src/main/java/com/baeldung/handler/EmployeeHandler.java new file mode 100644 index 0000000000..9a6b79259c --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/handler/EmployeeHandler.java @@ -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 employeePromise = repository.findEmployeeById(id); + employeePromise.map(employee -> employee.getName()) + .then(name -> ctx.getResponse() + .send(name)); + } +} diff --git a/ratpack/src/main/java/com/baeldung/handler/FooHandler.java b/ratpack/src/main/java/com/baeldung/handler/FooHandler.java new file mode 100644 index 0000000000..d2c4dbdce5 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/handler/FooHandler.java @@ -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!"); + } +} diff --git a/ratpack/src/main/java/com/baeldung/handler/RedirectHandler.java b/ratpack/src/main/java/com/baeldung/handler/RedirectHandler.java new file mode 100644 index 0000000000..c95543a961 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/handler/RedirectHandler.java @@ -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 responsePromise = client.get(uri); + responsePromise.map(response -> response.getBody() + .getText() + .toUpperCase()) + .then(responseText -> ctx.getResponse() + .send(responseText)); + } +} \ No newline at end of file diff --git a/ratpack/src/main/java/com/baeldung/repository/EmployeeRepository.java b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepository.java new file mode 100644 index 0000000000..de04c23da5 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.repository; + +import com.baeldung.model.Employee; +import ratpack.exec.Promise; + +public interface EmployeeRepository { + + Promise findEmployeeById(Long id) throws Exception; + +} diff --git a/ratpack/src/main/java/com/baeldung/repository/EmployeeRepositoryImpl.java b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepositoryImpl.java new file mode 100644 index 0000000000..6d15012ccb --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepositoryImpl.java @@ -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 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 findEmployeeById(Long id) throws Exception { + return Promise.async(downstream -> { + Thread.sleep(500); + downstream.success(EMPLOYEE_MAP.get(id)); + }); + } +} diff --git a/ratpack/src/test/java/com/baeldung/AppHttpUnitTest.java b/ratpack/src/test/java/com/baeldung/AppHttpUnitTest.java new file mode 100644 index 0000000000..a97516dd74 --- /dev/null +++ b/ratpack/src/test/java/com/baeldung/AppHttpUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung; + +import com.baeldung.model.Employee; +import org.junit.Test; +import ratpack.exec.Promise; +import ratpack.func.Action; +import ratpack.handling.Chain; +import ratpack.handling.Handler; +import ratpack.registry.Registry; +import ratpack.test.embed.EmbeddedApp; +import ratpack.test.exec.ExecHarness; + +import static org.junit.Assert.assertEquals; + +public class AppHttpUnitTest { + + @Test + public void givenAnyUri_GetEmployeeFromSameRegistry() throws Exception { + Handler allHandler = ctx -> { + Long id = Long.valueOf(ctx.getPathTokens() + .get("id")); + Employee employee = new Employee(id, "Mr", "NY"); + ctx.next(Registry.single(Employee.class, employee)); + }; + Handler empNameHandler = ctx -> { + Employee employee = ctx.get(Employee.class); + ctx.getResponse() + .send("Name of employee with ID " + employee.getId() + " is " + employee.getName()); + }; + Handler empTitleHandler = ctx -> { + Employee employee = ctx.get(Employee.class); + ctx.getResponse() + .send("Title of employee with ID " + employee.getId() + " is " + employee.getTitle()); + }; + + Action chainAction = chain -> chain.prefix("employee/:id", empChain -> { + empChain.all(allHandler) + .get("name", empNameHandler) + .get("title", empTitleHandler); + }); + EmbeddedApp.fromHandlers(chainAction) + .test(testHttpClient -> { + assertEquals("Name of employee with ID 1 is NY", testHttpClient.get("employee/1/name") + .getBody() + .getText()); + assertEquals("Title of employee with ID 1 is Mr", testHttpClient.get("employee/1/title") + .getBody() + .getText()); + }); + } + + @Test + public void givenSyncDataSource_GetDataFromPromise() throws Exception { + String value = ExecHarness.yieldSingle(execution -> Promise.sync(() -> "Foo")) + .getValueOrThrow(); + assertEquals("Foo", value); + } +}