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

The following examples show how to use java.io.ByteArrayInputStream#reset() . 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
Source File: TestDatabaseReadPerformance.java    From reladomo with Apache License 2.0 6 votes vote down vote up
public void testArchiveReadTime() throws IOException, ClassNotFoundException
{
    Operation op = PositionQuantityFinder.businessDate().equalsEdgePoint();
    op = op.and(PositionQuantityFinder.processingDate().equalsEdgePoint());
    op = op.and(PositionQuantityFinder.acmapCode().eq(SOURCE_X));

    PositionQuantityList positionQuantityList = new PositionQuantityList(op);
    positionQuantityList.setBypassCache(true);
    MithraRuntimeCacheController cacheController = new MithraRuntimeCacheController(PositionQuantityFinder.class);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    cacheController.archiveObjects(baos, positionQuantityList);
    ByteArrayInputStream bain = new ByteArrayInputStream(baos.toByteArray());
    for(int i=0; i < 6; i++)
    {
        long now = System.currentTimeMillis();
        cacheController.readCacheFromArchive(bain);
        long totalTime = (System.currentTimeMillis() - now);
        System.out.println("took "+totalTime +" ms "+" per object: "+((double)totalTime*1000)/positionQuantityList.size()+ " microseconds");
        bain.reset();
    }
}
 
Example 2
Source File: TestWebbUtils_Mock.java    From DavidWebb with MIT License 6 votes vote down vote up
public void testParseResponseBody() throws Exception {
    // String
    Response response = mock(Response.class);
    String expected = "München 1 Maß 10 €";
    byte[] payloadInBytes = expected.getBytes("UTF-8");
    ByteArrayInputStream payload = new ByteArrayInputStream(payloadInBytes);

    WebbUtils.parseResponseBody(String.class, response, payload);
    verify(response).setBody(expected);

    // byte[]
    response = mock(Response.class);

    payload.reset();
    WebbUtils.parseResponseBody(Const.BYTE_ARRAY_CLASS, response, payload);
    verify(response).setBody(payloadInBytes);

    // void
    response = mock(Response.class);

    WebbUtils.parseResponseBody(Void.class, response, null);
    verify(response, never()).setBody(anyObject());
}
 
Example 3
Source File: TestSOSService.java    From sensorhub with Mozilla Public License 2.0 6 votes vote down vote up
@Test(expected = OGCException.class)
public void testGetObsWrongFormat() throws Exception
{
    deployService(buildSensorProvider1());
    
    InputStream is = new URL(SERVICE_ENDPOINT + "?service=SOS&version=2.0&request=GetObservation&offering=urn:mysos:sensor1&observedProperty=urn:blabla:temperature&responseFormat=badformat").openStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    IOUtils.copy(is, os);
    
    // read back and print
    ByteArrayInputStream bis = new ByteArrayInputStream(os.toByteArray());
    IOUtils.copy(bis, System.out);
    bis.reset();
    
    // parse and generate exception
    OGCExceptionReader.parseException(bis);
}
 
Example 4
Source File: TestHelper.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
public static void assertStreamsAreEqualAtIndex(ByteArrayInputStream src, ByteArrayInputStream dst, int srcIndex,
        int dstIndex, int length, int bufferSize) throws IOException {
    dst.reset();
    src.reset();

    dst.skip(dstIndex);
    src.skip(srcIndex);
    byte[] srcBuffer = new byte[bufferSize];
    byte[] destBuffer = new byte[bufferSize];
    src.read(srcBuffer);
    dst.read(destBuffer);

    for (int i = 0; i < length; i++) {
        Assert.assertEquals(src.read(), dst.read());
    }
}
 
Example 5
Source File: TestImage.java    From Open-Imaging with Apache License 2.0 5 votes vote down vote up
public TestImage(final String name, final int width, final int height, final int frames) throws IOException {
	this.name = name;
	path = Paths.get(GifDecoderTest.IN_FOLDER, name + ".gif");
	this.width = width;
	this.height = height;
	this.frames = frames;
	data = Files.readAllBytes(path);
	stream = new ByteArrayInputStream(data);
	stream.reset();
}
 
