io.netty.util.CharsetUtil Java Examples

The following examples show how to use io.netty.util.CharsetUtil. 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: WebSocketServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private static void sendHttpResponse(
        ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example #2
Source File: DataCompressionHttp2Test.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void gzipEncodingSingleMessage() throws Exception {
    final String text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccc";
    final ByteBuf data = Unpooled.copiedBuffer(text.getBytes());
    bootstrapEnv(data.readableBytes());
    try {
        final Http2Headers headers = new DefaultHttp2Headers().method(POST).path(PATH)
                .set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);

        runInChannel(clientChannel, new Http2Runnable() {
            @Override
            public void run() throws Http2Exception {
                clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient());
                clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient());
                clientHandler.flush(ctxClient());
            }
        });
        awaitServer();
        assertEquals(text, serverOut.toString(CharsetUtil.UTF_8.name()));
    } finally {
        data.release();
    }
}
 
Example #3
Source File: Responses.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static HttpResponse createStatusResponse(HttpResponseStatus responseStatus, HttpRequest request, String description) {
  if (request != null && request.method() == HttpMethod.HEAD) {
    return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus, Unpooled.EMPTY_BUFFER);
  }

  StringBuilder builder = new StringBuilder();
  String message = responseStatus.toString();
  builder.append("<!doctype html><title>").append(message).append("</title>").append("<h1 style=\"text-align: center\">").append(message).append("</h1>");
  if (description != null) {
    builder.append("<p>").append(description).append("</p>");
  }
  builder.append("<hr/><p style=\"text-align: center\">").append(StringUtil.notNullize(getServerHeaderValue())).append("</p>");

  DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus, ByteBufUtil
          .encodeString(ByteBufAllocator.DEFAULT, CharBuffer.wrap(builder), CharsetUtil.UTF_8));
  response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
  return response;
}
 
Example #4
Source File: KeyValueHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotCompressWithPoorCompressionRatio() throws Exception {
    String text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo " +
            "ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient " +
            "montes, nascetur ridiculus mus.";

    channel.pipeline().addFirst(new SnappyFeatureHandler());

    ByteBuf content = Unpooled.copiedBuffer(text, CharsetUtil.UTF_8);

    UpsertRequest request = new UpsertRequest("key", content.copy(), "bucket");
    request.partition((short) 512);
    channel.writeOutbound(request);
    FullBinaryMemcacheRequest outbound = (FullBinaryMemcacheRequest) channel.readOutbound();
    assertNotNull(outbound);

    assertEquals(0, outbound.getDataType());
    ReferenceCountUtil.release(outbound);
}
 
Example #5
Source File: KeyValueErrorMapTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void verifyConstantRetry() throws Exception {
    opFailRequest(Long.parseLong("7FF0", 16),  -1);
    startRetryVerifyRequest();
    try {
        String key = "upsert-key";
        UpsertRequest upsert = new UpsertRequest(key, Unpooled.copiedBuffer("", CharsetUtil.UTF_8), bucket());
        UpsertResponse response = cluster().<UpsertResponse>send(upsert).toBlocking().single();
        ReferenceCountUtil.releaseLater(response.content());
    } catch (Exception ex) {
        //ignore exception
    }
    checkRetryVerifyRequest(Long.parseLong("7FF0", 16), OP_UPSERT, 25);
    opFailRequest(Long.parseLong("7FF0", 16),  0);
}
 
Example #6
Source File: ServiceExceptionMessageCodec.java    From vertx-service-proxy with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceException decodeFromWire(int pos, Buffer buffer) {
  int failureCode = buffer.getInt(pos);
  pos += 4;
  boolean isNull = buffer.getByte(pos) == (byte)0;
  pos++;
  String message;
  if (!isNull) {
    int strLength = buffer.getInt(pos);
    pos += 4;
    byte[] bytes = buffer.getBytes(pos, pos + strLength);
    message = new String(bytes, CharsetUtil.UTF_8);
    pos += strLength;
  } else {
    message = null;
  }
  JsonObject debugInfo = new JsonObject();
  debugInfo.readFromBuffer(pos, buffer);
  return new ServiceException(failureCode, message, debugInfo);
}
 
