List of usage examples for io.netty.buffer ByteBuf readableBytes
public abstract int readableBytes();
From source file:com.github.sylvek.wsmqttfwd.decoder.PublishDecoder.java
License:Open Source License
@Override public PublishMessage decode(AttributeMap ctx, ByteBuf in) throws Exception { LOG.debug("decode invoked with buffer {}", in); in.resetReaderIndex();//from ww w .ja va 2 s.c om int startPos = in.readerIndex(); //Common decoding part PublishMessage message = new PublishMessage(); if (!decodeCommonHeader(message, in)) { LOG.debug("decode ask for more data after {}", in); in.resetReaderIndex(); return null; } int remainingLength = message.getRemainingLength(); //Topic name String topic = Utils.decodeString(in); if (topic == null) { in.resetReaderIndex(); return null; } //[MQTT-3.3.2-2] The Topic Name in the PUBLISH Packet MUST NOT contain wildcard characters. if (topic.contains("+") || topic.contains("#")) { throw new CorruptedFrameException( "Received a PUBLISH with topic containing wild card chars, topic: " + topic); } //check topic is at least one char [MQTT-4.7.3-1] if (topic.length() == 0) { throw new CorruptedFrameException("Received a PUBLISH with topic without any character"); } message.setTopicName(topic); if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) { message.setMessageID(in.readUnsignedShort()); } int stopPos = in.readerIndex(); //read the payload int payloadSize = remainingLength - (stopPos - startPos - 2) + (Utils.numBytesToEncode(remainingLength) - 1); if (in.readableBytes() < payloadSize) { in.resetReaderIndex(); return null; } ByteBuf bb = Unpooled.buffer(payloadSize); in.readBytes(bb); message.setPayload(bb.nioBuffer()); return message; }
From source file:com.github.sylvek.wsmqttfwd.decoder.Utils.java
License:Open Source License
public static boolean checkHeaderAvailability(ByteBuf in) { if (in.readableBytes() < 1) { return false; }//from www . j ava 2 s . c om //byte h1 = in.get(); //byte messageType = (byte) ((h1 & 0x00F0) >> 4); in.skipBytes(1); //skip the messageType byte int remainingLength = Utils.decodeRemainingLength(in); if (remainingLength == -1) { return false; } //check remaining length if (in.readableBytes() < remainingLength) { return false; } //return messageType == type ? MessageDecoderResult.OK : MessageDecoderResult.NOT_OK; return true; }
From source file:com.github.sylvek.wsmqttfwd.decoder.Utils.java
License:Open Source License
/** * Decode the variable remaining length as defined in MQTT v3.1 specification * (section 2.1).//from w w w.ja v a 2 s. c o m * * @return the decoded length or -1 if needed more data to decode the length field. */ static int decodeRemainingLength(ByteBuf in) { int multiplier = 1; int value = 0; byte digit; do { if (in.readableBytes() < 1) { return -1; } digit = in.readByte(); value += (digit & 0x7F) * multiplier; multiplier *= 128; } while ((digit & 0x80) != 0); return value; }
From source file:com.github.wens.netty.web.impl.RequestImp.java
License:Apache License
private void readBody() { try {/*from w ww . java 2 s . co m*/ ByteBuf content = httpRequest.content(); int readableBytes = content.readableBytes(); bodyBytes = new byte[readableBytes]; content.readBytes(bodyBytes); bodyString = new String(bodyBytes); } catch (Exception e) { throw new WebException("Exception when reading body", e); } }
From source file:com.goodgamenow.source.serverquery.MasterQueryHandler.java
License:Open Source License
/** * Decodes a master server response datagram packet into a list of * game server addresses.//from w ww . j av a2s .c o m * * @param ctx channel handler context * @param msg master server response packet * @exception UnsupportedEncodingException */ @Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws UnsupportedEncodingException { ByteBuf buf = msg.content(); // sanity check int ADDR_WIDTH = 6; assert (buf.readableBytes() % ADDR_WIDTH) == 0 : "Master response byte count is not 6 byte aligned."; // decode response header String header = decodeIpAddress(buf); assert EXPECTED_HEADER_STRING.equals(header); while (buf.isReadable(ADDR_WIDTH)) { lastAddress = decodeIpAddress(buf); // A last address of 0.0.0.0:0 denotes the end of transmission. if (DEFAULT_IP.equals(lastAddress)) { ctx.flush(); ctx.close(); finishTime = System.currentTimeMillis(); return; } if (parentContext != null) { InetSocketAddress address = createInetSocketAddress(lastAddress); ServerQuery template = query.template; ServerQuery squery = ServerQuery.createFromTemplate(address, template); parentContext.fireChannelRead(squery); } else { if (results == null) { // should never happen throw new IllegalStateException("Results container is null when there is no other " + "ChannelHandlerContext to send results."); } // we are storing for bulk access later. results.add(lastAddress); } } assert buf.readableBytes() == 0; // ask for more results this.channelActive(ctx); }
From source file:com.goodgamenow.source.serverquery.MasterQueryHandler.java
License:Open Source License
/** * Decodes the address and port from a six byte representation * 001.002.003.004:00056//w w w. j a va 2s.c o m * * @param buf master server response buffer * @return IpAddress:port representation */ private static String decodeIpAddress(ByteBuf buf) { assert 0 == (buf.readableBytes() % 6); return String.valueOf(decodeAddress(buf) + ':' + decodePort(buf)); }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpDownloadHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (!msg.decoderResult().isSuccess()) { failAndClose(new IOException("Failed to parse the HTTP response."), ctx); return;/* w ww . ja v a 2s.c o m*/ } if (!(msg instanceof HttpResponse) && !(msg instanceof HttpContent)) { failAndClose( new IllegalArgumentException("Unsupported message type: " + StringUtil.simpleClassName(msg)), ctx); return; } checkState(userPromise != null, "response before request"); if (msg instanceof HttpResponse) { response = (HttpResponse) msg; if (!response.protocolVersion().equals(HttpVersion.HTTP_1_1)) { HttpException error = new HttpException(response, "HTTP version 1.1 is required, was: " + response.protocolVersion(), null); failAndClose(error, ctx); return; } if (!HttpUtil.isContentLengthSet(response) && !HttpUtil.isTransferEncodingChunked(response)) { HttpException error = new HttpException(response, "Missing 'Content-Length' or 'Transfer-Encoding: chunked' header", null); failAndClose(error, ctx); return; } downloadSucceeded = response.status().equals(HttpResponseStatus.OK); if (!downloadSucceeded) { out = new ByteArrayOutputStream(); } keepAlive = HttpUtil.isKeepAlive((HttpResponse) msg); } if (msg instanceof HttpContent) { checkState(response != null, "content before headers"); ByteBuf content = ((HttpContent) msg).content(); content.readBytes(out, content.readableBytes()); if (msg instanceof LastHttpContent) { if (downloadSucceeded) { succeedAndReset(ctx); } else { String errorMsg = response.status() + "\n"; errorMsg += new String(((ByteArrayOutputStream) out).toByteArray(), HttpUtil.getCharset(response)); out.close(); HttpException error = new HttpException(response, errorMsg, null); failAndReset(error, ctx); } } } }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpDownloadHandlerTest.java
License:Open Source License
/** * Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND) with a * Content-Length header.//from www .jav a 2 s . c o m */ @Test public void httpErrorsWithContentAreSupported() throws IOException { EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler(null)); ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream()); DownloadCommand cmd = new DownloadCommand(CACHE_URI, true, "abcdef", out); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(cmd, writePromise); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); ByteBuf errorMessage = ByteBufUtil.writeAscii(ch.alloc(), "Error message"); response.headers().set(HttpHeaders.HOST, "localhost"); response.headers().set(HttpHeaders.CONTENT_LENGTH, String.valueOf(errorMessage.readableBytes())); response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.CLOSE); ch.writeInbound(response); // The promise must not be done because we haven't received the error message yet. assertThat(writePromise.isDone()).isFalse(); ch.writeInbound(new DefaultHttpContent(errorMessage)); ch.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT); assertThat(writePromise.isDone()).isTrue(); assertThat(writePromise.cause()).isInstanceOf(HttpException.class); assertThat(((HttpException) writePromise.cause()).response().status()) .isEqualTo(HttpResponseStatus.NOT_FOUND); // No data should have been written to the OutputStream and it should have been closed. assertThat(out.size()).isEqualTo(0); // The caller is responsible for closing the stream. verify(out, never()).close(); assertThat(ch.isOpen()).isFalse(); }
From source file:com.growcontrol.common.netty.JsonObjectDecoder.java
License:Apache License
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception { if (this.state == ST_CORRUPTED) { in.skipBytes(in.readableBytes()); return;//from w ww . ja v a 2s. c o m } // index of next byte to process. int idx = this.idx; final int wrtIdx = in.writerIndex(); if (wrtIdx > this.maxObjectLength) { // buffer size exceeded maxObjectLength; discarding the complete buffer. in.skipBytes(in.readableBytes()); reset(); throw new TooLongFrameException( "object length exceeds " + this.maxObjectLength + ": " + wrtIdx + " bytes discarded"); } for (/* use current idx */; idx < wrtIdx; idx++) { final byte c = in.getByte(idx); if (this.state == ST_DECODING_NORMAL) { decodeByte(c, in, idx); // All opening braces/brackets have been closed. That's enough to conclude // that the JSON object/array is complete. if (this.openBraces == 0) { ByteBuf json = extractObject(ctx, in, in.readerIndex(), idx + 1 - in.readerIndex()); if (json != null) { out.add(json); } // The JSON object/array was extracted => discard the bytes from // the input buffer. in.readerIndex(idx + 1); // Reset the object state to get ready for the next JSON object/text // coming along the byte stream. reset(); } } else if (this.state == ST_DECODING_ARRAY_STREAM) { decodeByte(c, in, idx); if (!this.insideString && (this.openBraces == 1 && c == ',' || this.openBraces == 0 && c == ']')) { // skip leading spaces. No range check is needed and the loop will terminate // because the byte at position idx is not a whitespace. for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) { in.skipBytes(1); } // skip trailing spaces. int idxNoSpaces = idx - 1; while (idxNoSpaces >= in.readerIndex() && Character.isWhitespace(in.getByte(idxNoSpaces))) { idxNoSpaces--; } ByteBuf json = extractObject(ctx, in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex()); if (json != null) { out.add(json); } in.readerIndex(idx + 1); if (c == ']') { reset(); } } // JSON object/array detected. Accumulate bytes until all braces/brackets are closed. } else if (c == '{' || c == '[') { initDecoding(c); // Discard the array bracket if (this.state == ST_DECODING_ARRAY_STREAM) in.skipBytes(1); // Discard leading spaces in front of a JSON object/array. } else if (Character.isWhitespace(c)) { in.skipBytes(1); } else { this.state = ST_CORRUPTED; throw new CorruptedFrameException( "invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in)); } } if (in.readableBytes() == 0) this.idx = 0; else this.idx = idx; }
From source file:com.gw.services.client.HttpsClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;/*from w w w. j ava 2 s. co m*/ } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } // Configure SSL context if necessary. final boolean ssl = "https".equalsIgnoreCase(scheme); final SSLContext sslCtx; if (ssl) { sslCtx = CLIENT_CONTEXT; } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpsClientInitializer(sslCtx)); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); String requestBody = "{\"productId\": 11,\"userName\": \"caiwei\",\"amount\": 1000}"; ByteBuf content = Unpooled.copiedBuffer(requestBody.getBytes(CharsetUtil.UTF_8)); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(), content); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json"); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes()); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // Send the HTTP request. ch.writeAndFlush(request); // Wait for the server to close the connection. ch.closeFuture().sync(); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); } }