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

The following examples show how to use io.vertx.core.http.HttpServerResponse#setChunked() . 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: NexusHttpProxy.java    From nexus-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Proxies the specified HTTP request, enriching its headers with authentication information.
 *
 * @param userId  the ID of the user making the request.
 * @param origReq the original request (i.e., {@link RoutingContext#request()}.
 * @param origRes the original response (i.e., {@link RoutingContext#request()}.
 */
public void proxyUserRequest(final String userId,
                             final HttpServerRequest origReq,
                             final HttpServerResponse origRes) {
    final Handler<HttpClientResponse> proxiedResHandler = proxiedRes -> {
        origRes.setChunked(true);
        origRes.setStatusCode(proxiedRes.statusCode());
        origRes.headers().setAll(proxiedRes.headers());
        proxiedRes.handler(origRes::write);
        proxiedRes.endHandler(v -> origRes.end());
    };

    final HttpClientRequest proxiedReq;
    proxiedReq = httpClient.request(origReq.method(), port, host, origReq.uri(), proxiedResHandler);
    if(origReq.method() == HttpMethod.OTHER) {
        proxiedReq.setRawMethod(origReq.rawMethod());
    }
    proxiedReq.setChunked(true);
    proxiedReq.headers().add(X_FORWARDED_PROTO, getHeader(origReq, X_FORWARDED_PROTO, origReq.scheme()));
    proxiedReq.headers().add(X_FORWARDED_FOR, getHeader(origReq, X_FORWARDED_FOR, origReq.remoteAddress().host()));
    proxiedReq.headers().addAll(origReq.headers());
    injectRutHeader(proxiedReq, userId);
    origReq.handler(proxiedReq::write);
    origReq.endHandler(v -> proxiedReq.end());
}
 
Example 2
Source File: ProxyService.java    From okapi with Apache License 2.0 6 votes vote down vote up
private void relayToResponse(HttpServerResponse hres,
                             HttpClientResponse res, ProxyContext pc) {
  if (pc.getHandlerRes() != 0) {
    hres.setStatusCode(pc.getHandlerRes());
    hres.headers().addAll(pc.getHandlerHeaders());
  } else if (pc.getAuthRes() != 0 && (pc.getAuthRes() < 200 || pc.getAuthRes() >= 300)) {
    hres.setStatusCode(pc.getAuthRes());
    hres.headers().addAll(pc.getAuthHeaders());
  } else {
    if (res != null) {
      hres.setStatusCode(res.statusCode());
      hres.headers().addAll(res.headers());
    }
  }
  sanitizeAuthHeaders(hres.headers());
  hres.headers().remove("Content-Length");
  hres.headers().remove("Transfer-Encoding");
  if (hres.getStatusCode() != 204) {
    hres.setChunked(true);
  }
}
 
Example 3
Source File: RestVerticle.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: ApiManagementEndpoint.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();

    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();
}
 
Example 5
Source File: ApisManagementEndpoint.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 {
        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();
}
 
Example 6
Source File: SSEHandlerImpl.java    From vertx-sse with Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example 7
Source File: ApiKeysServiceHandler.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 8
Source File: ApiKeyHandler.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();

    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();
}
 
Example 9
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 10
Source File: ApiSubscriptionsHandler.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();

    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();
}
 
Example 11
Source File: SyncHandler.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 12
Source File: HttpPolicyAdapter.java    From apiman with Apache License 2.0 5 votes vote down vote up
private void handlePolicyFailure(ApiRequest apimanRequest, PolicyFailure policyFailure, HttpServerResponse vertxResponse) {
    vertxResponse.setChunked(true);
    policyFailureWriter.write(apimanRequest, policyFailure, new IApiClientResponse() {

        @Override
        public void write(StringBuffer buffer) {
            vertxRequest.resume();
            vertxResponse.end(buffer.toString());
        }

        @Override
        public void write(StringBuilder builder) {
            vertxRequest.resume();
            vertxResponse.end(builder.toString());
        }

        @Override
        public void write(String body) {
            vertxRequest.resume();
            vertxResponse.end(body);
        }

        @Override
        public void setStatusCode(int code) {
            vertxResponse.setStatusCode(code);
        }

        @Override
        public void setHeader(String headerName, String headerValue) {
            vertxResponse.putHeader(headerName, headerValue);
        }
    });
}
 
Example 13
Source File: HttpPolicyAdapter.java    From apiman with Apache License 2.0 5 votes vote down vote up
private void handleError(ApiRequest apimanRequest, Throwable error, HttpServerResponse vertxResponse) {
    vertxResponse.setChunked(true);
    policyErrorWriter.write(apimanRequest, error, new IApiClientResponse() {

        @Override
        public void write(StringBuffer buffer) {
            vertxRequest.resume();
            vertxResponse.end(buffer.toString());
        }

        @Override
        public void write(StringBuilder builder) {
            vertxRequest.resume();
            vertxResponse.end(builder.toString());
        }

        @Override
        public void write(String body) {
            vertxRequest.resume();
            vertxResponse.end(body);
        }

        @Override
        public void setStatusCode(int code) {
            vertxResponse.setStatusCode(code);
        }

        @Override
        public void setHeader(String headerName, String headerValue) {
            vertxResponse.putHeader(headerName, headerValue);
        }
    });
}
 
Example 14
Source File: XhrTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
final void beforeSend() {
  if (log.isTraceEnabled()) log.trace("XHR sending frame");
  if (!headersWritten) {
    HttpServerResponse resp = rc.response();
    resp.putHeader(HttpHeaders.CONTENT_TYPE, "application/javascript; charset=UTF-8");
    setJSESSIONID(options, rc);
    setCORS(rc);
    if (rc.request().version() != HttpVersion.HTTP_1_0) {
      resp.setChunked(true);
    }
    // NOTE that this is streaming!!!
    // Client are not expecting to see Content-Length as we don't know it's value
    headersWritten = true;
  }
}
 
Example 15
Source File: HttpResponseFactory.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public void create(
    final HttpServerRequest httpRequest, final int statusCode, final JsonRpcResponse body) {
  final HttpServerResponse response = httpRequest.response();

  response.putHeader("Content", JSON);
  response.setStatusCode(statusCode);
  response.setChunked(false);
  response.end(Json.encodeToBuffer(body));
}
 
Example 16
Source File: PgUtil.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
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);
  });
}
 
