List of usage examples for io.vertx.core.http HttpServerRequest headers
@CacheReturn MultiMap headers();
From source file:com.englishtown.vertx.jersey.impl.DefaultJerseyHandler.java
License:Open Source License
protected URI getAbsoluteURI(HttpServerRequest vertxRequest) { URI absoluteUri;/*from www . j a va 2 s.co m*/ String hostAndPort = vertxRequest.headers().get(HttpHeaders.HOST); try { absoluteUri = URI.create(vertxRequest.absoluteURI()); if (hostAndPort != null && !hostAndPort.isEmpty()) { String[] parts = hostAndPort.split(":"); String host = parts[0]; int port = (parts.length > 1 ? Integer.valueOf(parts[1]) : -1); if (!host.equalsIgnoreCase(absoluteUri.getHost()) || port != absoluteUri.getPort()) { absoluteUri = UriBuilder.fromUri(absoluteUri).host(host).port(port).build(); } } return absoluteUri; } catch (IllegalArgumentException e) { String uri = vertxRequest.uri(); if (!uri.contains("?")) { throw e; } try { logger.warn("Invalid URI: " + uri + ". Attempting to parse query string.", e); QueryStringDecoder decoder = new QueryStringDecoder(uri); StringBuilder sb = new StringBuilder(decoder.path() + "?"); for (Map.Entry<String, List<String>> p : decoder.parameters().entrySet()) { for (String value : p.getValue()) { sb.append(p.getKey()).append("=").append(URLEncoder.encode(value, "UTF-8")); } } return URI.create(sb.toString()); } catch (Exception e1) { throw new RuntimeException(e1); } } }
From source file:com.englishtown.vertx.jersey.impl.DefaultJerseyHandler.java
License:Open Source License
protected void handle(final HttpServerRequest vertxRequest, final InputStream inputStream, final ContainerRequest jerseyRequest) { // Provide the vertx response writer jerseyRequest.setWriter(responseWriterProvider.get(vertxRequest, jerseyRequest)); // Set entity stream if provided (form posts) if (inputStream != null) { jerseyRequest.setEntityStream(inputStream); }//from w ww . j ava2 s . c o m // Copy headers for (Map.Entry<String, String> header : vertxRequest.headers().entries()) { jerseyRequest.getHeaders().add(header.getKey(), header.getValue()); } // Set request scoped instances jerseyRequest.setRequestScopedInitializer(locator -> { locator.<Ref<HttpServerRequest>>getService((new TypeLiteral<Ref<HttpServerRequest>>() { }).getType()).set(vertxRequest); locator.<Ref<HttpServerResponse>>getService((new TypeLiteral<Ref<HttpServerResponse>>() { }).getType()).set(vertxRequest.response()); }); // Call vertx before request processors if (!requestProcessors.isEmpty()) { // Pause the vert.x request if we haven't already read the body if (inputStream == null) { vertxRequest.pause(); } callVertxRequestProcessor(0, vertxRequest, jerseyRequest, aVoid -> { // Resume the vert.x request if we haven't already read the body if (inputStream == null) { vertxRequest.resume(); } applicationHandlerDelegate.handle(jerseyRequest); }); } else { applicationHandlerDelegate.handle(jerseyRequest); } }
From source file:com.englishtown.vertx.jersey.impl.DefaultJerseyHandler.java
License:Open Source License
protected boolean shouldReadData(HttpServerRequest vertxRequest) { HttpMethod method = vertxRequest.method(); // Only read input stream data for post/put methods if (!(HttpMethod.POST == method || HttpMethod.PUT == method)) { return false; }/*from w w w.j av a 2 s. c o m*/ String contentType = vertxRequest.headers().get(HttpHeaders.CONTENT_TYPE); if (contentType == null || contentType.isEmpty()) { // Special handling for IE8 XDomainRequest where content-type is missing // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx return true; } MediaType mediaType = MediaType.valueOf(contentType); // Allow text/plain if (MediaType.TEXT_PLAIN_TYPE.getType().equals(mediaType.getType()) && MediaType.TEXT_PLAIN_TYPE.getSubtype().equals(mediaType.getSubtype())) { return true; } // Only other media types accepted are application (will check subtypes next) String applicationType = MediaType.APPLICATION_FORM_URLENCODED_TYPE.getType(); if (!applicationType.equalsIgnoreCase(mediaType.getType())) { return false; } // Need to do some special handling for forms: // Jersey doesn't properly handle when charset is included if (mediaType.getSubtype().equalsIgnoreCase(MediaType.APPLICATION_FORM_URLENCODED_TYPE.getSubtype())) { if (!mediaType.getParameters().isEmpty()) { vertxRequest.headers().remove(HttpHeaders.CONTENT_TYPE); vertxRequest.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); } return true; } // Also accept json/xml sub types return MediaType.APPLICATION_JSON_TYPE.getSubtype().equalsIgnoreCase(mediaType.getSubtype()) || MediaType.APPLICATION_XML_TYPE.getSubtype().equalsIgnoreCase(mediaType.getSubtype()); }
From source file:com.klwork.spring.vertx.render.MyStaticHandlerImpl.java
License:Open Source License
private void sendDirectoryListing(String dir, RoutingContext context) { FileSystem fileSystem = new WindowsFileSystem((VertxInternal) context.vertx()); HttpServerRequest request = context.request(); fileSystem.readDir(dir, asyncResult -> { if (asyncResult.failed()) { context.fail(asyncResult.cause()); } else {/*from w w w.j a v a2s .com*/ String accept = request.headers().get("accept"); if (accept == null) { accept = "text/plain"; } if (accept.contains("html")) { String normalizedDir = context.normalisedPath(); if (!normalizedDir.endsWith("/")) { normalizedDir += "/"; } String file; StringBuilder files = new StringBuilder("<ul id=\"files\">"); List<String> list = asyncResult.result(); Collections.sort(list); for (String s : list) { file = s.substring(s.lastIndexOf(File.separatorChar) + 1); // skip dot files if (!includeHidden && file.charAt(0) == '.') { continue; } files.append("<li><a href=\""); files.append(normalizedDir); files.append(file); files.append("\" title=\""); files.append(file); files.append("\">"); files.append(file); files.append("</a></li>"); } files.append("</ul>"); // link to parent dir int slashPos = 0; for (int i = normalizedDir.length() - 2; i > 0; i--) { if (normalizedDir.charAt(i) == '/') { slashPos = i; break; } } String parent = "<a href=\"" + normalizedDir.substring(0, slashPos + 1) + "\">..</a>"; request.response().putHeader("content-type", "text/html"); request.response().end(directoryTemplate(context.vertx()).replace("{directory}", normalizedDir) .replace("{parent}", parent).replace("{files}", files.toString())); } else if (accept.contains("json")) { String file; JsonArray json = new JsonArray(); for (String s : asyncResult.result()) { file = s.substring(s.lastIndexOf(File.separatorChar) + 1); // skip dot files if (!includeHidden && file.charAt(0) == '.') { continue; } json.add(file); } request.response().putHeader("content-type", "application/json"); request.response().end(json.encode()); } else { String file; StringBuilder buffer = new StringBuilder(); for (String s : asyncResult.result()) { file = s.substring(s.lastIndexOf(File.separatorChar) + 1); // skip dot files if (!includeHidden && file.charAt(0) == '.') { continue; } buffer.append(file); buffer.append('\n'); } request.response().putHeader("content-type", "text/plain"); request.response().end(buffer.toString()); } } }); }
From source file:com.navercorp.pinpoint.plugin.vertx.VertxHttpHeaderFilter.java
License:Apache License
public void filter(final HttpServerRequest request) { if (!enable || request == null || request.headers() == null) { return;//from w w w .ja v a2s.c o m } for (String name : request.headers().names()) { if (Header.startWithPinpointHeader(name)) { request.headers().remove(name); } } }
From source file:com.sibvisions.vertx.HttpServer.java
License:Apache License
/** * Handles an upload request.//from w w w .j a v a2 s. co m * * @param pRequest the request */ private void handleUpload(final HttpServerRequest pRequest) { pRequest.handler(new Handler<Buffer>() { private OutputStream os; public void handle(Buffer event) { try { if (os == null) { String sFileName = getFileName(pRequest.headers().get("Content-Disposition")); if (sFileName == null) { pRequest.response().setStatusCode(HttpResponseStatus.BAD_REQUEST.code()); pRequest.response().end(); return; } RemoteFileHandle rfh = new RemoteFileHandle(sFileName, pRequest.params().get("KEY")); os = rfh.getOutputStream(); } os.write(event.getBytes()); } catch (IOException ioe) { throw new RuntimeException(ioe); } } }); pRequest.exceptionHandler(new Handler<Throwable>() { public void handle(Throwable event) { pRequest.response().end(); } }); pRequest.endHandler(new Handler<Void>() { public void handle(Void event) { pRequest.response().end(); } }); }
From source file:examples.HTTPExamples.java
License:Open Source License
public void example8(HttpServerRequest request) { MultiMap headers = request.headers(); // Get the User-Agent: System.out.println("User agent is " + headers.get("user-agent")); // You can also do this and get the same result: System.out.println("User agent is " + headers.get("User-Agent")); }
From source file:io.advantageous.qbit.vertx.http.server.HttpServerVertx.java
License:Apache License
private void handleRequestWithBody(HttpServerRequest request) { final String contentType = request.headers().get("Content-Type"); if (HttpContentTypes.isFormContentType(contentType)) { request.setExpectMultipart(true); }/*from w ww .j ava2 s . c o m*/ final Buffer[] bufferHolder = new Buffer[1]; final HttpRequest bodyHttpRequest = vertxUtils.createRequest(request, () -> bufferHolder[0], new HashMap<>(), simpleHttpServer.getDecorators(), simpleHttpServer.getHttpResponseCreator()); if (simpleHttpServer.getShouldContinueReadingRequestBody().test(bodyHttpRequest)) { request.bodyHandler((buffer) -> { bufferHolder[0] = buffer; simpleHttpServer.handleRequest(bodyHttpRequest); }); } else { logger.info("Request body rejected {} {}", request.method(), request.absoluteURI()); } }
From source file:io.advantageous.qbit.vertx.http.server.VertxServerUtils.java
License:Apache License
public HttpRequest createRequest(final HttpServerRequest request, final Supplier<Buffer> buffer, final Map<String, Object> data, final CopyOnWriteArrayList<HttpResponseDecorator> decorators, final HttpResponseCreator httpResponseCreator) { final MultiMap<String, String> headers = request.headers().size() == 0 ? MultiMap.empty() : new MultiMapWrapper(request.headers()); final String contentType = request.headers().get("Content-Type"); final String contentLengthHeaderValue = request.headers().get("Content-Length"); final int contentLength = contentLengthHeaderValue == null ? 0 : Integer.parseInt(contentLengthHeaderValue); final HttpRequestBuilder httpRequestBuilder = HttpRequestBuilder.httpRequestBuilder(); buildParams(httpRequestBuilder, request, contentType); final MultiMap<String, String> params = httpRequestBuilder.getParams(); final String requestPath = request.path(); httpRequestBuilder.setId(requestId.incrementAndGet()).setContentLength(contentLength).setData(data) .setUri(requestPath).setMethod(request.method().toString()) .setBodySupplier(() -> buffer == null ? null : buffer.get().getBytes()) .setRemoteAddress(request.remoteAddress().toString()) .setResponse(createResponse(requestPath, request.method().toString(), headers, params, request.response(), decorators, httpResponseCreator)) .setTimestamp(time == 0L ? Timer.timer().now() : time).setHeaders(headers); return httpRequestBuilder.build(); }
From source file:io.apiman.gateway.platforms.vertx3.http.HttpApiFactory.java
License:Apache License
public static ApiRequest buildRequest(HttpServerRequest req, boolean isTransportSecure) { ApiRequest apimanRequest = new ApiRequest(); apimanRequest.setApiKey(parseApiKey(req)); apimanRequest.setRemoteAddr(req.remoteAddress().host()); apimanRequest.setType(req.method().toString()); apimanRequest.setTransportSecure(isTransportSecure); multimapToMap(apimanRequest.getHeaders(), req.headers(), IGNORESET); multimapToMap(apimanRequest.getQueryParams(), req.params(), Collections.<String>emptySet()); parsePath(req, apimanRequest);/* w w w . j a v a 2s . c o m*/ return apimanRequest; }