Java Code Examples for java.nio.ByteBuffer.array()

The following are Jave code examples for showing how to use array() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: trust-wallet-android   File: CameraSource.java   View Source Code Vote up 6 votes
/**
 * Creates one buffer for the camera preview callback.  The size of the buffer is based off of
 * the camera preview size and the format of the camera image.
 *
 * @return a new preview buffer of the appropriate size for the current camera settings
 */
private byte[] createPreviewBuffer(Size previewSize) {
    int bitsPerPixel = ImageFormat.getBitsPerPixel(ImageFormat.NV21);
    long sizeInBits = previewSize.getHeight() * previewSize.getWidth() * bitsPerPixel;
    int bufferSize = (int) Math.ceil(sizeInBits / 8.0d) + 1;

    //
    // NOTICE: This code only works when using play services v. 8.1 or higher.
    //

    // Creating the byte array this way and wrapping it, as opposed to using .allocate(),
    // should guarantee that there will be an array to work with.
    byte[] byteArray = new byte[bufferSize];
    ByteBuffer buffer = ByteBuffer.wrap(byteArray);
    if (!buffer.hasArray() || (buffer.array() != byteArray)) {
        // I don't think that this will ever happen.  But if it does, then we wouldn't be
        // passing the preview content to the underlying detector later.
        throw new IllegalStateException("Failed to create valid buffer for camera source.");
    }

    mBytesToByteBuffer.put(byteArray, buffer);
    return byteArray;
}
 
