ratpack.server.RatpackServer Java Examples

The following examples show how to use ratpack.server.RatpackServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProxyMain.java    From consensusj with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) throws Exception {
    ServerConfig serverConfig = ServerConfig.of(config -> config
            .port(5050)
            .baseDir(BaseDir.find())
            .json("proxy-config.json")
            .require("/rpcclient", RpcConfig.class)
    );
    RatpackServer.start (server -> server
        .serverConfig(serverConfig)
        .registry(Guice.registry(b -> b.
                moduleConfig(BitcoinRpcProxyModule.class,
                        serverConfig.get("/rpcclient", RpcConfig.class))))
        .handlers(chain -> chain
                .post("rpc", RpcProxyHandler.class)
                .get("status", ChainStatusHandler.class)
                .get("gen", GenerateHandler.class)
                .get(ctx -> ctx.getResponse().send("Hello world! (Not RPC)"))
            )
    );
}
 
Example #2
Source File: Application.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

		RatpackServer
				.start(server -> server.registry(Guice.registry(bindings -> bindings.module(DependencyModule.class)))
						.handlers(chain -> chain.get("randomString", ctx -> {
							DataPumpService dataPumpService = ctx.get(DataPumpService.class);
							ctx.render(dataPumpService.generate());
						}).get("factory", ctx -> ctx.render(ServiceFactory.getInstance().generate()))));

//		RatpackServer.start(server -> server
//				.registry(Guice
//						.registry(bindings -> bindings.bindInstance(DataPumpService.class, new DataPumpServiceImpl())))
//				.handlers(chain -> chain.get("randomString", ctx -> {
//					DataPumpService dataPumpService = ctx.get(DataPumpService.class);
//					ctx.render(dataPumpService.generate());
//				}).get("factory", ctx -> ctx.render(ServiceFactory.getInstance().generate()))));

	}
 
Example #3
Source File: RatpackHystrixApp.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final int timeout = Integer.valueOf(System.getProperty("ratpack.hystrix.timeout"));
    final URI eugenGithubProfileUri = new URI("https://api.github.com/users/eugenp");

    RatpackServer.start(server -> server
      .registry(Guice.registry(bindingsSpec -> bindingsSpec.module(new HystrixModule().sse())))
      .handlers(chain -> chain
        .get("rx", ctx -> new HystrixReactiveHttpCommand(ctx.get(HttpClient.class), eugenGithubProfileUri, timeout)
          .toObservable()
          .subscribe(ctx::render))
        .get("async", ctx -> ctx.render(new HystrixAsyncHttpCommand(eugenGithubProfileUri, timeout)
          .queue()
          .get()))
        .get("sync", ctx -> ctx.render(new HystrixSyncHttpCommand(eugenGithubProfileUri, timeout).execute()))
        .get("hystrix", new HystrixMetricsEventStreamHandler())));

}
 
Example #4
Source File: RatpackParallelismApp.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Try hitting http://localhost:5050/movies to see the application in action.
 * 
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    RxRatpack.initialize();
    RatpackServer.start(def -> def.registryOf(regSpec -> regSpec.add(MovieObservableService.class, new MovieObservableServiceImpl()))
        .handlers(chain -> chain.get("movies", ctx -> {
            MovieObservableService movieSvc = ctx.get(MovieObservableService.class);
            Observable<Movie> movieObs = movieSvc.getMovies();
            Observable<String> upperCasedNames = movieObs.compose(RxRatpack::forkEach)
                .map(movie -> movie.getName()
                    .toUpperCase())
                .serialize();
            RxRatpack.promise(upperCasedNames)
                .then(movie -> {
                    ctx.render(Jackson.json(movie));
                });
        })));
}
 
Example #5
Source File: ratpack.java    From jbang with MIT License 5 votes vote down vote up
void run() throws Exception {
   RatpackServer.start((server) -> {
    server.serverConfig(sc -> sc.port(8080));
    server.handlers((chain) -> {
      chain
        .get(this::renderWorld)
        .get(":name", this::renderName);
    });
  });
}
 
