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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#hasRemaining() . 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: FASTCodec.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doDecode(
		IoSession session,
		IoBuffer in,
		ProtocolDecoderOutput out) throws Exception {
	if (!in.hasRemaining()) {
		return false;
	}
	int position = in.position();
	try {
		if (doRealDecode(session, in, out)) {
			return true;
		}
	} catch (Exception e) {
		logger.error("Can not decode message", e);
	}
	in.position(position);
	return false;
}
 
Example 2
Source File: IntegerDecodingState.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    while (in.hasRemaining()) {
        switch (counter) {
        case 0:
            firstByte = in.getUnsigned();
            break;
        case 1:
            secondByte = in.getUnsigned();
            break;
        case 2:
            thirdByte = in.getUnsigned();
            break;
        case 3:
            counter = 0;
            return finishDecode((firstByte << 24) | (secondByte << 16) | (thirdByte << 8) | in.getUnsigned(), out);
        default:
            throw new InternalError();
        }
        counter++;
    }

    return this;
}
 
Example 3
Source File: RTMPMinaProtocolEncoder.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
public static LinkedList<IoBuffer> chunk(IoBuffer message, int chunkSize, int desiredSize) {
    LinkedList<IoBuffer> chunks = new LinkedList<IoBuffer>();
    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;
        }
        // add a chunk
        chunks.add(message.getSlice(length));
    } while (message.hasRemaining());
    return chunks;
}
 
Example 4
Source File: RedisProtocolDecoder.java    From Redis-Synyed with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	RedisProtocolParser parser = (RedisProtocolParser) session.getAttribute(REDIS_PROTOCOL_PARSER);
	// 将接收到的数据通过解析器解析为Redis数据包对象
	parser.read(in.buf());

	// 获取解析器解析出的数据包
	RedisPacket[] redisPackets = parser.getPackets();
	if (redisPackets != null) {
		for (RedisPacket redisPacket : redisPackets) {
			out.write(redisPacket);
		}
	}

	// 以是否读取完数据为判断符
	return !in.hasRemaining();
}
 
Example 5
Source File: AACAudio.java    From red5-io with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public boolean addData(IoBuffer data) {
    if (data.hasRemaining()) {
        // mark
        int start = data.position();
        // ensure we are at the beginning
        data.rewind();
        byte frameType = data.get();
        log.trace("Frame type: {}", frameType);
        byte header = data.get();
        // if we don't have the AACDecoderConfigurationRecord stored
        if (blockDataAACDCR == null) {
            if ((((frameType & 0xf0) >> 4) == AudioCodec.AAC.getId()) && (header == 0)) {
                // back to the beginning
                data.rewind();
                blockDataAACDCR = new byte[data.remaining()];
                data.get(blockDataAACDCR);
            }
        }
        data.position(start);
    }
    return true;
}
 
Example 6
Source File: MinaUtil.java    From seed with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    Context ctx = this.getContext(session);
    IoBuffer buffer = ctx.innerBuffer;
    int messageCount = ctx.getMessageCount();
    while(in.hasRemaining()){    //判断position和limit之间是否有元素
        buffer.put(in.get());    //get()读取buffer的position的字节,然后position+1
        if(messageCount++ == 5){ //约定:报文的前6个字符串表示报文总长度,不足6位则左侧补0
            buffer.flip();       //Set limit=position and position=0 and mark=-1
            //当Server的响应报文中含0x00时,Mina2.x的buffer.getString(fieldSize, decoder)方法会break
            //该方法的处理细节,详见org.apache.mina.core.buffer.AbstractIoBuffer类的第1718行源码,其说明如下
            //Reads a NUL-terminated string from this buffer using the specified decoder and returns it
            //ctx.setMessageLength(Integer.parseInt(buffer.getString(6, decoder)));
            byte[] messageLength = new byte[6];
            buffer.get(messageLength);
            try{
                //请求报文有误时,Server可能返回非约定报文,此时会抛java.lang.NumberFormatException
                ctx.setMessageLength(Integer.parseInt(new String(messageLength, charset)));
            }catch(NumberFormatException e){
                ctx.setMessageLength(in.limit());
            }
            //让两个IoBuffer的limit相等
            buffer.limit(in.limit());
        }
    }
    ctx.setMessageCount(messageCount);
    if(ctx.getMessageLength() == buffer.position()){
        buffer.flip();
        byte[] message = new byte[buffer.limit()];
        buffer.get(message);
        out.write(new String(message, charset));
        ctx.reset();
        return true;
    }else{
        return false;
    }
}
 
