org.apache.mina.filter.codec.ProtocolEncoderOutput Java Examples

The following examples show how to use org.apache.mina.filter.codec.ProtocolEncoderOutput. 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: TestFastCodec.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeDecodeMessage() throws Exception
{
	FASTCodec codec = getCodec(DICTIONARY_URI, TEMPLATE_TITLE);
	ProtocolEncoderOutput output = new MockProtocolEncoderOutput();

	IMessage message = new MapMessage("OEquity", "Logon");

       message.addField("Password", "tnp123");
       message.addField("Username", "MADTY0" );
       message.addField("SendingTime", "20120101-01:01:01.333");
       message.addField("ApplID", "0");
       message.addField("MessageType", "0");

	session.write(message);
	codec.encode(session, message, output);
	Queue<Object> msgQueue = ((AbstractProtocolEncoderOutput)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);
	System.out.println(HexDumper.getHexdump(bytes));
}
 
Example #2
Source File: InternalJsonCodec.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    if (message instanceof IMessage) {
        Map<String, Object> map = MessageUtil.convertToHashMap((IMessage)message);
        String json = objectMapper.writeValueAsString(map);

        long seq = sequence.getAndIncrement();

        IoBuffer buffer = IoBuffer.allocate(json.length() + HEADER_SIZE);
        buffer.putLong(json.length());
        buffer.putLong(seq);
        buffer.put(json.getBytes());

        out.write(buffer.flip());

        ((IMessage) message).getMetaData().setRawMessage(buffer.array());

        if (logger.isDebugEnabled()) {
            logger.debug("encode() sequnce {} as hex [{}]", seq, buffer.getHexDump());
        }
    } else {
        out.write(message);
    }
}
 
Example #3
Source File: MyTextLineCodecEncoder.java    From java-study with Apache License 2.0 6 votes vote down vote up
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    logger.info("开始进入编码方法-----------------------------------------------------------------");
    // 如果文本换行符未指定,使用默认值
    if (delimiter == null || "".equals(delimiter)) {
        delimiter = "\r\n";
    }

    if (charset == null) {
        charset = Charset.forName("utf-8");
    }

    String value = message.toString();        
    IoBuffer buf = IoBuffer.allocate(value.length()).setAutoExpand(true);       
    //真实数据
    buf.putString(value, charset.newEncoder()); 
    //文本换行符
    buf.putString(delimiter, charset.newEncoder());
    buf.flip();
    out.write(buf);
}
 
Example #4
Source File: RTMPMinaProtocolEncoder.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
public static int chunkAndWrite(ProtocolEncoderOutput out, IoBuffer message, int chunkSize, int desiredSize) {
    int sentChunks = 0;
    int targetSize = desiredSize > chunkSize ? desiredSize : chunkSize;
    int limit = message.limit();
    do {
        int length = 0;
        int pos = message.position();
        while (length < targetSize && pos < limit) {
            byte basicHeader = message.get(pos);
            length += getDataSize(basicHeader) + chunkSize;
            pos += length;
        }
        int remaining = message.remaining();
        log.trace("Length: {} remaining: {} pos+len: {} limit: {}", new Object[] { length, remaining, (message.position() + length), limit });
        if (length > remaining) {
            length = remaining;
        }
        // send it
        out.write(message.getSlice(length));
        sentChunks++;
    } while (message.hasRemaining());
    return sentChunks;
}
 
Example #5
Source File: ProtobufEncoder.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Check the id value and set it into context attachment.
 */
@Override
public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) 
		throws Exception {
	
	/**
	 * If the message is already in IoBuffer format, 
	 * directly output it to client.
	 * 
	 * TODO Maybe used to optimize SessionMessage.
	 */
	if (msg instanceof IoBuffer) {
		out.write(msg);
	} else if ( msg instanceof XinqiMessage ) {
		XinqiMessage message = (XinqiMessage)msg;
		if (message != null) {
			IoBuffer body = encodeXinqiMessage(message);
			out.write(body);
		}
	}
}
 
