List of usage examples for io.netty.buffer ByteBuf getBytes
public abstract ByteBuf getBytes(int index, ByteBuffer dst);
From source file:io.termd.core.telnet.netty.TelnetChannelHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; int size = buf.readableBytes(); byte[] data = new byte[size]; buf.getBytes(0, data); conn.receive(data);/*from w w w. ja va 2 s .co m*/ }
From source file:io.vertx.core.dns.impl.decoder.RecordDecoder.java
License:Open Source License
static Function<DnsRecord, String> address(int octets) { return record -> { ByteBuf data = ((DnsRawRecord) record).content(); int size = data.writerIndex() - data.readerIndex(); if (size != octets) { throw new DecoderException("Invalid content length, or reader index when decoding address [index: " + data.readerIndex() + ", expected length: " + octets + ", actual: " + size + "]."); }//from w w w .j a va 2s .com byte[] address = new byte[octets]; data.getBytes(data.readerIndex(), address); try { return InetAddress.getByAddress(address).getHostAddress(); } catch (UnknownHostException e) { throw new DecoderException("Could not convert address " + data.toString(data.readerIndex(), size, CharsetUtil.UTF_8) + " to InetAddress."); } }; }
From source file:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java
License:Apache License
private void onResponseAorAAAA(DnsRecordType qType, DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope) { // We often get a bunch of CNAMES as well when we asked for A/AAAA. final DnsResponse response = envelope.content(); final Map<String, String> cnames = buildAliasMap(response); final int answerCount = response.count(DnsSection.ANSWER); boolean found = false; for (int i = 0; i < answerCount; i++) { final DnsRecord r = response.recordAt(DnsSection.ANSWER, i); final DnsRecordType type = r.type(); if (type != DnsRecordType.A && type != DnsRecordType.AAAA) { continue; }/*from www . j a v a 2 s. co m*/ final String qName = question.name().toLowerCase(Locale.US); final String rName = r.name().toLowerCase(Locale.US); // Make sure the record is for the questioned domain. if (!rName.equals(qName)) { // Even if the record's name is not exactly same, it might be an alias defined in the CNAME records. String resolved = qName; do { resolved = cnames.get(resolved); if (rName.equals(resolved)) { break; } } while (resolved != null); if (resolved == null) { continue; } } if (!(r instanceof DnsRawRecord)) { continue; } final ByteBuf content = ((ByteBufHolder) r).content(); final int contentLen = content.readableBytes(); if (contentLen != INADDRSZ4 && contentLen != INADDRSZ6) { continue; } final byte[] addrBytes = new byte[contentLen]; content.getBytes(content.readerIndex(), addrBytes); final InetAddress resolved; try { resolved = InetAddress.getByAddress(hostname, addrBytes); } catch (UnknownHostException e) { // Should never reach here. throw new Error(e); } if (resolvedEntries == null) { resolvedEntries = new ArrayList<DnsCacheEntry>(8); } final DnsCacheEntry e = new DnsCacheEntry(hostname, resolved); resolveCache.cache(hostname, resolved, r.timeToLive(), parent.ch.eventLoop()); resolvedEntries.add(e); found = true; // Note that we do not break from the loop here, so we decode/cache all A/AAAA records. } if (found) { return; } if (traceEnabled) { addTrace(envelope.sender(), "no matching " + qType + " record found"); } // We aked for A/AAAA but we got only CNAME. if (!cnames.isEmpty()) { onResponseCNAME(question, envelope, cnames, false); } }
From source file:nearenough.protocol.RtMessage.java
License:Open Source License
private Map<RtTag, byte[]> extractMultiMapping(ByteBuf msg) { // extractOffsets will leave the reader index positioned at the first tag int[] offsets = extractOffsets(msg); int startOfValues = msg.readerIndex() + (4 * numTags); Map<RtTag, byte[]> mapping = new LinkedHashMap<>(numTags); RtTag prevTag = null;//from w ww . j a va 2 s.co m for (int i = 0; i < offsets.length; i++) { long uintCurrTag = msg.readUnsignedInt(); RtTag currTag = RtTag.fromUnsignedInt((int) uintCurrTag); if ((prevTag != null) && currTag.isLessThan(prevTag)) { String exMsg = String.format( "tags not strictly increasing: current '%s' (0x%08x), previous '%s' (0x%08x)", currTag, currTag.valueLE(), prevTag, prevTag.valueLE()); throw new TagsNotIncreasingException(exMsg); } int valueIdx = startOfValues + offsets[i]; int valueLen = ((i + 1) == offsets.length) ? msg.readableBytes() - offsets[i] : offsets[i + 1] - offsets[i]; byte[] valueBytes = new byte[valueLen]; msg.getBytes(valueIdx, valueBytes); mapping.put(currTag, valueBytes); prevTag = currTag; } return Collections.unmodifiableMap(mapping); }
From source file:net.anyflow.lannister.NettyUtil.java
License:Apache License
public static byte[] copy(ByteBuf buffer) { byte[] bytes = new byte[buffer.readableBytes()]; int readerIndex = buffer.readerIndex(); buffer.getBytes(readerIndex, bytes); return bytes; }
From source file:net.tomp2p.storage.AlternativeCompositeByteBuf.java
License:Apache License
@Override public AlternativeCompositeByteBuf getBytes(int index, ByteBuffer dst) { int limit = dst.limit(); int length = dst.remaining(); checkIndex(index, length);/* w w w .j av a 2 s. c o m*/ if (length == 0) { return this; } int i = findIndex(index); try { while (length > 0) { Component c = components.get(i); ByteBuf s = c.buf; int adjustment = c.offset; int localLength = Math.min(length, s.readableBytes() - (index - adjustment)); dst.limit(dst.position() + localLength); s.getBytes(index - adjustment, dst); index += localLength; length -= localLength; i++; } } finally { dst.limit(limit); } return this; }
From source file:net.tomp2p.storage.Data.java
License:Apache License
/** * Reads the header. Does not modify the buffer positions if header could * not be fully read./* www. java2s . c om*/ * * Header format: * <pre> * 1 byte - header * 1 or 4 bytes - length * 4 or 0 bytes - ttl (hasTTL) * 1 or 0 bytes - number of basedon keys (hasBasedOn) * n x 20 bytes - basedon keys (hasBasedOn, number of basedon keys) * 2 or 0 bytes - length of public key (hasPublicKey) * n bytes - public key (hasPublicKey, length of public key) * </pre> * * * @param buf * The buffer to read from * @return The data object, may be partially filled */ public static Data decodeHeader(final ByteBuf buf, final SignatureFactory signatureFactory) { // 2 is the smallest packet size, we could start if we know 1 byte to // decode the header, but we always need // a second byte. Thus, we are waiting for at least 2 bytes. if (buf.readableBytes() < Utils.BYTE_BYTE_SIZE + Utils.BYTE_BYTE_SIZE) { return null; } final int header = buf.getUnsignedByte(buf.readerIndex()); final Data.Type type = Data.type(header); //Data length final int length; final int indexLength = Utils.BYTE_BYTE_SIZE; final int indexTTL; switch (type) { case SMALL: length = buf.getUnsignedByte(buf.readerIndex() + indexLength); indexTTL = indexLength + Utils.BYTE_BYTE_SIZE; break; case LARGE: indexTTL = indexLength + Utils.INTEGER_BYTE_SIZE; if (buf.readableBytes() < indexTTL) { return null; } length = buf.getInt(buf.readerIndex() + indexLength); break; default: throw new IllegalArgumentException("unknown type"); } //TTL final int ttl; final int indexBasedOnNr; if (hasTTL(header)) { indexBasedOnNr = indexTTL + Utils.INTEGER_BYTE_SIZE; if (buf.readableBytes() < indexBasedOnNr) { return null; } ttl = buf.getInt(buf.readerIndex() + indexTTL); } else { ttl = -1; indexBasedOnNr = indexTTL; } //Nr BasedOn + basedon final int numBasedOn; final int indexPublicKeySize; final int indexBasedOn; final Set<Number160> basedOn = new HashSet<Number160>(); if (hasBasedOn(header)) { // get # of based on keys indexBasedOn = indexBasedOnNr + Utils.BYTE_BYTE_SIZE; if (buf.readableBytes() < indexBasedOn) { return null; } numBasedOn = buf.getUnsignedByte(buf.readerIndex() + indexBasedOnNr) + 1; indexPublicKeySize = indexBasedOn + (numBasedOn * Number160.BYTE_ARRAY_SIZE); if (buf.readableBytes() < indexPublicKeySize) { return null; } //get basedon int index = buf.readerIndex() + indexBasedOnNr + Utils.BYTE_BYTE_SIZE; final byte[] me = new byte[Number160.BYTE_ARRAY_SIZE]; for (int i = 0; i < numBasedOn; i++) { buf.getBytes(index, me); index += Number160.BYTE_ARRAY_SIZE; basedOn.add(new Number160(me)); } } else { // no based on keys indexPublicKeySize = indexBasedOnNr; numBasedOn = 0; } //public key and size final int publicKeySize; final int indexPublicKey; final int indexEnd; final PublicKey publicKey; if (hasPublicKey(header)) { indexPublicKey = indexPublicKeySize + Utils.SHORT_BYTE_SIZE; if (buf.readableBytes() < indexPublicKey) { return null; } publicKeySize = buf.getUnsignedShort(buf.readerIndex() + indexPublicKeySize); indexEnd = indexPublicKey + publicKeySize; if (buf.readableBytes() < indexEnd) { return null; } //get public key buf.skipBytes(indexPublicKeySize); publicKey = signatureFactory.decodePublicKey(buf); } else { publicKeySize = 0; indexPublicKey = indexPublicKeySize; buf.skipBytes(indexPublicKey); publicKey = null; } //now we have read the header and the length final Data data = new Data(header, length); data.ttlSeconds = ttl; data.basedOnSet = basedOn; data.publicKey = publicKey; return data; }
From source file:net.yuntutv.a8.ws.EchoServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { c = ctx.channel();/* w w w . j av a2 s . co m*/ ByteBuf bb = (ByteBuf) msg; byte[] bs = new byte[bb.readableBytes()]; bb.getBytes(0, bs); String s = new String(bs); s = s.replaceAll("\\s", ""); System.out.println(s); ctx.write(s); // try { // queue.put(s); // } catch (InterruptedException e) { // e.printStackTrace(); // } }
From source file:Netty4.MQSource.NettyTest.NettyTest.NettyDecoder.java
License:Apache License
@Override public long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) { buf = buf.order(order);/*from www . j av a2s . c o m*/ byte[] lendata = new byte[8]; buf.getBytes(0, lendata); int frameLength = Integer.parseInt(new String(lendata)); return frameLength; }
From source file:no.nb.nna.broprox.dnsservice.DnsLookup.java
License:Apache License
protected void storeDnsRecord(final String host, final State state) throws IOException, NoSuchAlgorithmException, InterruptedException, StatusException { ByteBuf payload = Unpooled.buffer(); // Start the record with a 14-digit date per RFC 2540 VariablePrecisionDateTime fetchDate = new VariablePrecisionDateTime(state.fetchStart, Granularity.SECOND); payload.writeCharSequence(fetchDate.toFormattedString(DateFormat.HERITRIX), StandardCharsets.UTF_8); payload.writeByte('\n'); for (Record r : state.answers) { payload.writeCharSequence(r.toString(), StandardCharsets.UTF_8); payload.writeByte('\n'); }/*from w ww .j a v a 2 s . c o m*/ byte[] buf = new byte[payload.readableBytes()]; payload.getBytes(payload.readerIndex(), buf); CrawlLog.Builder crawlLogBuilder = CrawlLog.newBuilder().setRecordType("response") .setRequestedUri("dns:" + host).setDiscoveryPath("P").setStatusCode(1) .setFetchTimeStamp(ProtoUtils.odtToTs(state.fetchStart)).setIpAddress(state.dnsIp) .setContentType("text/dns").setSize(payload.readableBytes()); // Shall we get a digest on the content downloaded? if (digestContent) { MessageDigest digest = MessageDigest.getInstance(getDigestAlgorithm()); String digestString = "sha1:" + new BigInteger(1, digest.digest(buf)).toString(16); crawlLogBuilder.setBlockDigest(digestString); } CrawlLog crawlLog = crawlLogBuilder.build(); if (db != null) { crawlLog = db.addCrawlLog(crawlLog); } if (contentWriterClient != null) { String uri = contentWriterClient.createSession().sendCrawlLog(crawlLog) .sendPayload(ByteString.copyFrom(buf)).finish(); } LOG.debug("DNS record for {} written", host); }