Java Code Examples for java.io.ByteArrayInputStream.reset()

The following are Jave code examples for showing how to use reset() of the java.io.ByteArrayInputStream 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: JavaTutorial   File: ByteArrayInputStreamExample.java   View Source Code Vote up 6 votes
public void readMarkAndReset(byte[] bytes,int mark) {
    StringBuffer sb = new StringBuffer();
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    bais.mark(mark);

    bais.skip(mark + 1);
    int tmp;
    while ((tmp = bais.read()) != -1) {
        sb.append(Integer.toHexString(tmp));
    }

    System.out.println("越过标记后的字符串");
    System.out.println(sb.toString());

    bais.reset();
    sb.setLength(0);

    int m;
    while ((m = bais.read()) != -1) {
        sb.append(Integer.toHexString(m));
    }

    System.out.println("重置之后的字符串");
    System.out.println(sb.toString());
}
 
Example 2
Project: CacheWebView   File: BytesEncodingDetect.java   View Source Code Vote up 6 votes
public String detectEncodingStr(ByteArrayInputStream inputStream,int len){
    String strEnc ="UTF-8";
    try{

        byte buffers[] = new byte[len];

        inputStream.read(buffers,0,len);
        inputStream.reset();

        int enc = detectEncoding(buffers);
        if (enc!=-1){
            String encStr =  Encoding.htmlname[enc];
            if (!encStr.equals("ASCII")){
                strEnc = encStr;
            }
        }
    }catch (Exception e){

    }
    return strEnc;
}
 
Example 3
Project: jdk8u-jdk   File: AttributeClass.java   View Source Code Vote up 5 votes
/**
 * 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 4
Project: CorePatch   File: MinimalZipParserTest.java   View Source Code Vote up 5 votes
@Test
public void testParseCentralDirectoryEntry() throws Exception {
  ByteArrayInputStream in = new ByteArrayInputStream(unitTestZipArchive);
  in.mark(unitTestZipArchive.length);
  int eocdOffset = MinimalZipParser.locateStartOfEocd(unitTestZipArchive);
  Assert.assertEquals(eocdOffset, in.skip(eocdOffset));
  MinimalCentralDirectoryMetadata metadata = MinimalZipParser.parseEocd(in);
  in.reset();
  Assert.assertEquals(
      metadata.getOffsetOfCentralDirectory(), in.skip(metadata.getOffsetOfCentralDirectory()));

  // Read each entry and verify all fields *except* the value returned by
  // MinimalZipEntry.getFileOffsetOfCompressedData(), as that has yet to be computed.
  for (UnitTestZipEntry expectedEntry : UnitTestZipArchive.allEntriesInFileOrder) {
    MinimalZipEntry parsed = MinimalZipParser.parseCentralDirectoryEntry(in);
    Assert.assertEquals(expectedEntry.path, parsed.getFileName());

    // Verify that the local signature header is at the calculated position
    byte[] expectedSignatureBlock = new byte[] {0x50, 0x4b, 0x03, 0x04};
    for (int index = 0; index < 4; index++) {
      byte actualByte = unitTestZipArchive[((int) parsed.getFileOffsetOfLocalEntry()) + index];
      Assert.assertEquals(expectedSignatureBlock[index], actualByte);
    }

    if (expectedEntry.level > 0) {
      Assert.assertEquals(8 /* deflate */, parsed.getCompressionMethod());
    } else {
      Assert.assertEquals(0 /* store */, parsed.getCompressionMethod());
    }
    byte[] uncompressedContent = expectedEntry.getUncompressedBinaryContent();
    Assert.assertEquals(uncompressedContent.length, parsed.getUncompressedSize());
    CRC32 crc32 = new CRC32();
    crc32.update(uncompressedContent);
    Assert.assertEquals(crc32.getValue(), parsed.getCrc32OfUncompressedData());
    byte[] compressedContent = expectedEntry.getCompressedBinaryContent();
    Assert.assertEquals(compressedContent.length, parsed.getCompressedSize());
  }
}
 