Example 7
Source File: CrLfDecodingState.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    boolean found = false;
    boolean finished = false;
    while (in.hasRemaining()) {
        byte b = in.get();
        if (!hasCR) {
            if (b == CR) {
                hasCR = true;
            } else {
                if (b == LF) {
                    found = true;
                } else {
                    in.position(in.position() - 1);
                    found = false;
                }
                finished = true;
                break;
            }
        } else {
            if (b == LF) {
                found = true;
                finished = true;
                break;
            }

            throw new ProtocolDecoderException("Expected LF after CR but was: " + (b & 0xff));
        }
    }

    if (finished) {
        hasCR = false;
        return finishDecode(found, out);
    }

    return this;
}
 
Example 8
Source File: SslHandler.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
WriteFuture writeNetBuffer(NextFilter nextFilter, boolean needFuture) throws Exception {
	// Check if any net data needed to be writen
	if (outNetBuffer == null || !outNetBuffer.hasRemaining())
		return null; // no; bail out

	// set flag that we are writing encrypted data (used in SSLFilter.filterWrite())
	writingEncryptedData = true;

	// write net data
	WriteFuture writeFuture = (needFuture ? new DefaultWriteFuture(session) : null);

	try {
		IoBuffer writeBuffer = fetchOutNetBuffer();
		sslFilter.filterWrite(nextFilter, session, writeFuture != null ? new DefaultWriteRequest(writeBuffer, writeFuture) : writeBuffer);

		// loop while more writes required to complete handshake
		while (handshakeStatus == HandshakeStatus.NEED_WRAP && !isInboundDone()) {
			try {
				handshake(nextFilter);
			} catch (SSLException ssle) {
				SSLException newSsle = new SSLHandshakeException("SSL handshake failed");
				newSsle.initCause(ssle);
				throw newSsle;
			}

			IoBuffer currentOutNetBuffer = fetchOutNetBuffer();
			if (currentOutNetBuffer != null && currentOutNetBuffer.hasRemaining()) {
				writeFuture = (needFuture ? new DefaultWriteFuture(session) : null);
				sslFilter.filterWrite(nextFilter, session, writeFuture != null ? new DefaultWriteRequest(currentOutNetBuffer, writeFuture) : currentOutNetBuffer);
			}
		}
	} finally {
		writingEncryptedData = false;
	}

	return writeFuture;
}
 
Example 9
Source File: CompositeByteArray.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
public void get(IoBuffer bb) {
    while (bb.hasRemaining()) {
        int remainingBefore = bb.remaining();
        prepareForAccess(remainingBefore);
        componentCursor.get(bb);
        int remainingAfter = bb.remaining();
        // Advance index by actual amount got.
        int chunkSize = remainingBefore - remainingAfter;
        index += chunkSize;
    }
}
 
Example 10
Source File: SslFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void handleAppDataRead(NextFilter nextFilter, SslHandler handler) {
    // forward read app data
    IoBuffer readBuffer = handler.fetchAppBuffer();

    if (readBuffer.hasRemaining()) {
        handler.scheduleMessageReceived(nextFilter, readBuffer);
    }
}
 
Example 11
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;
}
 
