Java Code Examples for io.vertx.core.http.HttpServerResponse#end()

The following examples show how to use io.vertx.core.http.HttpServerResponse#end() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SubscriptionsServiceHandler.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {
    HttpServerResponse response = ctx.response();
    response.setStatusCode(HttpStatusCode.OK_200);
    response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    response.setChunked(true);

    try {
        Json.prettyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        response.write(Json.prettyMapper.writeValueAsString(new ExecutorStatistics()));
    } catch (JsonProcessingException jpe) {
        response.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500);
        LOGGER.error("Unable to transform data object to JSON", jpe);
    }

    response.end();
}
 
Example 2
Source File: ExecuteRSByte.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Override
protected void errorRespond(String result, int statuscode) {
  final HttpServerResponse response = context.response();
  if (!response.ended()) {
    ResponseExecution.updateHeaderAndStatuscode(headers, statuscode, response);
    if (result != null) {
      response.end(result);
    } else {
      response.end();
    }
  }
}
 
Example 3
Source File: WriteHandler.java    From nassh-relay with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(final RoutingContext context) {
    final HttpServerRequest request = context.request();
    final HttpServerResponse response = context.response();
    response.putHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
    response.putHeader("Pragma", "no-cache");
    if (request.params().contains("sid") && request.params().contains("wcnt") && request.params().contains("data")) {
        final UUID sid = UUID.fromString(request.params().get("sid"));
        final byte[] data = Base64.getUrlDecoder().decode(request.params().get("data"));
        response.setStatusCode(200);
        final LocalMap<String, Session> map = vertx.sharedData().getLocalMap(Constants.SESSIONS);
        final Session session = map.get(sid.toString());
        if (session == null) {
            response.setStatusCode(410);
            response.end();
            return;
        }
        session.setWrite_count(Integer.parseInt(request.params().get("wcnt")));
        final Buffer message = Buffer.buffer();
        message.appendBytes(data);
        vertx.eventBus().publish(session.getHandler(), message);
        response.end();
    } else {
        response.setStatusCode(410);
        response.end();
    }
}
 
Example 4
Source File: JsonExceptionHandler.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Throwable exception, HttpServerRequest request, HttpServerResponse response) {

	response.setStatusCode(406);

	ErrorJSON error = new ErrorJSON();
	error.code = response.getStatusCode();
	error.message = exception.getMessage();

	response.end(JsonUtils.toJson(error));
}
 
Example 5
Source File: DefaultErrorHandler.java    From nubes with Apache License 2.0 5 votes vote down vote up
private void renderViewError(String tpl, RoutingContext context, Throwable cause) {
  HttpServerResponse response = context.response();
  if (tpl != null) {
    context.put("error", cause);
    if (tpl.endsWith(".html")) {
      response.sendFile(tpl);
      return;
    }
    if (config.isDisplayErrors()) {
      context.put("stackTrace", StackTracePrinter.asHtml(new StringBuilder(), cause).toString());
    }

    String fileName = Paths.get(tpl).getFileName().toString();
    String path = tpl.replace(fileName, "");

    templManager.fromViewName(tpl).render(context, fileName, path, res -> {
      if (res.succeeded()) {
        response.end(res.result());
      } else {
        LOG.error("Could not read error template : " + tpl, res.cause());
        response.end(errorMessages.get(500));
      }
    });
  } else {
    response.end(cause.getMessage());
  }
}
 
Example 6
Source File: EventbusRequest.java    From vxms with Apache License 2.0 5 votes vote down vote up
protected void respond(HttpServerResponse response, Object resp) {
  if (resp instanceof String) {
    response.end((String) resp);
  } else if (resp instanceof byte[]) {
    response.end(Buffer.buffer((byte[]) resp));
  } else if (resp instanceof JsonObject) {
    response.end(JsonObject.class.cast(resp).encode());
  } else if (resp instanceof JsonArray) {
    response.end(JsonArray.class.cast(resp).encode());
  }
}
 
