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

The following examples show how to use io.vertx.core.http.HttpServerResponse#ended() . 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: HttpStatusAccessItem.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void appendServerFormattedItem(ServerAccessLogEvent accessLogEvent, StringBuilder builder) {
  HttpServerResponse response = accessLogEvent.getRoutingContext().response();
  if (null == response) {
    builder.append(EMPTY_RESULT);
    return;
  }
  if (response.closed() && !response.ended()) {
    LOGGER.warn(
        "Response is closed before sending any data. "
            + "Please check idle connection timeout for provider is properly configured.");
    builder.append(EMPTY_RESULT);
    return;
  }
  builder.append(response.getStatusCode());
}
 
Example 2
Source File: RestRouter.java    From rest.vertx with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static void produceResponse(Object result,
                                    RoutingContext context,
                                    RouteDefinition definition,
                                    HttpResponseWriter writer) throws Throwable {

	HttpServerResponse response = context.response();
	HttpServerRequest request = context.request();
	MediaType accept = MediaTypeHelper.valueOf(request.getHeader(HttpHeaders.ACCEPT));

	// add default response headers per definition (or from writer definition)
	writer.addResponseHeaders(definition, accept, response);
	writer.write(result, request, response);

	// find and trigger events from // result / response
	eventExecutor.triggerEvents(result, response.getStatusCode(), definition, context, injectionProvider);

	// finish if not finished by writer
	// and is not an Async REST (Async RESTs must finish responses on their own)
	if (!definition.isAsync() && !response.ended()) {
		response.end();
	}
}
 
Example 3
Source File: EchoServerVertx.java    From apiman with Apache License 2.0 5 votes vote down vote up
private void handleError(HttpServerResponse rep, Throwable e) {
    log.error(e);
    if (!rep.ended()) {
        rep.setStatusCode(500);
        rep.end();
    }
}
 
Example 4
Source File: AbstractEdgeDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
protected void onFailure(RoutingContext context) {
  LOGGER.error("edge server failed.", context.failure());
  HttpServerResponse response = context.response();
  if (response.closed() || response.ended()) {
    return;
  }

  if (context.failure() instanceof InvocationException) {
    InvocationException exception = (InvocationException) context.failure();
    response.setStatusCode(exception.getStatusCode());
    response.setStatusMessage(exception.getReasonPhrase());
    if (null == exception.getErrorData()) {
      response.end();
      return;
    }

    String responseBody;
    try {
      responseBody = RestObjectMapperFactory.getRestObjectMapper().writeValueAsString(exception.getErrorData());
      response.putHeader("Content-Type", MediaType.APPLICATION_JSON);
    } catch (JsonProcessingException e) {
      responseBody = exception.getErrorData().toString();
      response.putHeader("Content-Type", MediaType.TEXT_PLAIN);
    }
    response.end(responseBody);
  } else {
    response.setStatusCode(Status.BAD_GATEWAY.getStatusCode());
    response.setStatusMessage(Status.BAD_GATEWAY.getReasonPhrase());
    response.end();
  }
}
 
Example 5
Source File: DefaultErrorHandler.java    From nubes with Apache License 2.0 5 votes vote down vote up
private void handleHttpError(RoutingContext context, HttpServerResponse response, PayloadMarshaller marshaller) {
  final int status = context.statusCode();
  response.setStatusCode(status);
  String msg = errorMessages.getOrDefault(status, "Internal server error");
  if (context.get(ERROR_DETAILS) != null) {
    msg = context.get(ERROR_DETAILS);
  }
  if (marshaller != null) {
    response.end(marshaller.marshallHttpStatus(status, msg));
  } else {
    if (!response.ended()) {
      response.end(msg);
    }
  }
}
 
Example 6
Source File: PayloadTypeProcessor.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
public void afterAll(RoutingContext context) {
  Payload<?> payload = context.get(Payload.DATA_ATTR);
  HttpServerResponse response = context.response();
  if (response.ended()) {
    return;
  }
  Object userPayload = payload.get();
  if (userPayload == null) {
    response.setStatusCode(204);
    response.end();
  } else {
    String contentType = ContentTypeProcessor.getContentType(context);
    if (contentType == null) {
      context.fail(new IllegalArgumentException("No content-type defined, cannot marshall payload"));
      return;
    }
    PayloadMarshaller marshaller = marshallers.get(contentType);
    if (marshaller == null) {
      context.fail(new IllegalArgumentException("No marshaller found for content-type : " + contentType));
      return;
    }
    String marshalled = marshaller.marshallPayload(userPayload);
    response.setStatusCode(200);
    response.end(marshalled);
  }
}
 