Example 5
Project: CorePatch   File: MinimalZipParserTest.java   View Source Code Vote up 5 votes
@Test
public void testParseLocalEntryAndGetCompressedDataOffset() throws Exception {
  ByteArrayInputStream in = new ByteArrayInputStream(unitTestZipArchive);
  in.mark(unitTestZipArchive.length);
  int eocdOffset = MinimalZipParser.locateStartOfEocd(unitTestZipArchive);
  Assert.assertEquals(eocdOffset, in.skip(eocdOffset));
  MinimalCentralDirectoryMetadata metadata = MinimalZipParser.parseEocd(in);
  in.reset();
  Assert.assertEquals(
      metadata.getOffsetOfCentralDirectory(), in.skip(metadata.getOffsetOfCentralDirectory()));

  // Read each entry and verify all fields *except* the value returned by
  // MinimalZipEntry.getFileOffsetOfCompressedData(), as that has yet to be computed.
  List<MinimalZipEntry> parsedEntries = new ArrayList<MinimalZipEntry>();
  for (int x = 0; x < UnitTestZipArchive.allEntriesInFileOrder.size(); x++) {
    parsedEntries.add(MinimalZipParser.parseCentralDirectoryEntry(in));
  }

  for (int x = 0; x < UnitTestZipArchive.allEntriesInFileOrder.size(); x++) {
    UnitTestZipEntry expectedEntry = UnitTestZipArchive.allEntriesInFileOrder.get(x);
    MinimalZipEntry parsedEntry = parsedEntries.get(x);
    in.reset();
    Assert.assertEquals(
        parsedEntry.getFileOffsetOfLocalEntry(),
        in.skip(parsedEntry.getFileOffsetOfLocalEntry()));
    long relativeDataOffset = MinimalZipParser.parseLocalEntryAndGetCompressedDataOffset(in);
    Assert.assertTrue(relativeDataOffset > 0);
    checkExpectedBytes(
        expectedEntry.getCompressedBinaryContent(),
        (int) (parsedEntry.getFileOffsetOfLocalEntry() + relativeDataOffset));
  }
}
 
Example 6
Project: OpenJSharp   File: AttributeClass.java   View Source Code Vote up 5 votes
/**
 * 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 7
Project: OpenJSharp   File: AttributeClass.java   View Source Code Vote up 5 votes
/**
 * 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 8
Project: openjdk-jdk10   File: AttributeClass.java   View Source Code Vote up 5 votes
/**
 * 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 9
Project: helper   File: BungeeMessaging.java   View Source Code Vote up 4 votes
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] data) {
    if (!channel.equals(CHANNEL)) {
        return;
    }

    ByteArrayInputStream inputStream = new ByteArrayInputStream(data);

    ByteArrayDataInput in = ByteStreams.newDataInput(inputStream);
    String subChannel = in.readUTF();

    // exclude the first value from the input stream
    inputStream.mark(/* ignored */ 0);

    lock.lock();
    try {
        Iterator<MessageCallback> it = listeners.iterator();
        while (it.hasNext()) {
            MessageCallback e = it.next();

            if (!e.getSubChannel().equals(subChannel)) {
                continue;
            }

            inputStream.reset();
            boolean accepted = e.test(player, in);

            if (!accepted) {
                continue;
            }

            inputStream.reset();
            boolean shouldRemove = e.accept(player, in);

            if (shouldRemove) {
                it.remove();
            }
        }
    } finally {
        lock.unlock();
    }
}
 
Example 10
Project: openaudible   File: ID3Unsynchronization.java   View Source Code Vote up 4 votes
/**
 * Unsynchronize an array of bytes, this should only be called if the decision has already been made to
 * unsynchronize the byte array
 * <p/>
 * In order to prevent a media player from incorrectly interpreting the contents of a tag, all $FF bytes
 * followed by a byte with value >=224 must be followed by a $00 byte (thus, $FF $F0 sequences become $FF $00 $F0).
 * Additionally because unsynchronisation is being applied any existing $FF $00 have to be converted to
 * $FF $00 $00
 *
 * @param abySource a byte array to be unsynchronized
 * @return a unsynchronized representation of the source
 */
