List of usage examples for io.vertx.core.http HttpServerRequest getHeader
@GenIgnore(GenIgnore.PERMITTED_TYPE)
default String getHeader(CharSequence headerName)
From source file:com.klwork.spring.vertx.render.MyStaticHandlerImpl.java
License:Open Source License
private void sendFile(RoutingContext context, String file, FileProps fileProps) { HttpServerRequest request = context.request(); Long offset = null;/*from w w w . j a v a2 s. co m*/ Long end = null; MultiMap headers = null; if (rangeSupport) { // check if the client is making a range request String range = request.getHeader("Range"); // end byte is length - 1 end = fileProps.size() - 1; if (range != null) { Matcher m = RANGE.matcher(range); if (m.matches()) { try { String part = m.group(1); // offset cannot be empty offset = Long.parseLong(part); // offset must fall inside the limits of the file if (offset < 0 || offset >= fileProps.size()) { throw new IndexOutOfBoundsException(); } // length can be empty part = m.group(2); if (part != null && part.length() > 0) { // ranges are inclusive end = Long.parseLong(part); // offset must fall inside the limits of the file if (end < offset || end >= fileProps.size()) { throw new IndexOutOfBoundsException(); } } } catch (NumberFormatException | IndexOutOfBoundsException e) { context.fail(REQUESTED_RANGE_NOT_SATISFIABLE.code()); return; } } } // notify client we support range requests headers = request.response().headers(); headers.set("Accept-Ranges", "bytes"); // send the content length even for HEAD requests headers.set("Content-Length", Long.toString(end + 1 - (offset == null ? 0 : offset))); } writeCacheHeaders(request, fileProps); if (request.method() == HttpMethod.HEAD) { request.response().end(); } else { if (rangeSupport && offset != null) { // must return content range headers.set("Content-Range", "bytes " + offset + "-" + end + "/" + fileProps.size()); // return a partial response request.response().setStatusCode(PARTIAL_CONTENT.code()); // Wrap the sendFile operation into a TCCL switch, so the file resolver would find the file from the set // classloader (if any). final Long finalOffset = offset; final Long finalEnd = end; wrapInTCCLSwitch(() -> request.response().sendFile(file, finalOffset, finalEnd + 1, res2 -> { if (res2.failed()) { context.fail(res2.cause()); } }), null); } else { // Wrap the sendFile operation into a TCCL switch, so the file resolver would find the file from the set // classloader (if any). wrapInTCCLSwitch(() -> request.response().sendFile(file, res2 -> { if (res2.failed()) { context.fail(res2.cause()); } }), null); } } }
From source file:com.navercorp.pinpoint.plugin.vertx.interceptor.HttpServerRequestAdaptor.java
License:Apache License
@Override public String getHeader(HttpServerRequest request, String name) { return request.getHeader(name); }
From source file:com.navercorp.pinpoint.plugin.vertx.interceptor.ServerConnectionHandleRequestInterceptor.java
License:Apache License
private boolean samplingEnable(HttpServerRequest request) { // optional value final String samplingFlag = request.getHeader(Header.HTTP_SAMPLED.toString()); if (isDebug) { logger.debug("SamplingFlag={}", samplingFlag); }//from w w w . ja va 2 s.co m return SamplingFlagUtils.isSamplingFlag(samplingFlag); }
From source file:com.navercorp.pinpoint.plugin.vertx.interceptor.ServerConnectionHandleRequestInterceptor.java
License:Apache License
private TraceId populateTraceIdFromRequest(HttpServerRequest request) { final String transactionId = request.getHeader(Header.HTTP_TRACE_ID.toString()); if (transactionId != null) { final long parentSpanID = NumberUtils .parseLong(request.getHeader(Header.HTTP_PARENT_SPAN_ID.toString()), SpanId.NULL); final long spanID = NumberUtils.parseLong(request.getHeader(Header.HTTP_SPAN_ID.toString()), SpanId.NULL);/*from w w w.jav a 2 s .c om*/ final short flags = NumberUtils.parseShort(request.getHeader(Header.HTTP_FLAGS.toString()), (short) 0); final TraceId id = traceContext.createTraceId(transactionId, parentSpanID, spanID, flags); if (isDebug) { logger.debug("TraceID exist. continue trace. {}", id); } return id; } else { return null; } }
From source file:com.navercorp.pinpoint.plugin.vertx.interceptor.ServerConnectionHandleRequestInterceptor.java
License:Apache License
private void recordRootSpan(final SpanRecorder recorder, final HttpServerRequest request) { // root/*from www. j a v a 2 s . c o m*/ recorder.recordServiceType(VertxConstants.VERTX_HTTP_SERVER); final String requestURL = request.path(); if (requestURL != null) { recorder.recordRpcName(requestURL); } if (request.localAddress() != null) { final int port = request.localAddress().port(); if (port <= 0) { recorder.recordEndPoint(request.host()); } else { recorder.recordEndPoint(request.host() + ":" + port); } } final String remoteAddr = remoteAddressResolver.resolve(request); recorder.recordRemoteAddress(remoteAddr); if (!recorder.isRoot()) { recordParentInfo(recorder, request); } recorder.recordApi(VERTX_HTTP_SERVER_METHOD_DESCRIPTOR); // record proxy HTTP header. this.proxyHttpHeaderRecorder.record(recorder, new ProxyHttpHeaderHandler() { @Override public String read(String name) { return request.getHeader(name); } }); }
From source file:com.navercorp.pinpoint.plugin.vertx.interceptor.ServerConnectionHandleRequestInterceptor.java
License:Apache License
private void recordParentInfo(SpanRecorder recorder, HttpServerRequest request) { String parentApplicationName = request.getHeader(Header.HTTP_PARENT_APPLICATION_NAME.toString()); if (parentApplicationName != null) { final String host = request.getHeader(Header.HTTP_HOST.toString()); if (host != null) { recorder.recordAcceptorHost(host); } else {/*from w w w.j a v a2 s . co m*/ recorder.recordAcceptorHost(NetworkUtils.getHostFromURL(request.uri().toString())); } final String type = request.getHeader(Header.HTTP_PARENT_APPLICATION_TYPE.toString()); final short parentApplicationType = NumberUtils.parseShort(type, ServiceType.UNDEFINED.getCode()); recorder.recordParentApplication(parentApplicationName, parentApplicationType); } }
From source file:io.apiman.gateway.platforms.vertx3.http.HttpServiceFactory.java
License:Apache License
private static void mungePath(HttpServerRequest request, VertxServiceRequest apimanRequest) { ServiceRequestPathInfo parsedPath = ApimanPathUtils.parseServiceRequestPath( request.getHeader(ApimanPathUtils.X_API_VERSION_HEADER), request.getHeader(ApimanPathUtils.ACCEPT_HEADER), request.path()); apimanRequest.setServiceOrgId(parsedPath.orgId); apimanRequest.setServiceId(parsedPath.serviceId); apimanRequest.setServiceVersion(parsedPath.serviceVersion); apimanRequest.setUrl(request.absoluteURI()); apimanRequest.setDestination(parsedPath.resource); if (apimanRequest.getServiceOrgId() == null) { throw new IllegalArgumentException("Invalid endpoint provided: " + request.path()); }/*w w w. j a v a2 s . c o m*/ }
From source file:io.nitor.api.backend.lambda.LambdaHandler.java
License:Apache License
@Override public void handle(RoutingContext ctx) { HttpServerRequest sreq = ctx.request(); final String path = normalizePath(sreq.path(), routeLength); if (path == null) { ctx.response().setStatusCode(NOT_FOUND.code()).end(); return;/*w ww. j a v a2 s .c o m*/ } HttpServerResponse sres = ctx.response(); PathMatchResult<Entry<String, String>> matchRes = pathTemplateMatcher.match(path); final String lambdaFunction, qualifier; if (matchRes == null) { logger.error("No matching path template"); sres.setStatusCode(BAD_GATEWAY.code()); return; } else { lambdaFunction = matchRes.getValue().getKey(); qualifier = matchRes.getValue().getValue(); } sreq.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer event) { byte[] body = event.getBytes(); APIGatewayProxyRequestEvent reqObj = new APIGatewayProxyRequestEvent(); /* * Handle body */ String bodyObjStr = null; boolean isBase64Encoded = true; if (body != null && body.length > 0) { String ct = sreq.getHeader("content-type").toLowerCase(); if (ct.startsWith("text/") || ct.startsWith("application/json") || (ct.indexOf("charset=") > 0)) { String charset = "utf-8"; if (ct.indexOf("charset=") > 0) { charset = getCharsetFromContentType(ct); } try { bodyObjStr = Charset.forName(charset).newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(body)) .toString(); isBase64Encoded = false; } catch (CharacterCodingException e) { logger.error("Decoding body failed", e); } } if (bodyObjStr == null) { bodyObjStr = Base64.getEncoder().encodeToString(body); } reqObj = reqObj.withBody(bodyObjStr).withIsBase64Encoded(isBase64Encoded); } Map<String, List<String>> headerMultivalue = sreq.headers().entries().stream() .collect(toMap(Entry::getKey, x -> sreq.headers().getAll(x.getKey()))); Map<String, String> headerValue = sreq.headers().entries().stream() .collect(toMap(Entry::getKey, Entry::getValue)); /* * Handle request context */ RequestIdentity reqId = new RequestIdentity().withSourceIp(getRemoteAddress(ctx)) .withUserAgent(sreq.getHeader(USER_AGENT)); if (ctx.user() != null) { reqId.withUser(ctx.user().principal().toString()); } ProxyRequestContext reqCtx = new ProxyRequestContext() .withPath(sreq.path().substring(0, routeLength)).withHttpMethod(sreq.method().toString()) .withIdentity(reqId); reqObj = reqObj.withMultiValueHeaders(headerMultivalue).withHeaders(headerValue) .withHttpMethod(sreq.method().toString()).withPath(sreq.path()).withResource(path) .withQueryStringParameters(splitQuery(sreq.query())) .withMultiValueQueryStringParameters(splitMultiValueQuery(sreq.query())) .withPathParameters(matchRes.getParameters()).withRequestContext(reqCtx); String reqStr = JsonObject.mapFrom(reqObj).toString(); byte[] sendBody = reqStr.getBytes(UTF_8); InvokeRequest req = InvokeRequest.builder().invocationType(InvocationType.REQUEST_RESPONSE) .functionName(lambdaFunction).qualifier(qualifier).payload(SdkBytes.fromByteArray(sendBody)) .build(); logger.info("Calling lambda " + lambdaFunction + ":" + qualifier); logger.debug("Payload: " + reqStr); CompletableFuture<InvokeResponse> respFuture = lambdaCl.invoke(req); respFuture.whenComplete((iresp, err) -> { if (iresp != null) { try { String payload = iresp.payload().asString(UTF_8); JsonObject resp = new JsonObject(payload); int statusCode = resp.getInteger("statusCode"); sres.setStatusCode(statusCode); for (Entry<String, Object> next : resp.getJsonObject("headers").getMap().entrySet()) { sres.putHeader(next.getKey(), next.getValue().toString()); } String respBody = resp.getString("body"); byte[] bodyArr = new byte[0]; if (body != null && !respBody.isEmpty()) { if (TRUE.equals(resp.getBoolean("isBase64Encoded"))) { bodyArr = Base64.getDecoder().decode(body); } else { bodyArr = respBody.getBytes(UTF_8); } } sres.putHeader(CONTENT_LENGTH, String.valueOf(bodyArr.length)); Buffer buffer = Buffer.buffer(bodyArr); tryToCacheContent(ctx, buffer); sres.write(buffer); } catch (Throwable t) { logger.error("Error processing lambda request", t); if (!sres.headWritten()) { sres.setStatusCode(BAD_GATEWAY.code()); sres.putHeader(CONTENT_TYPE, "application/json"); Buffer response = Buffer.buffer(new LambdaErrorResponse(t).toString()); sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length())); sres.write(response); } } finally { sres.end(); } } else { logger.error("Error processing lambda request", err); sres.setStatusCode(BAD_GATEWAY.code()); sres.putHeader(CONTENT_TYPE, "application/json"); Buffer response = Buffer.buffer(new LambdaErrorResponse(err).toString()); sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length())); sres.end(response); } }); } }); }
From source file:io.nitor.api.backend.msgraph.GraphQueryHandler.java
License:Apache License
@Override public void handle(RoutingContext ctx) { HttpServerRequest sreq = ctx.request(); String path = sreq.path();/*from ww w . j ava 2s. c o m*/ path = path.substring(routeLength); if (!path.startsWith("/")) { path = '/' + path; } path = baseUrl + path + paramsOf(ctx.request().absoluteURI()); Map<String, String> data = sessionHandler.getSessionData(ctx); String refreshToken = data.get(GRAPH_ACCESS_TOKEN_KEY); Future<TokenData> tokenFuture = tokenCache.getAccessToken(refreshToken); HttpServerResponse sres = ctx.response(); String finalPath = path; tokenFuture.setHandler(tokenResult -> { if (tokenResult.failed()) { sessionHandler.removeCookie(ctx); String err = tokenResult.cause().toString(); logger.error(err); sres.setStatusCode(INTERNAL_SERVER_ERROR.code()).end(err); return; } TokenData token = tokenResult.result(); if (!refreshToken.equals(token.refreshToken)) { Map<String, String> newData = new HashMap<>(data); newData.put(GRAPH_ACCESS_TOKEN_KEY, token.refreshToken); sessionHandler.setSessionData(ctx, newData); } String clientRequestId = UUID.randomUUID().toString(); logger.info("Querying " + sreq.method() + " " + finalPath + " [" + clientRequestId + "]"); HttpClientRequest creq = httpClient.requestAbs(sreq.method(), finalPath) .putHeader(AUTHORIZATION, "Bearer " + token.accessToken).putHeader(ACCEPT, APPLICATION_JSON) .putHeader("client-request-id", clientRequestId).setTimeout(SECONDS.toMillis(20)) .exceptionHandler(err -> { logger.error("Graph query failed [" + clientRequestId + "]", err); if (!sres.ended()) { sres.setStatusCode(INTERNAL_SERVER_ERROR.code()).write("Graph query failed: " + err) .end(); } }); for (String header : allowedRequestHeaders) { ofNullable(sreq.getHeader(header)).ifPresent(value -> creq.putHeader(header, value)); } if (sres.headers().getAll("transfer-encoding").stream().anyMatch(v -> v.equals("chunked"))) { creq.setChunked(true); } sres.closeHandler(close -> creq.connection().close()); creq.handler(cres -> mapResponse(cres, sres, clientRequestId)); if (sreq.isEnded()) { creq.end(); } else { sreq.endHandler(v -> { try { creq.end(); } catch (IllegalStateException ex) { // ignore - nothing can be done - the request is already complete/closed - TODO log? } }); Pump resPump = Pump.pump(sreq, creq); resPump.start(); } }); }
From source file:io.nitor.api.backend.s3.AWSRequestSigner.java
License:Apache License
private void putHeader(MultiMap headers, StringBuilder canonicalHeaders, StringBuilder signedHeaders, String name, HttpServerRequest sreq) { String value = sreq.getHeader(name); if (value != null) { putHeader(headers, canonicalHeaders, signedHeaders, name, value.replaceAll("\\s+", " ").trim()); }/*w w w . ja v a2 s . c o m*/ }