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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#put() . 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: DefaultBinaryContext.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void encodeDoubleCollection ( final IoBuffer buffer, final byte fieldNumber, final Collection<Double> data ) throws Exception
{
    buffer.put ( fieldNumber );
    if ( data != null )
    {
        buffer.put ( TYPE_DOUBLE_LIST );
        buffer.putInt ( data.size () );
        for ( final Double entry : data )
        {
            buffer.putDouble ( entry );
        }
    }
    else
    {
        buffer.put ( TYPE_NULL );
    }
}
 
Example 2
Source File: WebSocketDecoder.java    From red5-websocket with Apache License 2.0 6 votes vote down vote up
/**
 * Build an HTTP 403 "Forbidden" response.
 * 
 * @return response
 * @throws WebSocketException
 */
private HandshakeResponse build403Response(WebSocketConnection conn) throws WebSocketException {
    if (log.isDebugEnabled()) {
        log.debug("build403Response: {}", conn);
    }
    // make up reply data...
    IoBuffer buf = IoBuffer.allocate(32);
    buf.setAutoExpand(true);
    buf.put("HTTP/1.1 403 Forbidden".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 3
Source File: ByteArray.java    From red5-io with Apache License 2.0 6 votes vote down vote up
/**
 * Decompress contents using zlib.
 */
public void uncompress() {
    data.position(0);
    byte[] buffer = new byte[8192];
    IoBuffer tmp = IoBuffer.allocate(0);
    tmp.setAutoExpand(true);
    try (InflaterInputStream inflater = new InflaterInputStream(data.asInputStream())) {
        while (inflater.available() > 0) {
            int decompressed = inflater.read(buffer);
            if (decompressed <= 0) {
                // Finished decompression
                break;
            }
            tmp.put(buffer, 0, decompressed);
        }
    } catch (IOException e) {
        tmp.free();
        throw new RuntimeException("could not uncompress data", e);
    }
    data.free();
    data = tmp;
    data.flip();
    prepareIO();
}
 
Example 4
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 5
Source File: DefaultBinaryContext.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public <E extends Enum<E>> void encodeEnum ( final IoBuffer buffer, final byte fieldNumber, final E value ) throws Exception
{
    buffer.put ( fieldNumber );
    if ( value != null )
    {
        buffer.put ( TYPE_ENUM );
        inlineEncodeEnum ( buffer, value );
    }
    else
    {
        buffer.put ( TYPE_NULL );
    }
}
 
Example 6
Source File: RTMPHandshakeTest.java    From red5-client with Apache License 2.0 5 votes vote down vote up
private void fillBuffer(IoBuffer buf, String byteDumpFile) throws Exception {
    File f = new File(String.format("%s/target/test-classes/%s", System.getProperty("user.dir"), byteDumpFile));
    FileInputStream fis = new FileInputStream(f);
    ByteBuffer bb = ByteBuffer.allocate((int) f.length());
    fis.getChannel().read(bb);
    bb.flip();
    buf.put(bb);
    buf.flip();
    log.debug("Filled buffer: {}", buf);
    fis.close();
}
 
Example 7
Source File: Structures.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected static void inlineEncodeEventInformation ( final BinaryContext context, final IoBuffer data, final org.eclipse.scada.ae.data.EventInformation value ) throws Exception
{
    // number of fields
    data.put ( (byte)4 );

    // encode attributes
    context.encodeString ( data, (byte)1, value.getId () );
    context.encodePrimitiveLong ( data, (byte)2, value.getSourceTimestamp () );
    context.encodePrimitiveLong ( data, (byte)3, value.getEntryTimestamp () );
    context.encodeVariantMap ( data, (byte)4, value.getAttributes () );

}
 
Example 8
Source File: DaveFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Encode the request address in the parameters area
 * 
 * @param data
 * @param request
 */
private void encodeAddress ( final IoBuffer data, final Request request )
{
    data.put ( (byte)0x12 );
    data.put ( (byte)0x0a ); // could be the length of the parameter
    data.put ( (byte)0x10 );

    data.put ( request.getType ().getType () );

    data.putShort ( request.getCount () ); // length in bytes
    data.putShort ( request.getBlock () ); // DB number
    data.put ( request.getArea () );
    data.putMediumInt ( request.getStart () * startFactor ( request ) ); // start address in bits
}
 
Example 9
Source File: MsgUtil.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 去掉消息【id|msgid|data】的id部分并转换为【length|msgid|data】
 *
 * @param bytes
 * @param idlength
 * @return 【length|msgid|data】
 */
   public static IoBuffer toIobufferWithoutID(final byte[] bytes, final int idlength) {
	if (bytes.length < idlength || bytes.length < 1) {
		return null;
	}
	byte[] target = Arrays.copyOfRange(bytes, idlength, bytes.length);
	IoBuffer buf = IoBuffer.allocate(target.length + 4);
	buf.putInt(target.length);
	buf.put(target);
	buf.rewind();
	return buf;
}
 
Example 10
Source File: Structures.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected static void inlineEncodeResponse ( final BinaryContext context, final IoBuffer data, final org.eclipse.scada.core.data.Response value ) throws Exception
{
    // number of fields
    data.put ( (byte)1 );

    // encode attributes
    org.eclipse.scada.core.protocol.ngp.codec.Structures.encodeRequest ( context, data, (byte)1, value.getRequest () );

}
 
Example 11
Source File: DefaultBinaryContext.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void encodePrimitiveInt ( final IoBuffer buffer, final byte fieldNumber, final int data ) throws Exception
{
    buffer.put ( fieldNumber );
    buffer.put ( TYPE_INT );
    buffer.putInt ( data );
}
 
Example 12
Source File: Structures.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected static void inlineEncodeUserInformation ( final BinaryContext context, final IoBuffer data, final org.eclipse.scada.core.data.UserInformation value ) throws Exception
{
    // number of fields
    data.put ( (byte)1 );

    // encode attributes
    context.encodeString ( data, (byte)1, value.getName () );

}
 
Example 13
Source File: Structures.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected static void inlineEncodeCallbackRequest ( final BinaryContext context, final IoBuffer data, final org.eclipse.scada.core.data.CallbackRequest value ) throws Exception
{
    // number of fields
    data.put ( (byte)2 );

    // encode attributes
    context.encodeString ( data, (byte)1, value.getType () );
    context.encodeProperties ( data, (byte)2, value.getAttributes () );

}
 
Example 14
Source File: StringFieldTypeHandler.java    From CXTouch with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void encode(String value, IoBuffer outBuffer) {
    byte[] bytes = value.getBytes(MessageUtil.CHARSET_UTF8);
    outBuffer.put(getType());
    outBuffer.putInt(bytes.length);
    outBuffer.put(bytes);
}
 
Example 15
Source File: MinaDecoder.java    From grain with MIT License 5 votes vote down vote up
private void storeRemainingInSession(IoBuffer buf, IoSession session) {
	IoBuffer remainingBuf = IoBuffer.allocate(buf.capacity());
	remainingBuf.setAutoExpand(true);
	remainingBuf.order(buf.order());
	remainingBuf.put(buf);
	session.setAttribute(BUFFER, remainingBuf);
}
 
Example 16
Source File: MinaProtocolDecoder.java    From jforgame with Apache License 2.0 4 votes vote down vote up
@Override
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	// 必须保证每一个数据包的字节缓存都和session绑定在一起,不然就读取不了上一次剩余的数据了
	CodecContext context = SessionManager.INSTANCE.getSessionAttr(session, MinaSessionProperties.CODEC_CONTEXT,
			CodecContext.class);
	if (context == null) {
		context = new CodecContext();
		session.setAttribute(MinaSessionProperties.CODEC_CONTEXT, context);
	}

	IoBuffer ioBuffer = context.getBuffer();
	ioBuffer.put(in);

	IMessageDecoder msgDecoder = SerializerHelper.getInstance().getDecoder();

	// 在循环里迭代,以处理数据粘包
	for (;;) {
		ioBuffer.flip();
		// 消息元信息常量3表示消息body前面的两个字段,一个short表示module,一个byte表示cmd,
		final int metaSize = 3;
		if (ioBuffer.remaining() < metaSize) {
			ioBuffer.compact();
			return;
		}
		// ----------------消息协议格式-------------------------
		// packetLength | moduleId | cmd  | body
		// int            short      byte byte[]
		int length = ioBuffer.getInt();
		// int packLen = length + metaSize;
		// 大于消息body长度,说明至少有一条完整的message消息
		if (ioBuffer.remaining() >= length) {
			short moduleId = ioBuffer.getShort();
			byte cmd = ioBuffer.get();
			int msgbodyLen = length - metaSize;
			byte[] body = new byte[msgbodyLen];
			ioBuffer.get(body);
			Message msg = msgDecoder.readMessage(moduleId, cmd, body);

			if (moduleId > 0) {
				out.write(msg);
			} else { // 属于组合包
				CombineMessage combineMessage = (CombineMessage) msg;
				List<Packet> packets = combineMessage.getPackets();
				for (Packet packet : packets) {
					// 依次拆包反序列化为具体的Message
					out.write(Packet.asMessage(packet));
				}
			}
			if (ioBuffer.remaining() == 0) {
				ioBuffer.clear();
				break;
			}
			ioBuffer.compact();
		} else {
			// 数据包不完整,继续等待数据到达
			ioBuffer.rewind();
			ioBuffer.compact();
			break;
		}
	}
}
 
Example 17
Source File: Socks5LogicHandler.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Encodes the authentication packet for supported authentication methods.
 * 
 * @param request the socks proxy request data
 * @return the encoded buffer
 * @throws GSSException when something fails while using GSSAPI
 */
private IoBuffer encodeGSSAPIAuthenticationPacket(final SocksProxyRequest request) throws GSSException {
    GSSContext ctx = (GSSContext) getSession().getAttribute(GSS_CONTEXT);
    if (ctx == null) {
        // first step in the authentication process
        GSSManager manager = GSSManager.getInstance();
        GSSName serverName = manager.createName(request.getServiceKerberosName(), null);
        Oid krb5OID = new Oid(SocksProxyConstants.KERBEROS_V5_OID);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Available mechs:");
            for (Oid o : manager.getMechs()) {
                if (o.equals(krb5OID)) {
                    LOGGER.debug("Found Kerberos V OID available");
                }
                LOGGER.debug("{} with oid = {}", manager.getNamesForMech(o), o);
            }
        }

        ctx = manager.createContext(serverName, krb5OID, null, GSSContext.DEFAULT_LIFETIME);

        ctx.requestMutualAuth(true); // Mutual authentication
        ctx.requestConf(false);
        ctx.requestInteg(false);

        getSession().setAttribute(GSS_CONTEXT, ctx);
    }

    byte[] token = (byte[]) getSession().getAttribute(GSS_TOKEN);
    if (token != null) {
        LOGGER.debug("  Received Token[{}] = {}", token.length, ByteUtilities.asHex(token));
    }
    IoBuffer buf = null;

    if (!ctx.isEstablished()) {
        // token is ignored on the first call
        if (token == null) {
            token = new byte[32];
        }

        token = ctx.initSecContext(token, 0, token.length);

        // Send a token to the server if one was generated by
        // initSecContext
        if (token != null) {
            LOGGER.debug("  Sending Token[{}] = {}", token.length, ByteUtilities.asHex(token));

            getSession().setAttribute(GSS_TOKEN, token);
            buf = IoBuffer.allocate(4 + token.length);
            buf.put(new byte[] { SocksProxyConstants.GSSAPI_AUTH_SUBNEGOTIATION_VERSION,
                    SocksProxyConstants.GSSAPI_MSG_TYPE });

            buf.put(ByteUtilities.intToNetworkByteOrder(token.length, 2));
            buf.put(token);
        }
    }

    return buf;
}
 