Example 17
Source File: KeepAliveHttpServerResponse.java    From sfs with Apache License 2.0 5 votes vote down vote up
public KeepAliveHttpServerResponse(VertxContext<Server> vertxContext, long timeout, TimeUnit timeUnit, HttpServerResponse delegate) {
    this.vertxContext = vertxContext;
    this.delegate = delegate;
    this.timeout = timeUnit.toMillis(timeout);
    delegate.setChunked(true);
    delegate.exceptionHandler(exception -> {
        ObservableFuture<Void> handler = RxHelper.observableFuture();
        stopKeepAlive(handler);
        handler.subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                handleThrowable(exception);
            }

            @Override
            public void onError(Throwable e) {
                handleThrowable(new CompositeException(exception, e));
            }

            @Override
            public void onNext(Void aVoid) {

            }
        });
    });
    startKeepAlive();
}
 
Example 18
Source File: MultipleFiltersController.java    From nubes with Apache License 2.0 4 votes vote down vote up
@BeforeFilter(1)
public void before2(HttpServerResponse response) {
	response.setChunked(true);
	response.write("before1;");
}
 
Example 19
Source File: QuarkusPlatformHttpConsumer.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
static Object toHttpResponse(HttpServerResponse response, Message message, HeaderFilterStrategy headerFilterStrategy) {
    final Exchange exchange = message.getExchange();

    final int code = determineResponseCode(exchange, message.getBody());
    response.setStatusCode(code);

    final TypeConverter tc = exchange.getContext().getTypeConverter();

    // copy headers from Message to Response
    if (headerFilterStrategy != null) {
        for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();
            // use an iterator as there can be multiple values. (must not use a delimiter)
            final Iterator<?> it = ObjectHelper.createIterator(value, null);
            String firstValue = null;
            List<String> values = null;
            while (it.hasNext()) {
                final String headerValue = tc.convertTo(String.class, it.next());
                if (headerValue != null
                        && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, exchange)) {
                    if (firstValue == null) {
                        firstValue = headerValue;
                    } else {
                        if (values == null) {
                            values = new ArrayList<String>();
                            values.add(firstValue);
                        }
                        values.add(headerValue);
                    }
                }
            }
            if (values != null) {
                response.putHeader(key, values);
            } else if (firstValue != null) {
                response.putHeader(key, firstValue);
            }
        }
    }

    Object body = message.getBody();
    final Exception exception = exchange.getException();

    if (exception != null) {
        // we failed due an exception so print it as plain text
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);

        // the body should then be the stacktrace
        body = ByteBuffer.wrap(sw.toString().getBytes(StandardCharsets.UTF_8));
        // force content type to be text/plain as that is what the stacktrace is
        message.setHeader(Exchange.CONTENT_TYPE, "text/plain; charset=utf-8");

        // and mark the exception as failure handled, as we handled it by returning it as the response
        ExchangeHelper.setFailureHandled(exchange);
    }

    // set the content-length if it can be determined, or chunked encoding
    final Integer length = determineContentLength(exchange, body);
    if (length != null) {
        response.putHeader("Content-Length", String.valueOf(length));
    } else {
        response.setChunked(true);
    }

    // set the content type in the response.
    final String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        response.putHeader("Content-Type", contentType);
    }
    return body;
}