Example #6
Source File: FASTCodec.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(
		IoSession session,
		Object message,
		ProtocolEncoderOutput out) throws Exception {

	IMessageToFastConverter converter = getIMessageToFastConverter();
	IMessage iMsg = (IMessage) message;

       Message fastMsg = converter.convert(iMsg);
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	Context oc = getOutputContext(session);
	MessageOutputStream msgOutStream = new MessageOutputStream(os, oc);
	msgOutStream.writeMessage(fastMsg);
	byte[] outputdata = os.toByteArray();
	byte[] blockHeader = TypeCodec.UINT.encode(new IntegerValue(outputdata.length));

	byte[] result = Arrays.copyOf(blockHeader, blockHeader.length + outputdata.length);
	System.arraycopy(outputdata, 0, result, blockHeader.length, outputdata.length);

	out.write(IoBuffer.wrap(result));
	if (settings.isResetContextAfterEachUdpPacket()) {
		oc.reset();
	}
}
 
Example #7
Source File: DataCodecEncoder.java    From oim-fx with MIT License 6 votes vote down vote up
@Override
public void encode(IoSession session, Object object, ProtocolEncoderOutput out) throws Exception {
	try {
		if (null != object) {
			String xml = object.toString();
			byte[] xmlByte = xml.getBytes(charset);
			IoBuffer io = IoBuffer.allocate(xmlByte.length + 4).setAutoExpand(true);
			io.putInt(xmlByte.length);
			io.put(xmlByte);
			io.flip();
			out.write(io);
		}
	} catch (Exception e) {
		logger.error("",e);
		e.printStackTrace();
	}
}
 
Example #8
Source File: WebSocketEncoder.java    From red5-websocket with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    WebSocketConnection conn = (WebSocketConnection) session.getAttribute(Constants.CONNECTION);
    IoBuffer resultBuffer;
    if (message instanceof Packet) {
        Packet packet = (Packet) message;
        // if the connection is not native / direct, add websocket encoding
        resultBuffer = conn.isWebConnection() ? encodeOutgoingData(packet) : packet.getData();
    } else if (message instanceof HandshakeResponse) {
        HandshakeResponse resp = (HandshakeResponse) message;
        resultBuffer = resp.getResponse();
    } else if (message instanceof HandshakeRequest) {
        HandshakeRequest req = (HandshakeRequest) message;
        resultBuffer = req.getRequest();
    } else {
        throw new Exception("message not a websocket type");
    }
    out.write(resultBuffer);
}
 
Example #9
Source File: FIXCodec.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    if (message instanceof IMessage) {
        IMessage originIMessage = (IMessage)message;

        MsgMetaData metaData = originIMessage.getMetaData();
        IMessage encoded = originIMessage.cloneMessage();
        String messageName = getMessageName(encoded);
        RawMessage rawMessage = qfjConverter.convertDirty(encoded, messageName);

        metaData.setRawMessage(rawMessage.getBytes());

        IoBuffer buffer = IoBuffer.wrap(metaData.getRawMessage());
        out.write(buffer);
    } else {
        out.write(message);
    }
}
 
Example #10
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 #11
Source File: MassProtocolEncoder.java    From game-server with MIT License 6 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)) {
        return;
    }
    IoBuffer buf = null;
    if (obj instanceof MassMessage) {
        buf = MsgUtil.toIobuffer((MassMessage) obj);
    } else {
        log.warn("未知的数据类型");
        return;
    }
    if (buf != null && session.isConnected()) {
        buf.rewind();
        out.write(buf);
        out.flush();
    }
}
 