Example #7
Source File: FindNodeProcessor.java    From dht-spider with MIT License 6 votes vote down vote up
@Override
public void activeProcess(ProcessDto processDto) {
    log.info("FindNodeProcessor activeProcess "+processDto.getMessageInfo()+"talbesize="+routingTables.size());
    Map<String, Object> rMap = DHTUtil.getParamMap(processDto.getRawMap(), "r", "FIND_NODE,找不到r参数.map:" + processDto.getRawMap());
    List<Node> nodeList = DHTUtil.getNodeListByRMap(rMap);
    //为空退出
    if (CollectionUtils.isEmpty(nodeList)) return;
    //去重
    Node[] nodes = nodeList.stream().distinct().toArray(Node[]::new);
    //将nodes加入发送队列
    for (Node node : nodes) {
        FileUtil.wirteNode("nodes1=="+node.getIp()+","+node.getPort()+"\r\n");
        findNodeTask.put(node.toAddress());
    }
    byte[] id = DHTUtil.getParamString(rMap, "id", "FIND_NODE,找不到id参数.map:" + processDto.getRawMap()).getBytes(CharsetUtil.ISO_8859_1);
    //将发送消息的节点加入路由表
    routingTables.get(processDto.getNum()).put(new Node(id, processDto.getSender(), NodeRankEnum.FIND_NODE_RECEIVE.getKey()));

}
 
Example #8
Source File: KeyValueHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReleaseStoreRequestContentOnSuccess() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
        content);
    response.setStatus(BinaryMemcacheResponseStatus.SUCCESS);

    UpsertRequest requestMock = mock(UpsertRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    when(requestMock.content()).thenReturn(requestContent);
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(0, requestContent.refCnt());
}
 
Example #9
Source File: HttpClientCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailsOnIncompleteChunkedResponse() {
    HttpClientCodec codec = new HttpClientCodec(4096, 8192, 8192, true);
    EmbeddedChannel ch = new EmbeddedChannel(codec);

    ch.writeOutbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost/"));
    ByteBuf buffer = ch.readOutbound();
    assertNotNull(buffer);
    buffer.release();
    assertNull(ch.readInbound());
    ch.writeInbound(Unpooled.copiedBuffer(INCOMPLETE_CHUNKED_RESPONSE, CharsetUtil.ISO_8859_1));
    assertThat(ch.readInbound(), instanceOf(HttpResponse.class));
    ((HttpContent) ch.readInbound()).release(); // Chunk 'first'
    ((HttpContent) ch.readInbound()).release(); // Chunk 'second'
    assertNull(ch.readInbound());

    try {
        ch.finish();
        fail();
    } catch (CodecException e) {
        assertTrue(e instanceof PrematureChannelClosureException);
    }
}
 
Example #10
Source File: DFClusterManager.java    From dfactor with MIT License 6 votes vote down vote up
protected int broadcast(String srcActor, String dstNodeType, String dstActor, int userCmd, String userData){
	int failedNum = 0;
	DFNodeList nodeLs = null;
	if(dstNodeType == null){ //all node
		nodeLs = _getAllNodeSafe();
	}else{  //by type
		nodeLs = _getNodeByTypeSafe(dstNodeType);
	}
	if(nodeLs != null){
		byte[] bufUser = null;
		if(userData != null){
			bufUser = userData.getBytes(CharsetUtil.UTF_8);
		}
		//
		DFNode curNode = null;
		Iterator<DFNode> it = nodeLs.lsNode.iterator();
		while(it.hasNext()){
			curNode = it.next();
			if(_sendToNode(srcActor, curNode.name, dstActor, null, 0, userCmd, bufUser, RpcParamType.STRING) != 0){
				++failedNum;
			}
		}
	}
	return failedNum;
}
 
Example #11
Source File: HttpContentCompressorTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * If the length of the content is 0 for sure, {@link HttpContentEncoder} should skip encoding.
 */
@Test
public void testEmptyFullContent() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpContentCompressor());
    ch.writeInbound(newRequest());

    FullHttpResponse res = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.EMPTY_BUFFER);
    ch.writeOutbound(res);

    Object o = ch.readOutbound();
    assertThat(o, is(instanceOf(FullHttpResponse.class)));

    res = (FullHttpResponse) o;
    assertThat(res.headers().get(HttpHeaderNames.TRANSFER_ENCODING), is(nullValue()));

    // Content encoding shouldn't be modified.
    assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING), is(nullValue()));
    assertThat(res.content().readableBytes(), is(0));
    assertThat(res.content().toString(CharsetUtil.US_ASCII), is(""));
    res.release();

    assertThat(ch.readOutbound(), is(nullValue()));
}
 
