List of usage examples for io.vertx.core.http HttpServerRequest response
@CacheReturn HttpServerResponse response();
From source file:com.djmmedia.samplecode.PingVerticle.java
License:Apache License
public void start() { // timeout set to 1 minute final long periodicTimerId = vertx.setPeriodic(60_000, new Handler() { @Override/*from w w w . j av a2 s . c o m*/ public void handle(Object event) { //log.info("Trigger Data Fetch"); System.out.println("Trigger Data Fetch"); } }); vertx.createHttpServer().requestHandler(new Handler<HttpServerRequest>() { @Override public void handle(HttpServerRequest httpServerRequest) { httpServerRequest.response().end("Hello smartjava"); } }).listen(8888); System.out.println("Ping started"); }
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 w w . ja va 2s . 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.groupon.vertx.http.HttpServerRequestWrapper.java
License:Apache License
public HttpServerRequestWrapper(HttpServerRequest serverRequest) { this(serverRequest, serverRequest.response()); }
From source file:com.groupon.vertx.utils.HealthcheckHandler.java
License:Apache License
protected void processHeartBeatResponse(Boolean exists, HttpServerRequest request, long startTime) { HttpResponseStatus status;//from ww w . ja v a 2s. c om final boolean includeBody = !request.method().equals(HttpMethod.HEAD); if (exists) { status = HttpResponseStatus.OK; } else { status = HttpResponseStatus.SERVICE_UNAVAILABLE; } setCommonHttpResponse(request, status); String responseBody = status.reasonPhrase(); if (includeBody) { request.response().end(responseBody); } else { request.response().putHeader(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(responseBody.length())); request.response().end(); } long totalTime = System.currentTimeMillis() - startTime; LOG.debug("handle", "healthcheckResponse", new String[] { "method", "status", "totalTime" }, request.method(), status.code(), totalTime); }
From source file:com.groupon.vertx.utils.HealthcheckHandler.java
License:Apache License
protected void processExceptionResponse(HttpServerRequest request, Exception ex, long startTime) { HttpResponseStatus status = HttpResponseStatus.SERVICE_UNAVAILABLE; final boolean includeBody = !request.method().equals(HttpMethod.HEAD); String responseBody = status.reasonPhrase() + ": " + ex.getMessage(); setCommonHttpResponse(request, status); if (includeBody) { request.response().end(responseBody); } else {/* ww w . j av a 2 s.c om*/ request.response().putHeader(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(responseBody.length())); request.response().end(); } long totalTime = System.currentTimeMillis() - startTime; LOG.debug("handle", "healthcheckResponse", new String[] { "method", "status", "totalTime" }, request.method(), status.code(), totalTime); }
From source file:com.groupon.vertx.utils.HealthcheckHandler.java
License:Apache License
private void setCommonHttpResponse(HttpServerRequest request, HttpResponseStatus status) { request.response().putHeader(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE); request.response().putHeader(HttpHeaderNames.CACHE_CONTROL, CACHE_CONTROL); request.response().setStatusCode(status.code()); request.response().setStatusMessage(status.reasonPhrase()); }
From source file:com.klwork.spring.vertx.render.MyStaticHandlerImpl.java
License:Open Source License
/** * Create all required header so content can be cache by Caching servers or Browsers * * @param request base HttpServerRequest * @param props file properties//from w ww .j a v a 2s . co m */ private void writeCacheHeaders(HttpServerRequest request, FileProps props) { MultiMap headers = request.response().headers(); if (cachingEnabled) { // We use cache-control and last-modified // We *do not use* etags and expires (since they do the same thing - redundant) headers.set("cache-control", "public, max-age=" + maxAgeSeconds); headers.set("last-modified", dateTimeFormatter.format(props.lastModifiedTime())); } // date header is mandatory headers.set("date", dateTimeFormatter.format(new Date())); }
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 . ja v a2 s . c om*/ 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.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 .ja v a2 s. c o m*/ 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.interceptor.ServerConnectionHandleRequestInterceptor.java
License:Apache License
@Override public void before(Object target, Object[] args) { if (isDebug) { logger.beforeInterceptor(target, args); }/* www . j av a 2 s . c o m*/ if (traceContext.currentRawTraceObject() != null) { // duplicate trace. return; } try { if (!validate(args)) { // invalid args. return; } final HttpServerRequest request = (HttpServerRequest) args[0]; final HttpServerResponse response = request.response(); if (!(response instanceof AsyncContextAccessor)) { if (isDebug) { logger.debug("Invalid response. Need metadata accessor({}).", AsyncContextAccessor.class.getName()); } return; } // create trace for standalone entry point. final Trace trace = createTrace(request); if (trace == null) { return; } entryScope(trace); this.httpHeaderFilter.filter(request); if (!trace.canSampled()) { return; } final SpanEventRecorder recorder = trace.traceBlockBegin(); recorder.recordServiceType(VertxConstants.VERTX_HTTP_SERVER_INTERNAL); // make asynchronous trace-id final AsyncContext asyncContext = recorder.recordNextAsyncContext(true); ((AsyncContextAccessor) request)._$PINPOINT$_setAsyncContext(asyncContext); ((AsyncContextAccessor) response)._$PINPOINT$_setAsyncContext(asyncContext); if (isDebug) { logger.debug("Set closeable-AsyncContext {}", asyncContext); } } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("BEFORE. Caused:{}", t.getMessage(), t); } } }