Example #12
Source File: HttpServerEncoderImpl.java    From game-server with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
	LOG.debug("encode {}", message.getClass().getCanonicalName());
	if ((message instanceof HttpResponseImpl)) {
		HttpResponseImpl msg = (HttpResponseImpl) message;
		IoBuffer buf = IoBuffer.allocate(128).setAutoExpand(true);
		buf.putString(msg.getStatus().line(), ENCODER);
		for (Map.Entry<String, String> header : msg.getHeaders().entrySet()) {
			buf.putString((CharSequence) header.getKey(), ENCODER);
			buf.putString(": ", ENCODER);
			buf.putString((CharSequence) header.getValue(), ENCODER);
			buf.put(CRLF);
		}
		if (msg.getBody() != null) {
			buf.putString(CONTENTLENGTH, ENCODER);
			buf.putString(String.valueOf(msg.getBody().length), ENCODER);
			buf.put(CRLF);
		}
		buf.put(CRLF);
		if (msg.getBody() != null) {
			buf.put(msg.getBody());
		}
		buf.flip();
		out.write(buf);
	}
}
 
Example #13
Source File: ArduinoCodec.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void encode ( final IoSession session, final Object message, final ProtocolEncoderOutput output ) throws Exception
{
    final IoBuffer data = IoBuffer.allocate ( 0 );
    data.order ( ByteOrder.LITTLE_ENDIAN );
    data.setAutoExpand ( true );

    if ( message instanceof WriteRequestMessage )
    {
        encodeHeader ( data, (CommonMessage)message );
        encodeWriteRequest ( data, (WriteRequestMessage)message );
    }
    else if ( message instanceof CommonMessage )
    {
        encodeHeader ( data, (CommonMessage)message );
    }
    data.flip ();
    output.write ( data );
}
 
Example #14
Source File: FrameEncoder.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void encode ( final IoSession session, final Object message, final ProtocolEncoderOutput output ) throws Exception
{
    if ( ! ( message instanceof Frame ) )
    {
        throw new IllegalStateException ( String.format ( "Can only encode messages of type Frame but got %s", message.getClass () ) );
    }

    final Frame frame = (Frame)message;

    if ( logger.isTraceEnabled () )
    {
        logger.trace ( "Encode frame - type: {}, data: {}", frame.getType (), frame.getData () );
    }

    final IoBuffer buffer = IoBuffer.allocate ( 1 + 1 + 4 + frame.getData ().remaining () );
    buffer.put ( (byte)0x01 ); // version - #0
    buffer.put ( (byte)frame.getType ().ordinal () ); // frame type - #1
    buffer.putInt ( frame.getData ().remaining () ); // data size - #2
    buffer.put ( frame.getData () ); // data - #6
    buffer.flip ();

    output.write ( buffer );
}
 
Example #15
Source File: ObjectSerializationEncoder.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    if (!(message instanceof Serializable)) {
        throw new NotSerializableException();
    }

    IoBuffer buf = IoBuffer.allocate(64);
    buf.setAutoExpand(true);
    buf.putObject(message);

    int objectSize = buf.position() - 4;
    if (objectSize > maxObjectSize) {
        throw new IllegalArgumentException("The encoded object is too big: " + objectSize + " (> " + maxObjectSize
                + ')');
    }

    buf.flip();
    out.write(buf);
}
 
Example #16
Source File: SumkProtocolEncoder.java    From sumk with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
	if (message == null) {
		return;
	}
	if (String.class.isInstance(message)) {
		encodeString(0, session, (String) message, out);
		return;
	}
	Class<?> clz = message.getClass();
	for (SumkMinaEncoder encoder : this.encoders) {
		if (encoder.accept(clz)) {
			encoder.encode(session, message, out);
			return;
		}
	}
	throw new ProtocolEncoderException(message.getClass().getName() + " not support in ProtocolEncoder");
}
 
