本文整理汇总了Java中ratpack.handling.Context.render方法的典型用法代码示例。如果您正苦于以下问题:Java Context.render方法的具体用法?Java Context.render怎么用?Java Context.render使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ratpack.handling.Context
的用法示例。
在下文中一共展示了Context.render方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: handle
import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(final Context ctx) throws Exception {
final PathBinding pathBinding = ctx.getPathBinding();
final String path = pathBinding.getPastBinding();
final String resourePathStr = Joiner.on("/").join(WEBJAR_ROOT, moduleName, version, includePath, path);
final Path resourcePath = jarFileSystem.isPresent() ?
jarFileSystem.map(fs -> fs.getPath(resourePathStr)).get() :
ctx.getFileSystemBinding().file(resourePathStr);
if (Files.exists(resourcePath)) {
ctx.render(resourcePath);
} else {
ctx.next();
}
}
示例2: handle
import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(final Context ctx) throws Exception {
final RamlModelRepository ramlModelRepository = ctx.get(RamlModelRepository.class);
final Path filePath = ramlModelRepository.getFilePath();
final PathBinding pathBinding = ctx.getPathBinding();
final String path = pathBinding.getPastBinding();
if (path.isEmpty() || path.equals("index.html")) {
final String queryParams = QueryParams.queryParams(ctx);
final Integer port = ctx.getServerConfig().getPort();
final String jsonFileName = filePath.toAbsolutePath().toString().replaceAll("raml$", "json");
final File jsonFile = new File(jsonFileName);
final ImmutableMap<String, Object> model =
ImmutableMap.of(
"ramlPath", "api-raml/Vrap-Extension.raml",
"queryParams", queryParams,
"proxyHost", "localhost",
"proxyPort", port,
"jsonFile", jsonFile.exists() ? "/api-raml/" + jsonFile.getName() : ""
);
ctx.render(handlebarsTemplate(model, basePath + "/index.html"));
}
else {
ctx.next();
}
}
示例3: handle
import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(Context ctx) throws Exception {
String token = null;
List<Voice> voices = new ArrayList<>();
while (true) {
DescribeVoicesResult result;
if (token == null) {
result = polly.describeVoices(new DescribeVoicesRequest());
} else {
result = polly.describeVoices(new DescribeVoicesRequest().withNextToken(token));
}
voices.addAll(result.getVoices());
if (result.getNextToken() != null) {
token = result.getNextToken();
} else {
ctx.render(Jackson.toJsonString(voices));
break;
}
}
}
示例4: handle
import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(Context ctx) throws Exception {
try {
Iterable<Action<String,String>> actions = new LinkedList<>(Arrays.asList(
new LongBlockingIOAction("foo", "data"),
new LongBlockingIOAction("bar", "data"),
Action.<String,String>of("buzz", "data", (execControl, data) -> execControl
.promise(fulfiller -> {
throw new IOException("CONTROLLED EXCEPTION");
})),
new LongBlockingIOAction("quzz", "data"),
new LongBlockingIOAction("foo_1", "data"),
new LongBlockingIOAction("foo_2", "data"),
new LongBlockingIOAction("foo_3", "data"),
new LongBlockingIOAction("foo_4", "data"),
new LongBlockingIOAction("foo_5", "data"),
new LongBlockingIOAction("foo_6", "data")
));
Parallel<String,String> pattern = new Parallel<>();
ctx.render(pattern.apply(ctx, ctx, actions));
} catch (Exception ex) {
ctx.clientError(404);
}
}
示例5: handle
import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
@SuppressWarnings("unchecked")
public void handle(Context ctx) throws Exception {
final ReceivedResponse receivedResponse = ctx.get(ReceivedResponse.class);
final Validator validator = ctx.get(Validator.class);
final Boolean dryRun = ctx.get(VrapApp.VrapOptions.class).getDryRun();
final Method method = ctx.get(Method.class);
final Optional<Validator.ValidationErrors> receivedResponseErrors = validator.validateReceivedResponse(ctx, receivedResponse, method);
Optional<Validator.ValidationErrors> requestValidationErrors;
try {
requestValidationErrors = Optional.of(ctx.get(Validator.ValidationErrors.class));
} catch (NotInRegistryException e) {
requestValidationErrors = Optional.empty();
}
if (requestValidationErrors.isPresent() && !dryRun) {
Integer statusCode = receivedResponse.getStatusCode();
if (statusCode < 400 && statusCode > 499) {
ctx.getResponse().status(VrapStatus.INVALID_REQUEST);
Validator.ValidationErrors errors = new Validator.ValidationErrors(
requestValidationErrors.get().getErrors(),
receivedResponse.getStatusCode(),
receivedResponse.getBody().getText());
ctx.render(json(errors));
return;
}
}
if (receivedResponseErrors.isPresent() && !dryRun) {
ctx.getResponse().status(VrapStatus.INVALID_RESPONSE);
ctx.render(json(receivedResponseErrors.get()));
} else {
ctx.next();
}
}
示例6: renderHtml
import ratpack.handling.Context; //导入方法依赖的package包/类
private void renderHtml(final Context ctx, final String fileName, final String content) {
final RamlModelRepository ramlModelRepository = ctx.get(RamlModelRepository.class);
final Api api = ramlModelRepository.getApi();
final Integer port = ctx.getServerConfig().getPort();
String contentWithIncludeLinks = content.replaceAll("(!include\\s*)(\\S*)", "$1<a class=\"hljs-string\" href=\"$2\">$2</a>");
final ImmutableMap<String, String> model =
ImmutableMap.of("fileName", fileName,
"fileContent", contentWithIncludeLinks,
"apiTitle", api.title().value(),
"proxyUri", "http://localhost:" + port.toString());
ctx.render(handlebarsTemplate(model, "api-raml/raml.html"));
}
示例7: handle
import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(Context ctx) throws Exception {
caughtException = null;
try {
validator.validate(ctx.getRequest(), key);
ctx.render("OK");
} catch (Exception e) {
caughtException = e;
ctx.error(e);
}
}
示例8: getGroceryList
import ratpack.handling.Context; //导入方法依赖的package包/类
public void getGroceryList(Context ctx) {
String id = ctx.getPathTokens().get("id");
UUID uuid = UUID.fromString(id);
Optional<GroceryList> match = repository.getList(uuid);
if (match.isPresent())
ctx.render(json(match.get()));
else
ctx.getResponse().status(404).send("Could not find a grocery list with id:" + id);
}
示例9: error
import ratpack.handling.Context; //导入方法依赖的package包/类
/**
* Processes the given exception that occurred processing the given context.
* <p>
* Implementations should strive to avoid throwing exceptions.
* If exceptions are thrown, they will just be logged at a warning level and the response will be finalised with a 500 error code and empty body.
*
* @param context The context being processed
* @param throwable The throwable that occurred
* @throws Exception if something goes wrong handling the error
*/
@Override
public void error(Context context, Throwable throwable) throws Exception {
if (throwable instanceof NotAcceptableException) {
// Don't use error(...) in this handler,
// otherwise we end up throwing the same exception again.
logger.debug("not acceptable request", throwable);
context.getResponse().status(406);
context.getResponse().contentType("text/plain");
context.render("notAcceptable: " + throwable.getMessage());
} else if (throwable instanceof BadRequestException) {
logger.debug("bad request", throwable);
context.getResponse().status(400);
context.render(error("badRequest", throwable.getMessage()));
} else if (throwable instanceof InternalServerErrorException) {
InternalServerErrorException internalError = (InternalServerErrorException) throwable;
logger.error("an internal error occurred", internalError);
context.getResponse().status(500);
context.render(error("internalServerError", internalError.getMessage()));
} else if (throwable instanceof UnauthorizedException) {
logger.debug("unauthorized access", throwable);
context.getResponse().status(401);
context.render(error("unauthorized", throwable.getMessage()));
} else if (throwable instanceof NotFoundException) {
logger.debug("not found", throwable);
context.getResponse().status(404);
context.render(error("resource not found", throwable.getMessage()));
}
else {
logger.error("an internal error occurred", throwable);
context.getResponse().status(500);
context.render(error("internalServerError", throwable.getMessage()));
}
}
示例10: handleByName
import ratpack.handling.Context; //导入方法依赖的package包/类
/**
* Run health check with the given name. If it is not registered HTTP 404 is send to the client
* All exceptions from health check are wrapped in unhealthy result with error=Exception.
* @param context request context
* @param name health check name
* @throws Exception
*/
private void handleByName(Context context, String name) throws Exception {
if (name == null || "".equals(name) || DEFAULT_NAME_TOKEN.equals(name)) {
context.clientError(404);
return;
}
SortedMap<String, HealthCheck.Result> hcheckResults = new ConcurrentSkipListMap<>();
Optional<HealthCheck> hcheck = context.first(TypeToken.of(HealthCheck.class), hc -> hc.getName().equals(name));
if (!hcheck.isPresent()) {
context.clientError(404);
return;
}
try {
Promise<HealthCheck.Result> promise = hcheck.get().check(context.getExecution().getControl());
promise.onError(throwable -> {
hcheckResults.put(hcheck.get().getName(), HealthCheck.Result.unhealthy(throwable));
context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>copyOfSorted(hcheckResults)));
}).then(r -> {
hcheckResults.put(hcheck.get().getName(), r);
context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>copyOfSorted(hcheckResults)));
});
}
catch (Exception ex) {
hcheckResults.put(hcheck.get().getName(), HealthCheck.Result.unhealthy(ex));
context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>copyOfSorted(hcheckResults)));
}
}
示例11: handle
import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(Context ctx) throws Exception {
ctx.render(json(bananaChain.getBlocks()));
}
示例12: handle
import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(Context ctx) throws Exception {
ctx.render(json(bananaChain.getMempool()));
}
示例13: handle
import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(Context context) throws Exception {
final String selfUrl = serverConfig.getPublicAddress().resolve("/" + Paths.PATH_CAPABILITIES).toString();
final String callbackUrl = serverConfig.getPublicAddress().resolve("/" + Paths.PATH_INSTALL).toString();
final String messageUrl = serverConfig.getPublicAddress().resolve("/" + Paths.PATH_WEBHOOK_ROOM_MESSAGE).toString();
final Capabilities caps = Capabilities.builder()
.name("LazyBot")
.description("Awesome LazyBot!")
.key("org.royjacobs.lazybot")
.links(
Links.builder()
.self(selfUrl)
.build()
)
.capabilities(
CapabilitiesContent.builder()
.installable(
Installable.builder()
.allowGlobal(false)
.allowRoom(true)
.callbackUrl(callbackUrl)
.build()
)
.hipChatApiConsumer(
HipChatApiConsumer.builder()
.scopes(hipChatConfig.getScopes())
.build()
)
.webhook(WebHook.builder()
.name("messages")
.event("room_message")
.url(messageUrl)
.authentication("jwt")
.pattern("^/[lL][aA][zZ][yY][bB][oO][tT]")
.build()
)
.build()
)
.build();
context.render(json(caps));
}
示例14: getAllGroceryLists
import ratpack.handling.Context; //导入方法依赖的package包/类
public void getAllGroceryLists(Context ctx) {
ctx.render(json(repository.getLists()));
}
示例15: handle
import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(Context ctx) throws Exception {
try {
AtomicInteger execCounter = new AtomicInteger(0);
Action<String,String> action = Action.<String, String>of("foo", "data", (execControl, data) -> execControl
.promise(fulfiller -> {
if (execCounter.incrementAndGet() <= 3) {
throw new IOException("FAILED EXECUTION");
}
fulfiller.success(ActionResult.success("BAR"));
})
);
// check if retries have to be executed asynchronously
boolean asyncRetry = false;
MultiValueMap<String, String> queryAttrs = ctx.getRequest().getQueryParams();
System.out.println("QUERY: " + queryAttrs.toString());
if ("async".equals(queryAttrs.get("retrymode"))) {
asyncRetry = true;
}
//InvokeWithRetry pattern = ctx.get(PATTERN_TYPE_TOKEN);
PatternsModule.Config patternsConfig = ctx.get(PATTERN_CONFIG_TYPE_TOKEN);
Objects.requireNonNull(patternsConfig);
InvokeWithRetry<String,String> pattern = new InvokeWithRetry<>(patternsConfig.getDefaultRetryCount());
// check if action should be executed asynchronously (in background)
boolean asyncAction = false;
if ("async".equals(queryAttrs.get("mode"))) {
asyncAction = true;
}
if (asyncAction) {
boolean finalAsyncRetry = asyncRetry;
ctx.exec().start(execution -> pattern.apply(execution, ctx, action, 5, finalAsyncRetry)
.then(actionResults -> {
// TODO: log and store results for the future
}));
ctx.render(ctx.promiseOf(new ActionResults<>(ImmutableMap.of(action.getName(), ActionResult.success("EXECUTING IN BACKGROUND")))));
} else {
ctx.render(pattern.apply(ctx, ctx, action, 5, asyncRetry));
}
} catch (Exception ex) {
ctx.clientError(404);
}
}