public static byte[] unsynchronize(byte[] abySource) {
    ByteArrayInputStream input = new ByteArrayInputStream(abySource);
    ByteArrayOutputStream output = new ByteArrayOutputStream(abySource.length);

    int count = 0;
    while (input.available() > 0) {
        int firstByte = input.read();
        count++;
        output.write(firstByte);
        if ((firstByte & MPEGFrameHeader.SYNC_BYTE1) == MPEGFrameHeader.SYNC_BYTE1) {
            // if byte is $FF, we must check the following byte if there is one
            if (input.available() > 0) {
                input.mark(1);  // remember where we were, if we don't need to unsynchronize
                int secondByte = input.read();
                if ((secondByte & MPEGFrameHeader.SYNC_BYTE2) == MPEGFrameHeader.SYNC_BYTE2) {
                    // we need to unsynchronize here
                    if (logger.isLoggable(Level.FINEST)) {
                        logger.finest("Writing unsynchronisation bit at:" + count);
                    }
                    output.write(0);

                } else if (secondByte == 0) {
                    // we need to unsynchronize here
                    if (logger.isLoggable(Level.FINEST)) {
                        logger.finest("Inserting zero unsynchronisation bit at:" + count);
                    }
                    output.write(0);
                }
                input.reset();
            }
        }
    }
    // if we needed to unsynchronize anything, and this tag ends with 0xff, we have to append a zero byte,
    // which will be removed on de-unsynchronization later
    if ((abySource[abySource.length - 1] & MPEGFrameHeader.SYNC_BYTE1) == MPEGFrameHeader.SYNC_BYTE1) {
        logger.finest("Adding unsynchronisation bit at end of stream");
        output.write(0);
    }
    return output.toByteArray();
}
 
Example 11
Project: PeSanKita-android   File: PduParser.java   View Source Code Vote up 4 votes
/**
 * Parse Text-String or Quoted-String.
 *
 * @param pduDataStream pdu data input stream
 * @param stringType TYPE_TEXT_STRING or TYPE_QUOTED_STRING
 * @return the string without End-of-string in byte array
 */
protected static byte[] parseWapString(ByteArrayInputStream pduDataStream,
        int stringType) {
    assert(null != pduDataStream);
    /**
     * From wap-230-wsp-20010705-a.pdf
     * Text-string = [Quote] *TEXT End-of-string
     * If the first character in the TEXT is in the range of 128-255,
     * a Quote character must precede it.
     * Otherwise the Quote character must be omitted.
     * The Quote is not part of the contents.
     * Quote = <Octet 127>
     * End-of-string = <Octet 0>
     *
     * Quoted-string = <Octet 34> *TEXT End-of-string
     *
     * Token-text = Token End-of-string
     */

    // Mark supposed beginning of Text-string
    // We will have to mark again if first char is QUOTE or QUOTED_STRING_FLAG
    pduDataStream.mark(1);

    // Check first char
    int temp = pduDataStream.read();
    assert(-1 != temp);
    if ((TYPE_QUOTED_STRING == stringType) &&
            (QUOTED_STRING_FLAG == temp)) {
        // Mark again if QUOTED_STRING_FLAG and ignore it
        pduDataStream.mark(1);
    } else if ((TYPE_TEXT_STRING == stringType) &&
            (QUOTE == temp)) {
        // Mark again if QUOTE and ignore it
        pduDataStream.mark(1);
    } else {
        // Otherwise go back to origin
        pduDataStream.reset();
    }

    // We are now definitely at the beginning of string
    /**
     * Return *TOKEN or *TEXT (Text-String without QUOTE,
     * Quoted-String without QUOTED_STRING_FLAG and without End-of-string)
     */
    return getWapString(pduDataStream, stringType);
}
 
Example 12
Project: PeSanKita-android   File: PduParser.java   View Source Code Vote up 4 votes
/**
 * Parse content type.
 *
 * @param pduDataStream pdu data input stream
 * @param map to store parameters in Content-Type header field
 * @return Content-Type value
 */