Example #17
Source File: TextLineEncoder.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    CharsetEncoder encoder = (CharsetEncoder) session.getAttribute(ENCODER);

    if (encoder == null) {
        encoder = charset.newEncoder();
        session.setAttribute(ENCODER, encoder);
    }

    String value = (message == null ? "" : message.toString());
    IoBuffer buf = IoBuffer.allocate(value.length()).setAutoExpand(true);
    buf.putString(value, encoder);

    if (buf.position() > maxLineLength) {
        throw new IllegalArgumentException("Line length: " + buf.position());
    }

    buf.putString(delimiter.getValue(), encoder);
    buf.flip();
    out.write(buf);
}
 
Example #18
Source File: MinaEncoder.java    From grain with MIT License 6 votes vote down vote up
@Override
public void encode(IoSession session, Object obj, ProtocolEncoderOutput out) throws Exception {
	TcpPacket packet = (TcpPacket) obj;
	byte[] byteData = packet.getByteData();
	int len = 18 + byteData.length;
	IoBuffer buf = IoBuffer.allocate(len);
	buf.put(HEAD);
	buf.putInt(len);
	buf.putInt(packet.gettOpCode());
	buf.putInt(packet.lockedId);
	buf.putInt(packet.unlockedId);
	buf.put(byteData);
	buf.flip();
	out.write(buf);

}
 
Example #19
Source File: TftpProtocolCodecFactory.java    From tftp4j with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws IOException {
    TftpPacket packet = (TftpPacket) message;
    IoBuffer buf = IoBuffer.allocate(packet.getWireLength());
    packet.toWire(buf.buf());
    buf.flip();
    out.write(buf);
}
 
Example #20
Source File: DhcpEncoder.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out)
        throws IOException {
    IoBuffer buf = IoBuffer.allocate(1024);
    encoder.encode(buf.buf(), (DhcpMessage) message);
    buf.flip();
    out.write(buf);
}
 
Example #21
Source File: SessionMessageRawEncoder.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Check the id value and set it into context attachment.
 */
@Override
public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) 
		throws Exception {
	
	SessionRawMessage sessionMessage = null;
	if ( msg instanceof SessionRawMessage ) {
		sessionMessage = (SessionRawMessage)msg;
	}
	
	byte[] rawMessage = sessionMessage.getRawMessage();
	if (rawMessage != null) {
		byte[] sessionKeyBytes = sessionMessage.getSessionkey().getRawKey();
		IoBuffer body = IoBuffer.allocate(SESSION_HEADER_LENGTH + sessionKeyBytes.length + RAW_HEADER_LENGTH + rawMessage.length);
		/*
		 * +---------------+               +-------------------+-----------------+--------------------------+--------------------+
		 * | Message Data  |-------------->| sessionkey length |    sessionkey   |        Raw Length        |     Any Raw Data   |
		 * |  (300 bytes)  |               |       0xFFFF      |      (bytes)    |        0xFFFFFFFF        |     (300 bytes)    |
		 * +---------------+               +-------------------+-----------------+--------------------------+--------------------+
		 */
		body.putShort((short)sessionKeyBytes.length);
		body.put(sessionKeyBytes);
		body.putInt(rawMessage.length);
		body.put(rawMessage);
		body.flip();
		out.write(body);
	
	} else {
		if ( log.isDebugEnabled() ) {
			log.debug("Raw message's content is empty.");
		}
	}
}
 
Example #22
Source File: StructEncoder.java    From javastruct with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void encode(IoSession session, Object obj, ProtocolEncoderOutput out) 
throws Exception {
	StructMessage m = (StructMessage)obj;
	byte[] buffer = JavaStruct.pack(m);
    ByteBuffer b = ByteBuffer.allocate(buffer.length + 8, false);
    b.putInt(buffer.length + 4);
    b.putInt(m.getID());
    b.put(buffer);
    b.flip();
    out.write(b);
}
 
Example #23
Source File: MinaCodecAdapter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) throws Exception {
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024);
    MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler);
    try {
    	codec.encode(channel, buffer, msg);
    } finally {
        MinaChannel.removeChannelIfDisconnectd(session);
    }
    out.write(ByteBuffer.wrap(buffer.toByteBuffer()));
    out.flush();
}
 