Example 18
Source File: ClientProtocolEncoder.java    From game-server with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void encode(IoSession session, Object obj, ProtocolEncoderOutput out) throws Exception {
	if (getOverScheduledWriteBytesHandler() != null
			&& session.getScheduledWriteMessages() > getMaxScheduledWriteMessages()
			&& getOverScheduledWriteBytesHandler().test(session)) {
		LOGGER.warn("{}消息{}大于最大累积{}",MsgUtil.getIp(session), session.getScheduledWriteMessages(),getMaxScheduledWriteMessages());
		return;
	}

	IoBuffer buf = null;
	if (obj instanceof Message) {
		buf = MsgUtil.toGameClientIobuffer((Message) obj);
	} else if (obj instanceof byte[]) {
		byte[] data = (byte[]) obj; // 消息ID(4字节)+protobuf
		buf = IoBuffer.allocate(data.length + 6);
		// 消息长度
		byte[] lengthBytes = IntUtil.short2Bytes((short) (data.length + 4), ByteOrder.LITTLE_ENDIAN);
		buf.put(lengthBytes);

		// 消息ID ,将顺序改变为前端客户端顺序
		byte[] idBytes = new byte[4];
		idBytes[0] = data[3];
		idBytes[1] = data[2];
		idBytes[2] = data[1];
		idBytes[3] = data[0];
		buf.put(idBytes);
		// protobuf长度
		int protobufLength = data.length - 4; // 移除消息ID长度
		buf.put(IntUtil.writeIntToBytesLittleEnding(protobufLength));
		// 数据
		buf.put(data, 4, protobufLength);

	}

	if (buf != null && session.isConnected()) {
		buf.rewind();
		out.write(buf);
		out.flush();
	}
}
 
