List of usage examples for io.netty.buffer ByteBuf readableBytes
public abstract int readableBytes();
From source file:com.lambdaworks.redis.protocol.CommandArgs.java
License:Apache License
@Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer(singularArguments.size() * 10); encode(buffer);//from www . ja va2s . c o m buffer.resetReaderIndex(); byte[] bytes = new byte[buffer.readableBytes()]; buffer.readBytes(bytes); sb.append(" [buffer=").append(new String(bytes)); sb.append(']'); buffer.release(); return sb.toString(); }
From source file:com.lampard.netty4.frame.fault.TimeServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req);/* w ww .j a v a 2 s . co m*/ String body = new String(req, "UTF-8").substring(0, req.length - System.getProperty("line.separator").length()); System.out.println("The time server receive order : " + body + " ; the counter is : " + ++counter); String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(System.currentTimeMillis()).toString() : "BAD ORDER"; currentTime = currentTime + System.getProperty("line.separator"); ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes()); ctx.writeAndFlush(resp); }
From source file:com.ldp.nettydemo.netty.codec.NettyMessageDecoder.java
License:Apache License
@Override protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf frame = (ByteBuf) super.decode(ctx, in); if (frame == null) { return null; }//w w w . j a v a2 s. c o m NettyMessage message = new NettyMessage(); Header header = new Header(); header.setCrcCode(frame.readInt()); header.setLength(frame.readInt()); header.setSessionID(frame.readLong()); header.setType(frame.readByte()); header.setPriority(frame.readByte()); int size = frame.readInt(); if (size > 0) { Map<String, Object> attch = new HashMap<String, Object>(size); int keySize = 0; byte[] keyArray = null; String key = null; for (int i = 0; i < size; i++) { keySize = frame.readInt(); keyArray = new byte[keySize]; frame.readBytes(keyArray); key = new String(keyArray, "UTF-8"); attch.put(key, ByteObjConverter.ByteToObject(new ByteBufToBytes().read(frame))); // attch.put(key, marshallingDecoder.decode(frame)); } keyArray = null; key = null; header.setAttachment(attch); } if (frame.readableBytes() > 4) { message.setBody(ByteObjConverter.ByteToObject(new ByteBufToBytes().read(frame))); // message.setBody(marshallingDecoder.decode(frame)); } message.setHeader(header); return message; }
From source file:com.ldp.nettydemo.netty.codec.NettyMessageEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, NettyMessage msg, ByteBuf sendBuf) throws Exception { if (msg == null || msg.getHeader() == null) throw new Exception("The encode message is null"); sendBuf.writeInt((msg.getHeader().getCrcCode())); sendBuf.writeInt((msg.getHeader().getLength())); sendBuf.writeLong((msg.getHeader().getSessionID())); sendBuf.writeByte((msg.getHeader().getType())); sendBuf.writeByte((msg.getHeader().getPriority())); sendBuf.writeInt((msg.getHeader().getAttachment().size())); String key = null;//from w w w . j av a 2 s. co m byte[] keyArray = null; Object value = null; for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) { key = param.getKey(); keyArray = key.getBytes("UTF-8"); sendBuf.writeInt(keyArray.length); sendBuf.writeBytes(keyArray); value = param.getValue(); sendBuf.writeBytes(ByteObjConverter.ObjectToByte(value)); // marshallingEncoder.encode(value, sendBuf); } key = null; keyArray = null; value = null; if (msg.getBody() != null) { sendBuf.writeBytes(ByteObjConverter.ObjectToByte(msg.getBody())); // marshallingEncoder.encode(msg.getBody(), sendBuf); } else sendBuf.writeInt(0); sendBuf.setInt(4, sendBuf.readableBytes() - 8); }
From source file:com.leadtone.riders.server.RidersWebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;//from w w w. j av a 2 s. c o m } // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the demo page and favicon.ico if ("/".equals(req.getUri())) { ByteBuf content = RidersWebSocketServerIndexPage.getContent(getWebSocketLocation(req)); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); setContentLength(res, content.readableBytes()); logger.info("response content " + res.content().toString()); sendHttpResponse(ctx, req, res); return; } if ("/favicon.ico".equals(req.getUri())) { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); return; } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, false); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); riderChannel.setChannelId(ctx.channel().id()); riderChannel.setChannel(ctx.channel()); } }
From source file:com.linecorp.armeria.client.endpoint.dns.DnsAddressEndpointGroup.java
License:Apache License
@Override ImmutableSortedSet<Endpoint> onDnsRecords(List<DnsRecord> records, int ttl) throws Exception { final ImmutableSortedSet.Builder<Endpoint> builder = ImmutableSortedSet.naturalOrder(); final boolean hasLoopbackARecords = records.stream().filter(r -> r instanceof DnsRawRecord) .map(DnsRawRecord.class::cast).anyMatch( r -> r.type() == DnsRecordType.A && r.content().getByte(r.content().readerIndex()) == 127); for (DnsRecord r : records) { if (!(r instanceof DnsRawRecord)) { continue; }/* w ww. ja va 2s . c om*/ final DnsRecordType type = r.type(); final ByteBuf content = ((ByteBufHolder) r).content(); final int contentLen = content.readableBytes(); // Skip invalid records. if (type == DnsRecordType.A) { if (contentLen != 4) { warnInvalidRecord(DnsRecordType.A, content); continue; } } else if (type == DnsRecordType.AAAA) { if (contentLen != 16) { warnInvalidRecord(DnsRecordType.AAAA, content); continue; } } else { continue; } // Convert the content into an IP address and then into an endpoint. final String ipAddr; final byte[] addrBytes = new byte[contentLen]; content.getBytes(content.readerIndex(), addrBytes); if (contentLen == 16) { // Convert some IPv6 addresses into IPv4 addresses to remove duplicate endpoints. if (addrBytes[0] == 0x00 && addrBytes[1] == 0x00 && addrBytes[2] == 0x00 && addrBytes[3] == 0x00 && addrBytes[4] == 0x00 && addrBytes[5] == 0x00 && addrBytes[6] == 0x00 && addrBytes[7] == 0x00 && addrBytes[8] == 0x00 && addrBytes[9] == 0x00) { if (addrBytes[10] == 0x00 && addrBytes[11] == 0x00) { if (addrBytes[12] == 0x00 && addrBytes[13] == 0x00 && addrBytes[14] == 0x00 && addrBytes[15] == 0x01) { // Loopback address (::1) if (hasLoopbackARecords) { // Contains an IPv4 loopback address already; skip. continue; } else { ipAddr = "::1"; } } else { // IPv4-compatible address. ipAddr = NetUtil.bytesToIpAddress(addrBytes, 12, 4); } } else if (addrBytes[10] == -1 && addrBytes[11] == -1) { // IPv4-mapped address. ipAddr = NetUtil.bytesToIpAddress(addrBytes, 12, 4); } else { ipAddr = NetUtil.bytesToIpAddress(addrBytes); } } else { ipAddr = NetUtil.bytesToIpAddress(addrBytes); } } else { ipAddr = NetUtil.bytesToIpAddress(addrBytes); } final Endpoint endpoint = port != 0 ? Endpoint.of(hostname, port) : Endpoint.of(hostname); builder.add(endpoint.withIpAddr(ipAddr)); } final ImmutableSortedSet<Endpoint> endpoints = builder.build(); if (logger().isDebugEnabled()) { logger().debug("{} Resolved: {} (TTL: {})", logPrefix(), endpoints.stream().map(Endpoint::ipAddr).collect(Collectors.joining(", ")), ttl); } return endpoints; }
From source file:com.linecorp.armeria.client.endpoint.dns.DnsServiceEndpointGroup.java
License:Apache License
@Override ImmutableSortedSet<Endpoint> onDnsRecords(List<DnsRecord> records, int ttl) throws Exception { final ImmutableSortedSet.Builder<Endpoint> builder = ImmutableSortedSet.naturalOrder(); for (DnsRecord r : records) { if (!(r instanceof DnsRawRecord) || r.type() != DnsRecordType.SRV) { continue; }//from w ww. jav a2 s . co m final ByteBuf content = ((ByteBufHolder) r).content(); if (content.readableBytes() <= 6) { // Too few bytes warnInvalidRecord(DnsRecordType.SRV, content); continue; } content.markReaderIndex(); content.skipBytes(2); // priority unused final int weight = content.readUnsignedShort(); final int port = content.readUnsignedShort(); final Endpoint endpoint; try { final String target = stripTrailingDot(DefaultDnsRecordDecoder.decodeName(content)); endpoint = port > 0 ? Endpoint.of(target, port) : Endpoint.of(target); } catch (Exception e) { content.resetReaderIndex(); warnInvalidRecord(DnsRecordType.SRV, content); continue; } builder.add(endpoint.withWeight(weight)); } final ImmutableSortedSet<Endpoint> endpoints = builder.build(); if (logger().isDebugEnabled()) { logger().debug("{} Resolved: {} (TTL: {})", logPrefix(), endpoints.stream().map(e -> e.authority() + '/' + e.weight()).collect(Collectors.joining(", ")), ttl); } return endpoints; }
From source file:com.linecorp.armeria.client.endpoint.dns.DnsTextEndpointGroup.java
License:Apache License
@Override ImmutableSortedSet<Endpoint> onDnsRecords(List<DnsRecord> records, int ttl) throws Exception { final ImmutableSortedSet.Builder<Endpoint> builder = ImmutableSortedSet.naturalOrder(); for (DnsRecord r : records) { if (!(r instanceof DnsRawRecord) || r.type() != DnsRecordType.TXT) { continue; }// w w w. j a v a 2 s .com final ByteBuf content = ((ByteBufHolder) r).content(); if (!content.isReadable()) { // Missing length octet warnInvalidRecord(DnsRecordType.TXT, content); continue; } content.markReaderIndex(); final int txtLen = content.readUnsignedByte(); if (txtLen == 0) { // Empty content continue; } if (content.readableBytes() != txtLen) { // Mismatching number of octets content.resetReaderIndex(); warnInvalidRecord(DnsRecordType.TXT, content); continue; } final byte[] txt = new byte[txtLen]; content.readBytes(txt); final Endpoint endpoint; try { endpoint = mapping.apply(txt); } catch (Exception e) { content.resetReaderIndex(); warnInvalidRecord(DnsRecordType.TXT, content); continue; } if (endpoint != null) { if (endpoint.isGroup()) { logger().warn("{} Ignoring group endpoint: {}", logPrefix(), endpoint); } else { builder.add(endpoint); } } } final ImmutableSortedSet<Endpoint> endpoints = builder.build(); if (logger().isDebugEnabled()) { logger().debug("{} Resolved: {} (TTL: {})", logPrefix(), endpoints.stream().map(Object::toString).collect(Collectors.joining(", ")), ttl); } return endpoints; }
From source file:com.linecorp.armeria.client.http.Http1ResponseDecoder.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof HttpObject)) { ctx.fireChannelRead(msg);//w ww . j av a2s . co m return; } try { switch (state) { case NEED_HEADERS: if (msg instanceof HttpResponse) { final HttpResponse nettyRes = (HttpResponse) msg; final DecoderResult decoderResult = nettyRes.decoderResult(); if (!decoderResult.isSuccess()) { fail(ctx, new ProtocolViolationException(decoderResult.cause())); return; } if (!HttpUtil.isKeepAlive(nettyRes)) { disconnectWhenFinished(); } final HttpResponseWrapper res = getResponse(resId); assert res != null; this.res = res; if (nettyRes.status().codeClass() == HttpStatusClass.INFORMATIONAL) { state = State.NEED_INFORMATIONAL_DATA; } else { state = State.NEED_DATA_OR_TRAILING_HEADERS; res.scheduleTimeout(ctx); } res.write(ArmeriaHttpUtil.toArmeria(nettyRes)); } else { failWithUnexpectedMessageType(ctx, msg); } break; case NEED_INFORMATIONAL_DATA: if (msg instanceof LastHttpContent) { state = State.NEED_HEADERS; } else { failWithUnexpectedMessageType(ctx, msg); } break; case NEED_DATA_OR_TRAILING_HEADERS: if (msg instanceof HttpContent) { final HttpContent content = (HttpContent) msg; final DecoderResult decoderResult = content.decoderResult(); if (!decoderResult.isSuccess()) { fail(ctx, new ProtocolViolationException(decoderResult.cause())); return; } final ByteBuf data = content.content(); final int dataLength = data.readableBytes(); if (dataLength > 0) { final long maxContentLength = res.maxContentLength(); if (maxContentLength > 0 && res.writtenBytes() > maxContentLength - dataLength) { fail(ctx, ContentTooLargeException.get()); return; } else { res.write(HttpData.of(data)); } } if (msg instanceof LastHttpContent) { final HttpResponseWriter res = removeResponse(resId++); assert this.res == res; this.res = null; state = State.NEED_HEADERS; final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders(); if (!trailingHeaders.isEmpty()) { res.write(ArmeriaHttpUtil.toArmeria(trailingHeaders)); } res.close(); if (needsToDisconnect()) { ctx.close(); } } } else { failWithUnexpectedMessageType(ctx, msg); } break; case DISCARD: break; } } finally { ReferenceCountUtil.release(msg); } }