Example #24
Source File: RTMPMinaCodecFactory.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws ProtocolCodecException {
    // get the connection from the session
    String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
    log.trace("Session id: {}", sessionId);
    RTMPConnection conn = (RTMPConnection) RTMPConnManager.getInstance().getConnectionBySessionId(sessionId);
    if (conn != null) {
        Red5.setConnectionLocal(conn);
        final Semaphore lock = conn.getEncoderLock();
        try {
            // acquire the encoder lock
            lock.acquire();
            // get the buffer
            final IoBuffer buf = message instanceof IoBuffer ? (IoBuffer) message : getEncoder().encode(message);
            if (buf != null) {
                if (log.isTraceEnabled()) {
                    log.trace("Writing output data: {}", Hex.encodeHexString(buf.array()));
                }
                out.write(buf);
            } else {
                log.trace("Response buffer was null after encoding");
            }
        } catch (Exception ex) {
            log.error("Exception during encode", ex);
        } finally {
            lock.release();
            Red5.setConnectionLocal(null);
        }
    } else {
        log.debug("Connection is no longer available for encoding, may have been closed already");
    }
}
 
Example #25
Source File: SumkProtocolEncoder.java    From sumk with Apache License 2.0 5 votes vote down vote up
public static void encodeString(int code, IoSession session, CharSequence message, ProtocolEncoderOutput out)
		throws CharacterCodingException, ProtocolEncoderException {
	code = code | Protocols.FORMAT_JSON;
	int size = message.length();
	int prefixLength = size <= (Protocols.MAX_ONE / CHAR_BYTE) ? 1
			: size <= (Protocols.MAX_TWO / CHAR_BYTE) ? 2 : 4;

	IoBuffer buffer = IoBuffer.allocate((int) (size * 1.5) + 10).setAutoExpand(true);
	putProtocol(code, buffer, prefixLength);

	buffer.putPrefixedString(message, prefixLength, Profile.UTF8.newEncoder());
	buffer.flip();

	out.write(buffer);
}
 
Example #26
Source File: AppMessageEncoder.java    From cim with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession iosession, Object object, ProtocolEncoderOutput out) {

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

		IoBuffer buff = IoBuffer.allocate(data.length + CIMConstant.DATA_HEADER_LENGTH).setAutoExpand(true);
		buff.put(createHeader(message.getType(), data.length));
		buff.put(data);

		buff.flip();
		out.write(buff);
}
 
Example #27
Source File: MinaCodecAdapter.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) throws Exception {
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024);
    MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler);
    try {
        codec.encode(channel, buffer, msg);
    } finally {
        MinaChannel.removeChannelIfDisconnected(session);
    }
    out.write(ByteBuffer.wrap(buffer.toByteBuffer()));
    out.flush();
}
 
Example #28
Source File: CommandEncoder.java    From mina with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    BaseCommand command = (BaseCommand) message;
    byte[] bytes = command.toBytes();
    IoBuffer buf = IoBuffer.allocate(bytes.length, false);

    buf.setAutoExpand(true);
    buf.putShort( (short) bytes.length );
    buf.put(bytes);

    buf.flip();
    out.write(buf);
}
 
Example #29
Source File: CommandEncoder.java    From mina with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    BaseCommand command = (BaseCommand) message;
    byte[] bytes = command.toBytes();
    IoBuffer buf = IoBuffer.allocate(bytes.length, false);

    buf.setAutoExpand(true);
    buf.putShort( (short) bytes.length );
    buf.put(bytes);

    buf.flip();
    out.write(buf);
}
 
Example #30
Source File: GameMsgEncoder.java    From GameServer with Apache License 2.0 5 votes vote down vote up
public void encode(IoSession session, Object message,
		ProtocolEncoderOutput out) throws Exception {
		ResponseMsg value = (ResponseMsg) message;
		
	out.write(value.entireMsg());
	value.release();
}