protected static byte[] parseContentType(ByteArrayInputStream pduDataStream,
        HashMap<Integer, Object> map) {
    /**
     * From wap-230-wsp-20010705-a.pdf
     * Content-type-value = Constrained-media | Content-general-form
     * Content-general-form = Value-length Media-type
     * Media-type = (Well-known-media | Extension-Media) *(Parameter)
     */
    assert(null != pduDataStream);

    byte[] contentType = null;
    pduDataStream.mark(1);
    int temp = pduDataStream.read();
    assert(-1 != temp);
    pduDataStream.reset();

    int cur = (temp & 0xFF);

    if (cur < TEXT_MIN) {
        int length = parseValueLength(pduDataStream);
        int startPos = pduDataStream.available();
        pduDataStream.mark(1);
        temp = pduDataStream.read();
        assert(-1 != temp);
        pduDataStream.reset();
        int first = (temp & 0xFF);

        if ((first >= TEXT_MIN) && (first <= TEXT_MAX)) {
            contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING);
        } else if (first > TEXT_MAX) {
            int index = parseShortInteger(pduDataStream);

            if (index < PduContentTypes.contentTypes.length) { //well-known type
                contentType = (PduContentTypes.contentTypes[index]).getBytes();
            } else {
                pduDataStream.reset();
                contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING);
            }
        } else {
            Log.e(LOG_TAG, "Corrupt content-type");
            return (PduContentTypes.contentTypes[0]).getBytes(); //"*/*"
        }

        int endPos = pduDataStream.available();
        int parameterLen = length - (startPos - endPos);
        if (parameterLen > 0) {//have parameters
            parseContentTypeParams(pduDataStream, map, parameterLen);
        }

        if (parameterLen < 0) {
            Log.e(LOG_TAG, "Corrupt MMS message");
            return (PduContentTypes.contentTypes[0]).getBytes(); //"*/*"
        }
    } else if (cur <= TEXT_MAX) {
        contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING);
    } else {
        contentType =
            (PduContentTypes.contentTypes[parseShortInteger(pduDataStream)]).getBytes();
    }

    return contentType;
}
 
Example 13
Project: EatDubbo   File: ThriftCodecTest.java   View Source Code Vote up 4 votes
@Test
public void testEncodeExceptionResponse() throws Exception {

    URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() );

    Channel channel = new MockedChannel( url );

    Request request = createRequest();

    RpcResult rpcResult = new RpcResult();
    String exceptionMessage = "failed";
    rpcResult.setException( new RuntimeException( exceptionMessage ) );

    Response response = new Response();
    response.setResult( rpcResult );
    response.setId( request.getId() );
    ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024);

    ThriftCodec.RequestData rd = ThriftCodec.RequestData.create(
            ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString" );
    ThriftCodec.cachedRequest.put( request.getId(), rd );
    codec.encode( channel, bos, response );

    byte[] buf = new byte[bos.writerIndex() - 4];
    System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 );
    ByteArrayInputStream bis = new ByteArrayInputStream( buf);

    if ( bis.markSupported() ) {
        bis.mark( 0 );
    }

    TIOStreamTransport transport = new TIOStreamTransport( bis );
    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() );
    Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() );
    int headerLength = protocol.readI16();

    Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() );
    Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() );
    Assert.assertEquals( request.getId(), protocol.readI64() );

    if ( bis.markSupported() ) {
        bis.reset();
        bis.skip( headerLength );
    }

    TMessage message = protocol.readMessageBegin();
    Assert.assertEquals( "echoString", message.name );
    Assert.assertEquals( TMessageType.EXCEPTION, message.type );
    Assert.assertEquals( ThriftCodec.getSeqId(), message.seqid );
    TApplicationException exception = TApplicationException.read( protocol );
    protocol.readMessageEnd();

    Assert.assertEquals( exceptionMessage, exception.getMessage() );

}
 