Example #12
Source File: WillTest.java    From lannister with Apache License 2.0 6 votes vote down vote up
@Test
public void testWillToNullOnNormalDisconnect() throws Exception {
	String willTopic = "will";
	String message = "ASTALAVISTA";

	String clientId = TestUtil.newClientId();
	ConnectOptions options = new ConnectOptions();
	options.clientId(clientId);
	options.will(
			new Message(-1, willTopic, null, message.getBytes(CharsetUtil.UTF_8), MqttQoS.AT_LEAST_ONCE, false));
	options.cleanSession(false);

	MqttClient client0 = new MqttClient("mqtt://localhost:" + Settings.INSTANCE.mqttPort());
	MqttConnectReturnCode ret = client0.connectOptions(options).connect();

	Assert.assertEquals(MqttConnectReturnCode.CONNECTION_ACCEPTED, ret);
	Assert.assertTrue(client0.isConnected());

	Assert.assertTrue(Session.NEXUS.get(clientId).will() != null
			&& Session.NEXUS.get(clientId).will().topicName().equals(willTopic));

	client0.disconnect(true);

	Thread.sleep(100);
	Assert.assertNull(Session.NEXUS.get(clientId).will());
}
 
Example #13
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testPredictionsValidRequestSize"})
public void testPredictionsDecodeRequest()
        throws InterruptedException, NoSuchFieldException, IllegalAccessException {
    Channel inferChannel = TestUtils.getInferenceChannel(configManager);
    Channel mgmtChannel = TestUtils.getManagementChannel(configManager);
    setConfiguration("decode_input_request", "true");
    loadTests(mgmtChannel, "noop-v1.0-config-tests.mar", "noop-config");
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop-config");
    req.content().writeCharSequence("{\"data\": \"test\"}", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    inferChannel.writeAndFlush(req);

    TestUtils.getLatch().await();

    Assert.assertEquals(TestUtils.getHttpStatus(), HttpResponseStatus.OK);
    Assert.assertFalse(TestUtils.getResult().contains("bytearray"));
    unloadTests(mgmtChannel, "noop-config");
}
 
Example #14
Source File: CallRequestFrameCodecTest.java    From tchannel-java with MIT License 6 votes vote down vote up
@Test
public void testEncodeDecode() throws Exception {

    CallRequestFrame callRequestFrame = Fixtures.callRequest(42, false, Unpooled.wrappedBuffer("Hello, World!".getBytes(StandardCharsets.UTF_8)));
    CallRequestFrame inboundCallRequestFrame =
        (CallRequestFrame) MessageCodec.decode(
            CodecTestUtil.encodeDecode(
                MessageCodec.encode(
                    ByteBufAllocator.DEFAULT, callRequestFrame
                )
            )
        );

    assertEquals("Hello, World!", inboundCallRequestFrame.getPayload().toString(CharsetUtil.UTF_8));
    inboundCallRequestFrame.getPayload().release();
}
 
Example #15
Source File: Http2StreamFrameToHttpObjectCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeDataAsClient() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
    ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
    assertTrue(ch.writeInbound(new DefaultHttp2DataFrame(hello)));

    HttpContent content = ch.readInbound();
    try {
        assertThat(content.content().toString(CharsetUtil.UTF_8), is("hello world"));
        assertFalse(content instanceof LastHttpContent);
    } finally {
        content.release();
    }

    assertThat(ch.readInbound(), is(nullValue()));
    assertFalse(ch.finish());
}
 
Example #16
Source File: KeyCertLoader.java    From WeCross with Apache License 2.0 6 votes vote down vote up
public String readContent(InputStream in) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        byte[] buf = new byte[8192];
        for (; ; ) {
            int ret = in.read(buf);
            if (ret < 0) {
                break;
            }
            out.write(buf, 0, ret);
        }
        return out.toString(CharsetUtil.US_ASCII.name());
    } finally {
        out.close();
    }
}
 
Example #17
Source File: KeyCertLoader.java    From WeCross with Apache License 2.0 6 votes vote down vote up
ByteBuf readPrivateKey(InputStream in) throws KeyException {
    String content;
    try {
        content = readContent(in);
    } catch (IOException e) {
        throw new KeyException("failed to read key input stream", e);
    }

    Matcher m = KEY_PATTERN.matcher(content);
    if (!m.find()) {
        throw new KeyException(
                "could not find a PKCS #8 private key in input stream"
                        + " (see https://netty.io/wiki/sslcontextbuilder-and-private-key.html for more information)");
    }

    ByteBuf base64 = Unpooled.copiedBuffer(m.group(1), CharsetUtil.US_ASCII);
    ByteBuf der = Base64.decode(base64);
    base64.release();
    return der;
}
 
