List of usage examples for io.netty.buffer ByteBuf array
public abstract byte[] array();
From source file:org.apache.tajo.util.NumberUtil.java
License:Apache License
/** * Parses the byte buffer argument as if it was an long value and returns the * result. Throws NumberFormatException if the string does not represent an * long quantity. The second argument specifies the radix to use when parsing * the value./*ww w . j a va 2s. c o m*/ * * @param bytes the string byte buffer * @param start * @param length a UTF-8 encoded string representation of a long quantity. * @param radix the base to use for conversion. * @return the value represented by the argument * @throws NumberFormatException if the argument could not be parsed as an long quantity. */ public static long parseLong(ByteBuf bytes, int start, int length, int radix) { if (!PlatformDependent.hasUnsafe()) { return parseInt(bytes.array(), start, length); } if (bytes == null) { throw new NumberFormatException("String is null"); } if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new NumberFormatException("Invalid radix: " + radix); } if (length == 0 || bytes.writerIndex() < start + length) { throw new NumberFormatException("Empty string or Invalid buffer!"); } long memoryAddress = bytes.memoryAddress(); int offset = start; boolean negative = PlatformDependent.getByte(memoryAddress + start) == '-'; if (negative || PlatformDependent.getByte(memoryAddress + start) == '+') { offset++; if (length == 1) { throw new NumberFormatException(bytes.toString(start, length, Charset.defaultCharset())); } } return parseLongInternal(bytes, memoryAddress, start, length, offset, radix, negative); }
From source file:org.asynchttpclient.providers.netty4.util.ByteBufUtil.java
License:Apache License
public static byte[] byteBuf2bytes(ByteBuf b) { int readable = b.readableBytes(); int readerIndex = b.readerIndex(); if (b.hasArray()) { byte[] array = b.array(); if (b.arrayOffset() == 0 && readerIndex == 0 && array.length == readable) { return array; }/* w ww. j a va 2 s . com*/ } byte[] array = new byte[readable]; b.getBytes(readerIndex, array); return array; }
From source file:org.atmosphere.nettosphere.BridgeRuntime.java
License:Apache License
private void handleHttp(final ChannelHandlerContext ctx, final Object messageEvent) throws URISyntaxException, IOException { boolean skipClose = false; AtmosphereResponse response = null;/*from www . j a v a2s .co m*/ AtmosphereRequest request = null; Action a = null; boolean resumeOnBroadcast = false; boolean keptOpen = false; ChannelWriter asyncWriter = null; String method = "GET"; boolean writeHeader = false; boolean forceSuspend = false; boolean aggregateBodyInMemory = config.aggregateRequestBodyInMemory(); try { if (messageEvent instanceof HttpRequest) { final HttpRequest hrequest = (HttpRequest) messageEvent; byte[] body = EMPTY; if (FullHttpRequest.class.isAssignableFrom(messageEvent.getClass())) { ByteBuf b = FullHttpRequest.class.cast(messageEvent).content(); if (b.isReadable()) { body = new byte[b.readableBytes()]; b.readBytes(body); } } // First let's try to see if it's a static resources if (!hrequest.getUri().contains(HeaderConfig.X_ATMOSPHERE)) { try { hrequest.headers().add(STATIC_MAPPING, "true"); super.channelRead(ctx, messageEvent); if (HttpHeaders.getHeader(hrequest, SERVICED) != null) { return; } } catch (Exception e) { logger.debug("Unexpected State", e); } finally { hrequest.headers().set(STATIC_MAPPING, "false"); } } boolean ka = HttpHeaders.isKeepAlive(hrequest); asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), true, ka) : new StreamWriter(ctx.channel(), true, ka); method = hrequest.getMethod().name(); request = createAtmosphereRequest(ctx, hrequest, body); request.setAttribute(KEEP_ALIVE, new Boolean(ka)); // Hacky. Is the POST doesn't contains a body, we must not close the connection yet. AtmosphereRequestImpl.Body b = request.body(); if (!aggregateBodyInMemory && !hrequest.getMethod().equals(GET) && !b.isEmpty() && (b.hasString() && b.asString().isEmpty()) || (b.hasBytes() && b.asBytes().length == 0)) { forceSuspend = true; } } else { request = State.class.cast(ctx.attr(ATTACHMENT).get()).request; boolean isLast = HttpChunkedInput.class.cast(messageEvent).isEndOfInput(); Boolean ka = (Boolean) request.getAttribute(KEEP_ALIVE); asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), isLast, ka) : new StreamWriter(ctx.channel(), isLast, ka); method = request.getMethod(); ByteBuf internalBuffer = HttpChunkedInput.class.cast(messageEvent).readChunk(ctx).content(); if (!aggregateBodyInMemory && internalBuffer.hasArray()) { request.body(internalBuffer.array()); } else { logger.trace("Unable to read in memory the request's bytes. Using stream"); request.body(new ByteBufInputStream(internalBuffer)); } if (!isLast) { forceSuspend = true; } } response = new AtmosphereResponseImpl.Builder().asyncIOWriter(asyncWriter).writeHeader(writeHeader) .destroyable(false).header("Connection", "Keep-Alive").header("Server", "Nettosphere/3.0") .request(request).build(); if (config.supportChunking()) { response.setHeader("Transfer-Encoding", "chunked"); } a = framework.doCometSupport(request, response); if (forceSuspend) { a.type(Action.TYPE.SUSPEND); // leave the stream open keptOpen = true; } String transport = (String) request.getAttribute(FrameworkConfig.TRANSPORT_IN_USE); if (transport == null) { transport = request.getHeader(X_ATMOSPHERE_TRANSPORT); } if (a.type() == Action.TYPE.SUSPEND) { if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.STREAMING_TRANSPORT) || transport.equalsIgnoreCase(SSE_TRANSPORT))) { keptOpen = true; } else if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.LONG_POLLING_TRANSPORT) || transport.equalsIgnoreCase(HeaderConfig.JSONP_TRANSPORT))) { resumeOnBroadcast = true; } } final Action action = (Action) request.getAttribute(NettyCometSupport.SUSPEND); final State state = new State(request, action == null ? Action.CONTINUE : action); ctx.attr(ATTACHMENT).set(state); if (action != null && action.type() == Action.TYPE.SUSPEND) { if (action.timeout() != -1) { final AtomicReference<ChannelWriter> w = new AtomicReference<ChannelWriter>(asyncWriter); final AtomicReference<Future<?>> f = new AtomicReference<Future<?>>(); f.set(suspendTimer.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (!w.get().isClosed() && (System.currentTimeMillis() - w.get().lastTick()) > action.timeout()) { AtmosphereResourceImpl impl = state.resource(); if (impl != null) { asynchronousProcessor.endRequest(impl, false); f.get().cancel(true); } } } }, action.timeout(), action.timeout(), TimeUnit.MILLISECONDS)); } } else if (action != null && action.type() == Action.TYPE.RESUME) { resumeOnBroadcast = false; } } catch (AtmosphereMappingException ex) { if (method.equalsIgnoreCase("GET")) { logger.trace("Unable to map the request {}, trying static file", messageEvent); } } catch (Throwable e) { logger.error("Unable to process request", e); throw new IOException(e); } finally { try { if (asyncWriter != null && !resumeOnBroadcast && !keptOpen) { if (!skipClose && response != null) { asyncWriter.close(response); } else { httpChannels.add(ctx.channel()); } } } finally { if (request != null && a != null && a.type() != Action.TYPE.SUSPEND) { request.destroy(); response.destroy(); framework.notify(Action.TYPE.DESTROYED, request, response); } } } }
From source file:org.ballerinalang.broker.BallerinaBroker.java
License:Open Source License
/** * Method to publish to a topic in the broker operating in in-memory mode, specifying the ByteBuf to publish. * * @param topic the topic for which the subscription is registered * @param payload the ByteBuf representing the payload to publish (message content) */// w w w.ja va 2 s .c om public void publish(String topic, ByteBuf payload) { Message message = new Message(Broker.getNextMessageId(), new Metadata(topic, "amq.topic", payload.array().length)); message.addChunk(new ContentChunk(0, payload)); try { broker.publish(message); } catch (BrokerException e) { logger.error("Error publishing to topic: ", e); } }
From source file:org.enderstone.server.packet.NetworkEncrypter.java
License:Open Source License
protected ByteBuf decrypt(ChannelHandlerContext ctx, ByteBuf inbytes) throws ShortBufferException { int readableBytes = inbytes.readableBytes(); byte[] byteArray = fillInBuffer(inbytes); ByteBuf localByteBuf = ctx.alloc().heapBuffer(this.cipher.getOutputSize(readableBytes)); localByteBuf.writerIndex(//from w w w.j a v a2 s. c o m this.cipher.update(byteArray, 0, readableBytes, localByteBuf.array(), localByteBuf.arrayOffset())); return localByteBuf; }
From source file:org.ensembl.gti.seqstore.server.RequestResponseServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { log.trace("Reading message"); ByteBuf in = (ByteBuf) msg;// w ww. jav a 2 s . com int l = in.readInt(); log.trace("Reading message of length " + l); ByteBuf x = in.readBytes(l); Response response = null; try { Request request = Request.parseFrom(x.array()); log.debug("Received " + request.getOperation()); String responseMsg; switch (request.getOperation()) { case START_SESSION: log.debug("Creating new session for " + request.getClientId()); Long id = seqStore.startSession(request.getClientId()); responseMsg = id.toString(); break; case ABORT_SESSION: log.debug("Aborting session " + request.getSessionId() + " for " + request.getClientId()); seqStore.clearSession(request.getSessionId()); responseMsg = "Aborted session " + request.getSessionId(); break; case STORE_GENOME: log.debug("Storing " + request.getGeneCount() + " genes"); long genomeId = seqStore.storeGenome(request.getSessionId(), new GenomeDelegate(request.getGenome())); responseMsg = String.valueOf(genomeId); break; case STORE_GENOME_SEQUENCE: log.info("Storing " + request.getGenomeSequenceCount() + " genome sequences"); int n = 0; for (GenomeSequence g : request.getGenomeSequenceList()) { seqStore.storeGenomeSequence(request.getSessionId(), new GenomeSequenceDelegate(g)); n++; } responseMsg = "Stored " + n + " genome sequences"; break; case STORE_GENE: log.debug("Storing " + request.getGeneCount() + " genes"); n = 0; for (Gene g : request.getGeneList()) { seqStore.storeGene(request.getSessionId(), new GeneDelegate(g)); n++; } responseMsg = "Stored " + n + " genes"; break; default: responseMsg = "Unknown operation " + request.getOperation(); response = Response.newBuilder().setStatus(Status.DATA_ERROR).setMessage(responseMsg).build(); throw new UnsupportedOperationException(responseMsg); } response = Response.newBuilder().setStatus(Status.OK).setMessage(responseMsg).build(); } catch (SeqStoreException e) { log.error("Error processing request", e); response = Response.newBuilder().setStatus(Status.DATA_ERROR).setMessage(e.getMessage()).build(); } catch (Throwable e) { log.error("Error processing request", e); response = Response.newBuilder().setStatus(Status.SERVER_ERROR).setMessage(e.getMessage()).build(); } finally { byte[] ra = response.toByteArray(); ctx.write(Unpooled.copyInt(ra.length)); ctx.write(Unpooled.copiedBuffer(ra)); ctx.flush(); if (x != null) x.release(); if (in != null) in.release(); } }
From source file:org.fiware.kiara.netty.Buffers.java
License:Open Source License
public static ByteBuffer toByteBuffer(ByteBuf msg) { final byte[] array; final int offset; final int length = msg.readableBytes(); if (msg.hasArray()) { array = msg.array(); offset = msg.arrayOffset() + msg.readerIndex(); } else {/*from w w w .j a v a 2s.c o m*/ array = new byte[length]; msg.getBytes(msg.readerIndex(), array, 0, length); offset = 0; } return ByteBuffer.wrap(array, offset, length); }
From source file:org.fiware.kiara.transport.http.HttpHandler.java
License:Open Source License
@Override protected void channelRead0(final ChannelHandlerContext ctx, Object msg) throws Exception { logger.debug("Handler: {} / Channel: {}", this, ctx.channel()); if (mode == Mode.SERVER) { if (msg instanceof FullHttpRequest) { final FullHttpRequest request = (FullHttpRequest) msg; HttpRequestMessage transportMessage = new HttpRequestMessage(this, request); transportMessage.setPayload(request.content().copy().nioBuffer()); if (logger.isDebugEnabled()) { logger.debug("RECEIVED CONTENT {}", HexDump.dumpHexString(transportMessage.getPayload())); //logger.debug("RECEIVED REQUEST WITH CONTENT {}", Util.bufferToString(transportMessage.getPayload())); }//from w ww . java 2 s .c om notifyListeners(transportMessage); boolean keepAlive = HttpHeaders.isKeepAlive(request); } } else { // CLIENT if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; headers = response.headers(); //if (!response.headers().isEmpty()) { // contentType = response.headers().get("Content-Type"); //} } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; ByteBuf buf = content.content(); if (buf.isReadable()) { if (buf.hasArray()) { bout.write(buf.array(), buf.readerIndex(), buf.readableBytes()); } else { byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(buf.readerIndex(), bytes); bout.write(bytes); } } if (content instanceof LastHttpContent) { //ctx.close(); bout.flush(); HttpResponseMessage response = new HttpResponseMessage(this, headers); response.setPayload(ByteBuffer.wrap(bout.toByteArray(), 0, bout.size())); onResponse(response); bout.reset(); } } } }
From source file:org.graylog2.gelfclient.encoder.GelfCompressionEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { try (final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final GZIPOutputStream stream = new GZIPOutputStream(bos)) { stream.write(msg.array()); stream.finish();//from w w w . ja v a2 s. com out.add(Unpooled.wrappedBuffer(bos.toByteArray())); } }
From source file:org.graylog2.gelfclient.encoder.GelfTcpFrameDelimiterEncoderTest.java
License:Apache License
@Test public void testEncode() throws Exception { final EmbeddedChannel channel = new EmbeddedChannel(new GelfTcpFrameDelimiterEncoder()); final byte[] message = "Test string".getBytes(StandardCharsets.UTF_8); assertTrue(channel.writeOutbound(Unpooled.wrappedBuffer(message))); assertTrue(channel.finish());//from www. j av a 2 s . c om final ByteBuf outboundBuffer = (ByteBuf) channel.readOutbound(); final byte[] bytes = outboundBuffer.array(); assertEquals(bytes[bytes.length - 1], (byte) 0); assertEquals(bytes.length, message.length + 1); assertNull(channel.readOutbound()); }