Example 6
Source File: AttributeClass.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 7
Source File: AttributeClass.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
Source File: AttributeClass.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
Source File: XmlImportExportTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactional() throws Exception {
   ClientSession session = basicSetUp();

   session.createQueue(new QueueConfiguration(QUEUE_NAME));

   ClientProducer producer = session.createProducer(QUEUE_NAME);

   ClientMessage msg = session.createMessage(true);
   producer.send(msg);

   session.close();
   locator.close();
   server.stop();

   ByteArrayOutputStream xmlOutputStream = new ByteArrayOutputStream();
   XmlDataExporter xmlDataExporter = new XmlDataExporter();
   xmlDataExporter.process(xmlOutputStream, server.getConfiguration().getBindingsDirectory(), server.getConfiguration().getJournalDirectory(), server.getConfiguration().getPagingDirectory(), server.getConfiguration().getLargeMessagesDirectory());
   System.out.print(new String(xmlOutputStream.toByteArray()));

   clearDataRecreateServerDirs();
   server.start();
   checkForLongs();
   locator = createInVMNonHALocator();
   factory = createSessionFactory(locator);
   session = factory.createSession(false, false, true);
   ClientSession managementSession = factory.createSession(false, true, true);

   ByteArrayInputStream xmlInputStream = new ByteArrayInputStream(xmlOutputStream.toByteArray());
   XmlDataImporter xmlDataImporter = new XmlDataImporter();
   xmlDataImporter.validate(xmlInputStream);
   xmlInputStream.reset();
   xmlDataImporter.process(xmlInputStream, session, managementSession);
   ClientConsumer consumer = session.createConsumer(QUEUE_NAME);
   session.start();

   msg = consumer.receive(CONSUMER_TIMEOUT);
   assertNotNull(msg);
}
 
Example 10
Source File: AttributeClass.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 File: AttributeClass.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 12
Source File: JPEGFactory.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Creates a new JPEG Image XObject from a byte array containing JPEG data.
 *
 * @param document the document where the image will be created
 * @param byteArray bytes of JPEG image
 * @return a new Image XObject
 *
 * @throws IOException if the input stream cannot be read
 */
public static PDImageXObject createFromByteArray(PDDocument document, byte[] byteArray)
        throws IOException
{
    // copy stream
    ByteArrayInputStream byteStream = new ByteArrayInputStream(byteArray);

    // read image
    Raster raster = readJPEGRaster(byteStream);
    byteStream.reset();

    PDColorSpace colorSpace;
    switch (raster.getNumDataElements())
    {
        case 1:
            colorSpace = PDDeviceGray.INSTANCE;
            break;
        case 3:
            colorSpace = PDDeviceRGB.INSTANCE;
            break;
        case 4:
            colorSpace = PDDeviceCMYK.INSTANCE;
            break;
        default:
            throw new UnsupportedOperationException("number of data elements not supported: " +
                    raster.getNumDataElements());
    }

    // create PDImageXObject from stream
    PDImageXObject pdImage = new PDImageXObject(document, byteStream, 
            COSName.DCT_DECODE, raster.getWidth(), raster.getHeight(), 8, colorSpace);

    if (colorSpace instanceof PDDeviceCMYK)
    {
        COSArray decode = new COSArray();
        decode.add(COSInteger.ONE);
        decode.add(COSInteger.ZERO);
        decode.add(COSInteger.ONE);
        decode.add(COSInteger.ZERO);
        decode.add(COSInteger.ONE);
        decode.add(COSInteger.ZERO);
        decode.add(COSInteger.ONE);
        decode.add(COSInteger.ZERO);
        pdImage.setDecode(decode);
    }

    return pdImage;
}
 
Example 13
Source File: HeaderedArchiveRecord.java    From webarchive-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Read header if present. Technique borrowed from HttpClient HttpParse
 * class. Using http parser code for now. Later move to more generic header
 * parsing code if there proves a need.
 * 
 * @return ByteArrayInputStream with the http header in it or null if no
 *         http header.
 * @throws IOException
 */
