当前位置: 首页>>代码示例>>Java>>正文


Java Context.get方法代码示例

本文整理汇总了Java中ratpack.handling.Context.get方法的典型用法代码示例。如果您正苦于以下问题:Java Context.get方法的具体用法?Java Context.get怎么用?Java Context.get使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ratpack.handling.Context的用法示例。


在下文中一共展示了Context.get方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: handle

import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(Context ctx) throws Exception {
    final RamlModelRepository ramlModelRepository = ctx.get(RamlModelRepository.class);
    final Path filePath = ramlModelRepository.getFilePath();
    final Path parent = ramlModelRepository.getParent();
    final String path = ctx.getPathBinding().getPastBinding();

    final Path resolvedFilePath = path.isEmpty() ? filePath : parent.resolve(path).normalize();
    final File file = resolvedFilePath.toFile();
    if (file.exists()) {
        final String content;
        if (QueryParams.resolveIncludes(ctx)) {
            content = new IncludeResolver().preprocess(resolvedFilePath).toString();
        } else {
            content = Files.asByteSource(file).asCharSource(Charsets.UTF_8).read();
        }
        ctx.byContent(byContentSpec -> byContentSpec
                .type("application/raml+yaml", () -> renderReplacedContent(ctx, content))
                .html(() -> renderHtml(ctx, path, content))
                .noMatch("application/raml+yaml"));
    } else {
        ctx.byContent(byContentSpec -> byContentSpec.noMatch(() -> ctx.render(ctx.file("api-raml/" + path))));
    }
}
 
开发者ID:vrapio,项目名称:vrap,代码行数:25,代码来源:RamlFilesHandler.java

示例2: handle

import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(final Context ctx) throws Exception {
    final Request request = ctx.getRequest();
    final HttpClient httpClient = ctx.get(HttpClient.class);
    final URI proxiedUri = URI.create(authUri);
    LOG.info("Forward to: {}", proxiedUri);

    ctx.parse(Form.class).then(form -> {
        httpClient.requestStream(proxiedUri, requestSpec -> {
            final String s = form.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining("&"));
            requestSpec.getBody().bytes(s.getBytes(Charsets.UTF_8));
            requestSpec.getHeaders().copy(request.getHeaders());
            requestSpec.method(request.getMethod());

            if (form.containsKey("client_id") && form.containsKey("client_secret")) {
                final String auth = Base64.getEncoder().encodeToString((form.get("client_id") + ":" + form.get("client_secret")).getBytes(Charsets.UTF_8));
                requestSpec.getHeaders().add("Authorization", "Basic " + auth);
            }
        }).then(receivedResponse ->
                receivedResponse.forwardTo(ctx.getResponse(), mutableHeaders -> {
                    mutableHeaders.add("Via", "Vrap OAuth 2.0 proxy");
                }));
    });
}
 
开发者ID:vrapio,项目名称:vrap,代码行数:25,代码来源:AuthRouter.java

示例3: 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();
    }
}
 
开发者ID:vrapio,项目名称:vrap,代码行数:27,代码来源:ApiConsoleHandler.java

示例4: handle

import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(final Context ctx) throws Exception {
    final RamlModelRepository ramlModelRepository = ctx.get(RamlModelRepository.class);
    final Api api = ramlModelRepository.getApi();
    final String path = ctx.getPathBinding().getPastBinding();

    if (path.equals("Vrap-Extension.raml")) {
        final Path filePath = ramlModelRepository.getFilePath();
        List<ResourceExtension> resourceExtensions = resourceExtensions(api.resources(), "");
        final Integer port = ctx.getServerConfig().getPort();
        final String authProxyUri = "http://localhost:" + port.toString() + "/auth";
        final String proxyUri = "http://localhost:" + port.toString() + "/" + apiUri + new URI(api.baseUri().value().replace("{", "%7B").replace("}", "%7D")).getPath().replace("%7B", "{").replace("%7D", "}");
        List<SecurityScheme> oauthSchemes = api.securitySchemes().stream().filter(securityScheme -> securityScheme.type().equals("OAuth 2.0")).collect(Collectors.toList());

        final ImmutableMap<String, Object> model =
                ImmutableMap.<String, Object>builder()
                        .put("fileName", filePath.getFileName())
                        .put("queryParams", ctx.getRequest().getQuery())
                        .put("resourceExtensions", resourceExtensions)
                        .put("proxyUri", proxyUri)
                        .put("modes", Joiner.on(", ").join(VrapMode.values()))
                        .put("flags", Joiner.on(", ").join(ValidationFlag.values()))
                        .put("authProxyUri", authProxyUri)
                        .put("oauthSchemes", oauthSchemes.stream().map(securityScheme -> securityScheme.name()).collect(Collectors.toList()))
                .build();

        ctx.byContent(byContentSpec -> byContentSpec
                .type("application/raml+yaml", () -> ctx.render(handlebarsTemplate(model, "api-raml/Vrap-Extension.raml")))
                .html(() -> ctx.render(handlebarsTemplate(model, "api-raml/Vrap-Extension.html")))
                .noMatch("application/raml+yaml"));
    } else {
        ctx.next();
    }
}
 
开发者ID:vrapio,项目名称:vrap,代码行数:35,代码来源:VrapExtensionHandler.java

示例5: validateRequest

import ratpack.handling.Context; //导入方法依赖的package包/类
private void validateRequest(final Context ctx, final TypedData body) throws Exception {
    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> validationErrors = validator.validateRequest(ctx, body, method);

    ctx.next(Registry.of(registrySpec -> {
        registrySpec.add(TypedData.class, body);
        validationErrors.ifPresent(validationErrors1 -> registrySpec.add(Validator.ValidationErrors.class, validationErrors1));
    }));
}
 
开发者ID:vrapio,项目名称:vrap,代码行数:12,代码来源:RamlRouter.java

示例6: handle

import ratpack.handling.Context; //导入方法依赖的package包/类
@Override
public void handle(final Context ctx) throws Exception {
    final Method method = ctx.get(Method.class);

    final List<TypeDeclaration> bodTypeDeclarations = method.responses().stream()
            .flatMap(r -> r.body().stream()).collect(Collectors.toList());

    final Map<String, ExampleSpec> contentTypeToExample = bodTypeDeclarations.stream()
            .collect(Collectors.toMap(TypeDeclaration::name, TypeDeclaration::example));

    ctx.byContent(byContentSpec ->
            contentTypeToExample.entrySet().stream()
                    .forEach(e -> byContentSpec.type(e.getKey(), () -> ctx.render(e.getValue().value()))));
}
 
开发者ID:vrapio,项目名称:vrap,代码行数:15,代码来源:RamlRouter.java

示例7: 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"));
}
 
开发者ID:vrapio,项目名称:vrap,代码行数:14,代码来源:RamlFilesHandler.java

示例8: mode

import ratpack.handling.Context; //导入方法依赖的package包/类
private VrapMode mode(final Context ctx) {
    final Headers headers = ctx.getRequest().getHeaders();
    final VrapApp.VrapOptions options = ctx.get(VrapApp.VrapOptions.class);

    return VrapMode.parse(headers.get(MODE_HEADER)).orElse(options.getMode());
}
 
开发者ID:vrapio,项目名称:vrap,代码行数:7,代码来源:RamlRouter.java

示例9: 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);
  }
}
 
开发者ID:zedar,项目名称:ratpack-examples,代码行数:46,代码来源:InvokeWithRetryHandler.java


注:本文中的ratpack.handling.Context.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。