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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#allocate() . 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: IoBufferDecoder.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Dynamically sets a new delimiter. Next time 
 * {@link IoBufferDecoder#decodeOnce(IoSession, int) } will be called it will use the new 
 * delimiter. Delimiter matching is reset only if <tt>resetMatchCount</tt> is true but 
 * decoding will continue from current position.
 * 
 * NB : Delimiter {@link LineDelimiter#AUTO} is not allowed.
 * 
 * @param delim the new delimiter as a byte array
 * @param resetMatchCount delimiter matching is reset if true
 */
public void setDelimiter(byte[] delim, boolean resetMatchCount) {
    if (delim == null) {
        throw new IllegalArgumentException("Null delimiter not allowed");
    }

    // Convert delimiter to IoBuffer.
    IoBuffer delimiter = IoBuffer.allocate(delim.length);
    delimiter.put(delim);
    delimiter.flip();

    ctx.setDelimiter(delimiter);
    ctx.setContentLength(-1);
    if (resetMatchCount) {
        ctx.setMatchCount(0);
    }
}
 
Example 2
Source File: MessageChannelCodecFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private IoBuffer encodeProperties ( final IoSession session, final Map<String, String> properties ) throws CharacterCodingException
{
    final IoBuffer data = IoBuffer.allocate ( 0 );
    data.setAutoExpand ( true );

    data.putInt ( properties.size () );

    final CharsetEncoder encoder = getCharsetEncoder ( session );

    for ( final Map.Entry<String, String> entry : properties.entrySet () )
    {
        final String key = entry.getKey ();
        final String value = entry.getValue ();

        data.putString ( key, encoder );
        data.put ( (byte)0x00 );
        data.putString ( value, encoder );
        data.put ( (byte)0x00 );
    }

    data.flip ();

    return data;
}
 
Example 3
Source File: MyDataEncoder.java    From QuickerAndroid with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void encode(IoSession session, Object message,
                   ProtocolEncoderOutput out) throws Exception {
    if (message instanceof MessageBase) {
        Gson gson = new Gson();
        String msgJson = gson.toJson(message);
        byte[] msgBytes = msgJson.getBytes("utf-8");

        IoBuffer buffer = IoBuffer.allocate(msgBytes.length + 16);
        buffer.putInt(0xFFFFFFFF);
        buffer.putInt(((MessageBase) message).getMessageType());
        buffer.putInt(msgBytes.length);
        buffer.put(msgBytes);
        buffer.putInt(0);
        buffer.flip();

        out.write(buffer);
    }

}
 
Example 4
Source File: WebSocketDecoder.java    From red5-websocket with Apache License 2.0 6 votes vote down vote up
/**
 * Build an HTTP 400 "Bad Request" response.
 * 
 * @return response
 * @throws WebSocketException
 */
private HandshakeResponse build400Response(WebSocketConnection conn) throws WebSocketException {
    if (log.isDebugEnabled()) {
        log.debug("build400Response: {}", conn);
    }
    // make up reply data...
    IoBuffer buf = IoBuffer.allocate(32);
    buf.setAutoExpand(true);
    buf.put("HTTP/1.1 400 Bad Request".getBytes());
    buf.put(Constants.CRLF);
    buf.put("Sec-WebSocket-Version-Server: 13".getBytes());
    buf.put(Constants.CRLF);
    buf.put(Constants.CRLF);
    if (log.isTraceEnabled()) {
        log.trace("Handshake error response size: {}", buf.limit());
    }
    return new HandshakeResponse(buf);
}
 
Example 5
Source File: RTMPHandshakeTest.java    From red5-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidate() {
    log.info("\ntestValidate");
    // client side handshake handler
    OutboundHandshake out = new OutboundHandshake();
    // set the handshake type
    out.setHandshakeType(RTMPConnection.RTMP_NON_ENCRYPTED);
    // try SO12
    IoBuffer S0S1S2 = IoBuffer.allocate(3073);
    S0S1S2.put(serverS0S1S2part1);
    S0S1S2.put(serverS0S1S2part2);
    S0S1S2.flip();
    // strip the 03 type byte
    S0S1S2.get();
    log.debug("Validate server: {}", S0S1S2);
    boolean server = out.validate(S0S1S2.array());
    log.debug("Handshake is valid: {}", server);
    // XXX S0S1S2 data needs to be regenerated, what we have is corrupt
    //Assert.assertTrue(server);
}
 
Example 6
Source File: AbstractAccessorAttribute.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void handleWrite ( final Variant value )
{
    final MemoryRequestBlock block = this.block;

    if ( block == null )
    {
        throw new IllegalStateException ( "Device is not connected" );
    }

    final T cvtValue = getValue ( value );
    if ( cvtValue != null )
    {
        final IoBuffer data = IoBuffer.allocate ( this.accessor.getBufferSize ( cvtValue ) );
        if ( this.order != null )
        {
            this.order.put ( data, this.accessor, cvtValue );
        }
        else
        {
            this.accessor.put ( data, cvtValue );
        }
        block.writeData ( toAddress ( this.index ), data.array () );
    }
}
 
Example 7
Source File: ModbusRtuDecoder.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public synchronized void decode ( final IoSession session, final IoBuffer in, final ProtocolDecoderOutput out ) throws Exception
{
    IoBuffer currentFrame = (IoBuffer)session.getAttribute ( SESSION_KEY_CURRENT_FRAME );
    if ( currentFrame == null )
    {
        currentFrame = IoBuffer.allocate ( Constants.MAX_PDU_SIZE + Constants.RTU_HEADER_SIZE );
        session.setAttribute ( SESSION_KEY_CURRENT_FRAME, currentFrame );
    }
    logger.trace ( "decode () current frame = {} data = {}", currentFrame.toString (), currentFrame.getHexDump () );
    logger.trace ( "decode () new     frame = {} data = {}", in.toString (), in.getHexDump () );

    final int expectedSize = currentFrame.position () + in.remaining ();
    if ( expectedSize > MAX_SIZE + 1 )
    {
        throw new ModbusProtocolError ( String.format ( "received size (%s) exceeds max size (%s)", expectedSize, MAX_SIZE ) );
    }
    currentFrame.put ( in );

    tick ( session, out );
}
 
Example 8
Source File: ModbusProtocol.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Encode the data from Java byte order to requested modbus byte order
 *
 * @param data
 *            the data to encode
 * @param dataOrder
 *            the target modbus byte order
 * @return the converted data, or the input data if no conversion was
 *         necessary
 */
public static IoBuffer convertData ( final IoBuffer data, final ByteOrder dataOrder )
{
    if ( dataOrder == ByteOrder.BIG_ENDIAN )
    {
        return data;
    }

    final IoBuffer result = IoBuffer.allocate ( data.capacity () );
    result.order ( dataOrder );

    for ( int i = 0; i < data.remaining () / 2; i++ )
    {
        // convert to LITTLE_ENDIAN
        result.putUnsignedShort ( data.getUnsignedShort ( i * 2 ) );
    }

    // the byte order we use is BIG_ENDIAN
    result.order ( ByteOrder.BIG_ENDIAN );

    return result;
}
 
Example 9
Source File: StopBrowse.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IoBuffer encodeMessage ( final BinaryContext context, final Object objectMessage ) throws Exception
{
    final IoBuffer data = IoBuffer.allocate ( 5 );
    data.putInt ( MESSAGE_CODE );
    data.put ( (byte)0 ); // number of fields 

    data.flip ();
    return data;
}
 
Example 10
Source File: WSMessage.java    From red5-websocket with Apache License 2.0 5 votes vote down vote up
/**
 * Adds additional payload data.
 * 
 * @param additionalPayload
 */
public void addPayload(IoBuffer additionalPayload) {
    if (payload == null) {
        payload = IoBuffer.allocate(additionalPayload.remaining());
        payload.setAutoExpand(true);
    }
    this.payload.put(additionalPayload);
}
 
Example 11
Source File: RTMPHandshake.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
public RTMPHandshake(byte handshakeType) {
    // set the handshake type
    setHandshakeType(handshakeType);
    // whether or not to use later handshake version
    fp9Handshake = "true".equals(System.getProperty("use.fp9.handshake", "true"));
    log.trace("Use fp9 handshake? {}", fp9Handshake);
    // create our handshake bytes
    createHandshakeBytes();
    // instance a buffer to handle fragmenting
    buffer = IoBuffer.allocate(Constants.HANDSHAKE_SIZE);
    buffer.setAutoExpand(true);
}
 
Example 12
Source File: StatusObjectService.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Cache status objects
 */
public void cacheStatusObjects() {

    cachedStatusObjects = new HashMap<String, byte[]>();

    String statusCode;
    IoBuffer out = IoBuffer.allocate(256);
    out.setAutoExpand(true);

    for (String s : statusObjects.keySet()) {
        statusCode = s;
        StatusObject statusObject = statusObjects.get(statusCode);
        if (statusObject instanceof RuntimeStatusObject) {
            continue;
        }
        serializeStatusObject(out, statusObject);
        out.flip();
        if (log.isTraceEnabled()) {
            log.trace(HexDump.formatHexDump(out.getHexDump()));
        }
        byte[] cachedBytes = new byte[out.limit()];
        out.get(cachedBytes);
        out.clear();
        cachedStatusObjects.put(statusCode, cachedBytes);
    }
    out.free();
    out = null;
}
 
Example 13
Source File: MsgUtil.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 转换为未携带消息长度的iobuff
 *
 * @param message
 * @return 【msgid|data】
 */
   public static IoBuffer toIobufferWithoutLength(final Message message) {
	int msgID = getMessageID(message);
	byte[] msgData = message.toByteArray();
	if (msgData.length < 1) {
		return null;
	}
	IoBuffer buf = IoBuffer.allocate(4 + msgData.length);
	buf.putInt(msgID);
	buf.put(msgData);
	buf.rewind();
	return buf;
}
 
Example 14
Source File: MessageSerializationTest.java    From red5-io with Apache License 2.0 5 votes vote down vote up
private <T> T serializeAndDeserialize(T obj, Class<T> type) {
    IoBuffer data = IoBuffer.allocate(0);
    data.setAutoExpand(true);

    Output output = new Output(data);
    output.enforceAMF3();
    Serializer.serialize(output, obj);

    Input input = new Input(data.flip());
    input.enforceAMF3();
    Object result = Deserializer.deserialize(input, type);

    return type.cast(result);
}
 
Example 15
Source File: WebMessageEncoder.java    From cim with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession iosession, Object object, ProtocolEncoderOutput out) throws Exception {


	Transportable message = (Transportable) object;
	byte[] data = message.getBody();

	/*
	 * websocket的握手响应
	 */
	if (message instanceof HandshakerResponse) {
		IoBuffer buff = IoBuffer.allocate(data.length).setAutoExpand(true);
		buff.put(data);
		buff.flip();
		out.write(buff);

		return;
	}

	byte[] protobuf = new byte[data.length + 1];
	protobuf[0] = message.getType();
	System.arraycopy(data,0, protobuf, 1, data.length);

	byte[] binaryFrame = encodeDataFrame(protobuf);
	IoBuffer buffer = IoBuffer.allocate(binaryFrame.length);
	buffer.put(binaryFrame);
	buffer.flip();
	out.write(buffer);


}
 
Example 16
Source File: AACAudio.java    From red5-io with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public IoBuffer getDecoderConfiguration() {
    if (blockDataAACDCR == null) {
        return null;
    }
    IoBuffer result = IoBuffer.allocate(4);
    result.setAutoExpand(true);
    result.put(blockDataAACDCR);
    result.rewind();
    return result;
}
 
Example 17
Source File: ModbusTcpEncoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void encode ( final IoSession session, final Object message, final ProtocolEncoderOutput out ) throws Exception
{
    logger.debug ( "Encoding: {}", message );
    final Pdu request = (Pdu)message;

    final IoBuffer buffer = IoBuffer.allocate ( request.getData ().remaining () + 7 );
    buffer.setAutoExpand ( true );

    final IoBuffer pdu = request.getData ();

    // put transaction identifier
    buffer.putUnsignedShort ( request.getTransactionId () );
    // put modbus protocol identifier (always 0)
    buffer.putUnsignedShort ( 0 );
    // put length, including slave id
    buffer.putUnsignedShort ( request.getData ().remaining () + 1 );
    // put slave id
    buffer.put ( request.getUnitIdentifier () );
    // put data
    buffer.put ( pdu );

    buffer.flip ();

    logger.trace ( "Encoded to: {}", buffer );

    out.write ( buffer );
}
 
Example 18
Source File: NIOConnection.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException {
    if (isClosed()) {
        backupDeliverer.deliver(packet);
    }
    else {
        boolean errorDelivering = false;
        IoBuffer buffer = IoBuffer.allocate(4096);
        buffer.setAutoExpand(true);
        try {
            buffer.putString(packet.getElement().asXML(), encoder.get());
            if (flashClient) {
                buffer.put((byte) '\0');
            }
            buffer.flip();
            
            ioSessionLock.lock();
            try {
                ioSession.write(buffer);
            } finally {
                ioSessionLock.unlock();
            }
        }
        catch (Exception e) {
            Log.debug("Error delivering packet:\n" + packet, e);
            errorDelivering = true;
        }
        if (errorDelivering) {
            close();
            // Retry sending the packet again. Most probably if the packet is a
            // Message it will be stored offline
            backupDeliverer.deliver(packet);
        }
        else {
            session.incrementServerPacketCount();
        }
    }
}
 
Example 19
Source File: SlaveHost.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected Object makeReadReply ( final BaseMessage baseMessage, final int[] data, final ByteOrder order )
{
    final IoBuffer reply = IoBuffer.allocate ( data.length * 2 );

    reply.order ( order );

    for ( int i = 0; i < data.length; i++ )
    {
        reply.putUnsignedShort ( data[i] );
    }
    reply.flip ();
    return new ReadResponse ( baseMessage.getTransactionId (), baseMessage.getUnitIdentifier (), baseMessage.getFunctionCode (), reply );
}
 
Example 20
Source File: BaseRTMPTConnection.java    From red5-client with Apache License 2.0 4 votes vote down vote up
public BaseRTMPTConnection(String type) {
    super(type);
    this.buffer = IoBuffer.allocate(2048);
    this.buffer.setAutoExpand(true);
}