java.nio.ByteBuffer#get ( )源码实例Demo

下面列出了java.nio.ByteBuffer#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Slyther   文件: WebSocketImpl.java
private HandshakeState isFlashEdgeCase( ByteBuffer request ) throws IncompleteHandshakeException {
	request.mark();
	if( request.limit() > Draft.FLASH_POLICY_REQUEST.length ) {
		return HandshakeState.NOT_MATCHED;
	} else if( request.limit() < Draft.FLASH_POLICY_REQUEST.length ) {
		throw new IncompleteHandshakeException( Draft.FLASH_POLICY_REQUEST.length );
	} else {

		for( int flash_policy_index = 0 ; request.hasRemaining() ; flash_policy_index++ ) {
			if( Draft.FLASH_POLICY_REQUEST[ flash_policy_index ] != request.get() ) {
				request.reset();
				return HandshakeState.NOT_MATCHED;
			}
		}
		return HandshakeState.MATCHED;
	}
}
 
源代码2 项目: javaide   文件: AnnotationParser.java
private static Object parseIntArray(int length,
                             ByteBuffer buf, ConstantPool constPool) {
    int[] result = new  int[length];
    boolean typeMismatch = false;
    int tag = 0;

    for (int i = 0; i < length; i++) {
        tag = buf.get();
        if (tag == 'I') {
            int index = buf.getShort() & 0xFFFF;
            result[i] = constPool.getIntAt(index);
        } else {
            skipMemberValue(tag, buf);
            typeMismatch = true;
        }
    }
    return typeMismatch ? exceptionProxy(tag) : result;
}
 
源代码3 项目: hash-bench   文件: JacksumHasher.java
@Override
public long hash(final ByteBuffer bb, final int off, final int len) {
  this.delegate.reset();
  if (bb.hasArray()) {
    this.delegate.update(bb.array(), off, len);
    return this.delegate.getValue();
  }

  final ByteBuffer view = bb.duplicate();
  view.position(off);
  view.limit(off + len);
  final byte[] data = new byte[len];
  view.get(data, 0, len);

  this.delegate.update(data);
  return this.delegate.getValue();
}
 
源代码4 项目: openjdk-8   文件: ISO2022.java
private int findDesigBuf(ByteBuffer in, byte[][] desigs) {
    if (desigs == null) return -1;
    int i = 0;
    while (i < desigs.length) {
        if (desigs[i] != null && in.remaining() >= desigs[i].length) {
            int j = 0;
            in.mark();
            while (j < desigs[i].length && in.get() == desigs[i][j]) { j++; }
            if (j == desigs[i].length)
                return i;
            in.reset();
        }
        i++;
    }
    return -1;
}
 
源代码5 项目: antsdb   文件: BufferUtils.java
public static String readString(ByteBuffer buf) {
    String result;
    int bytes = -1;
    for (int i=buf.position(); i<=buf.limit(); i++) {
        if (buf.get(i) == 0) {
            bytes = i - buf.position();
            break;
        }
    }
    if (bytes == -1) {
        // string might not be terminated by 0
        result = Charset.defaultCharset().decode(buf).toString();
    }
    else {
        int keep = buf.limit();
        buf.limit(buf.position() + bytes);
        result = Charset.defaultCharset().decode(buf).toString();
        buf.limit(keep);
        buf.get();
    }
    return result;
}
 
源代码6 项目: hottub   文件: DkCrypto.java
static byte[] charToUtf8(char[] chars) {
    Charset utf8 = Charset.forName("UTF-8");

    CharBuffer cb = CharBuffer.wrap(chars);
    ByteBuffer bb = utf8.encode(cb);
    int len = bb.limit();
    byte[] answer = new byte[len];
    bb.get(answer, 0, len);
    return answer;
}
 
