List of usage examples for io.netty.buffer ByteBuf setByte
public abstract ByteBuf setByte(int index, int value);
From source file:dorkbox.network.pipeline.ByteBufInput.java
License:Apache License
private String readAscii() { ByteBuf buffer = byteBuf; int start = buffer.readerIndex() - 1; int b;/* w w w.j av a 2s . com*/ do { b = buffer.readByte(); } while ((b & 0x80) == 0); int i = buffer.readerIndex() - 1; buffer.setByte(i, buffer.getByte(i) & 0x7F); // Mask end of ascii bit. int capp = buffer.readerIndex() - start; byte[] ba = new byte[capp]; buffer.getBytes(start, ba); @SuppressWarnings("deprecation") String value = new String(ba, 0, 0, capp); buffer.setByte(i, buffer.getByte(i) | 0x80); return value; }
From source file:dorkbox.network.pipeline.ByteBufOutput.java
License:Apache License
/** Writes the length and string, or null. Short strings are checked and if ASCII they are written more efficiently, else they * are written as UTF8. If a string is known to be ASCII, {@link #writeAscii(String)} may be used. The string can be read using * {@link ByteBufInput#readString()} or {@link ByteBufInput#readStringBuilder()}. * @param value May be null. *///from w w w . j ava 2 s. co m @Override public void writeString(String value) throws KryoException { if (value == null) { writeByte(0x80); // 0 means null, bit 8 means UTF8. return; } int charCount = value.length(); if (charCount == 0) { writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8. return; } // Detect ASCII. boolean ascii = false; if (charCount > 1 && charCount < 64) { // only snoop 64 chars in ascii = true; for (int i = 0; i < charCount; i++) { int c = value.charAt(i); if (c > 127) { ascii = false; break; } } } ByteBuf buffer = byteBuf; if (buffer.writableBytes() < charCount) { buffer.capacity(buffer.capacity() + charCount + 1); } if (!ascii) { writeUtf8Length(charCount + 1); } int charIndex = 0; // Try to write 8 bit chars. for (; charIndex < charCount; charIndex++) { int c = value.charAt(charIndex); if (c > 127) { break; // whoops! detect ascii. have to continue with a slower method! } buffer.writeByte((byte) c); } if (charIndex < charCount) { writeString_slow(value, charCount, charIndex); } else if (ascii) { // specify it's ASCII int i = buffer.writerIndex() - 1; buffer.setByte(i, buffer.getByte(i) | 0x80); // Bit 8 means end of ASCII. } }
From source file:dorkbox.network.pipeline.ByteBufOutput.java
License:Apache License
/** Writes a string that is known to contain only ASCII characters. Non-ASCII strings passed to this method will be corrupted. * Each byte is a 7 bit character with the remaining byte denoting if another character is available. This is slightly more * efficient than {@link #writeString(String)}. The string can be read using {@link ByteBufInput#readString()} or * {@link ByteBufInput#readStringBuilder()}. * @param value May be null. *//*from w ww.j a va2 s . c o m*/ @Override public void writeAscii(String value) throws KryoException { if (value == null) { writeByte(0x80); // 0 means null, bit 8 means UTF8. return; } int charCount = value.length(); if (charCount == 0) { writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8. return; } ByteBuf buffer = byteBuf; if (buffer.writableBytes() < charCount) { buffer.capacity(buffer.capacity() + charCount + 1); } int charIndex = 0; // Try to write 8 bit chars. for (; charIndex < charCount; charIndex++) { int c = value.charAt(charIndex); buffer.writeByte((byte) c); } // specify it's ASCII int i = buffer.writerIndex() - 1; buffer.setByte(i, buffer.getByte(i) | 0x80); // Bit 8 means end of ASCII. }
From source file:io.grpc.alts.internal.TsiTest.java
License:Apache License
/** Test corrupted ciphertext. */ public static void corruptedCiphertextTest(Handshakers handshakers, RegisterRef ref) throws GeneralSecurityException { performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc); TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc); String message = "hello world"; ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8)); final List<ByteBuf> protectOut = new ArrayList<>(); List<Object> unprotectOut = new ArrayList<>(); sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() { @Override/* w w w. ja v a 2 s . com*/ public void accept(ByteBuf buf) { protectOut.add(buf); } }, alloc); assertThat(protectOut.size()).isEqualTo(1); ByteBuf protect = ref.register(protectOut.get(0)); int ciphertextIdx = protect.writerIndex() - FakeChannelCrypter.getTagBytes() - 2; protect.setByte(ciphertextIdx, protect.getByte(ciphertextIdx) + 1); try { receiver.unprotect(protect, unprotectOut, alloc); fail("Exception expected"); } catch (AEADBadTagException ex) { assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE); } sender.destroy(); receiver.destroy(); }
From source file:io.grpc.alts.internal.TsiTest.java
License:Apache License
/** Test corrupted tag. */ public static void corruptedTagTest(Handshakers handshakers, RegisterRef ref) throws GeneralSecurityException { performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc); TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc); String message = "hello world"; ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8)); final List<ByteBuf> protectOut = new ArrayList<>(); List<Object> unprotectOut = new ArrayList<>(); sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() { @Override//from w ww. j a va 2 s . com public void accept(ByteBuf buf) { protectOut.add(buf); } }, alloc); assertThat(protectOut.size()).isEqualTo(1); ByteBuf protect = ref.register(protectOut.get(0)); int tagIdx = protect.writerIndex() - 1; protect.setByte(tagIdx, protect.getByte(tagIdx) + 1); try { receiver.unprotect(protect, unprotectOut, alloc); fail("Exception expected"); } catch (AEADBadTagException ex) { assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE); } sender.destroy(); receiver.destroy(); }
From source file:io.nodyn.buffer.Buffer.java
License:Apache License
public static Object fill(JSObject obj, Object val, int offset, int end) { int byteVal = 0; if (val instanceof Number) { byteVal = ((Number) val).intValue() & 0xFF; } else if (val instanceof String && !((String) val).isEmpty()) { byteVal = ((String) val).charAt(0); }/*from w w w . java 2s .c o m*/ ByteBuf b = extract(obj); for (int i = offset; i < end; ++i) { b.setByte(i, byteVal); } b.writerIndex(Math.max(b.writerIndex(), offset + end)); return obj; }
From source file:org.apache.bookkeeper.tools.perf.table.KeyGenerator.java
License:Apache License
public void generateKeyFromLong(ByteBuf slice, long n) { int startPos = 0; if (keysPerPrefix > 0) { long numPrefix = (numKeys + keysPerPrefix - 1) / keysPerPrefix; long prefix = n % numPrefix; int bytesToFill = Math.min(prefixSize, 8); for (int i = 0; i < bytesToFill; i++) { slice.setByte(i, (byte) (prefix % 256)); prefix /= 256;/*www. j a va2 s.c o m*/ } for (int i = 8; i < bytesToFill; ++i) { slice.setByte(i, '0'); } startPos = bytesToFill; } for (int i = slice.writableBytes() - 1; i >= startPos; --i) { slice.setByte(i, (byte) ('0' + (n % 10))); n /= 10; } }
From source file:org.apache.distributedlog.EnvelopedEntryWriter.java
License:Apache License
private ByteBuf finalizeBuffer() { if (!envelopeBeforeTransmit) { return buffer.retain(); }/*w w w. jav a 2 s. c o m*/ int dataOffset = HEADER_LENGTH; int dataLen = buffer.readableBytes() - HEADER_LENGTH; if (Type.NONE == codec) { // update version buffer.setByte(VERSION_OFFSET, CURRENT_VERSION); // update the flags buffer.setInt(FLAGS_OFFSET, flags); // update data len buffer.setInt(DECOMPRESSED_SIZE_OFFSET, dataLen); buffer.setInt(COMPRESSED_SIZE_OFFSET, dataLen); return buffer.retain(); } // compression CompressionCodec compressor = CompressionUtils.getCompressionCodec(codec); ByteBuf uncompressedBuf = buffer.slice(dataOffset, dataLen); ByteBuf compressedBuf = compressor.compress(uncompressedBuf, HEADER_LENGTH); // update version compressedBuf.setByte(VERSION_OFFSET, CURRENT_VERSION); // update the flags compressedBuf.setInt(FLAGS_OFFSET, flags); // update data len compressedBuf.setInt(DECOMPRESSED_SIZE_OFFSET, dataLen); compressedBuf.setInt(COMPRESSED_SIZE_OFFSET, compressedBuf.readableBytes() - HEADER_LENGTH); return compressedBuf; }
From source file:org.apache.drill.common.util.DrillStringUtils.java
License:Apache License
/** * In-place parsing of a hex encoded binary string. * * This function does not modify the {@code readerIndex} and {@code writerIndex} * of the byte buffer.//w w w .java 2 s. c om * * @return Index in the byte buffer just after the last written byte. */ public static int parseBinaryString(ByteBuf str, int strStart, int strEnd) { int length = (strEnd - strStart); int dstEnd = strStart; for (int i = strStart; i < strStart + length; i++) { byte b = str.getByte(i); if (b == '\\' && strEnd > i + 3 && (str.getByte(i + 1) == 'x' || str.getByte(i + 1) == 'X')) { // ok, take next 2 hex digits. byte hd1 = str.getByte(i + 2); byte hd2 = str.getByte(i + 3); if (isHexDigit(hd1) && isHexDigit(hd2)) { // [a-fA-F0-9] // turn hex ASCII digit -> number b = (byte) ((toBinaryFromHex(hd1) << 4) + toBinaryFromHex(hd2)); i += 3; // skip 3 } } str.setByte(dstEnd++, b); } return dstEnd; }
From source file:org.apache.jackrabbit.oak.plugins.segment.NetworkErrorProxy.java
License:Apache License
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { ByteBuf bb = (ByteBuf) msg; log.debug("FlipHandler. Got Buffer size: " + bb.readableBytes()); if (this.startingPos >= 0) { if (this.transferredBytes + bb.readableBytes() >= this.startingPos) { int i = this.startingPos - (int) this.transferredBytes; log.info("FlipHandler flips byte at offset " + (this.transferredBytes + i)); byte b = (byte) (bb.getByte(i) ^ 0x01); bb.setByte(i, b); this.startingPos = -1; }// w w w . j a v a 2 s .c om } } super.channelRead(ctx, msg); }