List of usage examples for io.netty.buffer ByteBuf readBytes
public abstract ByteBuf readBytes(ByteBuffer dst);
From source file:com.bosscs.spark.commons.extractor.client.codecs.ActionDecoder.java
License:Apache License
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { // Wait until the length prefix is available. if (in.readableBytes() < 5) { return;/*from w ww.j a v a 2s.c o m*/ } // Wait until the whole data is available. int dataLength = in.readInt(); if (in.readableBytes() < dataLength) { in.resetReaderIndex(); return; } // Convert the received data into a new BigInteger. byte[] decoded = new byte[dataLength]; in.readBytes(decoded); ByteArrayInputStream bis = new ByteArrayInputStream(decoded); ObjectInput inObj = null; Action action = null; try { inObj = new ObjectInputStream(bis); action = (Action) inObj.readObject(); } catch (IOException | ClassNotFoundException e) { LOG.error(e.getMessage()); } finally { try { bis.close(); } catch (IOException ex) { // ignore close exception } try { if (inObj != null) { inObj.close(); } } catch (IOException ex) { // ignore close exception } } out.add(action); }
From source file:com.bosscs.spark.commons.extractor.client.codecs.ResponseDecoder.java
License:Apache License
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { // Wait until the length prefix is available. if (in.readableBytes() < 5) { return;//from w w w . j a v a2s. com } // Wait until the whole data is available. int dataLength = in.readInt(); if (in.readableBytes() < dataLength) { in.resetReaderIndex(); return; } // Convert the received data into a new BigInteger. byte[] decoded = new byte[dataLength]; in.readBytes(decoded); ByteArrayInputStream bis = new ByteArrayInputStream(decoded); ObjectInput inObj = null; Response response = null; try { inObj = new ObjectInputStream(bis); response = (Response) inObj.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } finally { try { bis.close(); } catch (IOException ex) { // ignore close exception } try { if (inObj != null) { inObj.close(); } } catch (IOException ex) { // ignore close exception } } out.add(response); }
From source file:com.buildria.mocking.builder.action.RawBodyActionTest.java
License:Open Source License
@Test public void testApplyResponse() throws Exception { byte[] content = "content".getBytes(); Action action = new RawBodyAction(content); HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/p"); HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); res.headers().add(ACCEPT, "application/xml"); HttpResponse out = action.apply(req, res); assertThat(out, notNullValue());/* w w w.ja v a2s. c o m*/ assertThat(out.headers().get(CONTENT_LENGTH), is("7")); assertThat(out.headers().get(ACCEPT), is("application/xml")); assertThat(out, instanceOf(DefaultFullHttpResponse.class)); DefaultFullHttpResponse response = (DefaultFullHttpResponse) out; ByteBuf buf = response.content(); byte[] actual = new byte[buf.readableBytes()]; buf.readBytes(actual); assertThat(actual, is(content)); }
From source file:com.buildria.mocking.stub.Call.java
License:Open Source License
public static Call fromRequest(HttpRequest req) { Objects.requireNonNull(req);/*from w ww . j a v a 2 s . co m*/ Call call = new Call(); call.method = req.getMethod().name(); QueryStringDecoder decoder = new QueryStringDecoder(req.getUri()); call.path = QueryStringDecoder.decodeComponent(decoder.path()); Map<String, List<String>> params = decoder.parameters(); for (String name : params.keySet()) { List<String> values = params.get(name); for (String value : values) { call.parameters.add(new Pair(name, value)); } } HttpHeaders headers = req.headers(); for (String name : headers.names()) { List<String> values = headers.getAll(name); for (String value : values) { call.headers.add(new Pair(name, value)); } if (CONTENT_TYPE.equalsIgnoreCase(name)) { call.contentType = MediaType.parse(headers.get(CONTENT_TYPE)); } } if (req instanceof ByteBufHolder) { ByteBuf buf = ((ByteBufHolder) req).content(); if (buf != null) { call.body = new byte[buf.readableBytes()]; buf.readBytes(call.body); } } return call; }
From source file:com.cloudhopper.smpp.pdu.BaseSm.java
License:Apache License
@Override public void readBody(ByteBuf buffer) throws UnrecoverablePduException, RecoverablePduException { this.serviceType = ChannelBufferUtil.readNullTerminatedString(buffer); this.sourceAddress = ChannelBufferUtil.readAddress(buffer); this.destAddress = ChannelBufferUtil.readAddress(buffer); this.esmClass = buffer.readByte(); this.protocolId = buffer.readByte(); this.priority = buffer.readByte(); this.scheduleDeliveryTime = ChannelBufferUtil.readNullTerminatedString(buffer); this.validityPeriod = ChannelBufferUtil.readNullTerminatedString(buffer); this.registeredDelivery = buffer.readByte(); this.replaceIfPresent = buffer.readByte(); this.dataCoding = buffer.readByte(); this.defaultMsgId = buffer.readByte(); // this is always an unsigned version of the short message length short shortMessageLength = buffer.readUnsignedByte(); this.shortMessage = new byte[shortMessageLength]; buffer.readBytes(this.shortMessage); }
From source file:com.cloudhopper.smpp.util.ChannelBufferUtil.java
License:Apache License
/** * Reads a TLV from a buffer. This method is greedy and will read bytes * even if it won't be able to successfully complete. It's assumed this * method will only be called if its known ahead of time that all bytes * will be available ahead of time./*from w w w . ja va 2 s .c o m*/ * @param buffer The buffer to read from * @return A new TLV instance * @throws NotEnoughDataInBufferException */ static public Tlv readTlv(ByteBuf buffer) throws NotEnoughDataInBufferException { // a TLV is at least 4 bytes (tag+length) if (buffer.readableBytes() < 4) { throw new NotEnoughDataInBufferException("Parsing TLV tag and length", buffer.readableBytes(), 4); } short tag = buffer.readShort(); int length = buffer.readUnsignedShort(); // check if we have enough data for the TLV if (buffer.readableBytes() < length) { throw new NotEnoughDataInBufferException("Parsing TLV value", buffer.readableBytes(), length); } byte[] value = new byte[length]; buffer.readBytes(value); return new Tlv(tag, value); }
From source file:com.cloudhopper.smpp.util.ChannelBufferUtil.java
License:Apache License
/** * Reads a C-String (null terminated) from a buffer. This method will * attempt to find the null byte and read all data up to and including * the null byte. The returned String does not include the null byte. * Will throw an exception if no null byte is found and it runs out of data * in the buffer to read./*w w w . ja v a 2 s . co m*/ * @param buffer * @return * @throws TerminatingNullByteNotFoundException */ static public String readNullTerminatedString(ByteBuf buffer) throws TerminatingNullByteNotFoundException { // maximum possible length are the readable bytes in buffer int maxLength = buffer.readableBytes(); // if there are no readable bytes, return null if (maxLength == 0) { return null; } // the reader index is defaulted to the readerIndex int offset = buffer.readerIndex(); int zeroPos = 0; // search for NULL byte until we hit end or find it while ((zeroPos < maxLength) && (buffer.getByte(zeroPos + offset) != 0x00)) { zeroPos++; } if (zeroPos >= maxLength) { // a NULL byte was not found throw new TerminatingNullByteNotFoundException( "Terminating null byte not found after searching [" + maxLength + "] bytes"); } // at this point, we found a terminating zero String result = null; if (zeroPos > 0) { // read a new byte array byte[] bytes = new byte[zeroPos]; buffer.readBytes(bytes); try { result = new String(bytes, "ISO-8859-1"); } catch (UnsupportedEncodingException e) { logger.error("Impossible error", e); } } else { result = ""; } // at this point, we have just one more byte to skip over (the null byte) byte b = buffer.readByte(); if (b != 0x00) { logger.error("Impossible error: last byte read SHOULD have been a null byte, but was [" + b + "]"); } return result; }
From source file:com.codnos.dbgp.internal.handlers.DBGpCommandDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> objects) throws Exception { int nullPosition = in.forEachByte(ByteProcessor.FIND_NUL); if (nullPosition < 0) return;//www.ja va 2 s .c o m int length = nullPosition - in.readerIndex(); ByteBuf msgBuffer = in.readBytes(length); in.readByte(); objects.add(msgBuffer.toString(UTF_8)); msgBuffer.release(); }
From source file:com.codnos.dbgp.internal.handlers.DBGpResponseDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> objects) throws Exception { final int length = in.readableBytes(); LOGGER.fine("got something from engine (" + length + " bytes)"); int nullPosition = in.forEachByte(ByteProcessor.FIND_NUL); int readerIndex = in.readerIndex(); int numberOfBytes = nullPosition - readerIndex; LOGGER.fine("found nullposition on " + nullPosition + " and readerIndex is " + readerIndex + " calculated number of bytes " + numberOfBytes); if (numberOfBytes <= 0) { LOGGER.fine("not enough to read, finishing"); in.resetReaderIndex();/*from www . j ava2s .co m*/ return; } if (nullPosition > length) { LOGGER.fine("have null position further than length, finishing"); in.resetReaderIndex(); return; } ByteBuf sizeBuf = in.readBytes(numberOfBytes); in.readByte(); String sizeBufAsString = sizeBuf.toString(UTF_8); int size = Integer.parseInt(sizeBufAsString); int expectedSize = sizeBuf.readableBytes() + NULL_BYTE_SIZE + size + NULL_BYTE_SIZE; if (length < expectedSize) { LOGGER.fine("don't have the whole message yet (expected " + expectedSize + "), finishing"); in.resetReaderIndex(); sizeBuf.release(); return; } ByteBuf messageBuf = in.readBytes(size); in.readByte(); objects.add(messageBuf.toString(UTF_8)); sizeBuf.release(); messageBuf.release(); }
From source file:com.comphenix.protocol.compat.netty.independent.NettyChannelInjector.java
License:Open Source License
/** * Retrieve every byte in the given byte buffer. * @param buffer - the buffer.//from ww w. j av a 2 s . c om * @return The bytes. */ private byte[] getBytes(ByteBuf buffer) { byte[] data = new byte[buffer.readableBytes()]; buffer.readBytes(data); return data; }