Example #18
Source File: VerifyPayloadHandlingComponentTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_proxy_router_call_works_for_ssl_downstream_system() throws JsonProcessingException {
    SerializableObject widget = new SerializableObject(UUID.randomUUID().toString(), generateRandomBytes(32));
    String requestPayload = objectMapper.writeValueAsString(widget);
    String payloadHash = getHashForPayload(requestPayload.getBytes(CharsetUtil.UTF_8));

    ExtractableResponse response =
        given()
            .baseUri("http://127.0.0.1")
            .port(serverConfig.endpointsPort())
            .basePath(DownstreamProxySsl.MATCHING_PATH)
            .header(REQUEST_PAYLOAD_HASH_HEADER_KEY, payloadHash)
            .body(requestPayload)
            .log().all()
        .when()
            .post()
        .then()
            .log().all()
            .statusCode(200)
            .extract();

    String responsePayload = response.asString();
    assertThat(responsePayload).isEqualTo("success_proxy_downstream_endpoint_call_ssl_true");
}
 
Example #19
Source File: KeyValueMessageTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandleDoubleInsert() throws Exception {
    String key = "insert-key";
    String content = "Hello World!";
    InsertRequest insert = new InsertRequest(key, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8), bucket());
    InsertResponse insertResponse = cluster().<InsertResponse>send(insert).toBlocking().single();
    assertEquals(ResponseStatus.SUCCESS, insertResponse.status());
    ReferenceCountUtil.releaseLater(insertResponse.content());
    assertValidMetadata(insertResponse.mutationToken());

    insert = new InsertRequest(key, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8), bucket());
    insertResponse = cluster().<InsertResponse>send(insert).toBlocking().single();
    assertEquals(ResponseStatus.EXISTS, insertResponse.status());
    ReferenceCountUtil.releaseLater(insertResponse.content());
    assertNull(insertResponse.mutationToken());
}
 
Example #20
Source File: Http2StreamFrameToHttpObjectCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeDataEndWithTrailersAsClient() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
    ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
    LastHttpContent trailers = new DefaultLastHttpContent(hello, true);
    HttpHeaders headers = trailers.trailingHeaders();
    headers.set("key", "value");
    assertTrue(ch.writeOutbound(trailers));

    Http2DataFrame dataFrame = ch.readOutbound();
    try {
        assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world"));
        assertFalse(dataFrame.isEndStream());
    } finally {
        dataFrame.release();
    }

    Http2HeadersFrame headerFrame = ch.readOutbound();
    assertThat(headerFrame.headers().get("key").toString(), is("value"));
    assertTrue(headerFrame.isEndStream());

    assertThat(ch.readOutbound(), is(nullValue()));
    assertFalse(ch.finish());
}
 
Example #21
Source File: HttpContentEncoderTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFullContent() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new TestEncoder());
    ch.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));

    FullHttpResponse res = new DefaultFullHttpResponse(
        HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(new byte[42]));
    ch.writeOutbound(res);

    assertEncodedResponse(ch);
    HttpContent c = ch.readOutbound();
    assertThat(c.content().readableBytes(), is(2));
    assertThat(c.content().toString(CharsetUtil.US_ASCII), is("42"));
    c.release();

    LastHttpContent last = ch.readOutbound();
    assertThat(last.content().readableBytes(), is(0));
    last.release();

    assertThat(ch.readOutbound(), is(nullValue()));
}
 
Example #22
Source File: DataCompressionHttp2Test.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void deflateEncodingWriteLargeMessage() throws Exception {
    final int BUFFER_SIZE = 1 << 12;
    final byte[] bytes = new byte[BUFFER_SIZE];
    new Random().nextBytes(bytes);
    bootstrapEnv(BUFFER_SIZE);
    final ByteBuf data = Unpooled.wrappedBuffer(bytes);
    try {
        final Http2Headers headers = new DefaultHttp2Headers().method(POST).path(PATH)
                .set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.DEFLATE);

        runInChannel(clientChannel, new Http2Runnable() {
            @Override
            public void run() throws Http2Exception {
                clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient());
                clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient());
                clientHandler.flush(ctxClient());
            }
        });
        awaitServer();
        assertEquals(data.resetReaderIndex().toString(CharsetUtil.UTF_8),
                serverOut.toString(CharsetUtil.UTF_8.name()));
    } finally {
        data.release();
    }
}
 
Example #23
Source File: NettyRestHandlerContainer.java    From tajo with Apache License 2.0 6 votes vote down vote up
private void sendError(HttpResponseStatus status, final Throwable error) {
  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
      Unpooled.copiedBuffer(error.getMessage(), CharsetUtil.UTF_8));
  response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
  ChannelPromise promise = ctx.newPromise();
  promise.addListener(new GenericFutureListener<ChannelFuture>() {

    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (!future.isSuccess()) {
        throw new ContainerException(error);
      }
    }
  });

  ctx.writeAndFlush(response, promise);
}
 