源代码7 项目: hottub   文件: TrueTypeFont.java
protected void initAllNames(int requestedID, HashSet names) {

        byte[] name = new byte[256];
        ByteBuffer buffer = getTableBuffer(nameTag);

        if (buffer != null) {
            ShortBuffer sbuffer = buffer.asShortBuffer();
            sbuffer.get(); // format - not needed.
            short numRecords = sbuffer.get();

            /* The name table uses unsigned shorts. Many of these
             * are known small values that fit in a short.
             * The values that are sizes or offsets into the table could be
             * greater than 32767, so read and store those as ints
             */
            int stringPtr = ((int) sbuffer.get()) & 0xffff;
            for (int i=0; i<numRecords; i++) {
                short platformID = sbuffer.get();
                if (platformID != MS_PLATFORM_ID) {
                    sbuffer.position(sbuffer.position()+5);
                    continue; // skip over this record.
                }
                short encodingID = sbuffer.get();
                short langID     = sbuffer.get();
                short nameID     = sbuffer.get();
                int   nameLen    = ((int) sbuffer.get()) & 0xffff;
                int   namePtr    = (((int) sbuffer.get()) & 0xffff) + stringPtr;

                if (nameID == requestedID) {
                    buffer.position(namePtr);
                    buffer.get(name, 0, nameLen);
                    names.add(makeString(name, nameLen, encodingID));
                }
            }
        }
    }
 
源代码8 项目: kylin   文件: BigDecimalSerializer.java
@Override
public BigDecimal deserialize(ByteBuffer in) {
    int scale = BytesUtil.readVInt(in);
    int n = BytesUtil.readVInt(in);

    if (n < 0) {
        return null;
    }

    byte[] bytes = new byte[n];
    in.get(bytes);

    return new BigDecimal(new BigInteger(bytes), scale);
}
 
源代码9 项目: trekarta   文件: ICUBinary.java
private static boolean startsWithPackageName(ByteBuffer bytes, int start) {
    // Compare all but the trailing 'b' or 'l' which depends on the platform.
    int length = ICUData.PACKAGE_NAME.length() - 1;
    for (int i = 0; i < length; ++i) {
        if (bytes.get(start + i) != ICUData.PACKAGE_NAME.charAt(i)) {
            return false;
        }
    }
    // Check for 'b' or 'l' followed by '/'.
    byte c = bytes.get(start + length++);
    if ((c != 'b' && c != 'l') || bytes.get(start + length) != '/') {
        return false;
    }
    return true;
}
 
源代码10 项目: MikuMikuStudio   文件: VMDMotion.java
public VMDMotion readFromBuffer(ByteBuffer bb) {
//        boneName = BufferUtil.readString(bb, 15);
        boneIndex = bb.getShort();
        frameNo = bb.getInt();
        BufferUtil.readPoint3f(bb, location);
        BufferUtil.readQuat4f(bb, rotation);
        bb.get(interpolation);
        return this;
    }
 
源代码11 项目: vespa   文件: Utf8ArrayTestCase.java
@Test
public final void testWrap() {
    ByteBuffer b1 = toCheck.wrap();
    ByteBuffer b2 = ByteBuffer.wrap(rawBytes);
    byte[] c1 = new byte[b1.remaining()];
    byte[] c2 = new byte[b2.remaining()];
    b1.get(c1);
    b2.get(c2);
    assertArrayEquals(c2, c1);
}
 
源代码12 项目: MediaSDK   文件: TrimmingAudioProcessor.java
@Override
public void queueInput(ByteBuffer inputBuffer) {
  int position = inputBuffer.position();
  int limit = inputBuffer.limit();
  int remaining = limit - position;

  if (remaining == 0) {
    return;
  }

  // Trim any pending start bytes from the input buffer.
  int trimBytes = Math.min(remaining, pendingTrimStartBytes);
  trimmedFrameCount += trimBytes / inputAudioFormat.bytesPerFrame;
  pendingTrimStartBytes -= trimBytes;
  inputBuffer.position(position + trimBytes);
  if (pendingTrimStartBytes > 0) {
    // Nothing to output yet.
    return;
  }
  remaining -= trimBytes;

  // endBuffer must be kept as full as possible, so that we trim the right amount of media if we
  // don't receive any more input. After taking into account the number of bytes needed to keep
  // endBuffer as full as possible, the output should be any surplus bytes currently in endBuffer
  // followed by any surplus bytes in the new inputBuffer.
  int remainingBytesToOutput = endBufferSize + remaining - endBuffer.length;
  ByteBuffer buffer = replaceOutputBuffer(remainingBytesToOutput);

  // Output from endBuffer.
  int endBufferBytesToOutput = Util.constrainValue(remainingBytesToOutput, 0, endBufferSize);
  buffer.put(endBuffer, 0, endBufferBytesToOutput);
  remainingBytesToOutput -= endBufferBytesToOutput;

  // Output from inputBuffer, restoring its limit afterwards.
  int inputBufferBytesToOutput = Util.constrainValue(remainingBytesToOutput, 0, remaining);
  inputBuffer.limit(inputBuffer.position() + inputBufferBytesToOutput);
  buffer.put(inputBuffer);
  inputBuffer.limit(limit);
  remaining -= inputBufferBytesToOutput;

  // Compact endBuffer, then repopulate it using the new input.
  endBufferSize -= endBufferBytesToOutput;
  System.arraycopy(endBuffer, endBufferBytesToOutput, endBuffer, 0, endBufferSize);
  inputBuffer.get(endBuffer, endBufferSize, remaining);
  endBufferSize += remaining;

  buffer.flip();
}
 
