headers.remove(HttpConstants.CONTENT_ENCODING); headers.put(HttpConstants.CONTENT_LENGTH, Integer.toString(inflated.length)); res = res.builder().setEntity(inflated).setHeaders(headers).build();
RestResponse restResponse = new RestResponseBuilder().setStatus(HttpConstants.UNSUPPORTED_MEDIA_TYPE).build(); nextFilter.onError(new RestException(restResponse, e), requestContext, wireAttrs);
@Test(dataProvider = "headersData") public void testResponseCompressionRules(String acceptEncoding, int compressionThreshold, EncodingType expectedContentEncoding) throws CompressionException, URISyntaxException { ServerCompressionFilter serverCompressionFilter = new ServerCompressionFilter(ACCEPT_COMPRESSIONS); RequestContext context = new RequestContext(); context.putLocalAttr(HttpConstants.ACCEPT_ENCODING, acceptEncoding); context.putLocalAttr(HttpConstants.HEADER_RESPONSE_COMPRESSION_THRESHOLD, compressionThreshold); int originalLength = 100; byte[] entity = new byte[originalLength]; Arrays.fill(entity, (byte) 'A'); int compressedLength = (expectedContentEncoding == null) ? originalLength : expectedContentEncoding.getCompressor().deflate(new ByteArrayInputStream(entity)).length; String expectedContentEncodingName = (expectedContentEncoding == null) ? null : expectedContentEncoding.getHttpName(); RestResponse restResponse = new RestResponseBuilder().setEntity(entity).build(); serverCompressionFilter.onRestResponse(restResponse, context, Collections.<String, String>emptyMap(), new HeaderCaptureFilter(HttpConstants.CONTENT_ENCODING, expectedContentEncodingName, compressedLength)); } }
public static RestResponse simpleRestResponse() { return new RestResponseBuilder() .build(); }
private void writeResponse(Channel ch, TransportResponse<StreamResponse> response, RestResponse restResponse) { RestResponseBuilder responseBuilder = restResponse.builder() .unsafeOverwriteHeaders(WireAttributeHelper.toWireAttributes(response.getWireAttributes())); ch.writeAndFlush(responseBuilder.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); }
@Override public void onSuccess(ByteString result) { if (addContentLengthHeader) { builder.setHeader(HttpConstants.CONTENT_LENGTH, String.valueOf(result.length())); } RestResponse restResponse = builder.setEntity(result).build(); callback.onSuccess(restResponse); } };
private static RestResponse createErrorRestResponse(ErrorResponse errorResponse) { RestResponseBuilder builder = new RestResponseBuilder().setStatus(errorResponse.getStatus()); String errorMessage = errorResponse.getMessage(); if (errorMessage != null) { builder.setEntity(errorMessage.getBytes()); } return builder.build(); } }
private void writeError(Channel ch, TransportResponse<StreamResponse> response, Throwable ex) { RestResponseBuilder responseBuilder = new RestResponseBuilder(RestStatus.responseForError(RestStatus.INTERNAL_SERVER_ERROR, ex)) .unsafeOverwriteHeaders(WireAttributeHelper.toWireAttributes(response.getWireAttributes())); ch.writeAndFlush(responseBuilder.build()); }
/** * Return a new {@link RestResponse} message with the specified status code. * * @param status the status code to use for the response message. * @param detail a detail message to be included as the body of the {@link RestResponse}. * @return a new {@link RestResponse} constructed as described above. */ public static RestResponse responseForStatus(int status, String detail) { if (detail == null) { detail = "No detailed message"; } // TODO: set charset in Content-Type header return new RestResponseBuilder() .setStatus(status) .setEntity(detail.getBytes(UTF8)) .setHeader("Content-Type", "text/plain") .build(); }
@Override public Greeting call() throws Exception { throw new RestException(new RestResponseBuilder().setStatus(401).build()); } });
/** * @return {@link RestResponse} based on this exception */ public RestResponse buildRestResponse() { RestResponseBuilder builder = new RestResponseBuilder().setStatus(_status); if (getMessage() != null) { builder.setEntity(ByteString.copyString(getMessage(), Charset.defaultCharset())); } return builder.build(); } }
@Override public RestResponse readRestResponse(InputStream in) throws IOException { final RestResponseBuilder builder = new RestResponseBuilder(); readResLine(builder, in); readHeaders(builder, in, HttpConstants.RESPONSE_COOKIE_HEADER_NAME); builder.setEntity(readEntity(in)); return builder.build(); }
@Override public void onResponse(TransportResponse<RestResponse> response) { final RestResponseBuilder responseBuilder; if (response.hasError()) { // This onError is only getting called in cases where: // (1) the exception was thrown by the handleRequest() method, and the upper layer // dispatcher did not catch the exception or caught it and passed it here without // turning it into a Response, or // (2) the HttpBridge-installed callback's onError declined to convert the exception to a // response and passed it along to here. responseBuilder = new RestResponseBuilder(RestStatus.responseForError(RestStatus.INTERNAL_SERVER_ERROR, response.getError())); } else { responseBuilder = new RestResponseBuilder(response.getResponse()); } responseBuilder .unsafeOverwriteHeaders(WireAttributeHelper.toWireAttributes(response.getWireAttributes())) .build(); ch.writeAndFlush(responseBuilder.build()); } };
private static RestResponse aggregateResponses(IndividualResponseMap responses, Map<String, HttpCookie> responseCookies) { MultiplexedResponseContent aggregatedResponseContent = new MultiplexedResponseContent(); aggregatedResponseContent.setResponses(responses); byte[] aggregatedResponseData = DataMapUtils.mapToBytes(aggregatedResponseContent.data()); return new RestResponseBuilder() .setStatus(HttpStatus.S_200_OK.getCode()) .setEntity(aggregatedResponseData) .setCookies(CookieUtil.encodeSetCookies(new ArrayList<>(responseCookies.values()))) .build(); } }
@Action(name = "callback") public void callback(@ActionParam(value = "id") final String key, @CallbackParam final Callback<Greeting> callback) { // Non-RestLiServiceException passed to callback if (key.equals("returnNonService")) { callback.onError(new RestException(new RestResponseBuilder().setStatus(401).build())); } // RestLiServiceException passed to callback if (key.equals("returnService")) { callback.onError(new RestLiServiceException(HttpStatus.S_401_UNAUTHORIZED)); } //RestLiServiceException thrown if (key.equals("throwService")) { throw new RestLiServiceException(HttpStatus.S_401_UNAUTHORIZED); } if (key.equals("throwNonService")) { // Non-RestLiServiceException thrown throw new IllegalStateException(); } callback.onSuccess(new Greeting()); } }
public static RestException buildRestException(RestLiResponseException restLiResponseException) { RestLiResponse restLiResponse = restLiResponseException.getRestLiResponse(); RestResponseBuilder responseBuilder = new RestResponseBuilder() .setHeaders(restLiResponse.getHeaders()) .setCookies(CookieUtil.encodeSetCookies(restLiResponse.getCookies())) .setStatus(restLiResponse.getStatus().getCode()); if (restLiResponse.hasData()) { DataMap dataMap = restLiResponse.getDataMap(); ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); DataMapUtils.write(dataMap, null, baos, true); responseBuilder.setEntity(ByteString.unsafeWrap(baos.toByteArray())); // TODO: Error response not always built in requested content type. responseBuilder.setHeader(RestConstants.HEADER_CONTENT_TYPE, ContentType.JSON.getHeaderKey()); } RestResponse restResponse = responseBuilder.build(); return new RestException(restResponse, restLiResponseException.getCause()); }
private static RestResponse buildIndividualRestResponse(Response<?> envelopeResponse, IndividualResponse individualResponse) throws IOException, MimeTypeParseException { IndividualBody body = individualResponse.getBody(GetMode.NULL); ByteString entity = (body != null) ? DataMapConverter.dataMapToByteString(individualResponse.getHeaders(), body.data()) : ByteString.empty(); return new RestResponseBuilder() .setStatus(individualResponse.getStatus()) .setHeaders(inheritHeaders(individualResponse, envelopeResponse)) .setCookies(CookieUtil.encodeSetCookies(envelopeResponse.getCookies())) .setEntity(entity) .build(); }
public static RestResponse buildResponse(RoutingResult routingResult, RestLiResponse restLiResponse) { RestResponseBuilder builder = new RestResponseBuilder() .setHeaders(restLiResponse.getHeaders()) .setCookies(CookieUtil.encodeSetCookies(restLiResponse.getCookies())) .setStatus(restLiResponse.getStatus().getCode()); ServerResourceContext context = routingResult.getContext(); ResourceEntityType resourceEntityType = routingResult.getResourceMethod() .getResourceModel() .getResourceEntityType(); if (restLiResponse.hasData() && ResourceEntityType.STRUCTURED_DATA == resourceEntityType) { DataMap dataMap = restLiResponse.getDataMap(); String mimeType = context.getResponseMimeType(); builder = encodeResult(mimeType, builder, dataMap); } return builder.build(); }