Example 7
Source File: ExecuteRSString.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 8
Source File: ExecuteRSString.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Override
protected void respond(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 9
Source File: ExecuteRSString.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Override
protected void checkAndCloseResponse(int retry) {
  final HttpServerResponse response = context.response();
  if (retry == 0 && !response.ended()) {
    response.end();
  }
}
 
Example 10
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 11
Source File: ExecuteRSByte.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Override
protected void respond(byte[] result, int statuscode) {
  final HttpServerResponse response = context.response();
  if (!response.ended()) {
    ResponseExecution.updateHeaderAndStatuscode(headers, statuscode, response);
    if (result != null) {
      response.end(Buffer.buffer(result));
    } else {
      response.end();
    }
  }
}
 
Example 12
Source File: ExecuteRSByte.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Override
protected void checkAndCloseResponse(int retry) {
  final HttpServerResponse response = context.response();
  if (retry == 0 && !response.ended()) {
    response.end();
  }
}
 
Example 13
Source File: ExecuteRSObject.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Override
protected void respond(Serializable result, int statuscode) {
  final HttpServerResponse response = context.response();
  if (!response.ended()) {
    ResponseExecution.updateHeaderAndStatuscode(headers, statuscode, response);
    if (result != null) {
      ResponseExecution.encode(result, encoder)
          .ifPresent(value -> ResponseExecution.sendObjectResult(value, context.response()));
    } else {
      response.end();
    }
  }
}
 
Example 14
Source File: ExecuteRSObject.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Override
protected void respond(Serializable result) {
  final HttpServerResponse response = context.response();
  if (!response.ended()) {
    ResponseExecution.updateHeaderAndStatuscode(headers, httpStatusCode, response);
    if (result != null) {
      ResponseExecution.encode(result, encoder)
          .ifPresent(value -> ResponseExecution.sendObjectResult(value, context.response()));
    } else {
      response.end();
    }
  }
}
 
Example 15
Source File: ExecuteRSObject.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 16
Source File: ExecuteRSObject.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Override
protected void checkAndCloseResponse(int retry) {
  final HttpServerResponse response = context.response();
  if (retry == 0 && !response.ended()) {
    response.end();
  }
}
 
Example 17
Source File: HystrixMetricEventStream.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
private static void endQuietly(HttpServerResponse response) {
  if (response.ended()) {
    return;
  }
  try {
    response.end();
  } catch (IllegalStateException e) {
    // Ignore it.
  }
}
 
Example 18
Source File: RestRouter.java    From rest.vertx with Apache License 2.0 4 votes vote down vote up
private static void handleException(Throwable e, RoutingContext context, final RouteDefinition definition) {

		ExecuteException ex = getExecuteException(e);

		// get appropriate exception handler/writer ...
		ExceptionHandler handler;
		try {
			Class<? extends Throwable> clazz;
			if (ex.getCause() == null) {
				clazz = ex.getClass();
			} else {
				clazz = ex.getCause().getClass();
			}

			Class<? extends ExceptionHandler>[] exHandlers = null;
			if (definition != null) {
				exHandlers = definition.getExceptionHandlers();
			}

			handler = handlers.getExceptionHandler(clazz, exHandlers, injectionProvider, context);
		}
		catch (ClassFactoryException classException) {
			// Can't provide exception handler ... rethrow
			log.error("Can't provide exception handler!", classException);
			// fall back to generic ...
			handler = new GenericExceptionHandler();
			ex = new ExecuteException(500, classException);
		}
		catch (ContextException contextException) {
			// Can't provide @Context for handler ... rethrow
			log.error("Can't provide @Context!", contextException);
			// fall back to generic ...
			handler = new GenericExceptionHandler();
			ex = new ExecuteException(500, contextException);
		}

		if (handler instanceof GenericExceptionHandler) {
			log.error("Handling exception: ", e);
		}
		else {
			log.debug("Handling exception, with: " + handler.getClass().getName(), e);
		}

		HttpServerResponse response = context.response();
		response.setStatusCode(ex.getStatusCode());

		HttpServerRequest request = context.request();
		MediaType accept = MediaTypeHelper.valueOf(request.getHeader(HttpHeaders.ACCEPT));

		handler.addResponseHeaders(definition, accept, response);

		try {
			handler.write(ex.getCause(), request, response);

			eventExecutor.triggerEvents(ex.getCause(), response.getStatusCode(), definition, context, injectionProvider);
		}
		catch (Throwable handlerException) {
			// this should not happen
			log.error("Failed to write out handled exception: " + e.getMessage(), e);
		}

		// end response ...
		if (!response.ended()) {
			response.end();
		}
	}
 
Example 19
Source File: HttpResponseWriter.java    From rest.vertx with Apache License 2.0 4 votes vote down vote up
/**
 * @param definition route definition
 * @param requestMediaType client requested media type .. accept header or null for all
 * @param response response to add response headers
 */
default void addResponseHeaders(RouteDefinition definition, MediaType requestMediaType, HttpServerResponse response) {

	if (!response.ended()) {


		Map<String, String> headers = new HashMap<>();

		// collect all headers to put into response ...

		// 1. add definition headers
		headers = join(headers, definition.getHeaders());

		// 2. add REST produces
		headers = join(headers, requestMediaType, definition.getProduces());

		// 3. add / override Writer headers
		Header writerHeader = this.getClass().getAnnotation(Header.class);
		if (writerHeader != null && writerHeader.value().length > 0) {
			headers = join(headers, AnnotationProcessor.getNameValuePairs(writerHeader.value()));
		}

		// 4. add / override with Writer produces
		Produces writerProduces = this.getClass().getAnnotation(Produces.class);
		if (writerProduces != null && writerProduces.value().length > 0) {
			headers = join(headers, requestMediaType, MediaTypeHelper.getMediaTypes(writerProduces.value()));
		}

		// 5. add wildcard if no content-type present
		if (!headers.containsKey(HttpHeaders.CONTENT_TYPE.toString())) {
			headers.put(HttpHeaders.CONTENT_TYPE.toString(), MediaType.WILDCARD);
		}

		String selectedContentType = headers.get(HttpHeaders.CONTENT_TYPE.toString());
		if (requestMediaType == null) {
			log.trace("No 'Accept' header present in request using first @Produces Content-Type='" + selectedContentType + "', for: " + definition.getPath());
		}
		else {
			log.trace("Selected Content-Type='" + selectedContentType + "', for: " + definition.getPath());
		}

		// add all headers not present in response
		for (String name : headers.keySet()) {
			if (!response.headers().contains(name)) {
				response.headers().add(name, headers.get(name));
			}
		}
	}
}
 
Example 20
Source File: HttpUtils.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * 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);
    }
}