Example 12
Source File: MyTextLineCodecDecoder.java    From java-study with Apache License 2.0 4 votes vote down vote up
private void decodeNormal(Context ctx, IoBuffer in, ProtocolDecoderOutput out) throws CharacterCodingException {
   
    // 取出未完成任务中已经匹配的文本换行符的个数
    int matchCount = ctx.getMatchCount();
		   
    // 设置匹配文本换行符的IoBuffer变量
    if (delimBuf == null) {
        IoBuffer tmp = IoBuffer.allocate(2).setAutoExpand(true);
        tmp.putString(delimiter, charset.newEncoder());
        tmp.flip();
        delimBuf = tmp;
    }

    //解码的IoBuffer中数据的原始信息
    int oldPos = in.position();  //输出值为0
    int oldLimit = in.limit();   //输出值为1
           
    logger.info("******************************************************************************");       
    logger.info("开始进入解码方法-----------------------------------------------------------------");
    logger.info("");
    logger.info("init Start--------------------------------------------------------------------");
    logger.info("in.postion() = "+oldPos);
    logger.info("in.Limit() = "+oldLimit);
    logger.info("in.capacity() = "+in.capacity());
    logger.info("matchCount = "+matchCount);
    logger.info("init End---------------------------------------------------------------------");
    logger.info("");
   
    //变量解码的IoBuffer
    while (in.hasRemaining()) {           
       
        byte b = in.get();           
        logger.info("");
        logger.info("输入进来的字符为 = "+(char)b+",对应的ascii值 = "+b);
        logger.info("in.position() = "+in.position()+",in.limit() = "+in.limit());
        logger.info("");
       
        //当b的ascii值为13,10 即为\r,\n时,会进入下述if语句
        if (delimBuf.get(matchCount) == b) {
           
            // b='\r'时,matchCount=1, b='\n'时,matchCount=2
            matchCount++;   
           
            logger.info("matchCount = "+matchCount);
            //当前匹配到字节个数与文本换行符字节个数相同,即 b='\n'时
            //此时matchCount=2, delimBuf.limit()=2
           
            if (matchCount == delimBuf.limit()) {                       
               
                    // 获得当前匹配到的position(position前所有数据有效)
                    int pos = in.position();    //值为2           
                    logger.info("pos = "+pos);
                   
                    in.limit(pos); //值为2
                    // position回到原始位置
                    in.position(oldPos); //值为0
                   
                    // 追加到Context对象未完成数据后面
                    ctx.append(in); //将 \r\n这两个字符添加到 ctx.getBuf()中
                   
                    // in中匹配结束后剩余数据
                    in.limit(oldLimit); //值为2
                    in.position(pos); //值为2
                                       
                    IoBuffer buf = ctx.getBuf(); //此时是得到  he\r\n                       
                    buf.flip(); //此时 buf.position=0,buf.limit()=4            
                   
                    buf.limit(buf.limit() - matchCount);  //4-2 = 2
                    try{
                        // 输出解码内容 ,即 he
                        out.write(buf.getString(ctx.getDecoder()));
                    }
                    finally {
                        buf.clear(); // 释放缓存空间
                    }       
               
                    matchCount = 0;
                   
                }
        }else { //h字符,e字符时,均会进入 此else逻辑判断中   

            //把in中未解码内容放回buf中
            //下面会在 输入的字符不是 \r\n时会需要保存使用
            in.position(oldPos);
            ctx.append(in);
            ctx.setMatchCount(matchCount);
        }
    }           
}
 
Example 13
Source File: TextLineDecoder.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Decode a line using the delimiter defined by the caller
 */
private void decodeNormal(Context ctx, IoSession session, IoBuffer in, ProtocolDecoderOutput out)
        throws CharacterCodingException, ProtocolDecoderException {
    int matchCount = ctx.getMatchCount();

    // Try to find a match
    int oldPos = in.position();
    int oldLimit = in.limit();

    while (in.hasRemaining()) {
        byte b = in.get();

        if (delimBuf.get(matchCount) == b) {
            matchCount++;

            if (matchCount == delimBuf.limit()) {
                // Found a match.
                int pos = in.position();
                in.limit(pos);
                in.position(oldPos);

                ctx.append(in);

                in.limit(oldLimit);
                in.position(pos);

                if (ctx.getOverflowPosition() == 0) {
                    IoBuffer buf = ctx.getBuffer();
                    buf.flip();
                    buf.limit(buf.limit() - matchCount);

                    try {
                        writeText(session, buf.getString(ctx.getDecoder()), out);
                    } finally {
                        buf.clear();
                    }
                } else {
                    int overflowPosition = ctx.getOverflowPosition();
                    ctx.reset();
                    throw new RecoverableProtocolDecoderException("Line is too long: " + overflowPosition);
                }

                oldPos = pos;
                matchCount = 0;
            }
        } else {
            // fix for DIRMINA-506 & DIRMINA-536
            in.position(Math.max(0, in.position() - matchCount));
            matchCount = 0;
        }
    }

    // Put remainder to buf.
    in.position(oldPos);
    ctx.append(in);

    ctx.setMatchCount(matchCount);
}
 
Example 14
Source File: TextLineDecoder.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Decode a line using the default delimiter on the current system
 */
