io.vertx.core.http.HttpServerResponse#end ( )源码实例Demo

下面列出了io.vertx.core.http.HttpServerResponse#end ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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();
}
 
源代码2 项目: nassh-relay   文件: WriteHandler.java
@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();
    }
}
 
源代码3 项目: sfs   文件: Terminus.java
@Override
public void onCompleted() {

    LOGGER.debug("Ended onComplete");
    try {
        HttpServerResponse response = httpServerRequest.response();
        response.end();
    } finally {
        try {
            httpServerRequest.resume();
        } catch (Throwable e) {
            // do nothing
        }
    }
}
 
源代码4 项目: vertx-swagger   文件: SwaggerRouter.java
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();
}
 
源代码5 项目: rest.vertx   文件: MyXmlWriter.java
@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  + "\" />");
}
 
源代码6 项目: vxms   文件: EventbusRequest.java
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());
  }
}
 
源代码7 项目: nubes   文件: DefaultErrorHandler.java
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());
  }
}
 
源代码8 项目: rest.vertx   文件: JsonExceptionHandler.java
@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));
}
 
源代码9 项目: vxms   文件: ExecuteRSByte.java
@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();
    }
  }
}
 
源代码10 项目: besu   文件: TlsEnabledHttpServerFactory.java
private static void handleRequest(final RoutingContext context) {
  final HttpServerResponse response = context.response();
  if (!response.closed()) {
    response.end("I'm up!");
  }
}
 
源代码11 项目: nubes   文件: TestLocalMap.java
@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();
}
 
源代码12 项目: festival   文件: WebSocketTestController.java
@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();
}
 
源代码13 项目: festival   文件: WebSocketTestController.java
@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();
}
 
源代码14 项目: vertx-web   文件: BaseTransport.java
protected void sendInvalidJSON(HttpServerResponse response) {
  if (log.isTraceEnabled()) log.trace("Broken JSON");
  response.setStatusCode(500);
  response.end("Broken JSON encoding.");
}
 
源代码15 项目: jkube   文件: SimpleWebVerticle.java
private void handleGet(RoutingContext routingContext) {
    HttpServerResponse response = routingContext.response();
    String welcome = routingContext.request().getParam("welcome");
    response.end("Reply: " + welcome);
}
 
源代码16 项目: rest.vertx   文件: GuicedResponseWriter.java
@Override
public void write(Object result, HttpServerRequest request, HttpServerResponse response) {

	response.end(result + "=" + dummyService.get());
}
 
/**
 * 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();
}
 
源代码18 项目: rest.vertx   文件: MyExceptionHandler.java
@Override
public void write(MyExceptionClass result, HttpServerRequest request, HttpServerResponse response) {

	response.setStatusCode(result.getStatus());
	response.end("Exception: " + result.getError());
}
 
源代码19 项目: joyqueue   文件: ArchiveCommand.java
/**
 * 单个下载
 * @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())));
        }
    }
}
 
源代码20 项目: nubes   文件: PathParametersTestController.java
@GET("byName/:dog")
public void testParamByName(HttpServerResponse response, @Param String dog) {
	response.end(dog);
}