List of usage examples for io.netty.buffer ByteBuf array
public abstract byte[] array();
From source file:org.graylog2.gelfclient.encoder.GelfTcpFrameDelimiterEncoderTest.java
License:Apache License
@Test public void testEncodeMultipleMessages() throws Exception { final EmbeddedChannel channel = new EmbeddedChannel(new GelfTcpFrameDelimiterEncoder()); final byte[] message1 = "Test1".getBytes(StandardCharsets.UTF_8); final byte[] message2 = "Test2".getBytes(StandardCharsets.UTF_8); assertTrue(channel.writeOutbound(Unpooled.wrappedBuffer(message1))); assertTrue(channel.writeOutbound(Unpooled.wrappedBuffer(message2))); assertTrue(channel.finish());/*ww w.j ava 2 s . c om*/ final ByteBuf outboundBuffer1 = (ByteBuf) channel.readOutbound(); final byte[] bytes1 = outboundBuffer1.array(); assertEquals(bytes1[bytes1.length - 1], (byte) 0); assertEquals(bytes1.length, message1.length + 1); final ByteBuf outboundBuffer2 = (ByteBuf) channel.readOutbound(); final byte[] bytes2 = outboundBuffer2.array(); assertEquals(bytes2[bytes2.length - 1], (byte) 0); assertEquals(bytes2.length, message2.length + 1); assertNull(channel.readOutbound()); }
From source file:org.graylog2.inputs.codecs.GelfChunkAggregatorTest.java
License:Open Source License
private byte[] generateMessageId(int id) { final ByteBuf messageId = Unpooled.buffer(8); // 4 bytes of current time. messageId.writeInt((int) System.currentTimeMillis()); messageId.writeInt(id);/* w w w .ja v a2 s .c o m*/ return messageId.array(); }
From source file:org.hornetq.amqp.dealer.protonimpl.AbstractProtonSender.java
License:Apache License
protected int performSend(ProtonJMessage serverMessage, Object context) { if (!creditsSemaphore.tryAcquire()) { try {//from w w w . j a va2s.c o m creditsSemaphore.acquire(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // nothing to be done here.. we just keep going throw new IllegalStateException(e.getMessage(), e); } } //presettle means we can ack the message on the dealer side before we send it, i.e. for browsers boolean preSettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED; //we only need a tag if we are going to ack later byte[] tag = preSettle ? new byte[0] : protonSession.getTag(); ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); try { serverMessage.encode(new NettyWritable(nettyBuffer)); int size = nettyBuffer.writerIndex(); synchronized (connection.getTrio().getLock()) { final Delivery delivery; delivery = sender.delivery(tag, 0, tag.length); delivery.setContext(context); // this will avoid a copy.. patch provided by Norman using buffer.array() sender.send(nettyBuffer.array(), nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(), nettyBuffer.readableBytes()); if (preSettle) { delivery.settle(); } else { sender.advance(); } } connection.flush(); return size; } finally { nettyBuffer.release(); } }
From source file:org.hornetq.amqp.dealer.util.DeliveryUtil.java
License:Apache License
public static int readDelivery(Receiver receiver, ByteBuf buffer) { int initial = buffer.writerIndex(); // optimization by norman int count;//ww w. j av a 2 s.c o m while ((count = receiver.recv(buffer.array(), buffer.arrayOffset() + buffer.writerIndex(), buffer.writableBytes())) > 0) { // Increment the writer index by the number of bytes written into it while calling recv. buffer.writerIndex(buffer.writerIndex() + count); } return buffer.writerIndex() - initial; }
From source file:org.hornetq.amqp.test.SimpleTest.java
License:Apache License
@Test public void testMeasureMessageImpl() { long time = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { if (i % 10000 == 0) { System.out.println("Decoded " + i); }/*ww w. j av a2 s . c o m*/ ByteBuf buf = PooledByteBufAllocator.DEFAULT.heapBuffer(1024 * 1024); MessageImpl message = (MessageImpl) Message.Factory.create(); message.setBody(new Data(new Binary(new byte[5]))); Properties props = new Properties(); props.setMessageId("Some String"); props.setAbsoluteExpiryTime(new Date(System.currentTimeMillis())); message.setProperties(props); message.encode(new NettyWritable(buf)); MessageImpl readMessage = (MessageImpl) Message.Factory.create(); readMessage.decode(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes()); buf.release(); } long total = System.currentTimeMillis() - time; System.out.println("Took " + total); }
From source file:org.kaaproject.kaa.server.transports.http.transport.commands.AbstractHttpSyncCommand.java
License:Apache License
@Override public HttpResponse getResponse() { LOG.trace("CommandName: " + COMMAND_NAME + ": getHttpResponse.."); ByteBuf data = Unpooled.copiedBuffer(responseBody); LOG.warn("Response data: {}", Arrays.toString(data.array())); FullHttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, data); httpResponse.headers().set(CONTENT_TYPE, CommonEpConstans.RESPONSE_CONTENT_TYPE); httpResponse.headers().set(CONTENT_LENGTH, data.readableBytes()); LOG.warn("Response size: {}", data.readableBytes()); httpResponse.headers().set(CommonEpConstans.RESPONSE_TYPE, CommonEpConstans.RESPONSE_TYPE_OPERATION); if (responseSignature != null) { httpResponse.headers().set(CommonEpConstans.SIGNATURE_HEADER_NAME, encodeBase64String(responseSignature)); }// ww w. j a v a 2 s .co m if (isNeedConnectionClose()) { httpResponse.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); } else { if (HttpHeaders.isKeepAlive(getRequest())) { httpResponse.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } else { httpResponse.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); } } return httpResponse; }
From source file:org.knoxcraft.netty.server.HttpUploadServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { try {//from w w w.j a va2 s. com if (msg instanceof FullHttpRequest) { FullHttpRequest fullRequest = (FullHttpRequest) msg; if (fullRequest.getUri().startsWith("/kctupload")) { if (fullRequest.getMethod().equals(HttpMethod.GET)) { // HTTP Get request! // Write the HTML page with the form writeMenu(ctx); } else if (fullRequest.getMethod().equals(HttpMethod.POST)) { /* * HTTP Post request! Handle the uploaded form * HTTP parameters: /kctupload username (should match player's Minecraft name) language (java, python, etc) jsonfile (a file upload, or empty) sourcefile (a file upload, or empty) jsontext (a JSON string, or empty) sourcetext (code as a String, or empty) */ String language = null; String playerName = null; String client = null; String jsonText = null; String sourceText = null; Map<String, UploadedFile> files = new LinkedHashMap<String, UploadedFile>(); HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(fullRequest); try { logger.trace("is multipart? " + decoder.isMultipart()); while (decoder.hasNext()) { InterfaceHttpData data = decoder.next(); if (data == null) continue; try { if (data.getHttpDataType() == HttpDataType.Attribute) { Attribute attribute = (Attribute) data; String name = attribute.getName(); String value = attribute.getValue(); logger.trace(String.format("http attribute: %s => %s", name, value)); if (name.equals("language")) { language = value; } else if (name.equals("playerName")) { playerName = value; } else if (name.equals("client")) { client = value; } else if (name.equals("jsontext")) { jsonText = value; } else if (name.equals("sourcetext")) { sourceText = value; } else { logger.warn(String.format("Unknown kctupload attribute: %s => %s", name, value)); } } else if (data.getHttpDataType() == HttpDataType.FileUpload) { // Handle file upload // We may have json, source, or both FileUpload fileUpload = (FileUpload) data; logger.debug(String.format("http file upload name %s, filename: ", data.getName(), fileUpload.getFilename())); String filename = fileUpload.getFilename(); ByteBuf buf = fileUpload.getByteBuf(); String fileBody = new String(buf.array(), "UTF-8"); files.put(data.getName(), new UploadedFile(filename, fileBody)); } } finally { data.release(); } } } finally { if (decoder != null) { // clean up resources decoder.cleanFiles(); decoder.destroy(); } } /* * Error checking here makes the most sense, since we can send back a reasonable error message * to the uploading client at this point. Makes less sense to wait to compile. * * Upload possibilities: * * bluej: file1, file2, etc. All source code. Language should be set to Java. * Convert to JSON, then to KCTScript. Signal an error if one happens. * * web: jsontext and/or sourcetext. json-only is OK; source-only is OK if it's Java. * Cannot send source-only for non-Java languages, since we can't build them (yet). * * anything else: convert to Json and hope for the best */ try { KCTUploadHook hook = new KCTUploadHook(); StringBuilder res = new StringBuilder(); if (playerName == null || playerName.equals("")) { // XXX How do we know that the playerName is valid? // TODO: authenticate against Mojang's server? throw new TurtleException("You must specify your MineCraft player name!"); } if (client == null) { throw new TurtleException("Your uploading and submission system must specify " + "the type of client used for the upload (i.e. bluej, web, pykc, etc)"); } hook.setPlayerName(playerName); res.append( String.format("Hello %s! Thanks for using KnoxCraft Turtles\n\n", playerName)); TurtleCompiler turtleCompiler = new TurtleCompiler(logger); int success = 0; int failure = 0; if (client.equalsIgnoreCase("web") || client.equalsIgnoreCase("testclient") || client.startsWith("pykc")) { // WEB OR PYTHON UPLOAD logger.trace("Upload from web"); // must have both Json and source, either in text area or as uploaded files //XXX Conlfict of comments of the top and here??? What do we need both/ only JSon? //Is there a want we want, thus forcing it if (sourceText != null && jsonText != null) { KCTScript script = turtleCompiler.parseFromJson(jsonText); script.setLanguage(language); script.setSourceCode(sourceText); res.append(String.format( "Successfully uploaded KnoxCraft Turtle program " + "named %s, in programming language %s\n", script.getScriptName(), script.getLanguage())); success++; hook.addScript(script); } else if (files.containsKey("jsonfile") && files.containsKey("sourcefile")) { UploadedFile sourceUpload = files.get("sourcefile"); UploadedFile jsonUpload = files.get("jsonfile"); KCTScript script = turtleCompiler.parseFromJson(jsonUpload.body); script.setLanguage(language); script.setSourceCode(sourceUpload.body); res.append(String.format( "Successfully uploaded KnoxCraft Turtle program " + "named %s, in programming language %s\n", script.getScriptName(), script.getLanguage())); success++; hook.addScript(script); } else { throw new TurtleException( "You must upload BOTH json and the corresponding source code " + " (either as files or pasted into the text areas)"); } } else if ("bluej".equalsIgnoreCase(client)) { // BLUEJ UPLOAD logger.trace("Upload from bluej"); for (Entry<String, UploadedFile> entry : files.entrySet()) { try { UploadedFile uploadedFile = entry.getValue(); res.append(String.format("Trying to upload and compile file %s\n", uploadedFile.filename)); logger.trace(String.format("Trying to upload and compile file %s\n", uploadedFile.filename)); KCTScript script = turtleCompiler .compileJavaTurtleCode(uploadedFile.filename, uploadedFile.body); logger.trace("Returned KCTScript (it's JSON is): " + script.toJSONString()); hook.addScript(script); res.append(String.format( "Successfully uploaded file %s and compiled KnoxCraft Turtle program " + "named %s in programming language %s\n\n", uploadedFile.filename, script.getScriptName(), script.getLanguage())); success++; } catch (TurtleCompilerException e) { logger.warn("Unable to compile Turtle code", e); res.append(String.format("%s\n\n", e.getMessage())); failure++; } catch (TurtleException e) { logger.error("Error in compiling (possibly a server side error)", e); res.append(String.format("Unable to process Turtle code %s\n\n", e.getMessage())); failure++; } catch (Exception e) { logger.error("Unexpected error compiling Turtle code to KCTScript", e); failure++; res.append(String.format("Failed to load script %s\n", entry.getKey())); } } } else { // UNKNOWN CLIENT UPLOAD // TODO Unknown client; make a best effort to handle upload res.append(String.format( "Unknown upload client: %s; making our best effort to handle the upload")); } res.append(String.format("\nSuccessfully uploaded %d KnoxCraft Turtles programs\n", success)); if (failure > 0) { res.append(String.format("\nFailed to upload %d KnoxCraft Turtles programs\n", failure)); } Canary.hooks().callHook(hook); writeResponse(ctx.channel(), fullRequest, res.toString(), client); } catch (TurtleException e) { // XXX can this still happen? Don't we catch all of these? writeResponse(ctx.channel(), fullRequest, e.getMessage(), "error"); } } } } } catch (Exception e) { logger.error("Internal Server Error: Channel error", e); throw e; } }
From source file:org.mashupbots.socko.netty.HttpChunkedFile.java
License:Apache License
@Override public HttpContent readChunk(ChannelHandlerContext ctx) throws Exception { long offset = this.offset; if (offset >= endOffset) { if (sentLastChunk) { return null; } else {/*from ww w.j a va 2 s.c o m*/ // Send last chunk for this file sentLastChunk = true; return new DefaultLastHttpContent(); } } int chunkSize = (int) Math.min(this.chunkSize, endOffset - offset); // Check if the buffer is backed by an byte array. If so we can optimize it a bit an safe a copy ByteBuf buf = ctx.alloc().heapBuffer(chunkSize); boolean release = true; try { file.readFully(buf.array(), buf.arrayOffset(), chunkSize); buf.writerIndex(chunkSize); this.offset = offset + chunkSize; release = false; return new DefaultHttpContent(buf); } finally { if (release) { buf.release(); } } }
From source file:org.onosproject.lisp.ctl.impl.LispMessageEncoderTest.java
License:Apache License
@Test public void testEncode() throws Exception { LispMessageEncoder encoder = new LispMessageEncoder(); MockLispMessage request = new MockLispMessage(LispType.LISP_MAP_REQUEST); MockLispMessage reply = new MockLispMessage(LispType.LISP_MAP_REPLY); MockLispMessage register = new MockLispMessage(LispType.LISP_MAP_REGISTER); MockLispMessage notify = new MockLispMessage(LispType.LISP_MAP_NOTIFY); ByteBuf buff = Unpooled.buffer(); List<DatagramPacket> list = Lists.newArrayList(); List<MockLispMessage> messages = ImmutableList.of(request, reply, register, notify); encoder.encode(null, messages, list); list.forEach(p -> {//w ww . j ava 2 s. c o m byte[] tmp = new byte[p.content().writerIndex()]; p.content().readBytes(tmp); buff.writeBytes(tmp); }); assertThat(buff, notNullValue()); StringBuilder expBuilder = new StringBuilder(); expBuilder.append("LISP message [LISP_MAP_REQUEST] "); expBuilder.append("LISP message [LISP_MAP_REPLY] "); expBuilder.append("LISP message [LISP_MAP_REGISTER] "); expBuilder.append("LISP message [LISP_MAP_NOTIFY] "); String expected = expBuilder.toString(); String returned = new String(buff.array(), StandardCharsets.UTF_8).substring(0, expected.length()); assertThat(returned, is(expected)); }
From source file:org.onosproject.lisp.ctl.LispMessageEncoderTest.java
License:Apache License
public void testEncode() throws Exception { LispMessageEncoder encoder = new LispMessageEncoder(); MockLispMessage request = new MockLispMessage(LispType.LISP_MAP_REQUEST); MockLispMessage reply = new MockLispMessage(LispType.LISP_MAP_REPLY); MockLispMessage register = new MockLispMessage(LispType.LISP_MAP_REGISTER); MockLispMessage notify = new MockLispMessage(LispType.LISP_MAP_NOTIFY); ByteBuf buff = Unpooled.buffer(); List<MockLispMessage> messages = ImmutableList.of(request, reply, register, notify); encoder.encode(null, messages, Lists.newArrayList()); assertThat(buff, notNullValue());//from ww w . j a v a2 s. c o m StringBuilder expBuilder = new StringBuilder(); expBuilder.append("LISP message [LISP_MAP_REQUEST] "); expBuilder.append("LISP message [LISP_MAP_REPLY] "); expBuilder.append("LISP message [LISP_MAP_REGISTER] "); expBuilder.append("LISP message [LISP_MAP_NOTIFY] "); String expected = expBuilder.toString(); String returned = new String(buff.array(), StandardCharsets.UTF_8).substring(0, expected.length()); assertThat(returned, is(expected)); }