Example usage for io.vertx.core.http HttpServerResponse write

List of usage examples for io.vertx.core.http HttpServerResponse write

Introduction

In this page you can find the example usage for io.vertx.core.http HttpServerResponse write.

Prototype

Future<Void> write(String chunk);

Source Link

Document

Write a String to the response body, encoded in UTF-8.

Usage

From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailMicroserviceVerticle.java

License:Open Source License

/**
 * Render thumbnail event handler. Responds with a <code>image/jpeg</code>
 * body on success based on the <code>longestSide</code> and
 * <code>imageId</code> encoded in the URL or HTTP 404 if the {@link Image}
 * does not exist or the user does not have permissions to access it.
 * @param event Current routing context.
 *///from   w w  w  . j a  v  a2  s .  c  om
private void renderThumbnail(RoutingContext event) {
    final HttpServerRequest request = event.request();
    final HttpServerResponse response = event.response();
    final Map<String, Object> data = new HashMap<String, Object>();
    data.put("longestSide",
            Optional.ofNullable(request.getParam("longestSide")).map(Integer::parseInt).orElse(96));
    data.put("imageId", Long.parseLong(request.getParam("imageId")));
    data.put("omeroSessionKey", event.get("omero.session_key"));
    data.put("renderingDefId",
            Optional.ofNullable(request.getParam("rdefId")).map(Long::parseLong).orElse(null));

    vertx.eventBus().<byte[]>send(ThumbnailVerticle.RENDER_THUMBNAIL_EVENT, Json.encode(data), result -> {
        try {
            if (result.failed()) {
                Throwable t = result.cause();
                int statusCode = 404;
                if (t instanceof ReplyException) {
                    statusCode = ((ReplyException) t).failureCode();
                }
                response.setStatusCode(statusCode);
                return;
            }
            byte[] thumbnail = result.result().body();
            response.headers().set("Content-Type", "image/jpeg");
            response.headers().set("Content-Length", String.valueOf(thumbnail.length));
            response.write(Buffer.buffer(thumbnail));
        } finally {
            response.end();
            log.debug("Response ended");
        }
    });
}

From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailMicroserviceVerticle.java

License:Open Source License

/**
 * Get thumbnails event handler. Responds with a JSON dictionary of Base64
 * encoded <code>image/jpeg</code> thumbnails keyed by {@link Image}
 * identifier. Each dictionary value is prefixed with
 * <code>data:image/jpeg;base64,</code> so that it can be used with
 * <a href="http://caniuse.com/#feat=datauri">data URIs</a>.
 * @param event Current routing context.
 *//*from w ww. ja v a2s  .  co m*/
private void getThumbnails(RoutingContext event) {
    final HttpServerRequest request = event.request();
    final HttpServerResponse response = event.response();
    final Map<String, Object> data = new HashMap<String, Object>();
    final String callback = request.getParam("callback");
    data.put("longestSide",
            Optional.ofNullable(request.getParam("longestSide")).map(Integer::parseInt).orElse(96));
    data.put("imageIds",
            request.params().getAll("id").stream().map(Long::parseLong).collect(Collectors.toList()).toArray());
    data.put("omeroSessionKey", event.get("omero.session_key"));

    vertx.eventBus().<String>send(ThumbnailVerticle.GET_THUMBNAILS_EVENT, Json.encode(data), result -> {
        try {
            if (result.failed()) {
                Throwable t = result.cause();
                int statusCode = 404;
                if (t instanceof ReplyException) {
                    statusCode = ((ReplyException) t).failureCode();
                }
                response.setStatusCode(statusCode);
                return;
            }
            String json = result.result().body();
            String contentType = "application/json";
            if (callback != null) {
                json = String.format("%s(%s);", callback, json);
                contentType = "application/javascript";
            }
            response.headers().set("Content-Type", contentType);
            response.headers().set("Content-Length", String.valueOf(json.length()));
            response.write(json);
        } finally {
            response.end();
            log.debug("Response ended");
        }
    });
}

From source file:com.opinionlab.woa.WallOfAwesome.java

License:Open Source License

