Java Code Examples for io.netty.handler.codec.http.FullHttpResponse#content()

The following examples show how to use io.netty.handler.codec.http.FullHttpResponse#content() . 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: HttpResponseHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;
    }

    Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId);
    if (entry == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }

        entry.getValue().setSuccess();
    }
}
 
Example 2
Source File: HandshakeHandlerTest.java    From socketio with Apache License 2.0 6 votes vote down vote up
@Test
public void testChannelRead() throws Exception {
  HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/socket.io/1/");

  LastOutboundHandler lastOutboundHandler = new LastOutboundHandler();
  EmbeddedChannel channel = new EmbeddedChannel(lastOutboundHandler, handshakeHandler);
  channel.writeInbound(request);
  Object outboundMessage = lastOutboundHandler.getOutboundMessages().poll();
  assertTrue(outboundMessage instanceof FullHttpResponse);
  FullHttpResponse res = (FullHttpResponse) outboundMessage;
  assertEquals(HttpVersion.HTTP_1_1, res.protocolVersion());
  assertEquals(HttpResponseStatus.OK, res.status());
  ByteBuf content = res.content();
  assertTrue(content.toString(CharsetUtil.UTF_8).endsWith("60:60:websocket,flashsocket,xhr-polling,jsonp-polling"));
  channel.finish();
}
 
Example 3
Source File: ChunkEndPoint.java    From ThinkMap with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, context.alloc().buffer());
    response.headers().add("Access-Control-Allow-Origin", "*");
    response.headers().add("Access-Control-Allow-Methods", "POST");
    if (request.getMethod() == OPTIONS) {
        response.headers().add("Access-Control-Allow-Headers", "origin, content-type, accept");
    }

    if (request.getMethod() == POST) {
        String[] args = request.content().toString(Charsets.UTF_8).split(":");
        ByteBuf out = response.content();
        if (plugin.getChunkManager(plugin.getTargetWorld()).getChunkBytes(Integer.parseInt(args[0]), Integer.parseInt(args[1]), out)) {
            response.headers().add("Content-Encoding", "gzip");
        } else {
            out.writeBytes(new byte[1]);
        }
    }
    sendHttpResponse(context, request, response);
}
 
Example 4
Source File: HttpResponseHandler.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
@Override
protected void messageReceived(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;
    }

    ChannelPromise promise = streamidPromiseMap.get(streamId);
    if (promise == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }

        promise.setSuccess();
    }
}
 
Example 5
Source File: HttpResponseHandler.java    From http2-examples with Apache License 2.0 6 votes vote down vote up
@Override
protected void messageReceived(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;
    }

    ChannelPromise promise = streamidPromiseMap.get(streamId);
    if (promise == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println("After " + StopWatch.getInstance().currentTimeInSeconds() + " seconds: " + new String(arr, 0, contentLength));
        }

        promise.setSuccess();
    }
}
 
Example 6
Source File: Http2ResponseHandler.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        log.error("Http2ResponseHandler unexpected message received: " + msg);
        return;
    }

    Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId);
    if (entry == null) {
        log.error("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            log.debug(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }
        entry.getValue().setSuccess();
    }
}
 
Example 7
Source File: DefaultPampasResponse.java    From pampas with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    String body = null;
    Object status = null;
    if (responseData != null && responseData instanceof FullHttpResponse) {
        FullHttpResponse httpResponse = (FullHttpResponse) this.responseData;
        ByteBuf content = httpResponse.content();
        body = content.toString(UTF_8);
        status = httpResponse.status();
    }

    return MoreObjects.toStringHelper(this)
            .omitNullValues()
            .add("id", id)
            .add("success", success)
            .add("status", status)
            .add("responseData", body == null ? responseData : body)
            .add("exception", exception)
            .toString();
}
 
Example 8
Source File: WebSocketClientHandshaker00.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 WebSocket Protocol Handshake
 * Upgrade: WebSocket
 * Connection: Upgrade
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Location: ws://example.com/demo
 * Sec-WebSocket-Protocol: sample
 *
 * 8jKS'y:G*Co,Wxa-
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    if (!response.status().equals(HttpResponseStatus.SWITCHING_PROTOCOLS)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
    }

    HttpHeaders headers = response.headers();

    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
                + upgrade);
    }

    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + headers.get(HttpHeaderNames.CONNECTION));
    }

    ByteBuf challenge = response.content();
    if (!challenge.equals(expectedChallengeResponseBytes)) {
        throw new WebSocketHandshakeException("Invalid challenge");
    }
}
 