Example 14
Project: dubbocloud   File: ThriftCodecTest.java   View Source Code Vote up 4 votes
@Test
public void testEncodeReplyResponse() throws Exception {

    URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() );

    Channel channel = new MockedChannel( url );

    Request request = createRequest();

    RpcResult rpcResult = new RpcResult();
    rpcResult.setResult( "Hello, World!" );

    Response response = new Response();
    response.setResult( rpcResult );
    response.setId( request.getId() );
    ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024);

    ThriftCodec.RequestData rd = ThriftCodec.RequestData.create(
            ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString" );
    ThriftCodec.cachedRequest.putIfAbsent( request.getId(), rd );
    codec.encode( channel, bos, response );

    byte[] buf = new byte[bos.writerIndex() - 4];
    System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 );

    ByteArrayInputStream bis = new ByteArrayInputStream( buf );

    if ( bis.markSupported() ) {
        bis.mark( 0 );
    }

    TIOStreamTransport transport = new TIOStreamTransport( bis );
    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() );
    Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() );
    int headerLength = protocol.readI16();

    Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() );
    Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() );
    Assert.assertEquals( request.getId(), protocol.readI64() );

    if ( bis.markSupported() ) {
        bis.reset();
        bis.skip( headerLength );
    }

    TMessage message = protocol.readMessageBegin();
    Assert.assertEquals( "echoString", message.name );
    Assert.assertEquals( TMessageType.REPLY, message.type );
    Assert.assertEquals( ThriftCodec.getSeqId(), message.seqid );
    Demo.echoString_result result = new Demo.echoString_result();
    result.read( protocol );
    protocol.readMessageEnd();

    Assert.assertEquals( rpcResult.getValue(), result.getSuccess() );
}
 
Example 15
Project: dubbox-hystrix   File: ThriftCodecTest.java   View Source Code Vote up 4 votes
@Test
public void testEncodeExceptionResponse() throws Exception {

    URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() );

    Channel channel = new MockedChannel( url );

    Request request = createRequest();

    RpcResult rpcResult = new RpcResult();
    String exceptionMessage = "failed";
    rpcResult.setException( new RuntimeException( exceptionMessage ) );

    Response response = new Response();
    response.setResult( rpcResult );
    response.setId( request.getId() );
    ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024);

    ThriftCodec.RequestData rd = ThriftCodec.RequestData.create(
            ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString" );
    ThriftCodec.cachedRequest.put( request.getId(), rd );
    codec.encode( channel, bos, response );

    byte[] buf = new byte[bos.writerIndex() - 4];
    System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 );
    ByteArrayInputStream bis = new ByteArrayInputStream( buf);

    if ( bis.markSupported() ) {
        bis.mark( 0 );
    }

    TIOStreamTransport transport = new TIOStreamTransport( bis );
    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() );
    Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() );
    int headerLength = protocol.readI16();

    Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() );
    Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() );
    Assert.assertEquals( request.getId(), protocol.readI64() );

    if ( bis.markSupported() ) {
        bis.reset();
        bis.skip( headerLength );
    }

    TMessage message = protocol.readMessageBegin();
    Assert.assertEquals( "echoString", message.name );
    Assert.assertEquals( TMessageType.EXCEPTION, message.type );
    Assert.assertEquals( ThriftCodec.getSeqId(), message.seqid );
    TApplicationException exception = TApplicationException.read( protocol );
    protocol.readMessageEnd();

    Assert.assertEquals( exceptionMessage, exception.getMessage() );

}
 
Example 16
Project: dubbo2   File: ThriftCodecTest.java   View Source Code Vote up 4 votes
@Test
public void testEncodeExceptionResponse() throws Exception {

    URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() );

    Channel channel = new MockedChannel( url );

    Request request = createRequest();

    RpcResult rpcResult = new RpcResult();
    String exceptionMessage = "failed";
    rpcResult.setException( new RuntimeException( exceptionMessage ) );

    Response response = new Response();
    response.setResult( rpcResult );
    response.setId( request.getId() );
    ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024);

    ThriftCodec.RequestData rd = ThriftCodec.RequestData.create(
            ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString" );
    ThriftCodec.cachedRequest.put( request.getId(), rd );
    codec.encode( channel, bos, response );

    byte[] buf = new byte[bos.writerIndex() - 4];
    System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 );
    ByteArrayInputStream bis = new ByteArrayInputStream( buf);

    if ( bis.markSupported() ) {
        bis.mark( 0 );
    }

    TIOStreamTransport transport = new TIOStreamTransport( bis );
    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() );
    Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() );
    int headerLength = protocol.readI16();

    Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() );
    Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() );
    Assert.assertEquals( request.getId(), protocol.readI64() );

    if ( bis.markSupported() ) {
        bis.reset();
        bis.skip( headerLength );
    }

    TMessage message = protocol.readMessageBegin();
    Assert.assertEquals( "echoString", message.name );
    Assert.assertEquals( TMessageType.EXCEPTION, message.type );
    Assert.assertEquals( ThriftCodec.getSeqId(), message.seqid );
    TApplicationException exception = TApplicationException.read( protocol );
    protocol.readMessageEnd();

    Assert.assertEquals( exceptionMessage, exception.getMessage() );

}
 