Example #6
Source File: App.java    From smartapp-sdk-java with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {
    HttpVerificationService httpVerificationService = new HttpVerificationService();
    Module appModule = new AppModule();
    SmartApp smartApp = SmartApp.of(Guice.smartapp(bindings -> bindings.module(appModule)));
    RatpackServer.start(server -> {
        ObjectMapper objectMapper = DefaultConfigDataBuilder.newDefaultObjectMapper()
            .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        server
            .registry(ratpack.guice.Guice.registry(bindingsSpec -> {
                bindingsSpec.module(appModule);
                bindingsSpec.bindInstance(ObjectMapper.class, objectMapper);
            }))
            .handlers(chain -> chain
                .get(ctx -> ctx.getResponse()
                    .status(Status.FORBIDDEN)
                    .send("This app only functions as a SmartThings Automation webhook endpoint app"))
                .post("smartapp", ctx -> {
                    ctx.parse(ExecutionRequest.class).then(executionRequest -> {
                        Request request = ctx.getRequest();
                        Headers headers = request.getHeaders();
                        Map<String, String> headersMap = headers.getNames().stream()
                                .collect(Collectors.toMap(name -> name, name -> headers.get(name)));
                        String method = request.getMethod().getName();
                        if (executionRequest.getLifecycle() != AppLifecycle.PING
                                && !httpVerificationService.verify(method, request.getUri(), headersMap)) {
                            ctx.clientError(401);
                        } else {
                            ctx.render(json(smartApp.execute(executionRequest)));
                        }
                    });
                })
            );
        }
    );
}
 
Example #7
Source File: LogServiceApplication.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ConfigurableApplicationContext context =
            SpringApplication.run(LogServiceApplication.class, args);

    LogService logsService = context.getBean(LogService.class);
    FileService fileService = context.getBean(FileService.class);

    File tempFile = File.createTempFile("LogServiceApplication", ".tmp");
    tempFile.deleteOnExit();

    fileService.writeTo(tempFile.getAbsolutePath(), logsService.stream());

    RatpackServer.start(server ->
            server.handlers(chain ->
                    chain.all(ctx -> {

                        Publisher<String> logs = logsService.stream();

                        ServerSentEvents events = serverSentEvents(
                                logs,
                                event -> event.id(Objects::toString)
                                              .event("log")
                                              .data(Function.identity())
                        );

                        ctx.render(events);
                    })
            )
    );
}
 
Example #8
Source File: EmbedSpringBootApp.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    RatpackServer.start(server -> server
      .registry(spring(Config.class))
      .handlers(chain -> chain.get(ctx -> ctx.render(ctx
        .get(Content.class)
        .body()))));
}
 
Example #9
Source File: RatpackErrorHandlingApp.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Try hitting http://localhost:5050/error to see the error handler in action
 * @param args
 * @throws Exception
 */

public static void main(String[] args) throws Exception {
    RxRatpack.initialize();
    RatpackServer.start(def -> def.registryOf(regSpec -> regSpec.add(ServerErrorHandler.class, (ctx, throwable) -> {
        ctx.render("Error caught by handler : " + throwable.getMessage());
    }))
        .handlers(chain -> chain.get("error", ctx -> {
            Observable.<String> error(new Exception("Error from observable"))
                .subscribe(s -> {
                });
        })));
}
 
Example #10
Source File: RatpackITest.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {
  final RatpackServer server = RatpackServer.start(new Action<RatpackServerSpec>() {
    @Override
    public void execute(final RatpackServerSpec ratpackServerSpec) {
      ratpackServerSpec.handlers(new Action<Chain>() {
        @Override
        public void execute(final Chain chain) {
          chain.get(new Handler() {
            @Override
            public void handle(final Context context) {
              TestUtil.checkActiveSpan();
              context.render("Test");
            }
          });
        }
      });
    }
  });

  final HttpClient client = HttpClient.of(new Action<HttpClientSpec>() {
    @Override
    public void execute(final HttpClientSpec httpClientSpec) {
      httpClientSpec
        .poolSize(10)
        .maxContentLength(ServerConfig.DEFAULT_MAX_CONTENT_LENGTH)
        .readTimeout(Duration.of(60, ChronoUnit.SECONDS))
        .byteBufAllocator(PooledByteBufAllocator.DEFAULT);
    }
  });

  try (final ExecHarness harness = ExecHarness.harness()) {
    final ExecResult<ReceivedResponse> result = harness.yield(new Function<Execution,Promise<ReceivedResponse>>() {
      @Override
      public Promise<ReceivedResponse> apply(final Execution execution) {
        return client.get(URI.create("http://localhost:5050"));
      }
    });

    final int statusCode = result.getValue().getStatusCode();
    if (200 != statusCode)
      throw new AssertionError("ERROR: response: " + statusCode);
  }

  server.stop();
  TestUtil.checkSpan(new ComponentSpanCount("netty", 2, true));
}
 