private InputStream readContentHeaders() throws IOException {
    // If judged a record that doesn't have an http header, return
    // immediately.
    if (!hasContentHeaders()) {
        return null;
    }
    byte [] statusBytes = LaxHttpParser.readRawLine(getIn());
    int eolCharCount = getEolCharsCount(statusBytes);
    if (eolCharCount <= 0) {
        throw new IOException("Failed to read raw lie where one " +
            " was expected: " + new String(statusBytes));
    }
    String statusLine = EncodingUtil.getString(statusBytes, 0,
        statusBytes.length - eolCharCount, ARCConstants.DEFAULT_ENCODING);
    if (statusLine == null) {
        throw new NullPointerException("Expected status line is null");
    }
    // TODO: Tighten up this test.
    boolean isHttpResponse = StatusLine.startsWithHTTP(statusLine);
    boolean isHttpRequest = false;
    if (!isHttpResponse) {
        isHttpRequest = statusLine.toUpperCase().startsWith("GET") ||
            !statusLine.toUpperCase().startsWith("POST");
    }
    if (!isHttpResponse && !isHttpRequest) {
        throw new UnexpectedStartLineIOException("Failed parse of " +
            "status line: " + statusLine);
    }
    this.statusCode = isHttpResponse?
        (new StatusLine(statusLine)).getStatusCode(): -1;
    
    // Save off all bytes read.  Keep them as bytes rather than
    // convert to strings so we don't have to worry about encodings
    // though this should never be a problem doing http headers since
    // its all supposed to be ascii.
    ByteArrayOutputStream baos =
        new ByteArrayOutputStream(statusBytes.length + 4 * 1024);
    baos.write(statusBytes);
    
    // Now read rest of the header lines looking for the separation
    // between header and body.
    for (byte [] lineBytes = null; true;) {
        lineBytes = LaxHttpParser.readRawLine(getIn());
        eolCharCount = getEolCharsCount(lineBytes);
        if (eolCharCount <= 0) {
            throw new IOException("Failed reading headers: " +
                ((lineBytes != null)? new String(lineBytes): null));
        }
        // Save the bytes read.
        baos.write(lineBytes);
        if ((lineBytes.length - eolCharCount) <= 0) {
            // We've finished reading the http header.
            break;
        }
    }
    
    byte [] headerBytes = baos.toByteArray();
    // Save off where content body, post content headers, starts.
    this.contentHeadersLength = headerBytes.length;
    ByteArrayInputStream bais =
        new ByteArrayInputStream(headerBytes);
    if (!bais.markSupported()) {
        throw new IOException("ByteArrayInputStream does not support mark");
    }
    bais.mark(headerBytes.length);
    // Read the status line.  Don't let it into the parseHeaders function.
    // It doesn't know what to do with it.
    bais.read(statusBytes, 0, statusBytes.length);
    this.contentHeaders = LaxHttpParser.parseHeaders(bais,
        ARCConstants.DEFAULT_ENCODING);
    bais.reset();
    return bais;
}
 
Example 14
Source File: RecordBench.java    From hadoop-gpu with Apache License 2.0 4 votes vote down vote up
private static void runBinaryBench(String type, int numRecords, Times times)
  throws IOException {
  Record[] records = makeArray(type, numRecords, times);
  ByteArrayOutputStream bout = new ByteArrayOutputStream();
  BinaryRecordOutput rout = new BinaryRecordOutput(bout);
  DataOutputStream dout = new DataOutputStream(bout);
  
  for(int idx = 0; idx < numRecords; idx++) {
    records[idx].serialize(rout);
  }
  bout.reset();
  
  times.serialize = System.nanoTime();
  for(int idx = 0; idx < numRecords; idx++) {
    records[idx].serialize(rout);
  }
  times.serialize = System.nanoTime() - times.serialize;
  
  byte[] serialized = bout.toByteArray();
  ByteArrayInputStream bin = new ByteArrayInputStream(serialized);
  BinaryRecordInput rin = new BinaryRecordInput(bin);
  
  times.deserialize = System.nanoTime();
  for(int idx = 0; idx < numRecords; idx++) {
    records[idx].deserialize(rin);
  }
  times.deserialize = System.nanoTime() - times.deserialize;
  
  bout.reset();
  
  times.write = System.nanoTime();
  for(int idx = 0; idx < numRecords; idx++) {
    records[idx].write(dout);
  }
  times.write = System.nanoTime() - times.write;
  
  bin.reset();
  DataInputStream din = new DataInputStream(bin);
  
  times.readFields = System.nanoTime();
  for(int idx = 0; idx < numRecords; idx++) {
    records[idx].readFields(din);
  }
  times.readFields = System.nanoTime() - times.readFields;
}
 