Example 9
Source File: Http2ClearTextBadRequestTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void receiveHttpResponse(FullHttpResponse response) {
    this.response = response;
    if (response != null) {
        ByteBuf byteBuf = response.content();
        if (byteBuf.hasArray()) {
            content = byteBuf.array();
        } else {
            content = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(content);
        }
    }
    latch.countDown();
}
 
Example 10
Source File: NettyUtils.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
public static void sendJsonResponse(
        ChannelHandlerContext ctx, String json, HttpResponseStatus status) {
    FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, false);
    resp.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    ByteBuf content = resp.content();
    content.writeCharSequence(json, CharsetUtil.UTF_8);
    content.writeByte('\n');
    sendHttpResponse(ctx, resp, true);
}
 
Example 11
Source File: ComponentTestUtils.java    From riposte with Apache License 2.0 5 votes vote down vote up
public NettyHttpClientResponse(FullHttpResponse fullHttpResponse) {
    this.statusCode = fullHttpResponse.status().code();
    this.headers = fullHttpResponse.headers();
    ByteBuf content = fullHttpResponse.content();
    this.payloadBytes = new byte[content.readableBytes()];
    content.getBytes(content.readerIndex(), this.payloadBytes);
    this.payload = new String(this.payloadBytes, UTF_8);
    this.fullHttpResponse = fullHttpResponse;
}
 
Example 12
Source File: Http2ClientResponseHandler.java    From tutorials with MIT License 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers()
        .getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        logger.error("HttpResponseHandler unexpected message received: " + msg);
        return;
    }

    MapValues value = streamidMap.get(streamId);

    if (value == null) {
        logger.error("Message received for unknown stream id " + streamId);
        ctx.close();
    } else {
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            String response = new String(arr, 0, contentLength, CharsetUtil.UTF_8);
            logger.info("Response from Server: "+ (response));
            value.setResponse(response);
        }
        
        value.getPromise()
            .setSuccess();
    }
}
 
Example 13
Source File: HttpResponseHandler.java    From jmeter-http2-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void messageReceived(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;
    }

    ChannelPromise promise = streamidPromiseMap.get(streamId);
    if (promise == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }

        promise.setSuccess();

        // Set result
        streamidResponseMap.put(streamId, msg);
    }
}
 
Example 14
Source File: DFHttpSyncHandler.java    From dfactor with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	try{
		if(msg instanceof FullHttpResponse){
			FullHttpResponse rsp = (FullHttpResponse) msg;
			HttpHeaders headers = rsp.headers();
			long contentLen = HttpUtil.getContentLength(rsp);
			String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
			//
			DFHttpCliRsp dfRsp = null;
			ByteBuf buf = rsp.content();
			//parse msg
			boolean isString = contentIsString(contentType);
			if(isString){  //String
				String str = null;
				if(buf != null){
					str = (String) buf.readCharSequence(buf.readableBytes(), CharsetUtil.UTF_8);
				}
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						null, str);
			}else{  //binary
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						buf, null);
			}
			//
			_recvData = dfRsp;
			if(!isString && buf != null){
       			buf.retain();
       		}
		}
	}finally{
		if(_recvPromise != null){
			_recvPromise.setSuccess();
		}
		ReferenceCountUtil.release(msg);
	}
}
 
Example 15
Source File: WebSocketClientHandshaker00.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 WebSocket Protocol Handshake
 * Upgrade: WebSocket
 * Connection: Upgrade
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Location: ws://example.com/demo
 * Sec-WebSocket-Protocol: sample
 *
 * 8jKS'y:G*Co,Wxa-
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = new HttpResponseStatus(101, "WebSocket Protocol Handshake");

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    HttpHeaders headers = response.headers();

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
                + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + connection);
    }

    ByteBuf challenge = response.content();
    if (!challenge.equals(expectedChallengeResponseBytes)) {
        throw new WebSocketHandshakeException("Invalid challenge");
    }
}
 
Example 16
Source File: NettyUtils.java    From serve with Apache License 2.0 5 votes vote down vote up
public static void sendJsonResponse(
        ChannelHandlerContext ctx, String json, HttpResponseStatus status) {
    FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, false);
    resp.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    ByteBuf content = resp.content();
    content.writeCharSequence(json, CharsetUtil.UTF_8);
    content.writeByte('\n');
    sendHttpResponse(ctx, resp, true);
}
 
Example 17
Source File: OutputStreamImpl.java    From dorado with Apache License 2.0 4 votes vote down vote up
public OutputStreamImpl(FullHttpResponse response) {
	this.out = new ByteBufOutputStream(response.content());
}
 