Example 7
Source File: MyXmlWriter.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@Override
public void write(User result, HttpServerRequest request, HttpServerResponse response) {

	// response.headers().set("Content-Type", "text/xml");
	// response.putHeader("Cache-Control", "private,no-cache,no-store");
	response.end("<u name=\"" + result.name  + "\" />");
}
 
Example 8
Source File: SwaggerRouter.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
private static void manageError( ReplyException cause, HttpServerResponse response) {
    if(isExistingHttStatusCode(cause.failureCode())) {
        response.setStatusCode(cause.failureCode());
        if(StringUtils.isNotEmpty(cause.getMessage())) {
            response.setStatusMessage(cause.getMessage());
        }
    } else {
        response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
    }
    response.end();
}
 
Example 9
Source File: Terminus.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public void onCompleted() {

    LOGGER.debug("Ended onComplete");
    try {
        HttpServerResponse response = httpServerRequest.response();
        response.end();
    } finally {
        try {
            httpServerRequest.resume();
        } catch (Throwable e) {
            // do nothing
        }
    }
}
 
Example 10
Source File: BaseTransport.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
protected void sendInvalidJSON(HttpServerResponse response) {
  if (log.isTraceEnabled()) log.trace("Broken JSON");
  response.setStatusCode(500);
  response.end("Broken JSON encoding.");
}
 
Example 11
Source File: SimpleWebVerticle.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
private void handleGet(RoutingContext routingContext) {
    HttpServerResponse response = routingContext.response();
    String welcome = routingContext.request().getParam("welcome");
    response.end("Reply: " + welcome);
}
 
Example 12
Source File: WebSocketTestController.java    From festival with Apache License 2.0 4 votes vote down vote up
@GetMapping("/send")
public void sendInfo(@Param("id") String id, @Param("info") String info, HttpServerResponse response) {
    ServerWebSocket serverWebSocket = serverWebSocketMap.get(id);
    serverWebSocket.writeTextMessage(info);
    response.end();
}
 
Example 13
Source File: GuicedResponseWriter.java    From rest.vertx with Apache License 2.0 4 votes vote down vote up
@Override
public void write(Object result, HttpServerRequest request, HttpServerResponse response) {

	response.end(result + "=" + dummyService.get());
}
 
Example 14
Source File: AbstractDelegatingRegistryHttpEndpoint.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Writes a response based on generic result.
 * <p>
 * The behavior is as follows:
 * <ol>
 * <li>Set the status code on the response.</li>
 * <li>Try to serialize the object contained in the result to JSON and use it as the response body.</li>
 * <li>If the result is an {@code OperationResult} and contains a resource version, add an ETAG header
 * to the response using the version as its value.</li>
 * <li>If the handler is not {@code null}, invoke it with the response and the status code from the result.</li>
 * <li>Set the span's <em>http.status</em> tag to the result's status code.</li>
 * <li>End the response.</li>
 * </ol>
 *
 * @param ctx The context to write the response to.
 * @param result The generic result of the operation.
 * @param customHandler An (optional) handler for post processing successful HTTP response, e.g. to set any additional HTTP
 *                      headers. The handler <em>must not</em> write to response body. May be {@code null}.
 * @param span The active OpenTracing span for this operation.
 */
protected final void writeResponse(final RoutingContext ctx, final Result<?> result, final BiConsumer<MultiMap, Integer> customHandler, final Span span) {
    final int status = result.getStatus();
    final HttpServerResponse response = ctx.response();
    response.setStatusCode(status);
    if (result instanceof OperationResult) {
        ((OperationResult<?>) result).getResourceVersion().ifPresent(version -> response.putHeader(HttpHeaders.ETAG, version));
    }
    if (customHandler != null) {
        customHandler.accept(response.headers(), status);
    }
    // once the body has been written, the response headers can no longer be changed
    HttpUtils.setResponseBody(response, asJson(result.getPayload()), HttpUtils.CONTENT_TYPE_JSON_UTF8);
    Tags.HTTP_STATUS.set(span, status);
    response.end();
}
 
