本文整理汇总了Java中ratpack.handling.Context类的典型用法代码示例。如果您正苦于以下问题:Java Context类的具体用法?Java Context怎么用?Java Context使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Context类属于ratpack.handling包,在下文中一共展示了Context类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: validateRequest
import ratpack.handling.Context; //导入依赖的package包/类
/**
* Validates the body, headers, uri and query parameters of the request of the given context.
*
* @param context the context holding the requesz
* @param body the request body to validate
* @param method the method to validate the request aginst
* @return validation errors
*/
public Optional<ValidationErrors> validateRequest(final Context context, final TypedData body, final Method method) {
final List<ValidationError> errors = new ArrayList<>();
if (disableValidation(context.getRequest().getHeaders(), ValidationFlag.request)) {
return wrapAndLogErrors(errors);
}
final Api api = context.get(RamlModelRepository.class).getApi();
errors.addAll(validateQueryParameters(context.getRequest(), method));
errors.addAll(validateRequestHeaders(context.getRequest().getHeaders(), method));
final String contentType = Optional.ofNullable(body.getContentType().getType()).orElse(
!method.body().isEmpty() ? method.body().get(0).name() :
!api.mediaType().isEmpty() ? api.mediaType().get(0).value() : "application/json"
);
final Optional<TypeDeclaration> bodyTypeDeclaration = method.body().stream()
.filter(typeDeclaration -> contentType.equals(typeDeclaration.name())).findFirst();
errors.addAll(bodyTypeDeclaration
.map(bodyTypeDecl -> validate(body.getText(), bodyTypeDecl, ValidationKind.body, "request"))
.orElse(Collections.emptyList()));
return wrapAndLogErrors(errors);
}
示例2: preprocess
import ratpack.handling.Context; //导入依赖的package包/类
public StringWriter preprocess(Context ctx, final Path filePath, final Api api) throws IOException {
final Integer port = ctx.getServerConfig().getPort();
final StringWriter stringWriter = new StringWriter();
final String baseUri = api.baseUri().value();
final List<SecurityScheme> oauthSchemes = api.securitySchemes().stream().filter(securityScheme -> securityScheme.type().equals("OAuth 2.0")).collect(Collectors.toList());
String content = new String(Files.readAllBytes(filePath), Charsets.UTF_8);
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
final JsonNode file = mapper.readValue(filePath.toFile(), JsonNode.class);
if (file.has("baseUri")) {
content = content.replaceAll(baseUri, "http://localhost:" + port.toString() + "/api");
}
if (!oauthSchemes.isEmpty()) {
for (SecurityScheme scheme : oauthSchemes) {
content = content.replaceAll(scheme.settings().accessTokenUri().value(), "http://localhost:" + port.toString() + "/auth/" + scheme.name());
}
}
return stringWriter.append(content);
}
示例3: 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();
}
}
示例4: 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))));
}
}
示例5: 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");
}));
});
}
示例6: 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();
}
}
示例7: 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;
}
}
}
示例8: handle
import ratpack.handling.Context; //导入依赖的package包/类
@Override
public void handle(Context context) throws Exception {
context.parse(Map.class).then(payload -> {
Logger.info(QUERY + ": " + payload.get(QUERY));
@SuppressWarnings("unchecked")
Map<String, Object> variables = (Map<String, Object>) payload.get(VARIABLES);
ExecutionInput executionInput = ExecutionInput.newExecutionInput()
.query(payload.get(QUERY).toString())
.variables(variables)
.build();
final ExecutionResult executionResult = graphql.execute(executionInput);
Map<String, Object> result = new LinkedHashMap<>();
if (executionResult.getErrors().isEmpty()) {
result.put(DATA, executionResult.getData());
} else {
result.put(ERRORS, executionResult.getErrors());
Logger.error("Errors: {}", executionResult.getErrors());
}
context.render(json(result));
});
}
示例9: handle
import ratpack.handling.Context; //导入依赖的package包/类
public void handle(Context ctx, final BotOrchestrationService botOrchestrationService, final HipChatRequestValidator requestValidator, GlanceManager glanceManager) throws Exception {
final String oauthId = ctx.getPathTokens().get("oauthid");
botOrchestrationService.getActiveInstallationByOauthId(oauthId).ifPresent(installation -> requestValidator.validate(ctx.getRequest(), installation.getOauthSecret()));
final String key = ctx.getPathTokens().get("key");
final Optional<GlanceData> maybeGlance = glanceManager.get(oauthId, key);
if (maybeGlance.isPresent()) {
ctx
.header("Access-Control-Allow-Origin", "*")
.render(json(glanceManager.toContent(maybeGlance.get())));
} else {
ctx
.header("Access-Control-Allow-Origin", "*")
.notFound();
}
}
示例10: render
import ratpack.handling.Context; //导入依赖的package包/类
/**
* {@inheritDoc}
*
* @param context
* @param message
*/
@Override
public void render(Context context, Message message) throws Exception {
String bestMatch = MimeParse.bestMatch(SUPPORTED_TYPES, context.getRequest().getHeaders().get("accept"));
try {
switch (bestMatch) {
case TYPE_JSON:
context.getResponse().send(TYPE_JSON, PRINTER.print(message));
context.getResponse().contentType(TYPE_JSON);
break;
case TYPE_PROTOBUF:
context.getResponse().send(TYPE_PROTOBUF, message.toByteArray());
context.getResponse().contentType(TYPE_PROTOBUF);
break;
default:
throw new NotAcceptableException(context.getRequest().getHeaders().get("accept"), TYPE_JSON, TYPE_PROTOBUF);
}
} catch (InvalidProtocolBufferException e) {
// Can't happen, because we don't use any "Any" fields.
// https://developers.google.com/protocol-buffers/docs/proto3#any
throw new InternalServerErrorException("Attempt to transform an invalid protocol buffer into JSON.");
}
}
示例11: constructRatingView
import ratpack.handling.Context; //导入依赖的package包/类
/**
* constructs an RatingView
* @param builder the builder to use
* @param experimentID the ID of the experiment
* @param amount the amount to rate
* @param context the context provided by ratpack
* @return an instance of View with the Type Rating and the information needed for an to display an rating,
* or empty if no answers are available
* @throws BadRequestException if the experiment was not found
*/
protected Optional<View> constructRatingView(View.Builder builder, Context context, int experimentID, int amount) throws BadRequestException {
logger.debug("task chooser constructs rating-view");
if (logger.isTraceEnabled()) {
logger.trace("all the answers belonging to the experiment not from the worker with their count (max rating per answer is {}): {}",
experimentOperations.getExperiment(experimentID).getRatingsPerAnswer(),
experimentsPlatformOperations.getOtherAnswersWithCount(experimentID, context.get(WorkerID.class).get()));
}
List<View.Answer> toRate = experimentsPlatformOperations.prepareRating(context.get(WorkerID.class).get(), experimentID, amount).entrySet()
.stream()
.map(entry -> View.Answer.newBuilder()
.setAnswer(entry.getValue().getAnswer())
.setReservation(entry.getKey())
.setAnswerId(entry.getValue().getIdAnswer())
.build())
.collect(Collectors.toList());
logger.trace("worker {} can rate {}", context.get(WorkerID.class).get(), toRate);
if (toRate.isEmpty()) {
logger.error("no answers available to rate for experiment = {}, worker = {}", experimentID, context.get(WorkerID.class).get());
return Optional.empty();
}
return Optional.of(prepareBuilder(builder, experimentID)
.addAllAnswersToRate(toRate)
.setType(View.Type.RATING)
.build());
}
示例12: getNext
import ratpack.handling.Context; //导入依赖的package包/类
/**
* this method returns an instance of View, determining what the worker should see next.
* <p>
* it is indented to be called when the Router gets an /next-Request.
*
* @param context the Context of the Request
* @return the JSON-Representation of View
*/
public View getNext(Context context) {
checkForExperimentAndPlatform(context);
boolean skipCreative = false;
if ("skip".equals(context.getRequest().getQueryParams().get("answer"))) {
skipCreative = true;
}
logger.trace("skipCreative is: {}", skipCreative);
boolean skipRating = false;
if ("skip".equals(context.getRequest().getQueryParams().get("rating"))) {
skipRating = true;
}
logger.trace("skipRating is: {}", skipRating);
View next = getNext(prepareView(context), context, skipCreative, skipRating);
logger.debug("returning view: {}", next);
return next;
}
示例13: handleNoWorkerID
import ratpack.handling.Context; //导入依赖的package包/类
/**
* handles the case where no workerID was provided (workerID = -1).
* This method just asks the Platform what to ID the worker should have and then calls getNext.
*
* @param builder the builder to use
* @param context the Context of the Request
* @return an instance of View.
*/
private View.Builder handleNoWorkerID(View.Builder builder, Context context) {
String platformName = assertParameter(context, "platform");
logger.debug("handling no worker-id");
return communication.tryGetWorkerID(platformName, context.getRequest().getQueryParams().asMultimap())
.thenApply(result -> {
logger.debug("platform {} returned {}", platformName, result.map(Object::toString).orElse("nothing"));
return result;
})
.join()
.map(workerId -> {
context.getRequest().add(WorkerID.class, new WorkerID(workerId));
return builder.setAuthorization(jwtHelper.generateJWT(workerId));
})
.orElse(builder);
}
示例14: checkCalibrationAndQuality
import ratpack.handling.Context; //导入依赖的package包/类
/**
* checks if the worker has submitted the wrong calibration or whether the workers quality is under the
* threshold.
*
* @param builder the builder to use
* @param context the Context of the Request
* @return true if the worker is eligible for working on the assignment
*/
private boolean checkCalibrationAndQuality(View.Builder builder, Context context) {
String platformName = assertParameter(context, "platform");
int experiment = assertParameterInt(context, "experiment");
ExperimentRecord experimentRecord = experimentOperations.getExperiment(experiment);
boolean submittedWrongCalibrations = calibrationsOperations.hasSubmittedWrongCalibrations(experiment, platformName, context.get(WorkerID.class).get());
if (submittedWrongCalibrations) {
logger.debug("worker {} has submitted wrong calibrations", context.get(WorkerID.class).get());
return false;
}
boolean underThreshold = workerOperations.isUnderThreshold(experimentRecord.getWorkerQualityThreshold(), context.get(WorkerID.class).get());
if (underThreshold) {
logger.debug("worker {} is under the quality threshold", context.get(WorkerID.class).get());
}
return !underThreshold;
}
示例15: getCalibration
import ratpack.handling.Context; //导入依赖的package包/类
/**
* may returns the Calibration if there are needed Calibration left unanswered.
*
* @param builder the builder to use
* @param context the Context of the Request
* @return an instance of view if the worker has to fill in some Calibration, or empty if not.
*/
private Optional<View> getCalibration(View.Builder builder, Context context) {
String platformName = assertParameter(context, "platform");
int experiment = assertParameterInt(context, "experiment");
if (platformOperations.getPlatform(platformName).getRenderCalibrations()) {
logger.trace("platform {} is able to render calibrations", platformName);
Map<CalibrationRecord, Result<CalibrationAnswerOptionRecord>> calibrations =
calibrationsOperations.getCalibrations(experiment, platformName, context.get(WorkerID.class).get());
logger.trace("worker {} must answer the calibrations {}", context.get(WorkerID.class).get(), calibrations);
if (calibrations.isEmpty()) {
logger.debug("worker {} must not answer calibrations", context.get(WorkerID.class).get());
return Optional.empty();
} else {
logger.debug("worker {} must answer calibrations", context.get(WorkerID.class).get());
return Optional.of(constructCalibrationView(calibrations, builder));
}
} else {
logger.trace("platform {} is not able to render calibrations", platformName);
return Optional.empty();
}
}