Example 18
Source File: HttpResponseMessage.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Used for pipeline conversion from {@link FullHttpResponse} to {@link HttpResponseMessage} */
public HttpResponseMessage(FullHttpResponse response) {
  this(response.protocolVersion(), response.status(), response.content());

  response.headers().forEach((entry) -> headers().set(entry.getKey(), entry.getValue()));
}
 
Example 19
Source File: EtcdResponseHandler.java    From etcd4j with Apache License 2.0 4 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) throws Exception {
  final HttpResponseStatus status =response.status();
  final HttpHeaders headers = response.headers();
  final ByteBuf content = response.content();

  if (logger.isDebugEnabled()) {
    logger.debug("Received {} for {} {}",
      status.code(), this.request.getMethod().name(), this.request.getUri());
  }

  if (status.equals(HttpResponseStatus.MOVED_PERMANENTLY)
    || status.equals(HttpResponseStatus.TEMPORARY_REDIRECT)) {
    if (headers.contains(HttpHeaderNames.LOCATION)) {
      this.request.setUrl(headers.get(HttpHeaderNames.LOCATION));
      this.client.connect(this.request);
      // Closing the connection which handled the previous request.
      ctx.close();
      if (logger.isDebugEnabled()) {
        logger.debug("redirect for {} to {}",
          this.request.getHttpRequest().uri() ,
          headers.get(HttpHeaderNames.LOCATION)
        );
      }
    } else {
      this.promise.setFailure(new Exception("Missing Location header on redirect"));
    }
  } else {
    EtcdResponseDecoder<? extends Throwable> failureDecoder = failureDecoders.get(status);
    if(failureDecoder != null) {
      this.promise.setFailure(failureDecoder.decode(headers, content));
    } else if (!content.isReadable()) {
      // If connection was accepted maybe response has to be waited for
      if (!status.equals(HttpResponseStatus.OK)
        && !status.equals(HttpResponseStatus.ACCEPTED)
        && !status.equals(HttpResponseStatus.CREATED)) {
        this.promise.setFailure(new IOException(
          "Content was not readable. HTTP Status: " + status));
      }
    } else {
      try {
        this.promise.setSuccess(
          request.getResponseDecoder().decode(headers, content));
      } catch (Exception e) {
        if (e instanceof EtcdException) {
          this.promise.setFailure(e);
        } else {
          try {
            // Try to be smart, if an exception is thrown, first try to decode
            // the content and see if it is an EtcdException, i.e. an error code
            // not included in failureDecoders
            this.promise.setFailure(EtcdException.DECODER.decode(headers, content));
          } catch (Exception e1) {
            // if it fails again, set the original exception as failure
            this.promise.setFailure(e);
          }
        }
      }
    }
  }
}
 
Example 20
Source File: DFHttpCliHandler.java    From dfactor with MIT License 4 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	hasRsp = true;
	try{
		if(msg instanceof FullHttpResponse){
			int actorId = 0;
			FullHttpResponse rsp = (FullHttpResponse) msg;
			HttpHeaders headers = rsp.headers();
			long contentLen = HttpUtil.getContentLength(rsp);
			String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
			//
			DFHttpCliRsp dfRsp = null;
			ByteBuf buf = rsp.content();
			//parse msg
			boolean isString = contentIsString(contentType);
			if(isString){  //String
				String str = null;
				if(buf != null){
					str = (String) buf.readCharSequence(buf.readableBytes(), CharsetUtil.UTF_8);
				}
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						null, str);
			}else{  //binary
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						buf, null);
			}
			//
			Object msgWrap = null;
			//decode
			if(decoder != null){
				Object tmp = decoder.onDecode(dfRsp);
				if(tmp != null){
           			msgWrap = tmp;
           		}
			}
			if(msgWrap == null){  //没有解码
           		msgWrap = dfRsp;
           		if(!isString && buf != null){
           			buf.retain();
           		}
           	}
			//检测分发
			if(dispatcher != null){
				actorId = dispatcher.onQueryMsgActorId(addrRemote.getPort(), addrRemote, msgWrap);
			}
			//
			if(actorId == 0){
            	actorId = actorIdDef;
            }
			//
			if(actorId != 0 && msgWrap != null){ //可以后续处理
				DFActorManager.get().send(requestId, actorId, 2, 
						DFActorDefine.SUBJECT_NET, 
						DFActorDefine.NET_TCP_MESSAGE,  
						msgWrap, true, session, actorId==actorIdDef?userHandler:null, false);
            }
		}
	}finally{
		ReferenceCountUtil.release(msg);
		ctx.close();
	}
}