Example 15
Source File: TestAliasedBean.java    From spearal-java with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("boxing")
@Test
public void testClassNotFoundBean() throws IOException {
	SimpleBean bean = new SimpleBean(true, 1, 0.1, "blabla");
	
	SpearalFactory serverFactory = new DefaultSpearalFactory();
	serverFactory.getContext().configure(new AliasStrategy() {
		
		@Override
		public String alias(Class<?> cls) {
			return "org.error." + cls.getSimpleName();
		}
		
		@Override
		public String unalias(String aliasedClassName) {
			return aliasedClassName;
		}
	});
	
	SpearalFactory clientFactory = new DefaultSpearalFactory();

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	SpearalEncoder encoder = serverFactory.newEncoder(baos);
	encoder.writeAny(bean);
	
	byte[] bytes = baos.toByteArray();
	
	ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
	SpearalDecoder decoder = clientFactory.newDecoder(bais);
	decoder.printAny(clientFactory.newPrinter(printStream));
	printStream.println();
	
	bais.reset();
	decoder = clientFactory.newDecoder(bais);
	ClassNotFound clientBean = (ClassNotFound)decoder.readAny();
	
	Assert.assertEquals(
		clientBean.getClassNotFoundDescription(),
		"org.error.SimpleBean#booleanValue,doubleValue,intValue,stringValue"
	);
	Assert.assertEquals(bean.isBooleanValue(), clientBean.get("booleanValue"));
	Assert.assertEquals(Long.valueOf(bean.getIntValue()), clientBean.get("intValue"));
	Assert.assertEquals(bean.getDoubleValue(), clientBean.get("doubleValue"));
	Assert.assertEquals(bean.getStringValue(), clientBean.get("stringValue"));
	
	bais.reset();
	decoder = clientFactory.newDecoder(bais);
	SimpleBean copy = decoder.readAny(SimpleBean.class);
	Assert.assertEquals(bean, copy);
}
 
Example 16
Source File: XmlImportExportTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testLargeMessage() throws Exception {
   server = createServer(true);
   server.start();
   locator = createInVMNonHALocator();
   factory = createSessionFactory(locator);
   ClientSession session = factory.createSession(false, false);

   LargeServerMessageImpl fileMessage = new LargeServerMessageImpl((JournalStorageManager) server.getStorageManager());

   fileMessage.setMessageID(1005);
   fileMessage.setDurable(true);

   for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) {
      fileMessage.addBytes(new byte[]{getSamplebyte(i)});
   }

   fileMessage.putLongProperty(Message.HDR_LARGE_BODY_SIZE, 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE);

   fileMessage.releaseResources(false);

   session.createQueue(new QueueConfiguration("A"));

   ClientProducer prod = session.createProducer("A");

   prod.send(fileMessage);

   fileMessage.deleteFile();

   session.commit();

   session.close();
   locator.close();
   server.stop();

   ByteArrayOutputStream xmlOutputStream = new ByteArrayOutputStream();
   XmlDataExporter xmlDataExporter = new XmlDataExporter();
   xmlDataExporter.process(xmlOutputStream, server.getConfiguration().getBindingsDirectory(), server.getConfiguration().getJournalDirectory(), server.getConfiguration().getPagingDirectory(), server.getConfiguration().getLargeMessagesDirectory());
   System.out.print(new String(xmlOutputStream.toByteArray()));

   clearDataRecreateServerDirs();
   server.start();
   checkForLongs();
   locator = createInVMNonHALocator();
   factory = createSessionFactory(locator);
   session = factory.createSession(false, true, true);

   ByteArrayInputStream xmlInputStream = new ByteArrayInputStream(xmlOutputStream.toByteArray());
   XmlDataImporter xmlDataImporter = new XmlDataImporter();
   xmlDataImporter.validate(xmlInputStream);
   xmlInputStream.reset();
   xmlDataImporter.process(xmlInputStream, session);
   session.close();
   session = factory.createSession(false, false);
   session.start();

   ClientConsumer cons = session.createConsumer("A");

   ClientMessage msg = cons.receive(CONSUMER_TIMEOUT);

   assertNotNull(msg);

   assertEquals(2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE, msg.getBodySize());

   for (int i = 0; i < 2 * ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE; i++) {
      assertEquals(getSamplebyte(i), msg.getBodyBuffer().readByte());
   }

   msg.acknowledge();
   session.commit();
}
 
Example 17
Source File: ThriftCodecTest.java    From dubbox with Apache License 2.0 4 votes vote down vote up
@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 18
Source File: ThriftCodecTest.java    From dubbox with Apache License 2.0 4 votes vote down vote up
@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 19
Source File: ThriftCodecTest.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
@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 20
Source File: ThriftCodecTest.java    From dubbox with Apache License 2.0 2 votes vote down vote up
@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() );

}