@Override
public JournalStoreQuery parse(byte[] bytes) {
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    return new JournalStoreQuery(buffer.get(), buffer.getShort(), buffer.getLong(), buffer.getInt(), buffer.getLong());
}
 
源代码14 项目: Bytecoder   文件: FileChannelLinesSpliterator.java
@Override
public Spliterator<String> trySplit() {
    // Cannot split after partial traverse
    if (reader != null)
        return null;

    ByteBuffer b;
    if ((b = buffer) == null) {
        b = buffer = getMappedByteBuffer();
    }

    final int hi = fence, lo = index;

    // Check if line separator hits the mid point
    int mid = (lo + hi) >>> 1;
    int c =  b.get(mid);
    if (c == '\n') {
        mid++;
    } else if (c == '\r') {
        // Check if a line separator of "\r\n"
        if (++mid < hi && b.get(mid) == '\n') {
            mid++;
        }
    } else {
        // TODO give up after a certain distance from the mid point?
        // Scan to the left and right of the mid point
        int midL = mid - 1;
        int midR = mid + 1;
        mid = 0;
        while (midL > lo && midR < hi) {
            // Sample to the left
            c = b.get(midL--);
            if (c == '\n' || c == '\r') {
                // If c is "\r" then no need to check for "\r\n"
                // since the subsequent value was previously checked
                mid = midL + 2;
                break;
            }

            // Sample to the right
            c = b.get(midR++);
            if (c == '\n' || c == '\r') {
                mid = midR;
                // Check if line-separator is "\r\n"
                if (c == '\r' && mid < hi && b.get(mid) == '\n') {
                    mid++;
                }
                break;
            }
        }
    }

    // The left spliterator will have the line-separator at the end
    return (mid > lo && mid < hi)
           ? new FileChannelLinesSpliterator(fc, cs, lo, index = mid, b)
           : null;
}
 
源代码15 项目: pravega   文件: ByteArraySerializer.java
@Override
public byte[] deserialize(ByteBuffer serializedValue) {
    byte[] result = new byte[serializedValue.remaining()];
    serializedValue.get(result);
    return result;
}
 
@Override
protected void decodeData(ByteBuffer b, int length) {

    data.hasHistogram = false;
    data.hasAfFrame = false;

    if (length < 1000) {
        if (AppConfig.LOG) {
            Log.w(TAG, String.format("liveview data size too small %d", length));
        }
        return;
    }

    try {

        while (b.hasRemaining()) {
            int subLength = b.getInt();
            int type = b.getInt();

            if (subLength < 8) {
                throw new RuntimeException("Invalid sub size " + subLength);
            }

            int unknownInt = 0;

            switch (type) {
            case 0x01:
                data.bitmap = BitmapFactory.decodeByteArray(b.array(), b.position(), subLength - 8, options);
                b.position(b.position() + subLength - 8);
                break;
            case 0x04:
                data.zoomFactor = b.getInt();
                break;
            case 0x05:
                // zoomfocusx, zoomfocusy
                data.zoomRectRight = b.getInt();
                data.zoomRectBottom = b.getInt();
                if (AppConfig.LOG) {
                    Log.i(TAG, "header 5 " + data.zoomRectRight + " " + data.zoomRectBottom);
                }
                break;
            case 0x06:
                // imagex, imagey (if zoomed should be non zero)
                data.zoomRectLeft = b.getInt();
                data.zoomRectTop = b.getInt();
                if (AppConfig.LOG) {
                    Log.i(TAG, "header 6 " + data.zoomRectLeft + " " + data.zoomRectTop);
                }
                break;
            case 0x07:
                unknownInt = b.getInt();
                if (AppConfig.LOG) {
                    Log.i(TAG, "header 7 " + unknownInt + " " + subLength);
                }
                break;
            case 0x03:
                data.hasHistogram = true;
                b.get(data.histogram.array(), 0, 1024 * 4);
                break;
            case 0x08: // faces if faces focus
            case 0x0e: // TODO original width, original height
            default:
                b.position(b.position() + subLength - 8);
                if (AppConfig.LOG) {
                    Log.i(TAG, "unknown header " + type + " size " + subLength);
                }
                break;
            }

            if (length - b.position() < 8) {
                break;
            }
        }

    } catch (RuntimeException e) {
        Log.e(TAG, "" + e.toString());
        Log.e(TAG, "" + e.getLocalizedMessage());
    }
}
 