private void decodeAuto(Context ctx, IoSession session, IoBuffer in, ProtocolDecoderOutput out)
        throws CharacterCodingException, ProtocolDecoderException {
    int matchCount = ctx.getMatchCount();

    // Try to find a match
    int oldPos = in.position();
    int oldLimit = in.limit();

    while (in.hasRemaining()) {
        byte b = in.get();
        boolean matched = false;

        switch (b) {
        case '\r':
            // Might be Mac, but we don't auto-detect Mac EOL
            // to avoid confusion.
            matchCount++;
            break;

        case '\n':
            // UNIX
            matchCount++;
            matched = true;
            break;

        default:
            matchCount = 0;
        }

        if (matched) {
            // Found a match.
            int pos = in.position();
            in.limit(pos);
            in.position(oldPos);

            ctx.append(in);

            in.limit(oldLimit);
            in.position(pos);

            if (ctx.getOverflowPosition() == 0) {
                IoBuffer buf = ctx.getBuffer();
                buf.flip();
                buf.limit(buf.limit() - matchCount);

                try {
                    byte[] data = new byte[buf.limit()];
                    buf.get(data);
                    CharsetDecoder decoder = ctx.getDecoder();

                    CharBuffer buffer = decoder.decode(ByteBuffer.wrap(data));
                    String str = new String(buffer.array());
                    writeText(session, str, out);
                } finally {
                    buf.clear();
                }
            } else {
                int overflowPosition = ctx.getOverflowPosition();
                ctx.reset();
                throw new RecoverableProtocolDecoderException("Line is too long: " + overflowPosition);
            }

            oldPos = pos;
            matchCount = 0;
        }
    }

    // Put remainder to buf.
    in.position(oldPos);
    ctx.append(in);

    ctx.setMatchCount(matchCount);
}
 
Example 15
Source File: ProtocolCodecFilter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Process the incoming message, calling the session decoder. As the incoming
 * buffer might contains more than one messages, we have to loop until the decoder
 * throws an exception.
 * 
 *  while ( buffer not empty )
 *    try
 *      decode ( buffer )
 *    catch
 *      break;
 * 
 */
@Override
public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
    LOGGER.debug("Processing a MESSAGE_RECEIVED for session {}", session.getId());

    if (!(message instanceof IoBuffer)) {
        nextFilter.messageReceived(session, message);
        return;
    }

    IoBuffer in = (IoBuffer) message;
    ProtocolDecoder decoder = factory.getDecoder(session);
    ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter);

    // Loop until we don't have anymore byte in the buffer,
    // or until the decoder throws an unrecoverable exception or
    // can't decoder a message, because there are not enough
    // data in the buffer
    while (in.hasRemaining()) {
        int oldPos = in.position();

        try {
            synchronized (decoderOut) {
                // Call the decoder with the read bytes
                decoder.decode(session, in, decoderOut);
            }

            // Finish decoding if no exception was thrown.
            decoderOut.flush(nextFilter, session);
        } catch (Throwable t) {
            ProtocolDecoderException pde;
            if (t instanceof ProtocolDecoderException) {
                pde = (ProtocolDecoderException) t;
            } else {
                pde = new ProtocolDecoderException(t);
            }

            if (pde.getHexdump() == null) {
                // Generate a message hex dump
                int curPos = in.position();
                in.position(oldPos);
                pde.setHexdump(in.getHexDump());
                in.position(curPos);
            }

            // Fire the exceptionCaught event.
            decoderOut.flush(nextFilter, session);
            nextFilter.exceptionCaught(session, pde);

            // Retry only if the type of the caught exception is
            // recoverable and the buffer position has changed.
            // We check buffer position additionally to prevent an
            // infinite loop.
            if (!(t instanceof RecoverableProtocolDecoderException) || (in.position() == oldPos)) {
                break;
            }
        }
    }
}
 
