/** * {@inheritDoc} */ @Override public void encode( IoSession session, Object message, ProtocolEncoderOutput out ) throws Exception { ByteBuffer buffer = encoder.encodeMessage( ( Message ) message ); IoBuffer ioBuffer = IoBuffer.wrap( buffer ); if ( IS_DEBUG ) { byte[] dumpBuffer = new byte[buffer.limit()]; buffer.get( dumpBuffer ); buffer.flip(); CODEC_LOG.debug( "Encoded message \n " + message + "\n : " + Strings.dumpBytes( dumpBuffer ) ); } out.write( ioBuffer ); }
@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 ); }
@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 ); }
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); }
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); }
@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); }
@Override public void encode(final IoSession session, final Object message, final ProtocolEncoderOutput out) throws Exception { final MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY); if (client != null) { final byte[] input = ((MaplePacket) message).getBytes(); final byte[] unencrypted = new byte[input.length]; System.arraycopy(input, 0, unencrypted, 0, input.length); final byte[] ret = new byte[unencrypted.length + 4]; final byte[] header = client.getSendCrypto().getPacketHeader(unencrypted.length); synchronized(client.getSendCrypto()){ MapleCustomEncryption.encryptData(unencrypted); client.getSendCrypto().crypt(unencrypted); System.arraycopy(header, 0, ret, 0, 4); System.arraycopy(unencrypted, 0, ret, 4, unencrypted.length); final ByteBuffer out_buffer = ByteBuffer.wrap(ret); out.write(out_buffer); } } else { // no client object created yet, send unencrypted (hello) out.write(ByteBuffer.wrap(((MaplePacket) message).getBytes())); } }
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { if(!(message instanceof byte[])){ throw new Exception("must send byte[]"); } byte[] payload=(byte[]) message; ByteBuffer buf = ByteBuffer.allocate(payload.length, false); buf.put(payload); buf.flip(); out.write(buf); if (isDebugEnabled) LOGGER.debug(TairUtil.toHex(payload)); }
@Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { if (genericClass.isInstance(message)) { byte[] datas = serializer.serialize(message); IoBuffer buffer = IoBuffer.allocate(256); buffer.setAutoExpand(true); buffer.setAutoShrink(true); buffer.putInt(datas.length); buffer.put(datas); buffer.flip(); session.write(buffer); } }
@Override public void encode(IoSession session, byte[] message, ProtocolEncoderOutput out) throws Exception { try { IoBuffer buf = IoBuffer.allocate(1024); buf.setAutoExpand(true); int usedLen = 0; while (usedLen < message.length) { Packet pkg = Packet.PARSER.parseFrom(message, 0, message.length - usedLen); log.debug("Server FLUSH:" + pkg.toString()); usedLen += pkg.toByteArray().length; buf.put(MessageCodec.makePkg(pkg.getCmdId(), pkg.toByteArray())); } buf.flip(); out.write(buf); } catch (Exception e) { e.printStackTrace(); } }
/** * 同步处理要发送的数据。 * * @param bytes * @return */ public void getSendBuffer(byte[] bytes, ProtocolEncoderOutput out, MapleClient client) { IoBuffer buffer = IoBuffer.allocate(bytes.length + 4, true); try { mutex.lock(); buffer.put(getPacketHeader(bytes.length)); buffer.put(bytes); buffer.position(buffer.position() - bytes.length); crypt(buffer, true); buffer.flip(); // 建立完成待发送数据。 out.write(buffer); out.flush(); } finally { mutex.unlock(); } buffer.free(); }
@Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { try { byte compressedBytes[] = (byte[]) message; final IoBuffer buffer = IoBuffer.allocate(compressedBytes.length).setAutoExpand(true); buffer.put(compressedBytes); buffer.flip(); out.write(buffer); WriteFuture wf = out.flush(); wf.addListener(new IoFutureListener<IoFuture>() { @Override public void operationComplete(IoFuture future) { buffer.free(); } }); out.flush(); } catch (Exception e) { e.printStackTrace(); } }
@Override public void encode(IoSession is, Object o, ProtocolEncoderOutput peo) throws Exception { assert o instanceof RequestEnvelope; RequestEnvelope env = (RequestEnvelope) o; ByteArrayOutputStream bufOutStream = new ByteArrayOutputStream(); ProtoWriter writer = new ProtoWriter(bufOutStream); if (env.ticket != null) { writer.put(CoreTags.TAG_SESSION_TICKET, env.ticket); } if (env.userName != null) { writer.put(CoreTags.TAG_USER_NAME, env.userName); writer.put(CoreTags.TAG_PASSWORD, env.password != null ? env.password : ""); } PlatypusRequestWriter.write(env.request, writer); writer.flush(); peo.write(IoBuffer.wrap(bufOutStream.toByteArray())); }
@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); }
/** * 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); } } }
@Override public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) throws Exception { // TODO Auto-generated method stub // Start packet with 5E // Include length hash [int] // Include packet length [int] // Include data hash [int] // Command (no clue) [int] // Append existing data if (msg instanceof byte[]) { byte[] src = (byte[]) msg; byte[] output = new byte[src.length + 5]; output[0] = 0x5E; output[1] = (byte) (src.length & 0xFF); output[2] = (byte) (src.length >>> 8 & 0xFF); output[3] = (byte) (src.length >>> 16 & 0xFF); output[4] = (byte) (src.length >>> 24 & 0xFF); System.arraycopy(src, 0, output, 5, src.length); System.out.println(HexTool.toString(output)); out.write(IoBuffer.wrap(output)); } }
/** * convert LLRPMessage object to binary format */ public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { LLRPMessage llrp = (LLRPMessage) message; log.debug("encoding message " + llrp.getClass()); byte[] byteMsg; try { byteMsg = llrp.encodeBinary(); } catch (InvalidLLRPMessageException me) { log.warn("no message written because error occured: " + me.getMessage()); return; } // Note: ByteBuffer is renamed in MINA to IOBuffer IoBuffer buffer = IoBuffer.allocate(byteMsg.length, false); buffer.put(byteMsg); buffer.flip(); out.write(buffer); }
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; }
public void encode(IoSession session, UnsubscribeMessage message, ProtocolEncoderOutput out) throws Exception { if (message.topics().isEmpty()) { throw new IllegalArgumentException("Found an unsubscribe message with empty topics"); } if (message.getQos() != QOSType.LEAST_ONE) { throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos()); } IoBuffer variableHeaderBuff = IoBuffer.allocate(4).setAutoExpand(true); Utils.writeWord(variableHeaderBuff, message.getMessageID()); for (String topic : message.topics()) { variableHeaderBuff.put(Utils.encodeString(topic)); } variableHeaderBuff.flip(); int variableHeaderSize = variableHeaderBuff.remaining(); byte flags = Utils.encodeFlags(message); IoBuffer buff = IoBuffer.allocate(2 + variableHeaderSize); buff.put((byte) (AbstractMessage.UNSUBSCRIBE << 4 | flags)); buff.put(Utils.encodeRemainingLength(variableHeaderSize)); buff.put(variableHeaderBuff).flip(); out.write(buff); }
public void encode(IoSession session, SubAckMessage message, ProtocolEncoderOutput out) throws Exception { if (message.types().isEmpty()) { throw new IllegalArgumentException("Found a suback message with empty topics"); } IoBuffer variableHeaderBuff = IoBuffer.allocate(4).setAutoExpand(true); Utils.writeWord(variableHeaderBuff, message.getMessageID()); for (AbstractMessage.QOSType c : message.types()) { byte ord = (byte) c.ordinal(); variableHeaderBuff.put((byte)c.ordinal()); } variableHeaderBuff.flip(); int variableHeaderSize = variableHeaderBuff.remaining(); IoBuffer buff = IoBuffer.allocate(2 + variableHeaderSize); buff.put((byte) (AbstractMessage.SUBACK << 4 )); buff.put(Utils.encodeRemainingLength(variableHeaderSize)); buff.put(variableHeaderBuff).flip(); out.write(buff); }
/** {@inheritDoc} */ public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws ProtocolCodecException { final ProtocolState state = (ProtocolState) session.getAttribute(ProtocolState.SESSION_KEY); // pass the connection to the encoder for its use encoder.setConnection((RTMPConnection) session.getAttribute(RTMPConnection.RTMP_CONNECTION_KEY)); try { // We need to synchronize on the output and flush the generated data to prevent two packages to the same channel // to be sent in different order thus resulting in wrong headers being generated. final IoBuffer buf = encoder.encode(state, message); if (buf != null) { out.write(buf); out.mergeAll(); out.flush(); } else { log.trace("Response buffer was null after encoding"); } } catch (Exception ex) { log.error("Exception during encode", ex); } }
@Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { CodecContext context = (CodecContext) session.getAttribute(SessionProperties.CODEC_CONTEXT); if (context == null) { context = new CodecContext(); session.setAttribute(SessionProperties.CODEC_CONTEXT, context); } IoBuffer buffer = writeMessage((Message) message); out.write(buffer); }
@Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { if (message instanceof Msg) { Msg msg = (Msg) message; IoBuffer buffer = IoBuffer.allocate(msg.length + 8, false) .putInt(msg.code) .putInt(msg.length) .put(msg.data).flip(); out.write(buffer); } }
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(); }
@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 () + 3 ); buffer.setAutoExpand ( true ); final IoBuffer pdu = request.getData (); // put slave id buffer.put ( request.getUnitIdentifier () ); // put data buffer.put ( pdu ); // make and put crc final int crc = Checksum.crc16 ( buffer.array (), 0, pdu.limit () + 1 ); // including slave address buffer.order ( ByteOrder.LITTLE_ENDIAN ); buffer.putShort ( (short)crc ); buffer.flip (); logger.trace ( "Encoded to: {}", buffer ); out.write ( buffer ); }
@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 ); }
/** * {@inheritDoc} */ public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { State state = getState(session); MessageEncoder<Object> encoder = findEncoder(state, message.getClass()); if (encoder != null) { encoder.encode(session, message, out); } else { throw new UnknownMessageTypeException("No message encoder found for message: " + message); } }
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { String value = (String) message; IoBuffer buffer = IoBuffer.allocate(value.length()).setAutoExpand(true); buffer.putPrefixedString(value, prefixLength, charset.newEncoder()); if (buffer.position() > maxDataLength) { throw new IllegalArgumentException("Data length: " + buffer.position()); } buffer.flip(); out.write(buffer); }
@Override public void encode(IoSession session, BaseMessage message,ProtocolEncoderOutput out) throws Exception { System.out.println("hahhahahahah"); BaseMessage baseMessage = message; StringBean bean = (StringBean) baseMessage.getData(); out.write(bean.getFileName()); }
/** * 基本信息编码 * */ @Override public void encode(IoSession session, BaseMessage message,ProtocolEncoderOutput outPut) throws Exception { IoBuffer buffer = IoBuffer.allocate(1024); //创建自动缩小的Buffer Buffer会保持在上面设置的1024*1024*1,但是一旦需求超过会自动增加容量 buffer.setAutoExpand(true); //传入数据类型 buffer.putInt(message.getDataType()); //存储的业务数据 StringBean bean = (StringBean) message.getData(); //文件名 byte[] byteStr = bean.getFileName().getBytes(BeanUtil.charset); //传入文件名长度 buffer.putInt(byteStr.length); //传入文件名 //CharSequence charSequrnce = "你好"; //CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder(); //buffer.putString(charSequrnce, encoder); buffer.put(byteStr); //打包,归0数组指针 buffer.flip(); //发送 outPut.write(buffer); log.debug("编码完成"); //自动调整一下buffer的内存空间 buffer.shrink(); }
/** * 基本信息编码 * */ @Override public void encode(IoSession session, BaseMessage message,ProtocolEncoderOutput outPut) throws Exception { IoBuffer buffer = IoBuffer.allocate(1024*1024*1); //创建自动缩小的Buffer Buffer会保持在上面设置的1024*1024*1,但是一旦需求超过会自动增加容量 buffer.setAutoExpand(true); //传入数据类型 buffer.putInt(message.getDataType()); //存储的业务数据 FileBean bean = (FileBean) message.getData(); //文件名 byte[] byteStr = bean.getFileName().getBytes(BeanUtil.charset); //传入文件名长度 buffer.putInt(byteStr.length); //文件大小 buffer.putInt(bean.getFileSize()); //传入文件名 buffer.put(byteStr); //传入文件内容 buffer.put(bean.getFileContent()); //打包,归0数组指针 buffer.flip(); //发送 outPut.write(buffer); System.out.println("编码完成!"); buffer.shrink(); }
@Override public void encode(final IoSession session, final Object message, final ProtocolEncoderOutput out) throws Exception { final MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY); if (client != null) { final MapleAESOFB send_crypto = client.getSendCrypto(); final byte[] input = (byte[]) message; final byte[] unencrypted = new byte[input.length]; System.arraycopy(input, 0, unencrypted, 0, input.length); final byte[] ret = new byte[unencrypted.length + 4]; final byte[] header = send_crypto.getPacketHeader(unencrypted.length); MapleCustomEncryption.encryptData(unencrypted); final Lock mutex = client.getLock(); mutex.lock(); try { send_crypto.crypt(unencrypted); System.arraycopy(header, 0, ret, 0, 4); System.arraycopy(unencrypted, 0, ret, 4, unencrypted.length); out.write(IoBuffer.wrap(ret)); } finally { mutex.unlock(); } // System.arraycopy(unencrypted, 0, ret, 4, unencrypted.length); // out.write(ByteBuffer.wrap(ret)); } else { out.write(IoBuffer.wrap(((byte[]) message))); } }
@Override public void encode(final IoSession session, final Object message, final ProtocolEncoderOutput out) throws Exception { final MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY); if (client != null) { final MapleAESOFB send_crypto = client.getSendCrypto(); final byte[] inputInitialPacket = ((byte[]) message); final byte[] unencrypted = new byte[inputInitialPacket.length]; System.arraycopy(inputInitialPacket, 0, unencrypted, 0, inputInitialPacket.length); // Copy the input > "unencrypted" final byte[] ret = new byte[unencrypted.length + 4]; // Create new bytes with length = "unencrypted" + 4 final Lock mutex = client.getLock(); mutex.lock(); try { final byte[] header = send_crypto.getPacketHeader(unencrypted.length); // MapleCustomEncryption.encryptData(unencrypted); // Encrypting Data send_crypto.crypt(unencrypted); // Crypt it with IV System.arraycopy(header, 0, ret, 0, 4); // Copy the header > "Ret", first 4 bytes } finally { mutex.unlock(); } System.arraycopy(unencrypted, 0, ret, 4, unencrypted.length); // Copy the unencrypted > "ret" out.write(ByteBuffer.wrap(ret)); } else { // no client object created yet, send unencrypted (hello) out.write(ByteBuffer.wrap((byte[]) message)); } }
@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); }
public void encode(IoSession iosession, Object obj, ProtocolEncoderOutput out) throws Exception { HttpResponseMessage respMsg = (HttpResponseMessage) obj; StringBuilder sb = new StringBuilder(); sb.append(respMsg.getVersion()).append(" ").append(respMsg.getStatusCode()).append(" ").append(respMsg.getStatusMessage()).append("\r\n"); Iterator iterator = respMsg.getMessageHeader().entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); sb.append((String) entry.getKey()).append(": ").append((String) entry.getValue()).append("\r\n"); } sb.append("Content-Length").append(": ").append(respMsg.getContentLength()); sb.append("\r\n\r\n"); sb.append(respMsg.getMessageBody()); if (logger.isDebugEnabled()) { String msg = respMsg != null ? respMsg.toString() : ""; if (!msg.contains("<html") && !msg.contains("<HTML")) { logger.debug("resp:{}", respMsg); } logger.debug("#############################[响应请求解析完毕]###############################"); } IoBuffer buf = IoBuffer.allocate(sb.toString().length(), false); buf.setAutoExpand(true); buf.put(sb.toString().getBytes("UTF-8")); buf.flip(); out.write(buf); }