源代码17 项目: mp4parser   文件: IsoTypeReader.java
public static String readString(ByteBuffer byteBuffer, int length) {
    byte[] buffer = new byte[length];
    byteBuffer.get(buffer);
    return Utf8.convert(buffer);

}
 
源代码18 项目: onos   文件: ICMP6.java
@Override
public byte[] serialize() {
    byte[] payloadData = null;
    if (this.payload != null) {
        this.payload.setParent(this);
        payloadData = this.payload.serialize();
    }

    int payloadLength = 0;
    if (payloadData != null) {
        payloadLength = payloadData.length;
    }

    final byte[] data = new byte[HEADER_LENGTH + payloadLength];
    final ByteBuffer bbData = ByteBuffer.wrap(data);

    // Creating ByteBuffer for checksum calculation
    final byte[] checksumData =
        new byte[IPv6.FIXED_HEADER_LENGTH + HEADER_LENGTH + payloadLength];
    final ByteBuffer bbChecksum = ByteBuffer.wrap(checksumData);

    //
    // Creating IPv6 Pseudo Header for checksum calculation according
    // to RFC 4443 and RFC 2460
    //
    IPv6 ipv6Parent = null;
    for (IPacket p = this.parent; p != null; p = p.getParent()) {
        if (p instanceof IPv6) {
            ipv6Parent = (IPv6) p;
            break;
        }
    }
    if (ipv6Parent != null) {
        bbChecksum.put(ipv6Parent.getSourceAddress());
        bbChecksum.put(ipv6Parent.getDestinationAddress());
    } else {
        // NOTE: IPv6 source and destination addresses unknown. Use zeroes.
        bbChecksum.put(ZERO_ADDRESS);
        bbChecksum.put(ZERO_ADDRESS);
    }
    bbChecksum.putInt(HEADER_LENGTH + payloadLength);
    bbChecksum.put((byte) 0);
    bbChecksum.put((byte) 0);
    bbChecksum.put((byte) 0);
    bbChecksum.put(IPv6.PROTOCOL_ICMP6);
    bbChecksum.put(this.icmpType);
    bbChecksum.put(this.icmpCode);
    bbChecksum.put((byte) 0);
    bbChecksum.put((byte) 0);

    bbData.put(this.icmpType);
    bbData.put(this.icmpCode);
    bbData.putShort(this.checksum);
    if (payloadData != null) {
        bbData.put(payloadData);
        bbChecksum.put(payloadData);
    }

    if (this.parent != null) {
        if (this.parent instanceof IPv6) {
            ((IPv6) this.parent).setNextHeader(IPv6.PROTOCOL_ICMP6);
        } else if (this.parent instanceof IExtensionHeader) {
            ((IExtensionHeader) this.parent).setNextHeader(IPv6.PROTOCOL_ICMP6);
        }
    }

    // compute checksum if needed
    if (this.checksum == 0) {
        bbData.rewind();
        bbChecksum.rewind();
        int accumulation = 0;

        for (int i = 0; i < checksumData.length / 2; ++i) {
            accumulation += 0xffff & bbChecksum.getShort();
        }
        // pad to an even number of shorts
        if (checksumData.length % 2 > 0) {
            accumulation += (bbChecksum.get() & 0xff) << 8;
        }

        accumulation = (accumulation >> 16 & 0xffff)
                + (accumulation & 0xffff);
        this.checksum = (short) (~accumulation & 0xffff);
        bbData.putShort(2, this.checksum);
    }
    return data;
}
 
