下面列出了io.vertx.core.http.HttpServerResponse#write ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 单个下载
* @param
* @return
* @throws Exception
*
*/
@Path("download")
public void download(@QueryParam(Constants.ID) Long id, @QueryParam(Constants.TOPIC)String topic) throws Exception {
ConsumeRetry retry = retryService.getDataById(id,topic);
if (retry != null) {
HttpServerResponse response = request.response();
byte[] data = retry.getData();
if (data.length == 0) {
throw new JoyQueueException("消息内容为空",HTTP_BAD_REQUEST);
}
String fileName = retry.getId() +".txt";
response.reset();
BrokerMessage brokerMessage = Serializer.readBrokerMessage(ByteBuffer.wrap(data));
String message = brokerMessage.getText();
if (message == null) {
message = "";
}
response.putHeader("Content-Disposition","attachment;fileName=" + fileName)
.putHeader("content-type","text/plain")
.putHeader("Content-Length",String.valueOf(message.getBytes().length));
response.write(message,"UTF-8");
response.end();
}
}
void endRequestWithError(RoutingContext rc, int status, boolean chunked, String message, boolean[] isValid) {
if (isValid[0]) {
HttpServerResponse response = rc.response();
if (!response.closed()) {
response.setChunked(chunked);
response.setStatusCode(status);
if (status == 422) {
response.putHeader("Content-type", SUPPORTED_CONTENT_TYPE_JSON_DEF);
} else {
response.putHeader("Content-type", SUPPORTED_CONTENT_TYPE_TEXT_DEF);
}
if (message != null) {
response.write(message);
} else {
message = "";
}
response.end();
}
LogUtil.formatStatsLogMessage(rc.request().remoteAddress().toString(), rc.request().method().toString(),
rc.request().version().toString(), response.getStatusCode(), -1, rc.response().bytesWritten(),
rc.request().path(), rc.request().query(), response.getStatusMessage(), null, message);
}
// once we are here the call is not valid
isValid[0] = false;
}
@Override
public void handle(RoutingContext ctx) {
HttpServerResponse response = ctx.response();
try {
String sApi = ctx.request().getParam("apiId");
Api api = apiManager.get(sApi);
if (api == null) {
response.setStatusCode(HttpStatusCode.NOT_FOUND_404);
} else {
response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
response.setStatusCode(HttpStatusCode.OK_200);
response.setChunked(true);
Json.prettyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
response.write(Json.prettyMapper.writeValueAsString(api));
}
} 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(RoutingContext ctx) {
HttpServerResponse response = ctx.response();
response.setStatusCode(HttpStatusCode.OK_200);
response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
response.setChunked(true);
try {
Collection<ListApiEntity> apis = apiManager.apis().stream().map(api -> {
ListApiEntity entity = new ListApiEntity();
entity.setId(api.getId());
entity.setName(api.getName());
entity.setVersion(api.getVersion());
return entity;
}).collect(Collectors.toList());
Json.prettyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
response.write(Json.prettyMapper.writeValueAsString(apis));
} 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(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(RoutingContext ctx) {
HttpServerResponse response = ctx.response();
try {
String sApi = ctx.request().getParam("apiId");
ApiKeyRefresher apiKeyRefresher = apiKeyRefreshers.get(sApi);
if (apiKeyRefresher == null) {
response.setStatusCode(HttpStatusCode.NOT_FOUND_404);
} else {
response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
response.setStatusCode(HttpStatusCode.OK_200);
response.setChunked(true);
Json.prettyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
response.write(Json.prettyMapper.writeValueAsString(new RefresherStatistics(apiKeyRefresher)));
}
} 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(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(RoutingContext ctx) {
HttpServerResponse response = ctx.response();
try {
String sApi = ctx.request().getParam("apiId");
SubscriptionRefresher apiKeyRefresher = subscriptionRefreshers.get(sApi);
if (apiKeyRefresher == null) {
response.setStatusCode(HttpStatusCode.NOT_FOUND_404);
} else {
response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
response.setStatusCode(HttpStatusCode.OK_200);
response.setChunked(true);
Json.prettyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
response.write(Json.prettyMapper.writeValueAsString(new RefresherStatistics(apiKeyRefresher)));
}
} 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(RoutingContext context) {
HttpServerRequest request = context.request();
HttpServerResponse response = context.response();
response.setChunked(true);
SSEConnection connection = SSEConnection.create(context);
String accept = request.getHeader("Accept");
if (accept != null && !accept.contains("text/event-stream")) {
connection.reject(406, "Not acceptable");
return;
}
response.closeHandler(aVoid -> {
closeHandlers.forEach(closeHandler -> closeHandler.handle(connection));
connection.close();
});
response.headers().add("Content-Type", "text/event-stream");
response.headers().add("Cache-Control", "no-cache");
response.headers().add("Connection", "keep-alive");
connectHandlers.forEach(handler -> handler.handle(connection));
if (!connection.rejected()) {
response.setStatusCode(200);
response.setChunked(true);
response.write(EMPTY_BUFFER);
}
}
private void processReadBuffer(Buffer buffer) {
logger.info("Read {} bytes from pos {}", buffer.length(), positionInFile);
positionInFile += buffer.length();
if (buffer.length() == 0) {
closeCurrentFile();
return;
}
for (HttpServerResponse streamer : streamers) {
if (!streamer.writeQueueFull()) {
streamer.write(buffer.copy());
}
}
}
private static <T> void streamGetResult(PostgresClientStreamResult<T> result,
String element, HttpServerResponse response) {
response.setStatusCode(200);
response.setChunked(true);
response.putHeader(HttpHeaders.CONTENT_TYPE, "application/json");
response.write("{\n");
response.write(String.format(" \"%s\": [%n", element));
AtomicBoolean first = new AtomicBoolean(true);
result.exceptionHandler(res -> {
String message = res.getMessage();
List<Diagnostic> diag = new ArrayList<>();
diag.add(new Diagnostic().withCode("500").withMessage(message));
result.resultInto().setDiagnostics(diag);
streamTrailer(response, result.resultInto());
});
result.endHandler(res -> streamTrailer(response, result.resultInto()));
result.handler(res -> {
String itemString = null;
try {
itemString = OBJECT_MAPPER.writeValueAsString(res);
} catch (JsonProcessingException ex) {
logger.error(ex.getMessage(), ex);
throw new IllegalArgumentException(ex.getCause());
}
if (first.get()) {
first.set(false);
} else {
response.write(String.format(",%n"));
}
response.write(itemString);
});
}
@Override
public void handle(RoutingContext ctx) {
HttpServerResponse response = ctx.response();
JsonObject object = new JsonObject()
.put("counter", syncManager.getCounter())
.put("lastRefreshAt", syncManager.getLastRefreshAt());
response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
response.setChunked(true);
response.write(object.encodePrettily());
response.setStatusCode(HttpStatusCode.OK_200);
response.end();
}
/**
* 单个下载
* @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())));
}
}
}
private static void streamTrailer(HttpServerResponse response, ResultInfo resultInfo) {
response.write(String.format("],%n \"totalRecords\": %d,%n", resultInfo.getTotalRecords()));
response.end(String.format(" \"resultInfo\": %s%n}", Json.encode(resultInfo)));
}
@BeforeFilter(2)
public void before1(HttpServerResponse response) {
response.write("before2;");
}
@BeforeFilter(3)
public void before3(HttpServerResponse response) {
response.write("before3;");
}
@BeforeFilter(1)
public void before2(HttpServerResponse response) {
response.setChunked(true);
response.write("before1;");
}
@AfterFilter(2)
public void after2(HttpServerResponse response) {
response.write("after2;");
}
@AfterFilter(1)
public void after1(HttpServerResponse response) {
response.write("after1;");
}
/**
* Writes a Buffer to an HTTP response body.
* <p>
* This method also sets the <em>content-length</em> and <em>content-type</em>
* headers of the HTTP response accordingly but does not end the response.
* <p>
* If the response is already ended or closed or the buffer is {@code null}, this method
* does nothing.
*
* @param response The HTTP response.
* @param buffer The Buffer to set as the response body (may be {@code null}).
* @param contentType The type of the content. If {@code null}, a default value of
* {@link #CONTENT_TYPE_OCTET_STREAM} will be used.
* @throws NullPointerException if response is {@code null}.
*/
public static void setResponseBody(final HttpServerResponse response, final Buffer buffer, final String contentType) {
Objects.requireNonNull(response);
if (!response.ended() && !response.closed() && buffer != null) {
if (contentType == null) {
response.putHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_OCTET_STREAM);
} else {
response.putHeader(HttpHeaders.CONTENT_TYPE, contentType);
}
response.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(buffer.length()));
response.write(buffer);
}
}