Example #11
Source File: NewsServiceApp.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    SpringApplication.run(NewsServiceApp.class, args);

    RatpackServer.start(spec ->
        spec.serverConfig(ServerConfig.embedded().port(NEWS_SERVER_PORT))
            .handlers(chain -> chain.get(ctx -> ctx.render(json(Arrays.asList(
                    News.builder()
                        .author("test")
                        .category("test")
                        .content("test")
                        .publishedOn(new Date())
                        .title("test")
                        .build(),
                    News.builder()
                        .author("test")
                        .category("test")
                        .content("test")
                        .publishedOn(new Date())
                        .title("1test1")
                        .build(),
                    News.builder()
                        .author("test")
                        .category("test")
                        .content("test")
                        .publishedOn(new Date())
                        .title("2test2")
                        .build(),
                    News.builder()
                        .author("test")
                        .category("test")
                        .content("test")
                        .publishedOn(new Date())
                        .title("3test3")
                        .build(),
                    News.builder()
                        .author("test")
                        .category("test")
                        .content("test")
                        .publishedOn(new Date())
                        .title("4test4")
                        .build(),
                    News.builder()
                        .author("test")
                        .category("test")
                        .content("test")
                        .publishedOn(new Date())
                        .title("5test5")
                        .build(),
                    News.builder()
                        .author("test")
                        .category("test")
                        .content("test")
                        .publishedOn(new Date())
                        .title("6test6")
                        .build()
            )))))
    );
}
 
Example #12
Source File: Main.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void main(String... args) throws Exception {
    RxRatpack.initialize();

    RatpackServer.start(server -> server
            .serverConfig(c -> {
                c
                        .findBaseDir("application.yml")
                        .yaml("application.yml")
                        .args(args)
                        .require("/database", DatabaseConfig.class);
            })
            .registry(Guice.registry(b -> {
                        DatabaseConfig databaseConfig = b.getServerConfig().get("/database", DatabaseConfig.class);
                        ProfileConfig profileConfig = b.getServerConfig().get("/profile", ProfileConfig.class);

                        b.module(HandlebarsModule.class);

                        if (profileConfig != null) {
                            if ("pgclient".equals(profileConfig.getName())) {
                                b.module(PgClientModule.class, options -> {
                                    options.setDatabase(databaseConfig.getSchema());
                                    options.setHost(databaseConfig.getHost());
                                    options.setPort(databaseConfig.getPort());
                                    options.setUser(databaseConfig.getUsername());
                                    options.setPassword(databaseConfig.getPassword());
                                    options.setCachePreparedStatements(true);
                                    options.setMaxSize(1);
                                }).module(PgClientRepositoryModule.class);
                            } else if ("jdbc".equals(profileConfig.getName())) {
                                b.module(HikariModule.class, hikariConfig -> {
                                    hikariConfig.setJdbcUrl(String.format("jdbc:postgresql://%s:%s/%s", databaseConfig.getHost(), databaseConfig.getPort(),
                                            databaseConfig.getSchema()));
                                    hikariConfig.setUsername(databaseConfig.getUsername());
                                    hikariConfig.setPassword(databaseConfig.getPassword());
                                    hikariConfig.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2);
                                }).module(JdbcRepositoryModule.class);
                            }
                        }
                    }
            ))
            .handlers(chain -> chain
                    .all(new HeaderHandler())
                    .get("plaintext", new PlainTextHandler())
                    .get("json", new JsonHandler())
                    .get("db", new DbHandler())
                    .get("queries", new QueryHandler())
                    .get("fortunes", new FortuneHandler())
                    .get("updates", new UpdateHandler())
            )
    );
}
 
Example #13
Source File: Application.java    From tutorials with MIT License 4 votes vote down vote up
private Application() throws Exception {
    final RatpackServer server = RatpackServer.of(s -> s.handlers(chain -> chain.post("users", new UserHandler())));
    server.start();
}
 
Example #14
Source File: Application.java    From tutorials with MIT License 4 votes vote down vote up
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);
    }