源代码19 项目: jhdf   文件: ExtensibleArrayIndex.java
private ExtensibleArraySecondaryBlock(HdfFileChannel hdfFc, long address) {

                final int numberOfPointers = secondaryBlockPointerCounter.getNextNumberOfPointers();
                final int secondaryBlockSize = 6 + hdfFc.getSizeOfOffsets() +
                        blockOffsetSize +
                        // Page Bitmap ?
                        numberOfPointers * extensibleArrayElementSize +
                        4; // checksum


                final ByteBuffer bb = hdfFc.readBufferFromAddress(address, secondaryBlockSize);

                verifySignature(bb, EXTENSIBLE_ARRAY_SECONDARY_BLOCK_SIGNATURE);

                // Version Number
                final byte version = bb.get();
                if (version != 0) {
                    throw new HdfException("Unsupported fixed array data block version detected. Version: " + version);
                }

                final int clientId = bb.get();
                if (clientId != ExtensibleArrayIndex.this.clientId) {
                    throw new HdfException("Extensible array client ID mismatch. Possible file corruption detected");
                }

                final long headerAddress = readBytesAsUnsignedLong(bb, hdfFc.getSizeOfOffsets());
                if (headerAddress != ExtensibleArrayIndex.this.headerAddress) {
                    throw new HdfException("Extensible array secondary block header address mismatch");
                }

                final long blockOffset = readBytesAsUnsignedLong(bb, blockOffsetSize);

                // TODO page bitmap

                // Data block addresses
                for (int i = 0; i < numberOfPointers; i++) {
                    long dataBlockAddress = readBytesAsUnsignedLong(bb, hdfFc.getSizeOfOffsets());
                    if (dataBlockAddress == UNDEFINED_ADDRESS) {
                        break; // This is the last secondary block and not full.
                    }
                    new ExtensibleArrayDataBlock(hdfFc, dataBlockAddress);
                }

            }
 
源代码20 项目: openjsse   文件: SSLEngineInputRecord.java
private Plaintext[] handleUnknownRecord(ByteBuffer packet)
        throws IOException, BadPaddingException {
    //
    // The packet should be a complete record.
    //
    int srcPos = packet.position();
    int srcLim = packet.limit();

    byte firstByte = packet.get(srcPos);
    byte thirdByte = packet.get(srcPos + 2);

    // Does it look like a Version 2 client hello (V2ClientHello)?
    if (((firstByte & 0x80) != 0) && (thirdByte == 1)) {
        /*
         * If SSLv2Hello is not enabled, throw an exception.
         */
        if (helloVersion != ProtocolVersion.SSL20Hello) {
            throw new SSLHandshakeException("SSLv2Hello is not enabled");
        }

        byte majorVersion = packet.get(srcPos + 3);
        byte minorVersion = packet.get(srcPos + 4);

        if ((majorVersion == ProtocolVersion.SSL20Hello.major) &&
            (minorVersion == ProtocolVersion.SSL20Hello.minor)) {

            /*
             * Looks like a V2 client hello, but not one saying
             * "let's talk SSLv3".  So we need to send an SSLv2
             * error message, one that's treated as fatal by
             * clients (Otherwise we'll hang.)
             */
            if (SSLLogger.isOn && SSLLogger.isOn("record")) {
               SSLLogger.fine(
                        "Requested to negotiate unsupported SSLv2!");
            }

            // hack code, the exception is caught in SSLEngineImpl
            // so that SSLv2 error message can be delivered properly.
            throw new UnsupportedOperationException(        // SSLv2Hello
                    "Unsupported SSL v2.0 ClientHello");
        }

        /*
         * If we can map this into a V3 ClientHello, read and
         * hash the rest of the V2 handshake, turn it into a
         * V3 ClientHello message, and pass it up.
         */
        packet.position(srcPos + 2);        // exclude the header
        handshakeHash.receive(packet);
        packet.position(srcPos);

        ByteBuffer converted = convertToClientHello(packet);

        if (SSLLogger.isOn && SSLLogger.isOn("packet")) {
            SSLLogger.fine(
                    "[Converted] ClientHello", converted);
        }

        return new Plaintext[] {
                new Plaintext(ContentType.HANDSHAKE.id,
                majorVersion, minorVersion, -1, -1L, converted)
            };
    } else {
        if (((firstByte & 0x80) != 0) && (thirdByte == 4)) {
            throw new SSLException("SSL V2.0 servers are not supported.");
        }

        throw new SSLException("Unsupported or unrecognized SSL message");
    }
}