Example 16
Source File: MultiportSyslogTCPSource.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
@Override
public void messageReceived(IoSession session, Object message) {

  IoBuffer buf = (IoBuffer) message;
  IoBuffer savedBuf = (IoBuffer) session.getAttribute(SAVED_BUF);

  ParsedBuffer parsedLine = new ParsedBuffer();
  List<Event> events = Lists.newArrayList();

  // the character set can be specified per-port
  CharsetDecoder decoder = defaultDecoder.get();
  int port =
      ((InetSocketAddress) session.getLocalAddress()).getPort();
  if (portCharsets.containsKey(port)) {
    decoder = portCharsets.get(port).get();
  }

  // while the buffer is not empty
  while (buf.hasRemaining()) {
    events.clear();

    // take number of events no greater than batchSize
    for (int num = 0; num < batchSize && buf.hasRemaining(); num++) {

      if (lineSplitter.parseLine(buf, savedBuf, parsedLine)) {
        Event event = parseEvent(parsedLine, decoder);
        if (portHeader != null) {
          event.getHeaders().put(portHeader, String.valueOf(port));
        }
        events.add(event);
      } else {
        logger.trace("Parsed null event");
      }

    }

    // don't try to write anything if we didn't get any events somehow
    if (events.isEmpty()) {
      logger.trace("Empty set!");
      return;
    }

    int numEvents = events.size();
    sourceCounter.addToEventReceivedCount(numEvents);

    // write the events to the downstream channel
    try {
      channelProcessor.processEventBatch(events);
      sourceCounter.addToEventAcceptedCount(numEvents);
    } catch (Throwable t) {
      logger.error("Error writing to channel, event dropped", t);
      if (t instanceof Error) {
        Throwables.propagate(t);
      }
    }
  }

}
 
Example 17
Source File: RTMPProtocolDecoder.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/**
 * Decode the 'action' for a supplied an Invoke.
 * 
 * @param encoding
 *            AMF encoding
 * @param in
 *            buffer
 * @param header
 *            data header
 * @return notify
 */
private Invoke decodeAction(Encoding encoding, IoBuffer in, Header header) {
    // for response, the action string and invokeId is always encoded as AMF0 we use the first byte to decide which encoding to use
    in.mark();
    byte tmp = in.get();
    in.reset();
    Input input;
    if (encoding == Encoding.AMF3 && tmp == AMF.TYPE_AMF3_OBJECT) {
        input = new org.red5.io.amf3.Input(in);
        ((org.red5.io.amf3.Input) input).enforceAMF3();
    } else {
        input = new org.red5.io.amf.Input(in);
    }
    // get the action
    String action = Deserializer.deserialize(input, String.class);
    if (action == null) {
        throw new RuntimeException("Action was null");
    }
    if (log.isTraceEnabled()) {
        log.trace("Action: {}", action);
    }
    // instance the invoke
    Invoke invoke = new Invoke();
    // set the transaction id
    invoke.setTransactionId(readTransactionId(input));
    // reset and decode parameters
    input.reset();
    // get / set the parameters if there any
    Object[] params = in.hasRemaining() ? handleParameters(in, invoke, input) : new Object[0];
    // determine service information
    final int dotIndex = action.lastIndexOf('.');
    String serviceName = (dotIndex == -1) ? null : action.substring(0, dotIndex);
    // pull off the prefixes since java doesn't allow this on a method name
    if (serviceName != null && (serviceName.startsWith("@") || serviceName.startsWith("|"))) {
        serviceName = serviceName.substring(1);
    }
    String serviceMethod = (dotIndex == -1) ? action : action.substring(dotIndex + 1, action.length());
    // pull off the prefixes since java doesnt allow this on a method name
    if (serviceMethod.startsWith("@") || serviceMethod.startsWith("|")) {
        serviceMethod = serviceMethod.substring(1);
    }
    // create the pending call for invoke
    PendingCall call = new PendingCall(serviceName, serviceMethod, params);
    invoke.setCall(call);
    return invoke;
}
 