private static Handler<RoutingContext> makeDownloadRoute() {
    return routingContext -> EXECUTOR.execute(() -> {
        try {/*w w  w. j a  v  a2s  .co  m*/
            final HttpServerResponse response = routingContext.response();
            final AtomicBoolean first = new AtomicBoolean(true);
            response.putHeader("Content-Type", "text/plain");
            response.putHeader("Content-Disposition", "inline;filename=awesome.txt");

            response.setChunked(true);
            response.write("BEGIN AWESOME\n\n");
            AwesomeImap.fetchAwesome().forEach(awesome -> {
                if (!first.get()) {
                    response.write("\n\n---\n\n");
                } else {
                    first.set(false);
                }

                response.write(new ST(AWESOME_TEMPLATE).add("awesome", awesome).render());
            });
            response.write("\n\nEND AWESOME");
            response.end();
        } catch (Throwable t) {
            LOGGER.error("Unable to fetch messages.", t);
        }
    });
}

From source file:com.sibvisions.vertx.HttpServer.java

License:Apache License

/**
 * Handles a download request.// w  w w  .  j  ava 2 s.  c  o  m
 * 
 * @param pRequest the request
 */
private void handleDownload(HttpServerRequest pRequest) {
    String sKey = pRequest.params().get("KEY");

    if (sKey == null) {
        pRequest.response().setStatusCode(HttpResponseStatus.BAD_REQUEST.code());
        pRequest.response().end();

        return;
    }

    IFileHandle fh = (IFileHandle) ObjectCache.get(sKey);

    HttpServerResponse response = pRequest.response();

    String sType = MimeMapping.getMimeTypeForExtension(FileUtil.getExtension(fh.getFileName()));

    if (sType != null) {
        response.putHeader(HttpHeaders.CONTENT_TYPE, sType);
    }

    response.putHeader("Content-Disposition", "attachment; filename=\"" + fh.getFileName() + "\"");

    int iLen;

    byte[] byContent = new byte[4096];

    try {
        response.putHeader(HttpHeaders.CONTENT_LENGTH, "" + fh.getLength());

        InputStream in = fh.getInputStream();

        Buffer buffer;

        while ((iLen = in.read(byContent)) >= 0) {
            buffer = Buffer.buffer();
            buffer.appendBytes(byContent, 0, iLen);

            response.write(buffer);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    response.end();
}

From source file:examples.CoreExamples.java

License:Open Source License

public void example4(HttpServerRequest request) {
    HttpServerResponse response = request.response();
    response.putHeader("Content-Type", "text/plain");
    response.write("some text");
    response.end();/*from   www.  j a  v a  2 s .c  o m*/
}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example16(HttpServerRequest request, Buffer buffer) {
    HttpServerResponse response = request.response();
    response.write(buffer);
}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example17(HttpServerRequest request) {
    HttpServerResponse response = request.response();
    response.write("hello world!");
}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example19(HttpServerRequest request) {
    HttpServerResponse response = request.response();
    response.write("hello world!");
    response.end();/*from  ww w .j a v  a2  s. c  o  m*/
}

From source file:io.apiman.gateway.platforms.vertx3.http.HttpPolicyAdapter.java

License:Apache License

private static void handleError(HttpServerResponse response, Throwable error) {
    response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
    response.setStatusMessage(HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase());
    response.headers().add("X-Gateway-Error", String.valueOf(error.getMessage())); //$NON-NLS-1$
    response.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);

    EngineErrorResponse errorResponse = new EngineErrorResponse();
    errorResponse.setResponseCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
    errorResponse.setMessage(error.getMessage());
    errorResponse.setTrace(error);// w  w  w.j a v a  2 s  .  c o m
    response.setChunked(true);
    response.write(Json.encode(errorResponse));
    response.end();
}

From source file:io.fabric8.che.vertx.handler.CreateProjectHandler.java

License:Open Source License

@Override
public void handle(RoutingContext routingContext) {
    HttpServerResponse response = routingContext.response();
    response.putHeader("Content-Type", "application/json").setChunked(true);
    response.write(new Response().getResponse(Constants.CREATE_PROJECT_RESPONSE_TEMPLATE));
    response.end();/*  w w w  .j a  v  a 2  s  .  c om*/
}