Example 17
Project: mi-firma-android   File: BerTlv.java   View Source Code Vote up 4 votes
private void decode(final ByteArrayInputStream stream) throws IndexOutOfBoundsException {
    // Decode Tag
    this.tag = new BerTlvIdentifier();
    this.tag.decode(stream);

    // Decode length
    int tmpLength = stream.read();
    if (tmpLength <= 127) { // 0111 1111
        // Es un short
        this.length = tmpLength;
    }
    else if (tmpLength == 128) { // 1000 0000
        // Es un tipo indefinido, lo establecemos despues
        this.length = tmpLength;
    }
    else {
        // Es un long
        final int numberOfLengthOctets = tmpLength & 127; // turn off 8th bit
        tmpLength = 0;
        for (int i = 0; i < numberOfLengthOctets; i++) {
            final int nextLengthOctet = stream.read();
            tmpLength <<= 8;
            tmpLength |= nextLengthOctet;
        }
        this.length = tmpLength;
    }

    // Decodificamos el valor
    if (this.length == 128) { // 1000 0000
        // Formato indefinido
        stream.mark(0);
        int prevOctet = 1;
        int curOctet = 0;
        int len = 0;
        while (true) {
            len++;
            curOctet = stream.read();
            if (prevOctet == 0 && curOctet == 0) {
                break;
            }
            prevOctet = curOctet;
        }
        len -= 2;
        this.value = new byte[len];
        stream.reset();
        if (len != stream.read(this.value, 0, len)) {
            throw new IndexOutOfBoundsException("La longitud de los datos leidos no coincide con el parametro indicado"); //$NON-NLS-1$
        }
        this.length = len;
    }
    else {
        // Formato definido
        this.value = new byte[this.length];
        if (this.length != stream.read(this.value, 0, this.length)) {
            throw new IndexOutOfBoundsException("La longitud de los datos leidos no coincide con el parametro indicado"); //$NON-NLS-1$
        }
    }
}
 
Example 18
Project: MetadataEditor   File: ID3Unsynchronization.java   View Source Code Vote up 4 votes
/**
 * Unsynchronize an array of bytes, this should only be called if the decision has already been made to
 * unsynchronize the byte array
 *
 * In order to prevent a media player from incorrectly interpreting the contents of a tag, all $FF bytes
 * followed by a byte with value >=224 must be followed by a $00 byte (thus, $FF $F0 sequences become $FF $00 $F0).
 * Additionally because unsynchronisation is being applied any existing $FF $00 have to be converted to
 * $FF $00 $00
 *
 * @param abySource a byte array to be unsynchronized
 * @return a unsynchronized representation of the source
 */
