List of usage examples for io.netty.buffer Unpooled wrappedBuffer
public static ByteBuf wrappedBuffer(ByteBuffer... buffers)
From source file:com.uber.tchannel.messages.JSONSerializer.java
License:Open Source License
@Override public ByteBuf encodeEndpoint(String method) { return Unpooled.wrappedBuffer(method.getBytes()); }
From source file:com.uber.tchannel.messages.JSONSerializer.java
License:Open Source License
@Override public ByteBuf encodeHeaders(Map<String, String> applicationHeaders) { return Unpooled.wrappedBuffer(GSON.toJson(applicationHeaders, HEADER_TYPE).getBytes()); }
From source file:com.uber.tchannel.messages.JSONSerializer.java
License:Open Source License
@Override public ByteBuf encodeBody(Object body) { return Unpooled.wrappedBuffer(GSON.toJson(body).getBytes()); }
From source file:com.uber.tchannel.messages.ThriftSerializer.java
License:Open Source License
@Override public ByteBuf encodeEndpoint(String method) { return Unpooled.wrappedBuffer(method.getBytes()); }
From source file:com.uber.tchannel.messages.ThriftSerializer.java
License:Open Source License
@Override public ByteBuf encodeBody(Object body) { try {/*from w w w. ja va 2 s . c om*/ TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory()); byte[] payloadBytes = serializer.serialize((TBase) body); return Unpooled.wrappedBuffer(payloadBytes); } catch (TException e) { e.printStackTrace(); } return null; }
From source file:com.vmware.dcp.common.http.netty.NettyHttpClientRequestHandler.java
License:Open Source License
private void writeResponseUnsafe(ChannelHandlerContext ctx, Operation request) { ByteBuf bodyBuffer = null;//from w ww.j av a2s . c om FullHttpResponse response; try { byte[] data = Utils.encodeBody(request); if (data != null) { bodyBuffer = Unpooled.wrappedBuffer(data); } } catch (Throwable e1) { // Note that this is a program logic error - some service isn't properly checking or setting Content-Type this.host.log(Level.SEVERE, "Error encoding body: %s", Utils.toString(e1)); byte[] data; try { data = ("Error encoding body: " + e1.getMessage()).getBytes(Utils.CHARSET); } catch (UnsupportedEncodingException ueex) { this.exceptionCaught(ctx, ueex); return; } response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(data)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, request.getContentType()); response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); writeResponse(ctx, request, response); return; } if (bodyBuffer == null || request.getStatusCode() == Operation.STATUS_CODE_NOT_MODIFIED) { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(request.getStatusCode())); } else { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(request.getStatusCode()), bodyBuffer); } response.headers().set(HttpHeaderNames.CONTENT_TYPE, request.getContentType()); response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); // add any other custom headers associated with operation for (Entry<String, String> nameValue : request.getResponseHeaders().entrySet()) { response.headers().set(nameValue.getKey(), nameValue.getValue()); } // Add Set-Cookie header to response if authorization context is marked as internal. AuthorizationContext authorizationContext = request.getAuthorizationContext(); if (authorizationContext != null && authorizationContext.shouldPropagateToClient()) { StringBuilder buf = new StringBuilder().append(AuthenticationConstants.DCP_JWT_COOKIE).append('=') .append(authorizationContext.getToken()); // Add Path qualifier, cookie applies everywhere buf.append("; Path=/"); // Add an Max-Age qualifier if an expiry is set in the Claims object if (authorizationContext.getClaims().getExpirationTime() != null) { buf.append("; Max-Age="); long maxAge = authorizationContext.getClaims().getExpirationTime() - Utils.getNowMicrosUtc(); buf.append(maxAge > 0 ? TimeUnit.MICROSECONDS.toSeconds(maxAge) : 0); } response.headers().add(Operation.SET_COOKIE_HEADER, buf.toString()); } writeResponse(ctx, request, response); }
From source file:com.vmware.dcp.common.http.netty.NettyHttpServiceClient.java
License:Open Source License
private void sendRequest(Operation op) { if (!checkScheme(op)) { return;//from www . j ava 2 s . c om } try { byte[] body = Utils.encodeBody(op); String pathAndQuery; String path = op.getUri().getPath(); String query = op.getUri().getQuery(); path = path == null || path.isEmpty() ? "/" : path; if (query != null) { pathAndQuery = path + "?" + query; } else { pathAndQuery = path; } if (this.httpProxy != null) { pathAndQuery = op.getUri().toString(); } HttpRequest request = null; HttpMethod method = HttpMethod.valueOf(op.getAction().toString()); if (body == null || body.length == 0) { request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, pathAndQuery); } else { ByteBuf content = Unpooled.wrappedBuffer(body); request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, pathAndQuery, content); } for (Entry<String, String> nameValue : op.getRequestHeaders().entrySet()) { request.headers().set(nameValue.getKey(), nameValue.getValue()); } request.headers().set(HttpHeaderNames.CONTENT_LENGTH, Long.toString(op.getContentLength())); request.headers().set(HttpHeaderNames.CONTENT_TYPE, op.getContentType()); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); if (op.getContextId() != null) { request.headers().set(Operation.CONTEXT_ID_HEADER, op.getContextId()); } if (op.getReferer() != null) { request.headers().set(Operation.REFERER_HEADER, op.getReferer().toString()); } if (op.getCookies() != null) { String header = CookieJar.encodeCookies(op.getCookies()); request.headers().set(HttpHeaderNames.COOKIE, header); } request.headers().set(HttpHeaderNames.USER_AGENT, this.userAgent); request.headers().set(HttpHeaderNames.ACCEPT, Operation.MEDIA_TYPE_APPLICATION_JSON); request.headers().set(HttpHeaderNames.HOST, op.getUri().getHost() + ((op.getUri().getPort() != -1) ? (":" + op.getUri().getPort()) : "")); op.nestCompletion((o, e) -> { if (e != null) { fail(e, op); return; } // After request is sent control is transferred to the // NettyHttpServerResponseHandler. The response handler will nest completions // and call complete() when response is received, which will invoke this completion op.complete(); }); op.getSocketContext().writeHttpRequest(request); } catch (Throwable e) { op.setBody(ServiceErrorResponse.create(e, Operation.STATUS_CODE_BAD_REQUEST, EnumSet.of(ErrorDetail.SHOULD_RETRY))); fail(e, op); } }
From source file:com.vmware.xenon.common.http.netty.NettyHttpClientRequestHandler.java
License:Open Source License
private void writeResponseUnsafe(ChannelHandlerContext ctx, Operation request, Integer streamId) { ByteBuf bodyBuffer = null;//from w w w .j a va 2 s . c o m FullHttpResponse response; try { byte[] data = Utils.encodeBody(request); // if some service returns a response that is greater than the maximum allowed size, // we return an INTERNAL_SERVER_ERROR. if (request.getContentLength() > this.responsePayloadSizeLimit) { String errorMessage = "Content-Length " + request.getContentLength() + " is greater than max size allowed " + this.responsePayloadSizeLimit; this.host.log(Level.SEVERE, errorMessage); writeInternalServerError(ctx, request, streamId, errorMessage); return; } if (data != null) { bodyBuffer = Unpooled.wrappedBuffer(data); } } catch (Throwable e1) { // Note that this is a program logic error - some service isn't properly checking or setting Content-Type this.host.log(Level.SEVERE, "Error encoding body: %s", Utils.toString(e1)); writeInternalServerError(ctx, request, streamId, "Error encoding body: " + e1.getMessage()); return; } if (bodyBuffer == null || request.getStatusCode() == Operation.STATUS_CODE_NOT_MODIFIED) { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(request.getStatusCode()), false, false); } else { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(request.getStatusCode()), bodyBuffer, false, false); } if (streamId != null) { // This is the stream ID from the incoming request: we need to use it for our // response so the client knows this is the response. If we don't set the stream // ID, Netty assigns a new, unused stream, which would be bad. response.headers().setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), streamId); } response.headers().set(HttpHeaderNames.CONTENT_TYPE, request.getContentType()); response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); if (request.hasResponseHeaders()) { // add any other custom headers associated with operation for (Entry<String, String> nameValue : request.getResponseHeaders().entrySet()) { response.headers().set(nameValue.getKey(), nameValue.getValue()); } } // Add auth token to response if authorization context AuthorizationContext authorizationContext = request.getAuthorizationContext(); if (authorizationContext != null && authorizationContext.shouldPropagateToClient()) { String token = authorizationContext.getToken(); // The x-xenon-auth-token header is our preferred style response.headers().add(Operation.REQUEST_AUTH_TOKEN_HEADER, token); // Client can also use the cookie if they prefer StringBuilder buf = new StringBuilder().append(AuthenticationConstants.REQUEST_AUTH_TOKEN_COOKIE) .append('=').append(token); // Add Path qualifier, cookie applies everywhere buf.append("; Path=/"); // Add an Max-Age qualifier if an expiration is set in the Claims object if (authorizationContext.getClaims().getExpirationTime() != null) { buf.append("; Max-Age="); long maxAge = authorizationContext.getClaims().getExpirationTime() - Utils.getNowMicrosUtc(); buf.append(maxAge > 0 ? TimeUnit.MICROSECONDS.toSeconds(maxAge) : 0); } response.headers().add(Operation.SET_COOKIE_HEADER, buf.toString()); } writeResponse(ctx, request, response); }
From source file:com.vmware.xenon.common.http.netty.NettyHttpClientRequestHandler.java
License:Open Source License
private void writeInternalServerError(ChannelHandlerContext ctx, Operation request, Integer streamId, String err) {/*from w ww. j a v a 2 s . co m*/ byte[] data; try { data = err.getBytes(Utils.CHARSET); } catch (UnsupportedEncodingException ueex) { this.exceptionCaught(ctx, ueex); return; } FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(data), false, false); if (streamId != null) { response.headers().setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), streamId); } response.headers().set(HttpHeaderNames.CONTENT_TYPE, Operation.MEDIA_TYPE_TEXT_HTML); response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); writeResponse(ctx, request, response); return; }
From source file:com.waitme.game.net.netty.HttpServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { BlockTest bolck = Bootstrap.context.getBean("blockTest", BlockTest.class); bolck.init();/*w ww. j ava2s .com*/ HttpRequest req = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, KEEP_ALIVE); ctx.write(response); } } }