Java Code Examples for org.apache.mina.core.buffer.IoBuffer#wrap()

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#wrap() . 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: StreamWriteFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected IoBuffer getNextBuffer(InputStream is) throws IOException {
    byte[] bytes = new byte[getWriteBufferSize()];

    int off = 0;
    int n = 0;
    while (off < bytes.length && (n = is.read(bytes, off, bytes.length - off)) != -1) {
        off += n;
    }

    if (n == -1 && off == 0) {
        return null;
    }

    IoBuffer buffer = IoBuffer.wrap(bytes, 0, off);

    return buffer;
}
 
Example 2
Source File: AMF3IOTest.java    From red5-io with Apache License 2.0 6 votes vote down vote up
@Test
public void testVectorMixedInput() {
    log.debug("\n Testing Vector<Object>");
    //100700010607666f6f010a13256f72672e726564352e74673742e466f6f33000403
    //[foo, null, org.red5.test.Foo3[foo=0]] // Foo3 is a class instance
    byte[] v2 = new byte[] { (byte) 0x10, (byte) 0x07, (byte) 0x00, (byte) 0x01, (byte) 0x06, (byte) 0x07, (byte) 0x66, (byte) 0x6f, (byte) 0x6f, (byte) 0x01, (byte) 0x0a, (byte) 0x13, (byte) 0x25, (byte) 0x6f, (byte) 0x72, (byte) 0x67, (byte) 0x2e, (byte) 0x72, (byte) 0x65, (byte) 0x64, (byte) 0x35, (byte) 0x2e, (byte) 0x74, (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x2e, (byte) 0x46, (byte) 0x6f,
            (byte) 0x6f, (byte) 0x33, (byte) 0x00, (byte) 0x04, (byte) 0x03 };

    in = new Input(IoBuffer.wrap(v2));
    List<Object> vectorOut = Deserializer.deserialize(in, null);
    assertNotNull(vectorOut);
    assertEquals(vectorOut.size(), 3);
    for (int i = 0; i < vectorOut.size(); i++) {
        System.err.println("Vector: " + vectorOut.get(i));
    }
    resetOutput();
}
 
Example 3
Source File: WebSocketServerTest.java    From red5-websocket with Apache License 2.0 6 votes vote down vote up
@Test
public void testMasked() throws Throwable {
    log.info("testMasked enter");
    // masked
    IoBuffer in = IoBuffer.wrap(new byte[] { (byte) 0x81, (byte) 0x85, (byte) 0x37, (byte) 0xfa, (byte) 0x21, (byte) 0x3d, (byte) 0x7f, (byte) 0x9f, (byte) 0x4d, (byte) 0x51, (byte) 0x58 });
    // create session and conn
    DummySession session = new DummySession();
    WebSocketConnection conn = new WebSocketConnection(session);
    session.setAttribute(Constants.CONNECTION, conn);
    // decode
    DummyDecoder decoder = new DummyDecoder();
    decoder.dummyDecode(session, in, new DummyOutput());
    assertTrue(((WSMessage) writtenResult).getMessageType() == MessageType.TEXT);
    assertEquals("Hello", ((WSMessage) writtenResult).getMessageAsString());
    log.info("testMasked exit");
}
 
Example 4
Source File: AbstractDataSlave.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void processAnalogWrite ( final int startAddress, final int numRegisters, final byte[] rawData )
{
    final int[] regs = new int[numRegisters];
    final IoBuffer data = IoBuffer.wrap ( rawData );

    data.order ( this.order );

    for ( int i = 0; i < numRegisters; i++ )
    {
        regs[i] = data.getUnsignedShort ();
    }

    handleAnalogWrite ( startAddress, regs );
}
 
Example 5
Source File: MinaBuffer.java    From Lealone-Plugins with Apache License 2.0 5 votes vote down vote up
@Override
public MinaBuffer getBuffer(int start, int end) {
    byte[] bytes = new byte[end - start];
    // 不能直接这样用,get的javadoc是错的,start应该是bytes的位置
    // buffer.get(bytes, start, end - start);
    int pos = buffer.position();
    buffer.position(start);
    buffer.get(bytes, 0, end - start);
    buffer.position(pos);
    IoBuffer newBuffer = IoBuffer.wrap(bytes);
    newBuffer.setAutoExpand(true);
    return new MinaBuffer(newBuffer);
}
 
Example 6
Source File: InputTest.java    From red5-io with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnStreamSendMap() {
    // 02 = string
    // 08 = mixed array (map) max number = 0

    IoBuffer data = IoBuffer.wrap(IOUtils.hexStringToByteArray("02 00 0c 6f 6e 53 74 72 65 61 6d 53 65 6e 64 08 00000000 00 05 76 616c7565 02 00 01 31 00 00 09"));
    Input in0 = new Input(data);
    assertEquals(DataTypes.CORE_STRING, in0.readDataType());
    String method = in0.readString();
    assertEquals("onStreamSend", method);
    assertEquals(DataTypes.CORE_MAP, in0.readDataType());
    @SuppressWarnings("rawtypes")
    ObjectMap map = (ObjectMap) in0.readMap();
    assertEquals(map.get("value"), "1");
}
 
Example 7
Source File: DaveHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings ( "unused" )
private void sendInit ()
{
    final byte[] data = new byte[] { 0x32, 0x01, 0x00, 0x00, (byte)0xff, (byte)0xff, 0x00, 0x08, 0x00, 0x00, (byte)0xf0, 0x00, 0x00, 0x01, 0x00, 0x01, 0x03, (byte)0xc0 };
    final IoBuffer buffer = IoBuffer.wrap ( data );

    this.session.write ( new DataTPDU ( buffer ) );
}
 
Example 8
Source File: InputTest.java    From red5-io with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonZeroBasedEcmaArray() {
    // { '1': 'hello' }
    byte[] stream = new byte[] { 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x31, 0x02, 0x00, 0x05, 'h', 'e', 'l', 'l', 'o', 0x00, 0x00, 0x09 };
    Input input = new Input(IoBuffer.wrap(stream));
    Object actual = input.readMap();

    Map<Object, Object> expected = new HashMap<>();
    expected.put(1, "hello");

    assertEquals(expected, actual);
}
 
Example 9
Source File: Zlib.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Compress the input. The result will be put in a new buffer.
 *  
 * @param inBuffer the buffer to be compressed. The contents are transferred
 * into a local byte array and the buffer is flipped and returned intact.
 * @return the buffer with the compressed data
 * @throws IOException if the compression of teh buffer failed for some reason
 * @throws IllegalStateException if the mode is not <code>MODE_DEFLATER</code>
 */
public IoBuffer deflate(IoBuffer inBuffer) throws IOException {
    if (mode == MODE_INFLATER) {
        throw new IllegalStateException("not initialized as DEFLATER");
    }

    byte[] inBytes = new byte[inBuffer.remaining()];
    inBuffer.get(inBytes).flip();

    // according to spec, destination buffer should be 0.1% larger
    // than source length plus 12 bytes. We add a single byte to safeguard
    // against rounds that round down to the smaller value
    int outLen = (int) Math.round(inBytes.length * 1.001) + 1 + 12;
    byte[] outBytes = new byte[outLen];

    synchronized (zStream) {
        zStream.next_in = inBytes;
        zStream.next_in_index = 0;
        zStream.avail_in = inBytes.length;
        zStream.next_out = outBytes;
        zStream.next_out_index = 0;
        zStream.avail_out = outBytes.length;

        int retval = zStream.deflate(JZlib.Z_SYNC_FLUSH);
        if (retval != JZlib.Z_OK) {
            outBytes = null;
            inBytes = null;
            throw new IOException("Compression failed with return value : " + retval);
        }

        IoBuffer outBuf = IoBuffer.wrap(outBytes, 0, zStream.next_out_index);

        return outBuf;
    }
}
 
Example 10
Source File: TestITCHHelper.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
protected IMessage decode(Object lastMessage, ITCHCodec codec) throws Exception {
       if(codec == null) {
           codec = (ITCHCodec)messageHelper.getCodec(serviceContext);
       }
	MockProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();
	IoSession decodeSession = new DummySession();
	IoBuffer toDecode = IoBuffer.wrap( ((IoBuffer)lastMessage).array() );
	boolean decodeResult = codec.doDecode( decodeSession, toDecode, decoderOutput );
	    
	Assert.assertTrue("Decoding error.", decodeResult);
       Assert.assertTrue("Message queue size must not less then 1.", decoderOutput.getMessageQueue().size() >= 1);

	return (IMessage) decoderOutput.getMessageQueue().element();
}
 
Example 11
Source File: TestITCHVisitorPositive.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
/**
 * Test decode message testString from bytes and check Alpha_notrim
 */
@Test
public void testStringAlphaNotrimDecode(){
       byte[] array = { 58, 0, 1, 48, 0, 0, 0, 0,
               46, 13, 102, 102, 115, 116, 49, 32,
               32, 32, 49, 48, 58, 52, 57, 58,
               48, 48, 77, 111, 110, 32, 74, 117,
               108, 32, 48, 52, 32, 49, 52, 58,
               48, 50, 58, 51, 48, 32, 77, 83,
               75, 32, 50, 48, 49, 54, 0, 0,
               0, 0, 0, 0, 0, 0, 0, 0, };
  		IoBuffer toDecode = IoBuffer.wrap( array );
	toDecode.order(ByteOrder.LITTLE_ENDIAN);
	toDecode.position(0);

	IoSession decodeSession = new DummySession();
	MockProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();
	try{
		boolean decodableResult = codec.doDecode( decodeSession, toDecode, decoderOutput );
		Assert.assertTrue( "Decoding error.", decodableResult);
		IMessage message=(IMessage) decoderOutput.getMessageQueue().element();
		@SuppressWarnings("unchecked")
           List<IMessage> result = message.getField(ITCHMessageHelper.SUBMESSAGES_FIELD_NAME);
		Assert.assertEquals(2, result.size());
		Assert.assertEquals(1, (int)Integer.valueOf(result.get(1).getField("Alpha_notrim").toString().trim()));
	}catch(Exception e){
		e.printStackTrace(System.err);
		logger.error(e.getMessage(),e);
		Assert.fail(e.getMessage());
	}
}
 
Example 12
Source File: Red5AMFBase.java    From marshalsec with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @see marshalsec.BlazeDSBase#unmarshal(byte[])
 */
@Override
public Object unmarshal ( byte[] data ) throws Exception {
    IoBuffer buf = IoBuffer.wrap(data);
    Input i = createInput(buf);
    return Deserializer.deserialize(i, Object.class);
}
 
Example 13
Source File: HttpDecoderTest.java    From gameserver with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoDecodeWithHEAD() throws Exception {
	String request = "HEAD /equipment_config.lua HTTP/1.1\nHost: localhost\n\n";
	final HttpMessage expect = new HttpMessage();
	expect.setRequestUri("/equipment_config.lua");
	expect.setHead(true);
	
	HttpDecoder decoder = new HttpDecoder();
	
	IoSession session = createMock(IoSession.class);
	//Set mock behavior
	expect(session.getAttribute(eq("HttpDecoder.Session"))).andReturn(null).anyTimes();
	expect(session.setAttribute(eq("HttpDecoder.Session"), anyObject())).andReturn(null).anyTimes();
	replay(session);
	
	ProtocolDecoderOutput out = createNiceMock(ProtocolDecoderOutput.class);
	out.write(anyObject());
	expectLastCall().andAnswer(new IAnswer<Object>() {
		public Object answer() {
			HttpMessage message = (HttpMessage)getCurrentArguments()[0];
			assertTrue(compareHttpMessage(expect, message));
			assertTrue(message.isHead());
			return null;
		}
	});
	replay(out);
	
	IoBuffer in = IoBuffer.wrap(request.getBytes());
	
	int l = in.remaining();
	boolean result = true;
	while ( result ) {
		result = decoder.doDecode(session, in, out);
	}
	
	verify(session);
	verify(out);
	
	assertTrue(true);
}
 
Example 14
Source File: Packet.java    From red5-websocket with Apache License 2.0 4 votes vote down vote up
private Packet(byte[] buf, MessageType type) {
    this.data = IoBuffer.wrap(buf);
    this.type = type;
}
 
Example 15
Source File: TestFastCodec.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testDecodeFastMessage() throws Exception {

    String dictName = "FAST";
    SailfishURI dictUri = SailfishURI.unsafeParse(CORE_ALIAS + ":" + dictName);
    FASTCodec codec = getCodec(dictUri, dictName);

    byte[] sourceArray = { (byte) 0xab, (byte) 0xc0, (byte) 0x83, 0x42, (byte) 0xd7, 0x32, 0x30, 0x31, 0x36, 0x30, 0x32, 0x31, 0x30,
            0x2d, 0x30, 0x37, 0x3a, 0x31, 0x30, 0x3a, 0x30, 0x36, 0x2e, 0x31, 0x39, (byte) 0xb3, 0x36, 0x30, 0x36, 0x36, 0x36, (byte) 0xb0,
            (byte) 0x80, (byte) 0x82, (byte) 0x82, (byte) 0xc0, (byte) 0x87, 0x54, 0x4d, (byte) 0xd0, 0x21, (byte) 0xe9, 0x21, (byte) 0xee};

    IoBuffer toDecode = IoBuffer.wrap(sourceArray);
    toDecode.order(ByteOrder.LITTLE_ENDIAN);
    toDecode.position(0);

    IoSession decodeSession = new DummySession();

    MockProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();
    boolean decodableResult = codec.doDecode(decodeSession, toDecode, decoderOutput);
    Assert.assertTrue("Decoding error.", decodableResult);

    IMessage message = DefaultMessageFactory.getFactory().createMessage("ApplicationMessageRequest", "fast");
    message.addField("MsgType", "BW");
    message.addField("SendingTime", "20160210-07:10:06.193");
    message.addField("ApplReqID", "606660");
    message.addField("ApplReqType", 0L);
    message.addField("NoApplIDs", 1L);
    List<IMessage> list = new ArrayList<>();
    IMessage subMessage = DefaultMessageFactory.getFactory().createMessage("ApplicationMessageRequest_IndicesRequestEntries", "fast");
    subMessage.addField("RefApplID", "TMP");
    subMessage.addField("Reserved1", 6L);
    subMessage.addField("ApplBegSeqNum", 4328L);
    subMessage.addField("ApplEndSeqNum", 4333L);

    list.add(subMessage);
    message.addField("IndicesRequestEntries", list);

    AbstractProtocolEncoderOutput output = new MockProtocolEncoderOutput();

    session.write(message);
    codec.encode(session, message, output);
    Queue<Object> msgQueue = output.getMessageQueue();
    Object lastMessage = msgQueue.element();
    byte[] asd = ((IoBuffer) lastMessage).array();
    int limit = ((IoBuffer) lastMessage).limit();
    byte[] bytes = Arrays.copyOf(asd, limit);

    session.write(lastMessage);
    Assert.assertArrayEquals("Compare source and encoded\n" + HexDumper.getHexdump(bytes), sourceArray, bytes);
}
 
Example 16
Source File: TestNTGCodecNegative.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
/**
 * Negative test encode Heartbeat message with StartOfMessage=3 and decode it after
 */
@Test
public void testWrongMessage(){
       IMessage message = DefaultMessageFactory.getFactory().createMessage("Heartbeat", "NTG");
       IMessage messageHeader = DefaultMessageFactory.getFactory().createMessage("MessageHeader", "NTG");
	messageHeader.addField("StartOfMessage", 3);
	messageHeader.addField("MessageLength", 9);
	messageHeader.addField("MessageType", "2");
	message.addField("MessageHeader", messageHeader);
	try{
           IDictionaryStructure dictionary = TestNTGHelper.getDictionary();
           IMessageStructure msgStruct = dictionary.getMessages().get(message.getName());
		Assert.assertNotNull("Message structure is null.", msgStruct);
           NTGCodec encodeCodec = new NTGCodec();
		encodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);
           ProtocolEncoderOutput output = new TestNTGHelper().new MockProtocolEncoderOutput();
 		encodeCodec.encode(new DummySession(), message, output);

		Queue<Object> msgQueue = ((AbstractProtocolEncoderOutput) output).getMessageQueue();

		Assert.assertNotNull("Message queue from AbstractProtocolEncoderOutput.", msgQueue);
           Assert.assertTrue("Message queue size must be equal 1.", msgQueue.size() == 1);

		Object lastMessage = msgQueue.element();

		if (lastMessage instanceof IoBuffer) {
               NTGCodec decodeCodec = new NTGCodec();
			decodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);
			IoBuffer toDecode = IoBuffer.wrap( new byte[0] );
			toDecode.setAutoExpand(true);
			toDecode.put(((IoBuffer)lastMessage).array());
			toDecode.compact();
			toDecode.order(ByteOrder.LITTLE_ENDIAN);

			IoSession decodeSession = new DummySession();
			decodeCodec.decodable(decodeSession, toDecode);
			Assert.fail("Exception hasn't been thrown");
		}
	}catch(Exception e){
		Assert.assertEquals("Unexpected start of message: 3", e.getMessage());
	}

}
 
