Java Code Examples for io.netty.buffer.Unpooled#copiedBuffer()
The following examples show how to use
io.netty.buffer.Unpooled#copiedBuffer() .
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 tools-journey with Apache License 2.0 | 6 votes |
private static void sendHttpResponse( ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
Example 2
Source File: KeyValueHandlerTest.java From couchbase-jvm-core with Apache License 2.0 | 6 votes |
@Test public void shouldCompressSmallContent() throws Exception { String text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit."; text += text; 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(KeyValueHandler.DATATYPE_SNAPPY, outbound.getDataType()); byte[] compressed = new byte[outbound.content().readableBytes()]; outbound.content().getBytes(0, compressed); byte[] uncompressed = Snappy.uncompress(compressed); assertArrayEquals(text.getBytes(CharsetUtil.UTF_8), uncompressed); ReferenceCountUtil.release(outbound); }
Example 3
Source File: TestChangePinRESTHandler.java From arcusplatform with Apache License 2.0 | 6 votes |
private FullHttpRequest createRequest(String oldPin, String newPin) { PersonCapability.ChangePinRequest.Builder builder = PersonCapability.ChangePinRequest.builder(); if(oldPin != null) { builder.withCurrentPin(oldPin); } if(newPin != null) { builder.withNewPin(newPin); } ClientMessage msg = ClientMessage.builder() .withCorrelationId("correlationid") .withDestination(person.getAddress()) .withPayload(builder.build()) .create(); FullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/person/ChangePin"); req.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/json"); ByteBuf buffer = Unpooled.copiedBuffer(JSON.toJson(msg), CharsetUtil.UTF_8); req.headers().add(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes()); req.content().clear().writeBytes(buffer); return req; }
Example 4
Source File: BaseRemoteService.java From redisson with Apache License 2.0 | 6 votes |
protected long[] getMethodSignature(Method method) { long[] result = methodSignaturesCache.get(method); if (result == null) { String str = Arrays.stream(method.getParameterTypes()) .map(c -> c.getName()) .collect(Collectors.joining()); ByteBuf buf = Unpooled.copiedBuffer(str, CharsetUtil.UTF_8); result = Hash.hash128(buf); buf.release(); long[] oldResult = methodSignaturesCache.putIfAbsent(method, result); if (oldResult != null) { return oldResult; } } return result; }
Example 5
Source File: StreamServerHandler.java From IpCamera with Eclipse Public License 2.0 | 6 votes |
private void sendSnapshotImage(ChannelHandlerContext ctx, String contentType) throws IOException { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); ipCameraHandler.lockCurrentSnapshot.lock(); ByteBuf snapshotData = Unpooled.copiedBuffer(ipCameraHandler.currentSnapshot); ipCameraHandler.lockCurrentSnapshot.unlock(); response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType); response.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE); response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); response.headers().add(HttpHeaderNames.CONTENT_LENGTH, snapshotData.readableBytes()); response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Expose-Headers", "*"); ctx.channel().write(response); ctx.channel().write(snapshotData); ByteBuf footerBbuf = Unpooled.copiedBuffer("\r\n", 0, 2, StandardCharsets.UTF_8); ctx.channel().writeAndFlush(footerBbuf); }
Example 6
Source File: MoasClientHandler.java From onos with Apache License 2.0 | 6 votes |
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { log.info("Connected to server {}", ctx.channel().remoteAddress()); ArtemisMessage message = new ArtemisMessage(); message.setType(ArtemisMessage.Type.INITIATE_FROM_CLIENT); message.setLocalIp(localIp.toString()); message.setLocalPrefix(localPrefix.toString()); ObjectMapper mapper = new ObjectMapper(); try { String jsonInString = mapper.writeValueAsString(message); ByteBuf buffer = Unpooled.copiedBuffer(jsonInString, CharsetUtil.UTF_8); ctx.writeAndFlush(buffer); } catch (JsonProcessingException e) { log.warn("channelActive()", e); } }
Example 7
Source File: PacketDecoderTest.java From socketio with Apache License 2.0 | 5 votes |
@Test public void testDecodeErrorPacket() throws IOException { // Given String message = "7:::"; ByteBuf byteMessage = Unpooled.copiedBuffer(message, CharsetUtil.UTF_8); // When Packet packet = PacketDecoder.decodePacket(byteMessage); // Then assertEquals(PacketType.ERROR, packet.getType()); }
Example 8
Source File: SubdocumentDocumentFlagsTests.java From couchbase-jvm-core with Apache License 2.0 | 5 votes |
@Test public void shouldUpsertDocumentIfSetWithExpiryAndPathFlags() { String subPath = "first.hello"; ByteBuf fragment = Unpooled.copiedBuffer("\"world\"", CharsetUtil.UTF_8); ReferenceCountUtil.releaseLater(fragment); SubDictAddRequest insertRequest = new SubDictAddRequest("shouldUpsertDocumentIfSetWithExpiryAndPathFlags", subPath, fragment, bucket(), 10, 0); insertRequest.upsertDocument(true); insertRequest.createIntermediaryPath(true); SimpleSubdocResponse insertResponse = cluster().<SimpleSubdocResponse>send(insertRequest).toBlocking().single(); ReferenceCountUtil.releaseLater(insertResponse.content()); assertTrue(insertResponse.status().isSuccess()); RemoveResponse response = cluster().<RemoveResponse>send(new RemoveRequest("shouldUpsertDocumentIfSetWithExpiryAndPathFlags", bucket())).toBlocking().single(); assertEquals(response.status(), ResponseStatus.SUCCESS); }
Example 9
Source File: NettyServer.java From netty-learning with Apache License 2.0 | 5 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { logger.info("接收客户端msg:{}", msg); ByteBuf echo = Unpooled.copiedBuffer(String.format("Hello from server:", counter).getBytes()); ctx.writeAndFlush(echo); }
Example 10
Source File: CarrierRefresherTest.java From couchbase-jvm-core with Apache License 2.0 | 5 votes |
@Test public void shouldFallbackToNextOnPollWhenFirstFails() throws Exception { ClusterFacade cluster = mock(ClusterFacade.class); ConfigurationProvider provider = mock(ConfigurationProvider.class); BucketConfig config = mock(BucketConfig.class); CarrierRefresher refresher = new CarrierRefresher(ENVIRONMENT, cluster); refresher.provider(provider); when(config.name()).thenReturn("bucket"); List<NodeInfo> nodeInfos = new ArrayList<NodeInfo>(); Map<String, Integer> ports = new HashMap<String, Integer>(); ports.put("direct", 11210); nodeInfos.add(new DefaultNodeInfo(null, "1.2.3.4:8091", ports, null)); nodeInfos.add(new DefaultNodeInfo(null, "2.3.4.5:8091", ports, null)); when(config.nodes()).thenReturn(nodeInfos); ByteBuf content = Unpooled.copiedBuffer("{\"config\": true}", CharsetUtil.UTF_8); Observable<CouchbaseResponse> goodResponse = Observable.just((CouchbaseResponse) new GetBucketConfigResponse( ResponseStatus.SUCCESS, KeyValueStatus.SUCCESS.code(), "bucket", content, "1.2.3.4" )); Observable<CouchbaseResponse> badResponse = Observable.error(new CouchbaseException("Failure")); when(cluster.send(any(GetBucketConfigRequest.class))).thenReturn(badResponse, goodResponse); refresher.markTainted(config); Thread.sleep(1500); verify(provider, times(1)).proposeBucketConfig(any(ProposedBucketConfigContext.class)); assertEquals(0, content.refCnt()); }
Example 11
Source File: StringClosingPositionBufProcessorTest.java From couchbase-jvm-core with Apache License 2.0 | 5 votes |
@Test public void testClosingPosNotFoundInPartialStringLeftPart() { ByteBuf source = Unpooled.copiedBuffer(" \"\\\"Partial\\\" str", CharsetUtil.UTF_8); int closingPos = source.forEachByte(new StringClosingPositionBufProcessor()); assertEquals(-1, closingPos); assertEquals(0, source.readerIndex()); }
Example 12
Source File: CarrierRefresherTest.java From couchbase-jvm-core with Apache License 2.0 | 5 votes |
@Test public void shouldRefreshWithValidClusterConfig() throws Exception { ClusterFacade cluster = mock(ClusterFacade.class); CarrierRefresher refresher = new CarrierRefresher(ENVIRONMENT, cluster); refresher.registerBucket("bucket", ""); ConfigurationProvider provider = mock(ConfigurationProvider.class); refresher.provider(provider); ClusterConfig clusterConfig = mock(ClusterConfig.class); BucketConfig bucketConfig = mock(BucketConfig.class); when(bucketConfig.name()).thenReturn("bucket"); List<NodeInfo> nodeInfos = new ArrayList<NodeInfo>(); Map<String, Integer> ports = new HashMap<String, Integer>(); ports.put("direct", 11210); nodeInfos.add(new DefaultNodeInfo(null, "localhost:8091", ports, null)); when(bucketConfig.nodes()).thenReturn(nodeInfos); Map<String, BucketConfig> bucketConfigs = new HashMap<String, BucketConfig>(); bucketConfigs.put("bucket", bucketConfig); when(clusterConfig.bucketConfigs()).thenReturn(bucketConfigs); ByteBuf content = Unpooled.copiedBuffer("{\"config\": true}", CharsetUtil.UTF_8); when(cluster.send(any(GetBucketConfigRequest.class))).thenReturn(Observable.just( (CouchbaseResponse) new GetBucketConfigResponse( ResponseStatus.SUCCESS, KeyValueStatus.SUCCESS.code(), "bucket", content, "127.0.0.1" ) )); refresher.refresh(clusterConfig); Thread.sleep(200); verify(provider, times(1)).proposeBucketConfig(any(ProposedBucketConfigContext.class)); assertEquals(0, content.refCnt()); }
Example 13
Source File: ViewHandlerTest.java From couchbase-jvm-core with Apache License 2.0 | 5 votes |
@Test public void shouldDecodeWithDebugViewQueryResponse() throws Exception { String response = Resources.read("query_debug.json", this.getClass()); HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK")); HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8)); ViewQueryRequest requestMock = mock(ViewQueryRequest.class); queue.add(requestMock); channel.writeInbound(responseHeader, responseChunk); latch.await(1, TimeUnit.SECONDS); assertEquals(1, firedEvents.size()); ViewQueryResponse inbound = (ViewQueryResponse) firedEvents.get(0); assertTrue(inbound.status().isSuccess()); assertEquals(5, countAndRelease(inbound.rows())); inbound.info().toBlocking().forEach(new Action1<ByteBuf>() { @Override public void call(ByteBuf byteBuf) { try { Map<String, Object> found = DefaultObjectMapper.readValueAsMap(byteBuf.toString(CharsetUtil.UTF_8)); assertEquals(2, found.size()); assertTrue(found.containsKey("debug_info")); assertTrue(found.containsKey("total_rows")); } catch (IOException e) { e.printStackTrace(); assertFalse(true); } ReferenceCountUtil.releaseLater(byteBuf); } }); }
Example 14
Source File: AnonymousConnectionTest.java From sctp with GNU Affero General Public License v3.0 | 5 votes |
@Override public void onCommunicationUp(Association association, int maxInboundStreams, int maxOutboundStreams) { System.out.println(this + " onCommunicationUp"); assData.assocUp = true; PayloadData payloadData = new PayloadData(CLIENT_MESSAGE.length, Unpooled.copiedBuffer(CLIENT_MESSAGE), true, false, 3, 1); try { association.send(payloadData); } catch (Exception e) { e.printStackTrace(); } }
Example 15
Source File: IpCameraHandler.java From IpCamera with Eclipse Public License 2.0 | 5 votes |
public void sendMjpegFrame(byte[] jpg, ChannelGroup channelGroup) { final String BOUNDARY = "thisMjpegStream"; ByteBuf imageByteBuf = Unpooled.copiedBuffer(jpg); int length = imageByteBuf.readableBytes(); String header = "--" + BOUNDARY + "\r\n" + "content-type: image/jpeg" + "\r\n" + "content-length: " + length + "\r\n\r\n"; ByteBuf headerBbuf = Unpooled.copiedBuffer(header, 0, header.length(), StandardCharsets.UTF_8); ByteBuf footerBbuf = Unpooled.copiedBuffer("\r\n", 0, 2, StandardCharsets.UTF_8); streamToGroup(headerBbuf, channelGroup, false); streamToGroup(imageByteBuf, channelGroup, false); streamToGroup(footerBbuf, channelGroup, true); }
Example 16
Source File: SimpleSctpClientHandler.java From netty-cookbook with Apache License 2.0 | 4 votes |
public SimpleSctpClientHandler() { firstMessage = Unpooled.copiedBuffer("first message",CharsetUtil.UTF_8); secondMessage = Unpooled.copiedBuffer("second message",CharsetUtil.UTF_8); }
Example 17
Source File: InboundHttp2ToHttpAdapterTest.java From netty-4.1.22 with Apache License 2.0 | 4 votes |
@Test public void serverRequestPushPromise() throws Exception { boostrapEnv(1, 1, 1); final String text = "hello world big time data!"; final ByteBuf content = Unpooled.copiedBuffer(text.getBytes()); final String text2 = "hello world smaller data?"; final ByteBuf content2 = Unpooled.copiedBuffer(text2.getBytes()); final FullHttpMessage response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content, true); final FullHttpMessage response2 = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CREATED, content2, true); final FullHttpMessage request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/push/test", true); try { HttpHeaders httpHeaders = response.headers(); httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length()); httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16); HttpHeaders httpHeaders2 = response2.headers(); httpHeaders2.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "https"); httpHeaders2.set(HttpHeaderNames.HOST, "example.org"); httpHeaders2.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5); httpHeaders2.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_PROMISE_ID.text(), 3); httpHeaders2.setInt(HttpHeaderNames.CONTENT_LENGTH, text2.length()); httpHeaders = request.headers(); httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0); httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16); final Http2Headers http2Headers3 = new DefaultHttp2Headers().method(new AsciiString("GET")) .path(new AsciiString("/push/test")); runInChannel(clientChannel, new Http2Runnable() { @Override public void run() throws Http2Exception { clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers3, 0, true, newPromiseClient()); clientChannel.flush(); } }); awaitRequests(); ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); verify(serverListener).messageReceived(requestCaptor.capture()); capturedRequests = requestCaptor.getAllValues(); assertEquals(request, capturedRequests.get(0)); final Http2Headers http2Headers = new DefaultHttp2Headers().status(new AsciiString("200")); // The PUSH_PROMISE frame includes a header block that contains a // complete set of request header fields that the server attributes to // the request. // https://tools.ietf.org/html/rfc7540#section-8.2.1 // Therefore, we should consider the case where there is no Http response status. final Http2Headers http2Headers2 = new DefaultHttp2Headers() .scheme(new AsciiString("https")) .authority(new AsciiString("example.org")); runInChannel(serverConnectedChannel, new Http2Runnable() { @Override public void run() throws Http2Exception { serverHandler.encoder().writeHeaders(ctxServer(), 3, http2Headers, 0, false, newPromiseServer()); serverHandler.encoder().writePushPromise(ctxServer(), 3, 2, http2Headers2, 0, newPromiseServer()); serverHandler.encoder().writeData(ctxServer(), 3, content.retainedDuplicate(), 0, true, newPromiseServer()); serverHandler.encoder().writeData(ctxServer(), 5, content2.retainedDuplicate(), 0, true, newPromiseServer()); serverConnectedChannel.flush(); } }); awaitResponses(); ArgumentCaptor<FullHttpMessage> responseCaptor = ArgumentCaptor.forClass(FullHttpMessage.class); verify(clientListener).messageReceived(responseCaptor.capture()); capturedResponses = responseCaptor.getAllValues(); assertEquals(response, capturedResponses.get(0)); } finally { request.release(); response.release(); response2.release(); } }
Example 18
Source File: QueryHandlerTest.java From couchbase-jvm-core with Apache License 2.0 | 4 votes |
@Test public void testSplitAtStatusWithEmptyResponse() { String chunk1 = "{\n" + " \"requestID\": \"826e33cb-af29-4002-8a40-ef90915e05b1\",\n" + " \"clientContextID\": \"$$637\",\n" + " \"signature\": {\n" + " \"doc\": \"json\"\n" + " },\n" + " \"results\": [\n" + " ],\n" + " \"sta"; String chunk2 = "tus\": \"success\",\n" + " \"metrics\": {\n" + " \"elapsedTime\": \"4.69718ms\",\n" + " \"executionTime\": \"4.582526ms\",\n" + " \"resultCount\": 0,\n" + " \"resultSize\": 0\n" + " }\n" + "}"; HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK")); responseHeader.headers().add("Transfer-Encoding", "chunked"); responseHeader.headers().add("Content-Type", "application/json; version=1.0.0"); Object[] httpChunks = new Object[3]; httpChunks[0] = responseHeader; httpChunks[1] = new DefaultHttpContent(Unpooled.copiedBuffer(chunk1, CharsetUtil.UTF_8)); httpChunks[2] = new DefaultLastHttpContent(Unpooled.copiedBuffer(chunk2, CharsetUtil.UTF_8)); Subject<CouchbaseResponse,CouchbaseResponse> obs = AsyncSubject.create(); GenericQueryRequest requestMock = mock(GenericQueryRequest.class); when(requestMock.observable()).thenReturn(obs); queue.add(requestMock); channel.writeInbound(httpChunks); Exception error = null; GenericQueryResponse inbound = null; try { inbound = (GenericQueryResponse) obs.timeout(1, TimeUnit.SECONDS).toBlocking().last(); ReferenceCountUtil.release(inbound.info().timeout(1, TimeUnit.SECONDS).toBlocking().last()); } catch (Exception e) { error = e; } SoftAssertions softly = new SoftAssertions(); softly.assertThat(inbound).isNotNull(); softly.assertThat(error).isNull(); if (handler instanceof QueryHandler) { softly.assertThat(((QueryHandler) handler).getDecodingState()).isEqualTo(DecodingState.INITIAL); } softly.assertAll(); }
Example 19
Source File: StaticFileServerHandler.java From litchi with Apache License 2.0 | 4 votes |
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
Example 20
Source File: HttpResponseHelper.java From fastjgame with Apache License 2.0 | 2 votes |
/** * 构建字符串内容时的帮助方法 * * @param content 字符串内存 * @return ByteBuf */ public static ByteBuf buildStringContent(String content) { Objects.requireNonNull(content); return Unpooled.copiedBuffer(content.getBytes(StandardCharsets.UTF_8)); }