@Override public R2ResponseStatus handleResponse(Request<RestRequest> request, RestResponse response) { R2ResponseStatus status = new R2ResponseStatus(StatusType.OK); int statusCode = response.getStatus(); status.setStatusCode(statusCode); HttpUtils.updateStatusType(status, statusCode, errorCodeWhitelist); if (status.getType() == StatusType.OK) { status.setContent(response.getEntity()); status.setContentType(response.getHeader(CONTENT_TYPE_HEADER)); } else { log.info("Receive an unsuccessful response with status code: " + statusCode); Map<String, String> metadata = Maps.newHashMap(); metadata.put(HttpConstants.STATUS_CODE, String.valueOf(statusCode)); metadata.put(HttpConstants.REQUEST, request.toString()); if (status.getType() != StatusType.CONTINUE) { FailureEventBuilder failureEvent = new FailureEventBuilder(R2_FAILED_REQUEST_EVENT); failureEvent.addAdditionalMetadata(metadata); failureEvent.submit(metricsContext); } else { GobblinTrackingEvent event = new GobblinTrackingEvent(0L, R2_RESPONSE_EVENT_NAMESPACE, R2_FAILED_REQUEST_EVENT, metadata); metricsContext.submitEvent(event); } } return status; } }
String compressionHeader = res.getHeader(HttpConstants.CONTENT_ENCODING); if (compressionHeader != null && res.getEntity().length() > 0) byte[] inflated = encoding.getCompressor().inflate(res.getEntity().asInputStream()); Map<String, String> headers = new HashMap<String, String>(res.getHeaders()); headers.remove(HttpConstants.CONTENT_ENCODING); headers.put(HttpConstants.CONTENT_LENGTH, Integer.toString(inflated.length)); res = res.builder().setEntity(inflated).setHeaders(headers).build();
@Override public void onResponse(RestResponse restResponse, RequestContext requestContext, Map<String, String> wireAttrs) { String header = restResponse.getHeader(_headerName); Assert.assertEquals(header, _expectedValue); if (_entityLength > 0) { Assert.assertEquals(restResponse.getEntity().length(), _entityLength); } }
public Response<T> decodeResponse(RestResponse restResponse) throws RestLiDecodingException { return createResponse(restResponse.getHeaders(), restResponse.getStatus(), restResponse.getEntity(), restResponse.getCookies()); }
public String getStoreClientConfigString(List<String> storeNames, String coordinatorUrl) { try { // Create the REST request StringBuilder URIStringBuilder = new StringBuilder().append(coordinatorUrl) .append(URL_SEPARATOR) .append(STORE_CLIENT_CONFIG_OPS) .append(URL_SEPARATOR) .append(Joiner.on(",") .join(storeNames)); RestRequestBuilder requestBuilder = new RestRequestBuilder(new URI(URIStringBuilder.toString())); String timeoutStr = Long.toString(this.config.getTimeoutConfig() .getOperationTimeout(VoldemortOpCode.GET_OP_CODE)); requestBuilder.setMethod(requestType.GET.toString()); requestBuilder.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr); requestBuilder = setCommonRequestHeader(requestBuilder); RestRequest request = requestBuilder.build(); Future<RestResponse> future = client.restRequest(request); // This will block RestResponse response = future.get(); ByteString entity = response.getEntity(); return entity.asString("UTF-8"); } catch(Exception e) { if(e.getCause() instanceof RestException) { return ((RestException) e.getCause()).getResponse().getEntity().asString("UTF-8"); } handleRequestAndResponseException(e); } return null; }
private static IndividualResponse toIndividualResponse(String id, RestResponse restResponse) throws MimeTypeParseException, IOException { IndividualResponse individualResponse = new IndividualResponse(); individualResponse.setStatus(restResponse.getStatus()); individualResponse.setHeaders(new StringMap(restResponse.getHeaders())); ByteString entity = restResponse.getEntity(); if (!entity.isEmpty()) { // TODO Avoid converting bytes to datamap here. Individual response should have only the bytes. individualResponse.setBody(new IndividualBody(DataMapConverter.bytesToDataMap(restResponse.getHeaders(), entity))); } return individualResponse; }
private void handleRequestAndResponseException(Exception e) { if(e instanceof ExecutionException) { if(e.getCause() instanceof RestException) { RestException re = (RestException) e.getCause(); if(logger.isDebugEnabled()) { logger.debug("REST Exception Status: " + re.getResponse().getStatus()); } } else { throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e); } } else if(e instanceof InterruptedException) { if(logger.isDebugEnabled()) { logger.debug("Operation interrupted : " + e.getMessage(), e); } throw new VoldemortException("Operation interrupted exception: " + e.getMessage(), e); } else if(e instanceof URISyntaxException) { throw new VoldemortException("Illegal HTTP URL " + e.getMessage(), e); } else if(e instanceof UnsupportedEncodingException) { throw new VoldemortException("Illegal Encoding Type " + e.getMessage(), e); } else { throw new VoldemortException("Unknown exception: " + e.getMessage(), e); } }
if (res.getEntity().length() > 0) res.getEntity().length() > (Integer) requestContext.getLocalAttr(HttpConstants.HEADER_RESPONSE_COMPRESSION_THRESHOLD)) byte[] compressed = compressor.deflate(res.getEntity().asInputStream()); if (compressed.length < res.getEntity().length()) RestResponseBuilder resCompress = res.builder(); resCompress.addHeaderValue(HttpConstants.CONTENT_ENCODING, compressor.getContentEncodingName()); resCompress.setEntity(compressed); res = res.builder().setStatus(HttpConstants.NOT_ACCEPTABLE).setEntity(new byte[0]).build();
public String getErrorSource() { RestResponse response = getResponse(); return HeaderUtil.getErrorResponseHeaderValue(response.getHeaders()); }
@SuppressWarnings("unchecked") private Response<T> createResponseFromError(RestLiResponseException restLiResponseException) throws RemoteInvocationException { Response<T> response = null; // If the exception contains a decoded response, we use it. Otherwise we do manual response // creation which will not have an entity. if (restLiResponseException.hasDecodedResponse()) { response = new ResponseImpl<T>( (Response<T>) restLiResponseException.getDecodedResponse(), restLiResponseException); } else { response = new ResponseImpl<T>( restLiResponseException.getStatus(), restLiResponseException.getResponse().getHeaders(), CookieUtil.decodeSetCookies(restLiResponseException.getResponse().getCookies()), restLiResponseException); } return response; }
@Override protected Promise<? extends IndividualResponseWithCookies> run(Context context) throws Throwable { if (_restResponse.isFailed()) { return Promises.value(toErrorIndividualResponse(_restResponse.getError(), _errorResponseBuilder)); } try { RestResponse restResponse = _restResponse.get(); IndividualResponse response = toIndividualResponse(_restResponseId, restResponse); return Promises.value(new IndividualResponseWithCookies(response, restResponse.getCookies())); } catch (MimeTypeParseException e) { return Promises.value(createInternalServerErrorResponse("Invalid content type for individual response: " + _restResponseId, _errorResponseBuilder)); } catch (IOException e) { return Promises.value(createInternalServerErrorResponse("Unable to set body for individual response: " + _restResponseId, _errorResponseBuilder)); } catch(Exception e) { return Promises.value(toErrorIndividualResponse(e, _errorResponseBuilder)); } }
private void writeResponse(Channel ch, TransportResponse<StreamResponse> response, RestResponse restResponse) { RestResponseBuilder responseBuilder = restResponse.builder() .unsafeOverwriteHeaders(WireAttributeHelper.toWireAttributes(response.getWireAttributes())); ch.writeAndFlush(responseBuilder.build()); }
private static StreamResponse createStreamResponseWithAttachment(RestResponse structuredFirstPart, RestLiResponseAttachments attachments) { //Construct the StreamResponse and invoke the callback. The RestResponse entity should be the first part. //There may potentially be attachments included in the response. Note that unlike the client side request builders, //here it is possible to have a non-null attachment list with 0 attachments due to the way the builder in //RestLiResponseAttachments works. Therefore we have to make sure its a non zero size as well. final ByteStringWriter firstPartWriter = new ByteStringWriter(structuredFirstPart.getEntity()); final MultiPartMIMEWriter multiPartMIMEWriter = AttachmentUtils.createMultiPartMIMEWriter(firstPartWriter, structuredFirstPart.getHeader(RestConstants.HEADER_CONTENT_TYPE), attachments.getMultiPartMimeWriterBuilder()); //Ensure that any headers or cookies from the RestResponse make into the outgoing StreamResponse. The exception //of course being the Content-Type header which will be overridden by MultiPartMIMEStreamResponseFactory. return MultiPartMIMEStreamResponseFactory.generateMultiPartMIMEStreamResponse(AttachmentUtils.RESTLI_MULTIPART_SUBTYPE, multiPartMIMEWriter, Collections.emptyMap(), structuredFirstPart.getHeaders(), structuredFirstPart.getStatus(), structuredFirstPart.getCookies()); }
public RestLiResponseException(RestResponse rawResponse, Response<?> decodedResponse, ErrorResponse errorResponse) { super(rawResponse); _status = rawResponse.getStatus(); _errorResponse = errorResponse; _decodedResponse = decodedResponse; }
if (res.getEntity().length() > 0) res.getEntity().length() > (Integer) requestContext.getLocalAttr(HttpConstants.HEADER_RESPONSE_COMPRESSION_THRESHOLD)) byte[] compressed = compressor.deflate(res.getEntity().asInputStream()); if (compressed.length < res.getEntity().length()) RestResponseBuilder resCompress = res.builder(); resCompress.addHeaderValue(HttpConstants.CONTENT_ENCODING, compressor.getContentEncodingName()); resCompress.setEntity(compressed); res = res.builder().setStatus(HttpConstants.NOT_ACCEPTABLE).setEntity(new byte[0]).build();
@Override protected void channelRead0(ChannelHandlerContext ctx, RestResponse response) throws Exception { final Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); headers.putAll(response.getHeaders()); final Map<String, String> wireAttrs = WireAttributeHelper.removeWireAttributes(headers); final RestResponse newResponse = new RestResponseBuilder(response) .unsafeSetHeaders(headers) .build(); // In general there should always be a callback to handle a received message, // but it could have been removed due to a previous exception or closure on the // channel TransportCallback<RestResponse> callback = ctx.channel().attr(CALLBACK_ATTR_KEY).getAndSet(null); if (callback != null) { LOG.debug("{}: handling a response", ctx.channel().remoteAddress()); callback.onResponse(TransportResponseImpl.success(newResponse, wireAttrs)); } else { LOG.debug("{}: dropped a response", ctx.channel().remoteAddress()); } ctx.fireChannelRead(response); }
protected void encode(ChannelHandlerContext ctx, RestResponse response, List<Object> out) throws Exception { final ByteString entity = response.getEntity(); ByteBuf content = Unpooled.wrappedBuffer(entity.asByteBuffer()); HttpResponse nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(response.getStatus()), content); for (Map.Entry<String, String> e : response.getHeaders().entrySet()) { nettyResponse.headers().set(e.getKey(), e.getValue()); } nettyResponse.headers().set(HttpConstants.RESPONSE_COOKIE_HEADER_NAME, response.getCookies()); nettyResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, entity.length()); out.add(nettyResponse); } }