Example 17
Source File: TestNTGCodecPositive.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
private void testRoundTrip(IMessage message, IDictionaryStructure dictionary) {
	try
	{
           IMessageStructure msgStruct = dictionary.getMessages().get(message.getName());

		Assert.assertNotNull("Message structure is null.", msgStruct);

           NTGCodec encodeCodec = new NTGCodec();

		encodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);

           ProtocolEncoderOutput output = new TestNTGHelper().new MockProtocolEncoderOutput();
			encodeCodec.encode(new DummySession(), message, output);

		Queue<Object> msgQueue = ((AbstractProtocolEncoderOutput) output).getMessageQueue();

		Assert.assertNotNull("Message queue from AbstractProtocolEncoderOutput.", msgQueue);
           Assert.assertTrue("Message queue size must be equal 1.", msgQueue.size() == 1);

		Object lastMessage = msgQueue.element();

		if (lastMessage instanceof IoBuffer) {
               NTGCodec decodeCodec = new NTGCodec();
			decodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);
			AbstractProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();

			IoBuffer toDecode = IoBuffer.wrap( new byte[0] );
			toDecode.setAutoExpand(true);
			toDecode.put(((IoBuffer)lastMessage).array());
			//IoBuffer.wrap( Arrays.copyOf(((IoBuffer)lastMessage).array(), ((IoBuffer)lastMessage).limit() ));
			toDecode.compact();
			toDecode.order(ByteOrder.LITTLE_ENDIAN);

			IoSession decodeSession = new DummySession();
			boolean decodableResult = decodeCodec.decodable(decodeSession, toDecode);
			decoderOutput = new MockProtocolDecoderOutput();

			Assert.assertTrue("Test for decoding error.", decodableResult);

			boolean decodeResult = decodeCodec.doDecode(decodeSession, toDecode, decoderOutput);
			Assert.assertTrue("Decoding error.", decodeResult);

               Assert.assertTrue("Message queue size must not less then 1.", decoderOutput.getMessageQueue().size() >= 1);
			Object decodedMessage = decoderOutput.getMessageQueue().element();

			Assert.assertTrue( "Object must be instance of IMessage.", decodedMessage instanceof IMessage);
			Assert.assertTrue( "Object must be instance of MapMessage.", decodedMessage instanceof MapMessage);
               Assert.assertTrue("Messages must be equal. Original message:" + JsonMessageConverter.toJson(message, dictionary) + "; "
                       + "result message:" + JsonMessageConverter.toJson((IMessage)decodedMessage, dictionary),
                       message.compare((MapMessage) decodedMessage));
		}
	}
	catch (Exception e)
	{
	    logger.error(e.getMessage(), e);
		Assert.fail(ErrorUtil.formatException(e));
	}
}
 
Example 18
Source File: MsgUtil.java    From game-server with MIT License 4 votes vote down vote up
public static Message buildMessage(Class<? extends Message> clazz, final byte[] bytes, int off, int len)
		throws Exception {
	IoBuffer ib = IoBuffer.wrap(bytes, off, len);
	return buildMessage(clazz, ib);
}
 
Example 19
Source File: ModbusProtocol.java    From neoscada with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Read the requested number of bytes from the IoBuffer <br/>
 * This actually calls {@link #readBytesArrayWithPrefix(IoBuffer)} and wraps
 * the result in an IoBuffer
 *
 * @param buffer
 *            the buffer to read from
 * @return a new IoBuffer containing the bytes read
 */
private static IoBuffer readBytes ( final IoBuffer buffer )
{
    return IoBuffer.wrap ( readBytesArrayWithPrefix ( buffer ) );
}
 
Example 20
Source File: ImmutableTag.java    From red5-server-common with Apache License 2.0 2 votes vote down vote up
/**
 * Return the body IoBuffer
 * 
 * @return Tag body
 */
public IoBuffer getBody() {
    return IoBuffer.wrap(body);
}