Example 19
Source File: Zlib.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Uncompress the given buffer, returning it in a new buffer.
 * 
 * @param inBuffer the {@link IoBuffer} to be decompressed. The contents
 * of the buffer are transferred into a local byte array and the buffer is
 * flipped and returned intact.
 * @return the decompressed data
 * @throws IOException if the decompression of the data failed for some reason.
 * @throws IllegalArgumentException if the mode is not <code>MODE_DEFLATER</code>
 */
public IoBuffer inflate(IoBuffer inBuffer) throws IOException {
    if (mode == MODE_DEFLATER) {
        throw new IllegalStateException("not initialized as INFLATER");
    }

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

    // We could probably do this better, if we're willing to return multiple buffers
    // (e.g. with a callback function)
    byte[] outBytes = new byte[inBytes.length * 2];
    IoBuffer outBuffer = IoBuffer.allocate(outBytes.length);
    outBuffer.setAutoExpand(true);

    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 = 0;

        do {
            retval = zStream.inflate(JZlib.Z_SYNC_FLUSH);
            switch (retval) {
            case JZlib.Z_OK:
                // completed decompression, lets copy data and get out
            case JZlib.Z_BUF_ERROR:
                // need more space for output. store current output and get more
                outBuffer.put(outBytes, 0, zStream.next_out_index);
                zStream.next_out_index = 0;
                zStream.avail_out = outBytes.length;
                break;
            default:
                // unknown error
                outBuffer = null;
                if (zStream.msg == null) {
                    throw new IOException("Unknown error. Error code : " + retval);
                } else {
                    throw new IOException("Unknown error. Error code : " + retval + " and message : " + zStream.msg);
                }
            }
        } while (zStream.avail_in > 0);
    }

    return outBuffer.flip();
}
 