Example #24
Source File: AutobahnServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private static void sendHttpResponse(
        ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse res) {
    // Generate an error page if response status code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example #25
Source File: ServletNettyHandler.java    From nettyholdspringmvc with Apache License 2.0 5 votes vote down vote up
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
    response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.setContent(Unpooled.copiedBuffer(
            "Failure: " + status.toString() + "\r\n",
            CharsetUtil.UTF_8));

    // Close the connection as soon as the error message is sent.
    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #26
Source File: PacketEncoderTest.java    From socketio with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncodeHeartbeatPacket() throws IOException {
  // Given
  Packet packet = new Packet(PacketType.HEARTBEAT);

  // When
  String result = PacketEncoder.encodePacket(packet).toString(CharsetUtil.UTF_8);

  // Then
  assertEquals("2::", result);
}
 
Example #27
Source File: ResponseWriter.java    From ns4_frame with Apache License 2.0 5 votes vote down vote up
public static void write(Channel channel, HttpResponse httpResponse) {
    ByteBuf buf = copiedBuffer(httpResponse.getResponseContent(), CharsetUtil.UTF_8);
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponse.getStatus(), buf);
    response.headers().set(CONTENT_TYPE, httpResponse.getContentType().toValue());
    response.headers().set(CONTENT_LENGTH, buf.readableBytes());
    ChannelFuture future = channel.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    future.addListener(ChannelFutureListener.CLOSE);
}
 
Example #28
Source File: ByteBufUtilTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testToStringDoesNotThrowIndexOutOfBounds() {
    CompositeByteBuf buffer = Unpooled.compositeBuffer();
    try {
        byte[] bytes = "1234".getBytes(CharsetUtil.UTF_8);
        buffer.addComponent(Unpooled.buffer(bytes.length).writeBytes(bytes));
        buffer.addComponent(Unpooled.buffer(bytes.length).writeBytes(bytes));
        assertEquals("1234", buffer.toString(bytes.length, bytes.length, CharsetUtil.UTF_8));
    } finally {
        buffer.release();
    }
}
 
Example #29
Source File: ByteBufUtil.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
static ByteBuf encodeString0(ByteBufAllocator alloc, boolean enforceHeap, CharBuffer src, Charset charset,
                                 int extraCapacity) {
//        根据字符集获取字符集编码器
        final CharsetEncoder encoder = CharsetUtil.encoder(charset);
//        计算需要分配buffer的大小
        int length = (int) ((double) src.remaining() * encoder.maxBytesPerChar()) + extraCapacity;
        boolean release = true;
        final ByteBuf dst;
        if (enforceHeap) {
//            使用堆缓冲区
            dst = alloc.heapBuffer(length);
        } else {
//            使用堆缓冲区或者直接缓冲区
            dst = alloc.buffer(length);
        }
        try {
            final ByteBuffer dstBuf = dst.internalNioBuffer(dst.readerIndex(), length);
            final int pos = dstBuf.position();
            CoderResult cr = encoder.encode(src, dstBuf, true);
            if (!cr.isUnderflow()) {
                cr.throwException();
            }
            cr = encoder.flush(dstBuf);
            if (!cr.isUnderflow()) {
                cr.throwException();
            }
            dst.writerIndex(dst.writerIndex() + dstBuf.position() - pos);
            release = false;
            return dst;
        } catch (CharacterCodingException x) {
            throw new IllegalStateException(x);
        } finally {
            if (release) {
                dst.release();
            }
        }
    }
 
Example #30
Source File: HttpPostRequestDecoderTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testQuotedBoundary() throws Exception {
    final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";

    final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "http://localhost");

    req.setDecoderResult(DecoderResult.SUCCESS);
    req.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data; boundary=\"" + boundary + '"');
    req.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);

    // Force to use memory-based data.
    final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);

    for (String data : Arrays.asList("", "\r", "\r\r", "\r\r\r")) {
        final String body =
                "--" + boundary + "\r\n" +
                        "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" +
                        "Content-Type: image/gif\r\n" +
                        "\r\n" +
                        data + "\r\n" +
                        "--" + boundary + "--\r\n";

        req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8));
    }
    // Create decoder instance to test.
    final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req);
    assertFalse(decoder.getBodyHttpDatas().isEmpty());
    decoder.destroy();
}