List of usage examples for io.netty.buffer Unpooled copiedBuffer
public static ByteBuf copiedBuffer(ByteBuffer... buffers)
From source file:com.phei.netty.frame.fixedLen.TimeClientHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { for (int i = 0; i < 10; i++) { ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes())); }// w w w. j a va 2 s . c om }
From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpEventsIngestionHandlerTest.java
License:Apache License
private FullHttpRequest createRequest(HttpMethod method, String uri, String requestBody) { DefaultFullHttpRequest rawRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, "/v2.0/" + TENANT + "/events/" + uri); rawRequest.headers().set("tenantId", TENANT); if (!requestBody.equals("")) rawRequest.content().writeBytes(Unpooled.copiedBuffer(requestBody.getBytes())); return HttpRequestWithDecodedQueryParams.create(rawRequest); }
From source file:com.schibsted.triathlon.operators.GroupByOperatorTest.java
License:Apache License
@Test public void testDeployTwoDataCentersOddNumberOfInstances() throws Exception { initializeInstanceInfos(2);//ww w .j ava 2 s . c o m List<String> constraint = new ArrayList<String>() { { add("datacenter"); add("GROUP_BY"); } }; TriathlonService triathlonService = new TriathlonServiceImpl(); String content = IOUtils.toString(this.getClass().getResourceAsStream("group_by_operator_1.json"), "UTF-8"); ByteBuf buffer = Unpooled.copiedBuffer(content.getBytes()); Marathon appDefinition = triathlonService.parseJson(Observable.just(buffer)).toBlocking().toFuture().get(); appDefinition.setInstances(5); ConstraintModel constraintModel = ConstraintModel.createConstraintModel(constraint); Operator cluster = new GroupByOperator(triathlonService, constraintModel); Operator spyCluster = Mockito.spy(cluster); doReturn(Observable.just(Unpooled.wrappedBuffer("TEST".getBytes()))).when(spyCluster) .getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString()); Stack<Integer> values = new Stack<>(); values.push(2); values.push(3); when(spyCluster.getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString())) .thenAnswer(invocation -> { Object[] args = invocation.getArguments(); Observable<ByteBuf> val = Observable .just(Unpooled.wrappedBuffer(((String) args[1]).getBytes())); Marathon appDef = triathlonService.parseJson(val).toBlocking().toFuture().get(); Integer v = values.pop(); assertEquals(v, appDef.getInstances()); return val; }); spyCluster.apply(appDefinition).subscribe(); verify(spyCluster, times(2)).getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString()); }
From source file:com.schibsted.triathlon.operators.UniqueOperatorTest.java
License:Apache License
@Test public void testDeployFourInstancestoFourDataCenters() throws Exception { initializeInstanceInfos(4);/*from w w w . java2s.co m*/ List<String> constraint = new ArrayList<String>() { { add("datacenter"); add("UNIQUE"); } }; TriathlonService triathlonService = new TriathlonServiceImpl(); String content = IOUtils.toString(this.getClass().getResourceAsStream("unique_operator_1.json"), "UTF-8"); ByteBuf buffer = Unpooled.copiedBuffer(content.getBytes()); Marathon appDefinition = triathlonService.parseJson(Observable.just(buffer)).toBlocking().toFuture().get(); appDefinition.setInstances(5); ConstraintModel constraintModel = ConstraintModel.createConstraintModel(constraint); Operator cluster = new UniqueOperator(triathlonService, constraintModel); Operator spyCluster = Mockito.spy(cluster); doReturn(Observable.just(Unpooled.wrappedBuffer("TEST".getBytes()))).when(spyCluster) .getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString()); when(spyCluster.getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString())) .thenAnswer(invocation -> { Object[] args = invocation.getArguments(); Observable<ByteBuf> val = Observable .just(Unpooled.wrappedBuffer(((String) args[1]).getBytes())); Marathon appDef = triathlonService.parseJson(val).toBlocking().toFuture().get(); assertEquals(Integer.valueOf(1), appDef.getInstances()); return val; }); spyCluster.apply(appDefinition).subscribe(); verify(spyCluster, times(4)).getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString()); }
From source file:com.schibsted.triathlon.operators.UniqueOperatorTest.java
License:Apache License
@Test public void testDeployFourInstancestoTwoDataCenters() throws Exception { initializeInstanceInfos(2);/* w w w . j a v a2 s.com*/ List<String> constraint = new ArrayList<String>() { { add("datacenter"); add("UNIQUE"); } }; TriathlonService triathlonService = new TriathlonServiceImpl(); String content = IOUtils.toString(this.getClass().getResourceAsStream("unique_operator_1.json"), "UTF-8"); ByteBuf buffer = Unpooled.copiedBuffer(content.getBytes()); Marathon appDefinition = triathlonService.parseJson(Observable.just(buffer)).toBlocking().toFuture().get(); appDefinition.setInstances(5); ConstraintModel constraintModel = ConstraintModel.createConstraintModel(constraint); Operator cluster = new UniqueOperator(triathlonService, constraintModel); Operator spyCluster = Mockito.spy(cluster); doReturn(Observable.just(Unpooled.wrappedBuffer("TEST".getBytes()))).when(spyCluster) .getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString()); when(spyCluster.getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString())) .thenAnswer(invocation -> { Object[] args = invocation.getArguments(); Observable<ByteBuf> val = Observable .just(Unpooled.wrappedBuffer(((String) args[1]).getBytes())); Marathon appDef = triathlonService.parseJson(val).toBlocking().toFuture().get(); assertEquals(Integer.valueOf(1), appDef.getInstances()); return val; }); spyCluster.apply(appDefinition).subscribe(); verify(spyCluster, times(2)).getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString()); }
From source file:com.schibsted.triathlon.service.TriathlonServiceImplTest.java
License:Apache License
@Test public void testSerializeJson() throws Exception { String content = IOUtils.toString(this.getClass().getResourceAsStream("existing_datacenter.json"), "UTF-8"); ByteBuf buffer = Unpooled.copiedBuffer(content.getBytes()); TriathlonService service = new TriathlonServiceImpl(); Observable<Marathon> marathonObject = service.parseJson(Observable.just(buffer)); String serializedJson = service.serializeMarathon(marathonObject.toBlocking().toFuture().get()); assertThat(serializedJson, not(containsString("constraints"))); }
From source file:com.seagate.kinetic.client.io.provider.nio.http.HttpTransportProvider.java
License:Open Source License
/** * {@inheritDoc}// w ww . j a v a2 s .c o m */ @Override public void write(KineticMessage km) throws IOException { // interface message Message.Builder message = (Builder) km.getMessage(); // extended message ExtendedMessage.Builder extendedMessage = ExtendedMessage.newBuilder(); // set interface message extendedMessage.setInterfaceMessage(message); // set optional value if (km.getValue() != null) { extendedMessage.setValue(ByteString.copyFrom(km.getValue())); } // get serialized bytes byte[] array = extendedMessage.build().toByteArray(); // Prepare the HTTP request. DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/kinetic", Unpooled.copiedBuffer(array)); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.BINARY); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().set(CONNECTION, Values.KEEP_ALIVE); request.headers().set(CONTENT_TYPE, "application/octet-stream"); request.headers().set(HttpHeaders.Names.CONTENT_ENCODING, HttpHeaders.Values.BINARY); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes()); if (logger.isLoggable(Level.INFO)) { logger.info("writing http message, len=" + request.content().readableBytes()); } try { this.channel.writeAndFlush(request); } finally { // request.release(); } }
From source file:com.seagate.kinetic.simulator.io.provider.nio.http.HttpMessageServiceHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { int contentLength = 0; if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; logger.finest("protocol version: " + request.getProtocolVersion()); logger.finest("host: " + getHost(request, "unknown")); logger.finest("REQUEST_URI: " + request.getUri()); List<Map.Entry<String, String>> headers = request.headers().entries(); String lenstr = request.headers().get(HttpHeaders.Names.CONTENT_LENGTH); contentLength = Integer.parseInt(lenstr); logger.finest("content length=" + contentLength); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : request.headers().entries()) { String key = h.getKey(); String value = h.getValue(); logger.finest("HEADER: " + key + " = " + value); }/*from w w w. j ava 2s. c o m*/ } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { logger.finest("PARAM: " + key + " = " + val); } } } } // create extended builder ExtendedMessage.Builder extendedMessage = ExtendedMessage.newBuilder(); if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { byte[] body = new byte[contentLength]; content.getBytes(0, body); // read from serialized bytes extendedMessage.mergeFrom(body); } // build message ExtendedMessage extended = extendedMessage.build(); if (logger.isLoggable(Level.FINEST)) { logger.finest("received request: " + extended); } // create kinetic message for processing KineticMessage km = new KineticMessage(); // set interface message km.setMessage(extended.getInterfaceMessage()); // get command bytes ByteString commandBytes = extendedMessage.getInterfaceMessage().getCommandBytes(); // build command Command.Builder commandBuilder = Command.newBuilder(); try { commandBuilder.mergeFrom(commandBytes); km.setCommand(commandBuilder.build()); } catch (InvalidProtocolBufferException e) { logger.log(Level.WARNING, e.getMessage(), e); } // set value if (extended.hasValue()) { km.setValue(extended.getValue().toByteArray()); } // process request KineticMessage kmresp = this.lcservice.processRequest(km); // construct response message ExtendedMessage.Builder extendedResponse = ExtendedMessage.newBuilder(); // set interface message extendedResponse.setInterfaceMessage((Message.Builder) kmresp.getMessage()); // set value if (kmresp.getValue() != null) { extendedResponse.setValue(ByteString.copyFrom(kmresp.getValue())); } // get serialized value ByteBuf data = Unpooled.copiedBuffer(extendedResponse.build().toByteArray()); FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, data); httpResponse.headers().set(CONTENT_TYPE, "application/octet-stream"); httpResponse.headers().set(HttpHeaders.Names.CONTENT_ENCODING, HttpHeaders.Values.BINARY); httpResponse.headers().set(CONTENT_LENGTH, httpResponse.content().readableBytes()); httpResponse.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); // send response message ctx.writeAndFlush(httpResponse); if (logger.isLoggable(Level.FINEST)) { logger.finest("wrote and flushed response: " + kmresp); } } }
From source file:com.sk89q.worldedit.forge.ForgePlayer.java
License:Open Source License
@Override public void dispatchCUIEvent(CUIEvent event) { String[] params = event.getParameters(); String send = event.getTypeId(); if (params.length > 0) { send = send + "|" + StringUtil.joinString(params, "|"); }//from w w w .ja va 2 s .c o m PacketBuffer buffer = new PacketBuffer( Unpooled.copiedBuffer(send.getBytes(WECUIPacketHandler.UTF_8_CHARSET))); SPacketCustomPayload packet = new SPacketCustomPayload(ForgeWorldEdit.CUI_PLUGIN_CHANNEL, buffer); this.player.connection.sendPacket(packet); }
From source file:com.srotya.linea.network.InternalUDPTransportClient.java
License:Apache License
@Override public void onEvent(Event event, long sequence, boolean endOfBatch) throws Exception { Integer workerId = (Integer) event.getHeaders().get(Constants.FIELD_DESTINATION_WORKER_ID); try {/*from w ww . j a v a 2s.c o m*/ ByteBuffer buf = bufferMap.get(workerId); MutableShort bufferEventCount = bufferCounterMap.get(workerId); byte[] bytes = InternalTCPTransportServer.KryoObjectEncoder.eventToByteArray(event, InternalTCPTransportServer.COMPRESS); if (packingEnabled) { if (bytes.length > 1024) { // discard System.err.println("Discarded event"); } if (buf.remaining() - bytes.length >= 0) { buf.put(bytes); bufferEventCount.incrementAndGet(); } else { buf.putShort(0, bufferEventCount.getVal()); buf.rewind(); channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(buf), new InetSocketAddress(columbus.getWorkerMap().get(workerId).getWorkerAddress(), columbus.getWorkerMap().get(workerId).getDataPort()))); bufferEventCount.setVal((short) 0); buf.rewind(); buf.putShort(bufferEventCount.getVal()); buf.put(bytes); } } else { buf.rewind(); buf.putShort((short) 1); buf.put(bytes); buf.rewind(); channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(buf), new InetSocketAddress(columbus.getWorkerMap().get(workerId).getWorkerAddress(), columbus.getWorkerMap().get(workerId).getDataPort()))); } } catch (Exception e) { System.out.println("Exception:" + event + "\tSelf worker ID:" + columbus.getSelfWorkerId() + "\t" + workerId + "\t" + columbus.getWorkerMap()); throw e; } }