Example 20
Source File: RTMPProtocolEncoder.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/**
 * Encode packet.
 *
 * @param packet
 *            RTMP packet
 * @return Encoded data
 */
public IoBuffer encodePacket(Packet packet) {
    IoBuffer out = null;
    Header header = packet.getHeader();
    int channelId = header.getChannelId();
    //log.trace("Channel id: {}", channelId);
    IRTMPEvent message = packet.getMessage();
    if (message instanceof ChunkSize) {
        ChunkSize chunkSizeMsg = (ChunkSize) message;
        ((RTMPConnection) Red5.getConnectionLocal()).getState().setWriteChunkSize(chunkSizeMsg.getSize());
    }
    // normally the message is expected not to be dropped
    if (!dropMessage(channelId, message)) {
        //log.trace("Header time: {} message timestamp: {}", header.getTimer(), message.getTimestamp());
        IoBuffer data = encodeMessage(header, message);
        if (data != null) {
            RTMP rtmp = ((RTMPConnection) Red5.getConnectionLocal()).getState();
            // set last write packet
            rtmp.setLastWritePacket(channelId, packet);
            // ensure we're at the beginning
            if (data.position() != 0) {
                data.flip();
            } else {
                data.rewind();
            }
            // length of the data to be chunked
            int dataLen = data.limit();
            header.setSize(dataLen);
            //if (log.isTraceEnabled()) {
            //log.trace("Message: {}", data);
            //}
            // chunk size for writing
            int chunkSize = rtmp.getWriteChunkSize();
            // number of chunks to write
            int numChunks = (int) Math.ceil(dataLen / (float) chunkSize);
            // get last header
            Header lastHeader = rtmp.getLastWriteHeader(channelId);
            if (log.isTraceEnabled()) {
                log.trace("Channel id: {} chunkSize: {}", channelId, chunkSize);
            }
            // attempt to properly guess the size of the buffer we'll need
            int bufSize = dataLen + 18 + (numChunks * 2);
            //log.trace("Allocated buffer size: {}", bufSize);
            out = IoBuffer.allocate(bufSize, false);
            out.setAutoExpand(true);
            do {
                // encode the header
                encodeHeader(header, lastHeader, out);
                // write a chunk
                byte[] buf = new byte[Math.min(chunkSize, data.remaining())];
                data.get(buf);
                //log.trace("Buffer: {}", Hex.encodeHexString(buf));
                out.put(buf);
                // move header over to last header
                lastHeader = header.clone();
            } while (data.hasRemaining());
            // collapse the time stamps on the last header after decode is complete
            lastHeader.setTimerBase(lastHeader.getTimer());
            // clear the delta
            lastHeader.setTimerDelta(0);
            // set last write header
            rtmp.setLastWriteHeader(channelId, lastHeader);
            data.free();
            out.flip();
            data = null;
        }
    }
    message.release();
    return out;
}