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)); } }
headers.remove(HttpConstants.CONTENT_ENCODING); headers.put(HttpConstants.CONTENT_LENGTH, Integer.toString(inflated.length)); res = res.builder().setEntity(inflated).setHeaders(headers).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(); }
RestResponseBuilder builder = new RestResponseBuilder(); builder.setStatus(nettyResponse.status().code()); builder.addCookie(e.getValue()); builder.unsafeAddHeaderValue(e.getKey(), e.getValue()); builder.setEntity(entity); out.add(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()); }
public static RestResponse simpleRestResponse() { return new RestResponseBuilder() .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 RestResponseBuilder builder() { return new RestResponseBuilder(this); }
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 RestResponseBuilder encodeResult(String mimeType, RestResponseBuilder builder, DataMap dataMap) { try { ContentType type = ContentType.getContentType(mimeType).orElseThrow( () -> new RestLiServiceException(HttpStatus.S_406_NOT_ACCEPTABLE, "Requested mime type for encoding is not supported. Mimetype: " + mimeType)); assert type != null; builder.setHeader(RestConstants.HEADER_CONTENT_TYPE, type.getHeaderKey()); // Use unsafe wrap to avoid copying the bytes when request builder creates ByteString. builder.setEntity(ByteString.unsafeWrap(DataMapUtils.mapToBytes(dataMap, type.getCodec()))); } catch (MimeTypeParseException e) { throw new RestLiServiceException(HttpStatus.S_406_NOT_ACCEPTABLE, "Invalid mime type: " + mimeType); } return builder; }
private void readResLine(RestResponseBuilder builder, InputStream in) throws IOException { readIgnore(HTTP_1_1, in); readIgnore(SP, in); try { final String statusStr = readUntil(SP_CHAR, in); builder.setStatus(Integer.parseInt(statusStr)); } catch (NumberFormatException e) { throw new IOException("Failed to parse HTTP status code", e); } readIgnoreLine(in); }
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(); } }
@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()); } };
/** * Converts a StreamResponse to RestResponse * @param streamResponse the stream request to be converted * @param callback the callback to be invoked when the rest response is constructed * @param addContentLengthHeader whether the rest response should have content-length header */ public static void toRestResponse(StreamResponse streamResponse, final Callback<RestResponse> callback, final boolean addContentLengthHeader) { final RestResponseBuilder builder = new RestResponseBuilder(streamResponse); Callback<ByteString> assemblyCallback = new Callback<ByteString>() { @Override public void onError(Throwable e) { callback.onError(e); } @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); } }; streamResponse.getEntityStream().setReader(new FullEntityReader(assemblyCallback)); }
/** * @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 Greeting call() throws Exception { throw new RestException(new RestResponseBuilder().setStatus(401).build()); } });