Example 15
Source File: MyExceptionHandler.java    From rest.vertx with Apache License 2.0 4 votes vote down vote up
@Override
public void write(MyExceptionClass result, HttpServerRequest request, HttpServerResponse response) {

	response.setStatusCode(result.getStatus());
	response.end("Exception: " + result.getError());
}
 
Example 16
Source File: ArchiveCommand.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
/**
 * 单个下载
 * @param
 * @return
 * @throws Exception
 */
@Path("download")
public void download(@QueryParam("businessId") String businessId, @QueryParam("messageId") String messageId
        , @QueryParam("sendTime") String sendTime, @QueryParam("topic") String topic,@QueryParam("messageType") String messageType) throws Exception {
    if (businessId == null
            || messageId == null
            || sendTime == null
            || topic == null) {
        throw new ServiceException(HTTP_BAD_REQUEST, "请求参数错误!");
    }
    HttpServerResponse response = request.response();
    try {
        SendLog sendLog = archiveService.findSendLog(topic, Long.valueOf(sendTime), businessId, messageId);
        if (Objects.nonNull(sendLog)) {
            byte[] data = sendLog.getMessageBody();
            if (data.length == 0) {
                throw new ServiceException(Response.HTTP_NOT_FOUND,"消息内容为空" );
            }
            String fileName = sendLog.getMessageId() + ".txt";
            response.reset();
            ByteBuffer byteBuffer = ByteBuffer.wrap(data);
            BrokerMessage brokerMessage = Serializer.readBrokerMessage(byteBuffer);
            // Broker message without topic context,we should fill it
            brokerMessage.setTopic(topic);
            // filter target  broker message with index
            brokerMessage = filterBrokerMessage(brokerMessage,sendLog);
            if (Objects.nonNull(brokerMessage)) {
                String content = preview(brokerMessage, messageType);
                response.putHeader("Content-Disposition", "attachment;fileName=" + fileName)
                        .putHeader("content-type", "text/plain")
                        .putHeader("Content-Length", String.valueOf(content.getBytes().length));
                response.write(content, "UTF-8");
                response.end();
            }else {
                logger.error("Not found {} message id {},business id {} int batch",topic,messageId,businessId);
                throw new ServiceException(Response.HTTP_NOT_FOUND, "未找到消息!");
            }
        } else {
            logger.error("Not found {} message id {},business id {} in storage",topic,messageId,businessId);
            throw new ServiceException(Response.HTTP_NOT_FOUND, "未找到消息!");
        }
    }catch (Throwable e){
        if(e instanceof ServiceException){
            ServiceException se=(ServiceException)e;
            response.end(JSON.toJSONString(Responses.error(se.getStatus(),se.getMessage())));
        }else{
            response.end(JSON.toJSONString(Responses.error(ErrorCode.NoTipError.getCode(),e.getMessage())));
        }
    }
}
 
Example 17
Source File: WebSocketTestController.java    From festival with Apache License 2.0 4 votes vote down vote up
@GetMapping("/send")
public void sendInfo(@Param("id") String id, @Param("info") String info, HttpServerResponse response) {
    ServerWebSocket serverWebSocket = serverWebSocketMap.get(id);
    serverWebSocket.writeTextMessage(info);
    response.end();
}
 
Example 18
Source File: PathParametersTestController.java    From nubes with Apache License 2.0 4 votes vote down vote up
@GET("byName/:dog")
public void testParamByName(HttpServerResponse response, @Param String dog) {
	response.end(dog);
}
 
Example 19
Source File: TestLocalMap.java    From nubes with Apache License 2.0 4 votes vote down vote up
@GET("/dynamicValueWithParamName")
public void getDynamicValueWithParamName(HttpServerResponse response, @VertxLocalMap LocalMap<String, String> someMap, @Param String key) {
	response.putHeader("X-Map-Value", someMap.get(key));
	response.end();
}
 
Example 20
Source File: TlsEnabledHttpServerFactory.java    From besu with Apache License 2.0 4 votes vote down vote up
private static void handleRequest(final RoutingContext context) {
  final HttpServerResponse response = context.response();
  if (!response.closed()) {
    response.end("I'm up!");
  }
}