下面列出了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();
}
@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();
}
}
@Override
public void onCompleted() {
LOGGER.debug("Ended onComplete");
try {
HttpServerResponse response = httpServerRequest.response();
response.end();
} finally {
try {
httpServerRequest.resume();
} catch (Throwable e) {
// do nothing
}
}
}
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();
}
@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 + "\" />");
}
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());
}
}
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());
}
}
@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));
}
@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();
}
}
}
private static void handleRequest(final RoutingContext context) {
final HttpServerResponse response = context.response();
if (!response.closed()) {
response.end("I'm 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();
}
@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();
}
@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();
}
protected void sendInvalidJSON(HttpServerResponse response) {
if (log.isTraceEnabled()) log.trace("Broken JSON");
response.setStatusCode(500);
response.end("Broken JSON encoding.");
}
private void handleGet(RoutingContext routingContext) {
HttpServerResponse response = routingContext.response();
String welcome = routingContext.request().getParam("welcome");
response.end("Reply: " + welcome);
}
@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();
}
@Override
public void write(MyExceptionClass result, HttpServerRequest request, HttpServerResponse response) {
response.setStatusCode(result.getStatus());
response.end("Exception: " + result.getError());
}
/**
* 单个下载
* @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())));
}
}
}
@GET("byName/:dog")
public void testParamByName(HttpServerResponse response, @Param String dog) {
response.end(dog);
}