Example 2
Project: jdk8u-jdk   File: SingleByte.java   View Source Code Vote up 6 votes
private CoderResult decodeArrayLoop(ByteBuffer src, CharBuffer dst) {
    byte[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();

    char[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();

    CoderResult cr = CoderResult.UNDERFLOW;
    if ((dl - dp) < (sl - sp)) {
        sl = sp + (dl - dp);
        cr = CoderResult.OVERFLOW;
    }

    while (sp < sl) {
        char c = decode(sa[sp]);
        if (c == UNMAPPABLE_DECODING) {
            return withResult(CoderResult.unmappableForLength(1),
                       src, sp, dst, dp);
        }
        da[dp++] = c;
        sp++;
    }
    return withResult(cr, src, sp, dst, dp);
}
 
Example 3
Project: stroom-stats   File: TestRowKey.java   View Source Code Vote up 6 votes
private byte[] buildRowKeyArray() {
    final byte[] rowKey = new byte[RowKey.calculateRowKeyLength(3)];

    final ByteBuffer buffer = ByteBuffer.wrap(rowKey);
    buffer.put(STAT_TYPE_ID.getUidBytes());
    buffer.put(ROLL_UP_BIT_MASK);
    buffer.put(PARTIAL_TIMESTAMP);
    buffer.put(TAG_2.getUidBytes());
    buffer.put(VALUE_2.getUidBytes());
    buffer.put(TAG_1.getUidBytes());
    buffer.put(VALUE_1.getUidBytes());
    buffer.put(TAG_3.getUidBytes());
    buffer.put(VALUE_3.getUidBytes());

    return buffer.array();
}
 
Example 4
Project: kafka-0.11.0.0-src-with-comment   File: ByteBufferSerializer.java   View Source Code Vote up 6 votes
public byte[] serialize(String topic, ByteBuffer data) {
    if (data == null)
        return null;

    data.rewind();

    if (data.hasArray()) {
        byte[] arr = data.array();
        if (data.arrayOffset() == 0 && arr.length == data.remaining()) {
            return arr;
        }
    }

    byte[] ret = new byte[data.remaining()];
    data.get(ret, 0, ret.length);
    data.rewind();
    return ret;
}
 
Example 5
Project: openjdk-jdk10   File: SingleByte.java   View Source Code Vote up 6 votes
private CoderResult decodeArrayLoop(ByteBuffer src, CharBuffer dst) {
    byte[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();

    char[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();

    CoderResult cr = CoderResult.UNDERFLOW;
    if ((dl - dp) < (sl - sp)) {
        sl = sp + (dl - dp);
        cr = CoderResult.OVERFLOW;
    }

    while (sp < sl) {
        char c = decode(sa[sp]);
        if (c == UNMAPPABLE_DECODING) {
            return withResult(CoderResult.unmappableForLength(1),
                       src, sp, dst, dp);
        }
        da[dp++] = c;
        sp++;
    }
    return withResult(cr, src, sp, dst, dp);
}
 
Example 6
Project: soapbox-race-core   File: Crypto.java   View Source Code Vote up 6 votes
@GET
@Path("/cryptoticket")
@Produces(MediaType.APPLICATION_XML)
public String cryptoticket() {
	byte[] helloPacket = { 10, 11, 12, 13 };
	ByteBuffer byteBuffer = ByteBuffer.allocate(32);
	byteBuffer.put(helloPacket);
	byte[] cryptoTicketBytes = byteBuffer.array();
	String cryptoTicketBase64 = Base64.getEncoder().encodeToString(cryptoTicketBytes);
	StringBuilder stringBuilder = new StringBuilder();
	stringBuilder.append("<ClientServerCryptoTicket>\n");
	stringBuilder.append("<CryptoTicket>");
	stringBuilder.append(cryptoTicketBase64);
	stringBuilder.append("</CryptoTicket>\n");
	stringBuilder.append("<SessionKey>AAAAAAAAAAAAAAAAAAAAAA==</SessionKey>\n");
	stringBuilder.append("<TicketIv>AAAAAAAAAAAAAAAAAAAAAA==</TicketIv>\n");
	stringBuilder.append("</ClientServerCryptoTicket>");
	return stringBuilder.toString();
}
 
Example 7
Project: mycat-src-1.6.1-RELEASE   File: FastByteOperations.java   View Source Code Vote up 6 votes
public void copy(ByteBuffer srcBuf, int srcPosition, ByteBuffer trgBuf, int trgPosition, int length)
{
    Object src;
    long srcOffset;
    if (srcBuf.hasArray())
    {
        src = srcBuf.array();
        srcOffset = BYTE_ARRAY_BASE_OFFSET + srcBuf.arrayOffset();
    }
    else
    {
        src = null;
        srcOffset = theUnsafe.getLong(srcBuf, DIRECT_BUFFER_ADDRESS_OFFSET);
    }
    copy(src, srcOffset + srcPosition, trgBuf, trgPosition, length);
}
 
Example 8
Project: rmq4note   File: PullMessageProcessor.java   View Source Code Vote up 6 votes
private byte[] readGetMessageResult(final GetMessageResult getMessageResult, final String group, final String topic, final int queueId) {
    final ByteBuffer byteBuffer = ByteBuffer.allocate(getMessageResult.getBufferTotalSize());

    long storeTimestamp = 0;
    try {
        List<ByteBuffer> messageBufferList = getMessageResult.getMessageBufferList();
        for (ByteBuffer bb : messageBufferList) {

            byteBuffer.put(bb);
            storeTimestamp = bb.getLong(MessageDecoder.MESSAGE_STORE_TIMESTAMP_POSTION);
        }
    } finally {
        getMessageResult.release();
    }

    this.brokerController.getBrokerStatsManager().recordDiskFallBehindTime(group, topic, queueId, this.brokerController.getMessageStore().now() - storeTimestamp);
    return byteBuffer.array();
}
 
Example 9
Project: CoreX   File: BaseChunk.java   View Source Code Vote up 5 votes
@Override
public byte[] getBlockLightArray() {
    ByteBuffer buffer = ByteBuffer.allocate(2048 * SECTION_COUNT);
    for (int y = 0; y < SECTION_COUNT; y++) {
        buffer.put(this.sections[y].getLightArray());
    }
    return buffer.array();
}
 
Example 10
Project: PlusGram   File: PsshAtomUtil.java   View Source Code Vote up 5 votes
/**
 * Builds a PSSH atom for a given {@link UUID} containing the given scheme specific data.
 *
 * @param uuid The UUID of the scheme.
 * @param data The scheme specific data.
 * @return The PSSH atom.
 */
public static byte[] buildPsshAtom(UUID uuid, byte[] data) {
  int psshBoxLength = Atom.FULL_HEADER_SIZE + 16 /* UUID */ + 4 /* DataSize */ + data.length;
  ByteBuffer psshBox = ByteBuffer.allocate(psshBoxLength);
  psshBox.putInt(psshBoxLength);
  psshBox.putInt(Atom.TYPE_pssh);
  psshBox.putInt(0 /* version=0, flags=0 */);
  psshBox.putLong(uuid.getMostSignificantBits());
  psshBox.putLong(uuid.getLeastSignificantBits());
  psshBox.putInt(data.length);
  psshBox.put(data);
  return psshBox.array();
}
 
Example 11
Project: OpenJSharp   File: ISO_8859_1.java   View Source Code Vote up 5 votes
private CoderResult decodeArrayLoop(ByteBuffer src,
                                    CharBuffer dst)
{
    byte[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    assert (sp <= sl);
    sp = (sp <= sl ? sp : sl);
    char[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();
    assert (dp <= dl);
    dp = (dp <= dl ? dp : dl);

    try {
        while (sp < sl) {
            byte b = sa[sp];
            if (dp >= dl)
                return CoderResult.OVERFLOW;
            da[dp++] = (char)(b & 0xff);
            sp++;
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 12
Project: Nukkit-Java9   File: BaseChunk.java   View Source Code Vote up 5 votes
@Override
public byte[] getBlockIdColumn(int x, int z) {
    ByteBuffer buffer = ByteBuffer.allocate(256);
    for (int y = 0; y < SECTION_COUNT; y++) {
        buffer.put(this.sections[y].getBlockIdColumn(x, z));
    }
    return buffer.array();
}
 
Example 13
Project: openjdk-jdk10   File: CertStatusReqExtensionTests.java   View Source Code Vote up 5 votes
private static byte[] wrapExtData(byte[] extData) {
    int bufferLen = (extData != null ? extData.length : 0) + 4;
    ByteBuffer bb = ByteBuffer.allocate(bufferLen);
    bb.putShort((short)ExtensionType.EXT_STATUS_REQUEST.id);
    bb.putShort((short)(extData != null ? extData.length: 0));
    if (extData != null) {
        bb.put(extData);
    }
    return bb.array();
}
 
Example 14
Project: OpenJSharp   File: TrueTypeFont.java   View Source Code Vote up 5 votes
byte[] readBytes(int offset, int length) {
    ByteBuffer buffer = readBlock(offset, length);
    if (buffer.hasArray()) {
        return buffer.array();
    } else {
        byte[] bufferBytes = new byte[buffer.limit()];
        buffer.get(bufferBytes);
        return bufferBytes;
    }
}
 
Example 15
Project: jdk8u-jdk   File: EUC_JP_OLD.java   View Source Code Vote up 4 votes
private CoderResult encodeArrayLoop(CharBuffer src,
                                    ByteBuffer dst)
{
    char[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    assert (sp <= sl);
    sp = (sp <= sl ? sp : sl);
    byte[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();
    assert (dp <= dl);
    dp = (dp <= dl ? dp : dl);

    int outputSize = 0;
    byte[]  outputByte;
    int     inputSize = 0;                 // Size of input
    byte[]  tmpBuf = new byte[3];

    try {
        while (sp < sl) {
            outputByte = tmpBuf;
            char c = sa[sp];

            if (Character.isSurrogate(c)) {
                if (sgp.parse(c, sa, sp, sl) < 0)
                    return sgp.error();
                return sgp.unmappableResult();
            }

            outputSize = encodeSingle(c, outputByte);

            if (outputSize == 0) { // DoubleByte
                int ncode = encodeDouble(c);
                if (ncode != 0 ) {
                    if ((ncode & 0xFF0000) == 0) {
                        outputByte[0] = (byte) ((ncode & 0xff00) >> 8);
                        outputByte[1] = (byte) (ncode & 0xff);
                        outputSize = 2;
                    } else {
                        outputByte[0] = (byte) 0x8f;
                        outputByte[1] = (byte) ((ncode & 0xff00) >> 8);
                        outputByte[2] = (byte) (ncode & 0xff);
                        outputSize = 3;
                    }
                } else {
                        return CoderResult.unmappableForLength(1);
                }
            }
            if (dl - dp < outputSize)
                return CoderResult.OVERFLOW;
            // Put the byte in the output buffer
            for (int i = 0; i < outputSize; i++) {
                da[dp++] = outputByte[i];
            }
            sp++;
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 16
Project: xlight_android_native   File: WebSocketDelegateImpl.java   View Source Code Vote up 4 votes
public byte[] encodeGetRequest(URI requestURI, String[] names, String[] values) {
    
    // Any changes to this method should result in the getEncodeRequestSize method below
    // to get accurate length of the buffer that needs to be allocated.
    
    LOG.entering(CLASS_NAME, "encodeGetRequest", new Object[] {requestURI, names, values});
    int requestSize = getEncodeRequestSize(requestURI, names, values);
    ByteBuffer buf = ByteBuffer.allocate(requestSize);

    // Encode Request line
    buf.put(GET_BYTES);
    buf.put(SPACE_BYTES);
    String path = requestURI.getPath();
    if (requestURI.getQuery() != null) {
        path += "?" + requestURI.getQuery();
    }
    buf.put(path.getBytes());
    buf.put(SPACE_BYTES);
    buf.put(HTTP_1_1_BYTES);
    buf.put(CRLF_BYTES);

    // Encode headers
    for (int i = 0; i < names.length; i++) {
        String headerName = names[i];
        String headerValue = values[i];
        if (headerName != null && headerValue != null) {
            buf.put(headerName.getBytes());
            buf.put(COLON_BYTES);
            buf.put(SPACE_BYTES);
            buf.put(headerValue.getBytes());
            buf.put(CRLF_BYTES);
        }
    }

    // Encoding cookies, content length and content not done here as we
    // don't have it in the initial GET request.

    buf.put(CRLF_BYTES);
    buf.flip();
    return buf.array();
}
 
Example 17
Project: openjdk-jdk10   File: EUC_JP_OLD.java   View Source Code Vote up 4 votes
private CoderResult encodeArrayLoop(CharBuffer src,
                                    ByteBuffer dst)
{
    char[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    assert (sp <= sl);
    sp = (sp <= sl ? sp : sl);
    byte[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();
    assert (dp <= dl);
    dp = (dp <= dl ? dp : dl);

    int outputSize = 0;
    byte[]  outputByte;
    int     inputSize = 0;                 // Size of input
    byte[]  tmpBuf = new byte[3];

    try {
        while (sp < sl) {
            outputByte = tmpBuf;
            char c = sa[sp];

            if (Character.isSurrogate(c)) {
                if (sgp.parse(c, sa, sp, sl) < 0)
                    return sgp.error();
                return sgp.unmappableResult();
            }

            outputSize = encodeSingle(c, outputByte);

            if (outputSize == 0) { // DoubleByte
                int ncode = encodeDouble(c);
                if (ncode != 0 ) {
                    if ((ncode & 0xFF0000) == 0) {
                        outputByte[0] = (byte) ((ncode & 0xff00) >> 8);
                        outputByte[1] = (byte) (ncode & 0xff);
                        outputSize = 2;
                    } else {
                        outputByte[0] = (byte) 0x8f;
                        outputByte[1] = (byte) ((ncode & 0xff00) >> 8);
                        outputByte[2] = (byte) (ncode & 0xff);
                        outputSize = 3;
                    }
                } else {
                        return CoderResult.unmappableForLength(1);
                }
            }
            if (dl - dp < outputSize)
                return CoderResult.OVERFLOW;
            // Put the byte in the output buffer
            for (int i = 0; i < outputSize; i++) {
                da[dp++] = outputByte[i];
            }
            sp++;
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 18
Project: jdk8u-jdk   File: IBM964.java   View Source Code Vote up 4 votes
private CoderResult decodeArrayLoop(ByteBuffer src, CharBuffer dst) {
    byte[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    assert (sp <= sl);
    sp = (sp <= sl ? sp : sl);
    char[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();
    assert (dp <= dl);
    dp = (dp <= dl ? dp : dl);

    try {
    while (sp < sl) {
        int byte1, byte2;
        int inputSize = 1;
        char outputChar = '\uFFFD';
        byte1 = sa[sp] & 0xff;

        if (byte1 == SS2) {
            if (sl - sp < 4) {
                return CoderResult.UNDERFLOW;
            }
            byte1 = sa[sp + 1] & 0xff;
            inputSize = 2;
            if ( byte1 == 0xa2)
                mappingTableG2 = mappingTableG2a2;
            else if ( byte1 == 0xac)
                mappingTableG2 = mappingTableG2ac;
            else if ( byte1 == 0xad)
                mappingTableG2 = mappingTableG2ad;
            else
                return CoderResult.malformedForLength(2);
            byte1 = sa[sp + 2] & 0xff;
            if ( byte1 < 0xa1 || byte1 > 0xfe) {
                return CoderResult.malformedForLength(3);
            }
            byte2 = sa[sp + 3] & 0xff;
            if ( byte2 < 0xa1 || byte2 > 0xfe) {
              return CoderResult.malformedForLength(4);
            }
            inputSize = 4;
            outputChar = mappingTableG2.charAt(((byte1 - 0xa1) * 94) + byte2 - 0xa1);
        } else if(byte1 == SS3 ) {
            return CoderResult.malformedForLength(1);
        } else if ( byte1 <= 0x9f ) {                // valid single byte
            outputChar = byteToCharTable.charAt(byte1);
        } else if (byte1 < 0xa1 || byte1 > 0xfe) {   // invalid range?
            return CoderResult.malformedForLength(1);
        } else {                                     // G1
            if (sl - sp < 2) {
                return CoderResult.UNDERFLOW;
            }
            byte2 = sa[sp + 1] & 0xff;
            inputSize = 2;
            if ( byte2 < 0xa1 || byte2 > 0xfe) {
                return CoderResult.malformedForLength(2);
            }
            outputChar = mappingTableG1.charAt(((byte1 - 0xa1) * 94) + byte2 - 0xa1);
        }
        if  (outputChar == '\uFFFD')
            return CoderResult.unmappableForLength(inputSize);
        if (dl - dp < 1)
            return CoderResult.OVERFLOW;
        da[dp++] = outputChar;
        sp += inputSize;
    }
    return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 19
Project: lams   File: SpdyHeaderBlockParser.java   View Source Code Vote up 4 votes
@Override
protected void handleData(ByteBuffer resource) throws IOException {
    if(!beforeHeadersHandled) {
        if (!handleBeforeHeader(resource)) {
            return;
        }
    }
    beforeHeadersHandled = true;
    Pooled<ByteBuffer> outPooled = channel.getHeapBufferPool().allocate();
    Pooled<ByteBuffer> inPooled = channel.getHeapBufferPool().allocate();

    boolean extraOutput = false;
    try {
        ByteBuffer outputBuffer = outPooled.getResource();
        ByteBuffer inPooledResource = inPooled.getResource();
        if(dataOverflow != null) {
            outputBuffer.put(dataOverflow);
            dataOverflow = null;
            extraOutput = true;
        }
        byte[] inputBuffer = inPooledResource.array();
        while (resource.hasRemaining()) {
            int rem = resource.remaining();
            if (rem > inputBuffer.length) {
                resource.get(inputBuffer, inPooledResource.arrayOffset(), inPooledResource.limit());
            } else {
                resource.get(inputBuffer, inPooledResource.arrayOffset(), resource.remaining());
            }
            int inputLength = Math.min(rem, inPooledResource.limit());
            inflater.setInput(inputBuffer, inPooledResource.arrayOffset(), inputLength);
            while (!inflater.needsInput()) {
                int copied = 0;
                try {
                    copied = inflater.inflate(outputBuffer.array(), outputBuffer.arrayOffset() + outputBuffer.position(), outputBuffer.remaining());
                } catch (DataFormatException e) {
                    throw new StreamErrorException(StreamErrorException.PROTOCOL_ERROR);
                }
                if (copied == 0 && inflater.needsDictionary()) {
                    inflater.setDictionary(SpdyProtocolUtils.SPDY_DICT);
                } else if(copied > 0) {
                    outputBuffer.position(outputBuffer.position() + copied);
                    handleDecompressedData(outputBuffer);
                    if(outputBuffer.hasRemaining()) {
                        outputBuffer.compact();
                        extraOutput = true;
                    } else {
                        extraOutput = false;
                        outputBuffer.clear();
                    }
                }
            }
        }
    } finally {
        if(extraOutput) {
            outPooled.getResource().flip();
            dataOverflow = new byte[outPooled.getResource().remaining()];
            outPooled.getResource().get(dataOverflow);
        }
        inPooled.free();
        outPooled.free();
    }
}
 
Example 20
Project: LowPolyTerrain   File: FlatTerrainGenerator.java   View Source Code Vote up 3 votes
/**
 * @param heights
 *            - The heights of all the vertices in the terrain.
 * @param normals
 *            - The smooth normal vectors for every vertex of the terrain.
 * @param colours
 *            - The colour of every vertex.
 * @return The interleaved vertex data for all the vertices in this terrain.
 *         Each vertex has a position, normal, and colour. The vertex data
 *         is already in byte format, ready to be stored into a VBO.
 */
private static byte[] getMeshData(float[][] heights, Vector3f[][] normals, Colour[][] colours) {
	int byteSize = VERTEX_SIZE_BYTES * heights.length * heights[0].length;
	ByteBuffer buffer = ByteBuffer.allocate(byteSize).order(ByteOrder.nativeOrder());
	for (int z = 0; z < heights.length; z++) {
		for (int x = 0; x < heights[z].length; x++) {
			DataStoring.packVertexData(x, heights[z][x], z, normals[z][x], colours[z][x], buffer);
		}
	}
	return buffer.array();
}