public static byte[] unsynchronize(byte[] abySource)
{
    ByteArrayInputStream input = new ByteArrayInputStream(abySource);
    ByteArrayOutputStream output = new ByteArrayOutputStream(abySource.length);

    int count = 0;
    while (input.available() > 0)
    {
        int firstByte = input.read();
        count++;
        output.write(firstByte);
        if ((firstByte & MPEGFrameHeader.SYNC_BYTE1) == MPEGFrameHeader.SYNC_BYTE1)
        {
            // if byte is $FF, we must check the following byte if there is one
            if (input.available() > 0)
            {
                input.mark(1);  // remember where we were, if we don't need to unsynchronize
                int secondByte = input.read();
                if ((secondByte & MPEGFrameHeader.SYNC_BYTE2) == MPEGFrameHeader.SYNC_BYTE2)
                {
                    // we need to unsynchronize here
                    if (logger.isLoggable(Level.FINEST))
                    {
                        logger.finest("Writing unsynchronisation bit at:" + count);
                    }
                    output.write(0);

                }
                else if (secondByte == 0)
                {
                    // we need to unsynchronize here
                    if (logger.isLoggable(Level.FINEST))
                    {
                        logger.finest("Inserting zero unsynchronisation bit at:" + count);
                    }
                    output.write(0);
                }
                input.reset();
            }
        }
    }
    // if we needed to unsynchronize anything, and this tag ends with 0xff, we have to append a zero byte,
    // which will be removed on de-unsynchronization later
    if ((abySource[abySource.length - 1] & MPEGFrameHeader.SYNC_BYTE1) == MPEGFrameHeader.SYNC_BYTE1)
    {
        logger.finest("Adding unsynchronisation bit at end of stream");
        output.write(0);
    }
    return output.toByteArray();
}
 
Example 19
Project: EatDubbo   File: ThriftCodecTest.java   View Source Code Vote up 2 votes
@Test
public void testEncodeRequest() throws Exception {

    Request request = createRequest();

    ChannelBuffer output = ChannelBuffers.dynamicBuffer(1024);

    codec.encode( channel, output, request );

    byte[] bytes = new byte[output.readableBytes()];
    output.readBytes(bytes);

    ByteArrayInputStream bis = new ByteArrayInputStream( bytes );

    TTransport transport = new TIOStreamTransport( bis );

    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    // frame
    byte[] length = new byte[4];
    transport.read( length, 0, 4 );

    if ( bis.markSupported() ) {
        bis.mark( 0 );
    }

    // magic
    Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() );

    // message length
    int messageLength = protocol.readI32();
    Assert.assertEquals( messageLength + 4, bytes.length );

    // header length
    short headerLength = protocol.readI16();
    // version
    Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() );
    // service name
    Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() );
    // dubbo request id
    Assert.assertEquals( request.getId(), protocol.readI64() );

    // test message header length
    if ( bis.markSupported() ) {
        bis.reset();
        bis.skip( headerLength );
    }

    TMessage message = protocol.readMessageBegin();

    Demo.echoString_args args = new Demo.echoString_args();

    args.read( protocol );

    protocol.readMessageEnd();

    Assert.assertEquals( "echoString", message.name );

    Assert.assertEquals( TMessageType.CALL, message.type );

    Assert.assertEquals( "Hello, World!", args.getArg() );

}
 
Example 20
Project: dubbocloud   File: ThriftCodecTest.java   View Source Code Vote up 2 votes
@Test
public void testEncodeRequest() throws Exception {

    Request request = createRequest();

    ChannelBuffer output = ChannelBuffers.dynamicBuffer(1024);

    codec.encode( channel, output, request );

    byte[] bytes = new byte[output.readableBytes()];
    output.readBytes(bytes);

    ByteArrayInputStream bis = new ByteArrayInputStream( bytes );

    TTransport transport = new TIOStreamTransport( bis );

    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    // frame
    byte[] length = new byte[4];
    transport.read( length, 0, 4 );

    if ( bis.markSupported() ) {
        bis.mark( 0 );
    }

    // magic
    Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() );

    // message length
    int messageLength = protocol.readI32();
    Assert.assertEquals( messageLength + 4, bytes.length );

    // header length
    short headerLength = protocol.readI16();
    // version
    Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() );
    // service name
    Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() );
    // dubbo request id
    Assert.assertEquals( request.getId(), protocol.readI64() );

    // test message header length
    if ( bis.markSupported() ) {
        bis.reset();
        bis.skip( headerLength );
    }

    TMessage message = protocol.readMessageBegin();

    Demo.echoString_args args = new Demo.echoString_args();

    args.read( protocol );

    protocol.readMessageEnd();

    Assert.assertEquals( "echoString", message.name );

    Assert.assertEquals( TMessageType.CALL, message.type );

    Assert.assertEquals( "Hello, World!", args.getArg() );

}