Java Code Examples for java.io.ByteArrayInputStream#available()

The following examples show how to use java.io.ByteArrayInputStream#available() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static void testSerialization(String[] values) throws IOException {
	ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
	DataOutputViewStreamWrapper serializer = new DataOutputViewStreamWrapper(baos);
	
	for (String value : values) {
		StringValue sv = new StringValue(value);
		sv.write(serializer);
	}
	
	serializer.close();
	baos.close();
	
	ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
	DataInputViewStreamWrapper deserializer = new DataInputViewStreamWrapper(bais);
	
	int num = 0;
	while (bais.available() > 0) {
		StringValue deser = new StringValue();
		deser.read(deserializer);
		
		assertEquals("DeserializedString differs from original string.", values[num], deser.getValue());
		num++;
	}
	
	assertEquals("Wrong number of deserialized values", values.length, num);
}
 
Example 2
Source Project: dremio-oss   File: RocksDBStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RocksEntry filterGet(byte[] valueFromRocks) {
  if (isRawValue(valueFromRocks)) {
    if (valueFromRocks == null) {
      return null;
    }
    return new RocksEntry(null, valueFromRocks);
  }

  try {
    // Slice off the prefix byte and start parsing where the metadata block is.
    final ByteArrayInputStream bais = new ByteArrayInputStream(valueFromRocks, 1, valueFromRocks.length);
    final Rocks.Meta meta = parseMetaAfterPrefix(bais);
    // We know this is not a blob because we are using the inline blob manager. Assume the value
    // is the rest of the byte array.
    final byte[] result = new byte[bais.available()];
    bais.read(result);
    return new RocksEntry(meta, result);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 3
Source Project: RipplePower   File: ServerNameList.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse a {@link ServerNameList} from an {@link InputStream}.
 * 
 * @param input
 *            the {@link InputStream} to parse from.
 * @return a {@link ServerNameList} object.
 * @throws IOException
 */
public static ServerNameList parse(InputStream input) throws IOException
{
    int length = TlsUtils.readUint16(input);
    if (length < 1)
    {
        throw new TlsFatalAlert(AlertDescription.decode_error);
    }

    byte[] data = TlsUtils.readFully(length, input);

    ByteArrayInputStream buf = new ByteArrayInputStream(data);

    Vector server_name_list = new Vector();
    while (buf.available() > 0)
    {
        ServerName entry = ServerName.parse(buf);
        server_name_list.addElement(entry);
    }

    return new ServerNameList(server_name_list);
}
 
Example 4
/**
 * 测试核心逻辑,将模拟好的报文按序写入buffer,并进行解析
 * @param mysqlPackgsStream
 * @param chunkSize
 * @return
 * @throws IOException
 */
private ByteBufferArray splitPackage(ByteArrayInputStream mysqlPackgsStream, int chunkSize) throws IOException {
    SharedBufferPool sharedPool = new SharedBufferPool(1024 * 1024 * 100, chunkSize);
    ReactorBufferPool reactBufferPool = new ReactorBufferPool(sharedPool, Thread.currentThread(), 1000);
    ByteBufferArray bufArray = reactBufferPool.allocate();
    bufArray.addNewBuffer();
    int readBufferOffset = 0;
    // @todo 构造符合MYSQL报文的数据包,进行测试

    MySQLConnection fakeCon = new MySQLFrontendConnection(null);

    while (mysqlPackgsStream.available() > 0) {
        ByteBuffer curBuf = bufArray.getLastByteBuffer();
        if (!curBuf.hasRemaining()) {
            curBuf = bufArray.addNewBuffer();
        }
        byte[] data = new byte[curBuf.remaining()];
        int readed = mysqlPackgsStream.read(data);
        curBuf.put(data, 0, readed);
        readBufferOffset = CommonPacketUtil.parsePackets(bufArray, curBuf, readBufferOffset, fakeCon);
    }
    return bufArray;
}
 
Example 5
Source Project: fuchsia   File: CEMILDataEx.java    License: Apache License 2.0 5 votes vote down vote up
void readPayload(ByteArrayInputStream is) throws KNXFormatException
{
	int len = is.read();
	// length field is 0 in RF frames
	if (len == 0)
		len = is.available();
	else {
		++len;
		if (len > is.available())
			throw new KNXFormatException("length of tpdu exceeds available data", len);
	}
	data = new byte[len];
	is.read(data, 0, len);
}
 
Example 6
Source Project: PacketProxy   File: Protobuf3.java    License: Apache License 2.0 5 votes vote down vote up
public static long decodeVar(ByteArrayInputStream input) {
	long var = 0;
	for (long i = 0; input.available() > 0; i++) {
		long nextB = (byte)(input.read() & 0xff) ;
		var = var | ((nextB & 0x7f) << (7*i));
		if ((nextB & 0x80) == 0)
			break;
	}
	return var;
}
 
Example 7
Source Project: azure-keyvault-java   File: SignatureEncoding.java    License: MIT License 5 votes vote down vote up
public static byte[] Decode(byte[] bytes, Ecdsa algorithm)
{
    int coordLength = algorithm.getCoordLength();

    ByteArrayInputStream asn1DerSignature = new ByteArrayInputStream(bytes);
    
    // verify byte 0 is 0x30
    if (asn1DerSignature.read() != 0x30)
    {
        throw new IllegalArgumentException("Invalid signature.");
    }

    int objLen = readFieldLength(asn1DerSignature);
    
    // verify the object lenth is equal to the remaining length of the _asn1DerSignature
    if (objLen != asn1DerSignature.available())
    {
        throw new IllegalArgumentException(String.format("Invalid signature; invalid field len %d", objLen));
    }

    byte[] rawSignature = new byte[coordLength * 2];

    // decode the r feild to the first half of _rawSignature
    decodeIntField(asn1DerSignature, rawSignature, 0, coordLength);

    // decode the s feild to the second half of _rawSignature
    decodeIntField(asn1DerSignature, rawSignature, rawSignature.length / 2, coordLength);

    return rawSignature;
}
 
Example 8
Source Project: fuchsia   File: TP1LPollData.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new L-polldata frame out of a byte array.
 * <p>
 * 
 * @param data byte array containing the L-polldata frame
 * @param offset start offset of frame structure in <code>data</code>, offset &gt;=
 *        0
 * @throws KNXFormatException if length of data too short for frame, on no valid frame
 *         structure
 */
public TP1LPollData(byte[] data, int offset) throws KNXFormatException
{
	final ByteArrayInputStream is =
		new ByteArrayInputStream(data, offset, data.length - offset);
	final int avail = is.available();
	if (avail < MIN_LENGTH)
		throw new KNXFormatException("data too short for L-polldata frame", avail);
	final int ctrl = is.read();
	// parse control field and check if valid
	if (ctrl != 0xF0)
		throw new KNXFormatException("invalid control field", ctrl);
	type = LPOLLDATA_FRAME;
	p = Priority.get((ctrl >> 2) & 0x3);
	int addr = (is.read() << 8) | is.read();
	src = new IndividualAddress(addr);
	addr = (is.read() << 8) | is.read();
	dst = new GroupAddress(addr);
	final int len = is.read() & 0x0f;
	expData = len;
	fcs = is.read();
	// do we really get poll data response here? don't know for sure..
	if (expData <= is.available()) {
		tpdu = new byte[expData];
		is.read(tpdu, 0, expData);
	}
}
 
Example 9
/**
 * Returns array of String values.
 */
public String[] getArrayOfStringValues() {

    byte[] bufArray = (byte[])myValue;
    if (bufArray != null) {
        ByteArrayInputStream bufStream =
            new ByteArrayInputStream(bufArray);
        int available = bufStream.available();

        // total number of values is at the end of the stream
        bufStream.mark(available);
        bufStream.skip(available-1);
        int length = bufStream.read();
        bufStream.reset();

        String[] valueArray = new String[length];
        for (int i = 0; i < length; i++) {
            // read length
            int valLength = bufStream.read();
            byte[] bufBytes = new byte[valLength];
            bufStream.read(bufBytes, 0, valLength);
            try {
                valueArray[i] = new String(bufBytes, "UTF-8");
            } catch (java.io.UnsupportedEncodingException uee) {
            }
        }
        return valueArray;
    }
    return null;
}
 
Example 10
/**
 * Returns array of int values.
 */
public int[] getArrayOfIntValues() {

    byte[] bufArray = (byte[])myValue;
    if (bufArray != null) {

        //ArrayList valList = new ArrayList();
        ByteArrayInputStream bufStream =
            new ByteArrayInputStream(bufArray);
        int available = bufStream.available();

        // total number of values is at the end of the stream
        bufStream.mark(available);
        bufStream.skip(available-1);
        int length = bufStream.read();
        bufStream.reset();

        int[] valueArray = new int[length];
        for (int i = 0; i < length; i++) {
            // read length
            int valLength = bufStream.read();
            if (valLength != 4) {
                // invalid data
                return null;
            }

            byte[] bufBytes = new byte[valLength];
            bufStream.read(bufBytes, 0, valLength);
            valueArray[i] = convertToInt(bufBytes);

        }
        return valueArray;
    }
    return null;
}
 
Example 11
Source Project: jphp   File: PHttpPart.java    License: Apache License 2.0 5 votes vote down vote up
@Reflection.Signature
public byte[] readAll() throws IOException {
    ByteArrayInputStream inputStream = (ByteArrayInputStream) getWrappedObject().getInputStream();
    byte[] array = new byte[inputStream.available()];
    inputStream.read(array);
    inputStream.close();
    return array;
}
 
Example 12
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
        ChannelBuffer source) throws Exception {
    // TODO #MN will modify the body with MessagePackBufferUnpacker.
    ByteBuffer buffer = source.toByteBuffer();
    if (!buffer.hasRemaining()) {
        return null;
    }
    source.markReaderIndex();

    byte[] bytes = buffer.array(); // FIXME buffer must has array
    int offset = buffer.arrayOffset() + buffer.position();
    int length = buffer.arrayOffset() + buffer.limit();
    ByteArrayInputStream stream = new ByteArrayInputStream(bytes, offset,
            length);
    int startAvailable = stream.available();
    try{
        Unpacker unpacker = msgpack.createUnpacker(stream);
        Value v = unpacker.readValue();
        source.skipBytes(startAvailable - stream.available());
        return v;
    }catch( EOFException e ){
        // not enough buffers.
        // So retry reading
        source.resetReaderIndex();
        return null;
    }
}
 
Example 13
public static KeyStore base64DecodePrivateKeyStore(String pks) throws GeneralSecurityException, IOException {
    if (pks != null && !pks.equals("")) {
        ByteArrayInputStream privateKeyStream = new ByteArrayInputStream(Base64.decodeBase64(pks));
        if (privateKeyStream.available() > 0) {
            KeyStore privateKeyStore = KeyStore.getInstance("PKCS12");
            privateKeyStore.load(privateKeyStream, GoogleSpreadsheet.SECRET);
            if (privateKeyStore.containsAlias("privatekey")) {
                return privateKeyStore;
            }
        }
    }
    return null;
}
 
Example 14
/**
 * Returns array of String values.
 */
public String[] getArrayOfStringValues() {

    byte[] bufArray = (byte[])myValue;
    if (bufArray != null) {
        ByteArrayInputStream bufStream =
            new ByteArrayInputStream(bufArray);
        int available = bufStream.available();

        // total number of values is at the end of the stream
        bufStream.mark(available);
        bufStream.skip(available-1);
        int length = bufStream.read();
        bufStream.reset();

        String[] valueArray = new String[length];
        for (int i = 0; i < length; i++) {
            // read length
            int valLength = bufStream.read();
            byte[] bufBytes = new byte[valLength];
            bufStream.read(bufBytes, 0, valLength);
            try {
                valueArray[i] = new String(bufBytes, "UTF-8");
            } catch (java.io.UnsupportedEncodingException uee) {
            }
        }
        return valueArray;
    }
    return null;
}
 
Example 15
Source Project: ripple-lib-java   File: TlsProtocol.java    License: ISC License 5 votes vote down vote up
/**
 * Make sure the InputStream 'buf' now empty. Fail otherwise.
 *
 * @param buf The InputStream to check.
 * @throws IOException If 'buf' is not empty.
 */
protected static void assertEmpty(ByteArrayInputStream buf)
    throws IOException
{
    if (buf.available() > 0)
    {
        throw new TlsFatalAlert(AlertDescription.decode_error);
    }
}
 
Example 16
/**
 * Returns array of String values.
 */
public String[] getArrayOfStringValues() {

    byte[] bufArray = (byte[])myValue;
    if (bufArray != null) {
        ByteArrayInputStream bufStream =
            new ByteArrayInputStream(bufArray);
        int available = bufStream.available();

        // total number of values is at the end of the stream
        bufStream.mark(available);
        bufStream.skip(available-1);
        int length = bufStream.read();
        bufStream.reset();

        String[] valueArray = new String[length];
        for (int i = 0; i < length; i++) {
            // read length
            int valLength = bufStream.read();
            byte[] bufBytes = new byte[valLength];
            bufStream.read(bufBytes, 0, valLength);
            try {
                valueArray[i] = new String(bufBytes, "UTF-8");
            } catch (java.io.UnsupportedEncodingException uee) {
            }
        }
        return valueArray;
    }
    return null;
}
 
Example 17
Source Project: PacketProxy   File: Protobuf3.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean validateBit64(ByteArrayInputStream input) {
	return input.available() < 8 ? false : true;
}
 
Example 18
Source Project: knox   File: UrlRewriteRequestTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testUnicodePayload() throws Exception {
  String data = "<?xml version=\"1.0\" standalone=\"no\"?><data>abc-大数据</data>";

  final ByteArrayInputStream bai = new ByteArrayInputStream(
      data.getBytes(StandardCharsets.UTF_8));

  final ServletInputStream payload = new ServletInputStream() {
    @Override
    public int read() {
      return bai.read();
    }

    @Override
    public int available() {
      return bai.available();
    }

    @Override
    public boolean isFinished() {
      return false;
    }

    @Override
    public boolean isReady() {
      return false;
    }

    @Override
    public void setReadListener(ReadListener readListener) {
    }
  };

  UrlRewriteProcessor rewriter = EasyMock.createNiceMock(UrlRewriteProcessor.class);

  ServletContext context = EasyMock.createNiceMock(ServletContext.class);
  EasyMock.expect(context.getServletContextName())
      .andReturn("test-cluster-name").anyTimes();
  EasyMock.expect(context.getInitParameter("test-init-param-name"))
      .andReturn("test-init-param-value").anyTimes();
  EasyMock.expect(context.getAttribute(
      UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME))
      .andReturn(rewriter).anyTimes();

  FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
  EasyMock.expect(config.getInitParameter("test-filter-init-param-name"))
      .andReturn("test-filter-init-param-value").anyTimes();
  EasyMock.expect(config.getServletContext()).andReturn(context).anyTimes();

  HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
  EasyMock.expect(request.getScheme()).andReturn("https").anyTimes();
  EasyMock.expect(request.getServerName()).andReturn("targethost.com").anyTimes();
  EasyMock.expect(request.getServerPort()).andReturn(80).anyTimes();
  EasyMock.expect(request.getRequestURI()).andReturn("/").anyTimes();
  EasyMock.expect(request.getQueryString()).andReturn(null).anyTimes();
  EasyMock.expect(request.getHeader("Host")).andReturn("sourcehost.com").anyTimes();

  EasyMock.expect(request.getMethod()).andReturn("POST").anyTimes();
  EasyMock.expect(request.getContentType()).andReturn("application/xml").anyTimes();
  EasyMock.expect(request.getInputStream()).andReturn(payload).anyTimes();
  EasyMock.expect(request.getContentLength()).andReturn(-1).anyTimes();

  HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
  EasyMock.replay(rewriter, context, config, request, response);

  UrlRewriteRequest rewriteRequest = new UrlRewriteRequest(config, request);

  assertEquals(data, IOUtils.toString(rewriteRequest.getInputStream(), StandardCharsets.UTF_8));
}
 
Example 19
Source Project: fuchsia   File: PL132LData.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new L-data frame out of a byte array.
 * <p>
 * 
 * @param data byte array containing the L-data frame
 * @param offset start offset of frame structure in <code>data</code>, offset &gt;=
 *        0
 * @throws KNXFormatException if length of data too short for frame, on no valid frame
 *         structure
 */
public PL132LData(byte[] data, int offset) throws KNXFormatException
{
	final ByteArrayInputStream is =
		new ByteArrayInputStream(data, offset, data.length - offset);
	final int avail = is.available();
	if (avail < MIN_LENGTH)
		throw new KNXFormatException("data too short for L-data frame", avail);
	doa = new byte[2];
	is.read(doa, 0, 2);
	final int ctrl = is.read();
	// parse control field and check if valid
	if ((ctrl & 0xC) != 0xC)
		throw new KNXFormatException("invalid control field", ctrl);
	type = LDATA_FRAME;
	ext = (ctrl & 0x80) == 0;
	repetition = (ctrl & 0x40) == 0;
	p = Priority.get(ctrl & 0x3);
	final boolean group = (ctrl & 0x20) == 0x20;
	ack = (ctrl & 0x10) == 0x10;
	// check fourth byte for extended control field
	final int ctrle = ext ? readCtrlEx(is) : 0;
	src = new IndividualAddress((is.read() << 8) | is.read());
	setDestination((is.read() << 8) | is.read(), group);

	final int npci = is.read();
	final int len;
	if (ext) {
		hopcount = (ctrle & 0x70) >> 4;
		len = npci;
		if (len > 64)
			throw new KNXFormatException("APDU length exceeds maximum of 64 bytes",
				len);
	}
	else {
		hopcount = (npci & 0x70) >> 4;
		len = npci & 0x0f;
	}
	tpdu = new byte[len + 1];
	if (is.read(tpdu, 0, tpdu.length) != tpdu.length)
		throw new KNXFormatException("data too short for L-data TPDU");
	fcs = is.read() << 8 | is.read();
}
 
Example 20
public static String prettyPrintAPDUResponse(byte[] data, int indentLength) {
    StringBuilder buf = new StringBuilder();
    ByteArrayInputStream stream = new ByteArrayInputStream(data);
    ppFirst = true;

    while (stream.available() > 0) {
        if (ppRecursed) {
            buf.append("\n\n");
        }
        else 
        if (!ppFirst) {
            buf.append("\n");
        }
        ppRecursed = false;
        ppFirst = false;
        buf.append(Util.getSpaces(indentLength));

        BERTLV tlv = TLVUtil.getNextTLV(stream);
        //Log.d(TAG, tlv.toString());

        byte[] tagBytes = tlv.getTagBytes();
        byte[] lengthBytes = tlv.getRawEncodedLengthBytes();
        byte[] valueBytes = tlv.getValueBytes();

        Tag tag = tlv.getTag();

        buf.append(Util.prettyPrintHex(tagBytes));
        buf.append(" ");
        buf.append(Util.prettyPrintHex(lengthBytes));
        buf.append(": ");
        buf.append(tag.getName());

        int extraIndent = 0;
        if (tag.isConstructed()) {
            // extra indents 3 and 7 (below) work well with courier new (fixed width),
            // but for some reason not with the monospace typeface (droid sans mono)
            extraIndent = 3;
            // recursion
            buf.append("\n");
            ppRecursed = true;
            buf.append(prettyPrintAPDUResponse(valueBytes, indentLength + extraIndent));
            
        } else {
            //extraIndent = (lengthBytes.length * 2) + (tagBytes.length * 2) + 3;
            extraIndent = 7;
            buf.append("\n");
            if (tag.getTagValueType() == TagValueType.DOL) {
                buf.append(TLVUtil.getFormattedTagAndLength(valueBytes, indentLength + extraIndent));
            } else {
                buf.append(Util.getSpaces(indentLength + extraIndent));
                buf.append(Util.prettyPrintHex(Util.byteArrayToHexString(valueBytes), indentLength + extraIndent));
                if (tag.getTagValueType() == TEXT || tag.getTagValueType() == MIXED) {
                    buf.append("\n");
                    buf.append(Util.getSpaces(indentLength + extraIndent));
                    buf.append("(");
                    buf.append(TLVUtil.getTagValueAsString(tag, valueBytes));
                    buf.append(")");
                }
                buf.append("\n");
            }
        }
    } // end while
    return buf.toString();
}