Example 18
Source File: WebSocketDecoder.java    From game-server with MIT License 4 votes vote down vote up
private static IoBuffer buildWSDataBuffer(IoBuffer in, IoSession session) {

        IoBuffer resultBuffer = null;
        do{
            byte frameInfo = in.get();            
            byte opCode = (byte) (frameInfo & 0x0f);
            if (opCode == 8) {
                // opCode 8 means close. See RFC 6455 Section 5.2
                // return what ever is parsed till now.
                session.close(true);
                return resultBuffer;
            }        
            int frameLen = (in.get() & (byte) 0x7F);
            if(frameLen == 126){
                frameLen = in.getShort();
            }
            
            // Validate if we have enough data in the buffer to completely
            // parse the WebSocket DataFrame. If not return null.
            if(frameLen+4 > in.remaining()){                
                return null;
            }
            byte mask[] = new byte[4];
            for (int i = 0; i < 4; i++) {
                mask[i] = in.get();
            }

            /*  now un-mask frameLen bytes as per Section 5.3 RFC 6455
                Octet i of the transformed data ("transformed-octet-i") is the XOR of
                octet i of the original data ("original-octet-i") with octet at index
                i modulo 4 of the masking key ("masking-key-octet-j"):

                j                   = i MOD 4
                transformed-octet-i = original-octet-i XOR masking-key-octet-j
            * 
            */
             
            byte[] unMaskedPayLoad = new byte[frameLen];
            for (int i = 0; i < frameLen; i++) {
                byte maskedByte = in.get();
                unMaskedPayLoad[i] = (byte) (maskedByte ^ mask[i % 4]);
            }
            
            if(resultBuffer == null){
                resultBuffer = IoBuffer.wrap(unMaskedPayLoad);
                resultBuffer.position(resultBuffer.limit());
                resultBuffer.setAutoExpand(true);
            }
            else{
                resultBuffer.put(unMaskedPayLoad);
            }
        }
        while(in.hasRemaining());
        
        resultBuffer.flip();
        return resultBuffer;

    }
 
Example 19
Source File: MyDataDecoder.java    From QuickerAndroid with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 返回值含义:
 * 1、当内容刚好时,返回false,告知父类接收下一批内容
 * 2、内容不够时需要下一批发过来的内容,此时返回false,这样父类 CumulativeProtocolDecoder
 * 会将内容放进IoSession中,等下次来数据后就自动拼装再交给本类的doDecode
 * 3、当内容多时,返回true,因为需要再将本批数据进行读取,父类会将剩余的数据再次推送本类的doDecode方法
 */
@Override
public boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
        throws Exception {
    Log.d(TAG, "解码消息... len = " + in.remaining());

    /**
     * 假定消息格式为:消息头(int类型:表示消息体的长度、short类型:表示事件号)+消息体
     */
    if (in.remaining() < 12)
    {
        return false;
    }

        //以便后继的reset操作能恢复position位置
        in.mark();

        int headFlag = in.getInt();
        int msgType = in.getInt();
        int msgLength = in.getInt();

        if (  in.remaining() >= (msgLength + 4) ) {
            String msgJson = in.getString(msgLength, Charset.forName("UTF-8").newDecoder());
            int end = in.getInt();

            MessageBase msg = deserializeMsg(msgType, msgJson);
            out.write(msg);

            if (in.hasRemaining()) {
                return true;
            }else {
                return false;
            }
        }else {
            in.reset();

            // 消息不完整
            return false;
        }


}
 
Example 20
Source File: NioProcessor.java    From jane with GNU Lesser General Public License v3.0 4 votes vote down vote up
void flushNow(NioSession session) {
	if (session.isClosing())
		return;
	try {
		WriteRequestQueue writeQueue = session.getWriteRequestQueue();
		for (WriteRequest req; (req = writeQueue.peek()) != null; writeQueue.poll()) {
			Object message = req.writeRequestMessage();
			if (message instanceof IoBuffer) {
				IoBuffer buf = (IoBuffer)message;
				if (buf.hasRemaining()) {
					session.getChannel().write(buf.buf());
					if (buf.hasRemaining()) {
						session.setInterestedInWrite(true);
						return;
					}
				}
				req.writeRequestFuture().setWritten();
				buf.free();
			} else if (message instanceof FileRegion) {
				FileRegion region = (FileRegion)message;
				long len = region.getRemainingBytes();
				if (len > 0) {
					region.update(region.getFileChannel().transferTo(region.getPosition(), len, session.getChannel()));
  						if (region.getRemainingBytes() > 0) {
  							session.setInterestedInWrite(true);
  							return;
  						}
				}
				req.writeRequestFuture().setWritten();
			} else if (req == NioSession.CLOSE_REQUEST) {
				session.closeNow();
				break;
			} else if (req == NioSession.SHUTDOWN_REQUEST) {
				session.getChannel().shutdownOutput();
				break;
			} else
				throw new IllegalStateException("unknown message type for writting: " + message.getClass().getName() + ": " + message);
		}
		session.setInterestedInWrite(false);
	} catch (Exception e) {
		session.closeNow();
		session.removeNow(e);
	}
}