Java Code Examples for org.apache.mina.core.buffer.IoBuffer#get()
The following examples show how to use
org.apache.mina.core.buffer.IoBuffer#get() .
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: HexDumper.java From sailfish-core with Apache License 2.0 | 6 votes |
public static byte[] peakBytes(IoBuffer in, int lengthLimit) { if (lengthLimit == 0) { throw new IllegalArgumentException("lengthLimit: " + lengthLimit + " (expected: 1+)"); } boolean truncate = in.remaining() > lengthLimit; int size = truncate ? lengthLimit : in.remaining(); if(size == 0) { return new byte[0]; } int mark = in.position(); byte[] array = new byte[size]; in.get(array); in.position(mark); return array; }
Example 2
Source File: ScreenVideo2.java From red5-io with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override public boolean canHandleData(IoBuffer data) { byte first = data.get(); boolean result = ((first & 0x0f) == VideoCodec.SCREEN_VIDEO2.getId()); data.rewind(); return result; }
Example 3
Source File: ScreenVideo2.java From red5-io with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override public boolean addData(IoBuffer data) { if (!this.canHandleData(data)) { return false; } data.get(); this.updateSize(data); int idx = 0; int pos = 0; byte[] tmpData = new byte[blockDataSize]; // reserved (6) has iframeimage (1) has palleteinfo (1) specInfo1 = data.get(); int countBlocks = blockCount; while (data.remaining() > 0 && countBlocks > 0) { short size = data.getShort(); countBlocks--; if (size == 0) { // Block has not been modified idx += 1; pos += blockDataSize; continue; } else { // imageformat specInfo2 = data.get(); size--; } // Store new block data blockSize[idx] = size; data.get(tmpData, 0, size); System.arraycopy(tmpData, 0, blockData, pos, size); idx += 1; pos += blockDataSize; } data.rewind(); return true; }
Example 4
Source File: ProtocolDecoderImpl.java From neoscada with Eclipse Public License 1.0 | 5 votes |
private BrowseAdded.Entry decodeBrowserAddEntry ( final IoBuffer data, final IoSession session ) throws ProtocolCodecException { final short register = (short)data.getUnsignedShort (); // FIXME: validate if short works final byte b = data.get (); final DataType dataType = DataType.fromByte ( b ); if ( dataType == null ) { throw new ProtocolCodecException ( String.format ( "Data type %s is unkown", b ) ); } final Set<BrowseAdded.Entry.Flags> flags = data.getEnumSet ( BrowseAdded.Entry.Flags.class ); final CharsetDecoder decoder = Sessions.getCharsetDecoder ( session ); try { final String name = data.getPrefixedString ( decoder ); final String description = data.getPrefixedString ( decoder ); final String unit = data.getPrefixedString ( decoder ); return new BrowseAdded.Entry ( register, name, description, unit, dataType, flags ); } catch ( final CharacterCodingException e ) { throw new ProtocolCodecException ( e ); } }
Example 5
Source File: ImmutableTag.java From red5-server-common with Apache License 2.0 | 5 votes |
public static ImmutableTag build(byte dataType, int timestamp, IoBuffer data) { if (data != null) { byte[] body = new byte[data.limit()]; int pos = data.position(); data.get(body); data.position(pos); return new ImmutableTag(dataType, timestamp, body); } else { return new ImmutableTag(dataType, timestamp, null); } }
Example 6
Source File: ServerProtocolTCPDecoder.java From seed with Apache License 2.0 | 5 votes |
@Override public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { byte[] message = new byte[in.limit()]; in.get(message); String fullMessage = StringUtils.toEncodedString(message, Charset.forName(SeedConstants.DEFAULT_CHARSET)); Token token = new Token(); token.setBusiCharset(SeedConstants.DEFAULT_CHARSET); token.setBusiType(Token.BUSI_TYPE_TCP); token.setBusiCode(fullMessage.substring(6, 11)); token.setBusiMessage(fullMessage); token.setFullMessage(fullMessage); out.write(token); return MessageDecoderResult.OK; }
Example 7
Source File: RTMPUtils.java From red5-server-common with Apache License 2.0 | 5 votes |
/** * Read integer in reversed order. * * @param in * Input buffer * @return Integer */ public static int readReverseInt(IoBuffer in) { final byte a = in.get(); final byte b = in.get(); final byte c = in.get(); final byte d = in.get(); int val = 0; val += (d & 0xff) << 24; val += (c & 0xff) << 16; val += (b & 0xff) << 8; val += (a & 0xff); return val; }
Example 8
Source File: RTMPUtils.java From red5-server-common with Apache License 2.0 | 5 votes |
/** * Read unsigned 24 bit integer. * * @param in input * @return unsigned int */ public static int readUnsignedMediumInt(IoBuffer in) { final byte a = in.get(); final byte b = in.get(); final byte c = in.get(); int val = 0; val += (a & 0xff) << 16; val += (b & 0xff) << 8; val += (c & 0xff); return val; }
Example 9
Source File: BitVariable.java From neoscada with Eclipse Public License 1.0 | 5 votes |
@Override protected Variant extractValue ( final IoBuffer data, final Map<String, Variant> attributes ) { final byte b = data.get ( toAddress ( this.index ) ); final boolean flag = ( b & 1 << this.subIndex ) != 0; return Variant.valueOf ( flag ); }
Example 10
Source File: AIProtobufDecoder.java From gameserver with Apache License 2.0 | 5 votes |
/** * Decode the message. */ @Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { // Make sure all the header bytes are ready. if ( !in.prefixedDataAvailable(HEADER_LENGTH, MAX_LENGTH) ) { return false; } byte[] bytes = new byte[in.getInt()]; in.get(bytes); AIMessage aiMessage = AIMessage.parseFrom(bytes); ByteString sessionBytes = aiMessage.getSession(); ByteString contentBytes = aiMessage.getContent(); if ( sessionBytes != null && contentBytes != null) { SessionKey sessionKey = SessionKey.createSessionKey(sessionBytes.toByteArray()); XinqiMessage xinqiMessage = XinqiMessage.fromByteArray(contentBytes.toByteArray()); if ( xinqiMessage != null ) { SessionAIMessage sessionMessage = new SessionAIMessage(); sessionMessage.setSessionKey(sessionKey); sessionMessage.setMessage(xinqiMessage); out.write(sessionMessage); } } else { logger.debug("AIProtocolDecoder sessionBytes or contentBytes is null"); } return true; }
Example 11
Source File: MsgUtil.java From game-server with MIT License | 5 votes |
public static Message buildMessage(Class<? extends Message> clazz, IoBuffer ioBuffer) throws Exception { if (ioBuffer.remaining() < 1) { return null; } byte[] bytes = new byte[ioBuffer.remaining()]; ioBuffer.get(bytes); return buildMessage(clazz, bytes); }
Example 12
Source File: WebSocketDecoder.java From game-server with MIT License | 4 votes |
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 13
Source File: CreateQuery.java From neoscada with Eclipse Public License 1.0 | 4 votes |
@Override public org.eclipse.scada.ae.data.message.CreateQuery decodeMessage ( final BinaryContext _context, final IoBuffer _data ) throws Exception { // message code { final int messageCode = _data.getInt (); if ( messageCode != MESSAGE_CODE ) { throw new IllegalStateException ( String.format ( "Expected messageCode %s but found %s", MESSAGE_CODE, messageCode ) ); } } final byte numberOfFields = _data.get (); // decode attributes long queryId = 0L; String queryType = null; String queryData = null; logger.trace ( "Decoding {} fields", numberOfFields ); for ( int i = 0; i < numberOfFields; i++ ) { final byte fieldNumber = _data.get (); switch ( fieldNumber ) { case 1: { queryId = _context.decodePrimitiveLong ( _data ); } break; case 2: { queryType = _context.decodeString ( _data ); } break; case 3: { queryData = _context.decodeString ( _data ); } break; default: logger.warn ( "Received unknown field number: {}", fieldNumber ); break; } } // create object return new org.eclipse.scada.ae.data.message.CreateQuery ( queryId, queryType, queryData ); }
Example 14
Source File: StartWriteAttributes.java From neoscada with Eclipse Public License 1.0 | 4 votes |
@Override public org.eclipse.scada.da.data.message.StartWriteAttributes decodeMessage ( final BinaryContext _context, final IoBuffer _data ) throws Exception { // message code { final int messageCode = _data.getInt (); if ( messageCode != MESSAGE_CODE ) { throw new IllegalStateException ( String.format ( "Expected messageCode %s but found %s", MESSAGE_CODE, messageCode ) ); } } final byte numberOfFields = _data.get (); // decode attributes org.eclipse.scada.core.data.Request request = null; String itemId = null; java.util.Map<String, org.eclipse.scada.core.Variant> attributes = null; org.eclipse.scada.core.data.OperationParameters operationParameters = null; Long callbackHandlerId = null; logger.trace ( "Decoding {} fields", numberOfFields ); for ( int i = 0; i < numberOfFields; i++ ) { final byte fieldNumber = _data.get (); switch ( fieldNumber ) { case 1: { request = org.eclipse.scada.core.protocol.ngp.codec.Structures.decodeRequest ( _context, _data, false ); } break; case 2: { itemId = _context.decodeString ( _data ); } break; case 3: { attributes = _context.decodeVariantMap ( _data ); } break; case 4: { operationParameters = org.eclipse.scada.core.protocol.ngp.codec.Structures.decodeOperationParameters ( _context, _data, true ); } break; case 5: { callbackHandlerId = _context.decodeLong ( _data ); } break; default: logger.warn ( "Received unknown field number: {}", fieldNumber ); break; } } // create object return new org.eclipse.scada.da.data.message.StartWriteAttributes ( request, itemId, attributes, operationParameters, callbackHandlerId ); }
Example 15
Source File: Segment.java From red5-hls-plugin with Apache License 2.0 | 4 votes |
public ByteBuffer read(ByteBuffer buf) { if (buffer != null) { Integer readPos = readPositionHolder.get(); log.trace("Current buffer read position: {}", readPos); int newPos = readPos + CHUNK_SIZE; int currentPosition = buffer.position(); if (newPos < currentPosition) { byte[] chunk = new byte[CHUNK_SIZE]; if (lock.tryLock()) { try { currentPosition = buffer.position(); IoBuffer slice = buffer.getSlice(readPos, CHUNK_SIZE); //log.trace("Slice - size: {} {}", slice.limit(), slice.getHexDump()); buffer.position(currentPosition); slice.get(chunk); slice.free(); } finally { lock.unlock(); } buf.put(chunk); buf.flip(); } //set back to thread local readPositionHolder.set(newPos); } else { //set previous value back in th readPositionHolder.set(readPos); //set the position to the end as an indicator buf.position(CHUNK_SIZE - 1); } } else { FileChannel readChannel = readChannelHolder.get(); try { //read from the file readChannel.read(buf); buf.flip(); } catch (IOException e) { e.printStackTrace(); } //set back to thread local readChannelHolder.set(readChannel); } return buf; }
Example 16
Source File: MonitorPoolDataUpdate.java From neoscada with Eclipse Public License 1.0 | 4 votes |
@Override public org.eclipse.scada.ae.data.message.MonitorPoolDataUpdate decodeMessage ( final BinaryContext _context, final IoBuffer _data ) throws Exception { // message code { final int messageCode = _data.getInt (); if ( messageCode != MESSAGE_CODE ) { throw new IllegalStateException ( String.format ( "Expected messageCode %s but found %s", MESSAGE_CODE, messageCode ) ); } } final byte numberOfFields = _data.get (); // decode attributes String monitorPoolId = null; java.util.List<org.eclipse.scada.ae.data.MonitorStatusInformation> addedOrUpdated = null; java.util.Set<String> removed = null; boolean full = false; logger.trace ( "Decoding {} fields", numberOfFields ); for ( int i = 0; i < numberOfFields; i++ ) { final byte fieldNumber = _data.get (); switch ( fieldNumber ) { case 1: { monitorPoolId = _context.decodeString ( _data ); } break; case 2: { addedOrUpdated = org.eclipse.scada.ae.protocol.ngp.codec.Structures.decodeListMonitorStatusInformation ( _context, _data, true ); } break; case 3: { removed = _context.decodeStringSet ( _data ); } break; case 4: { full = _context.decodePrimitiveBoolean ( _data ); } break; default: logger.warn ( "Received unknown field number: {}", fieldNumber ); break; } } // create object return new org.eclipse.scada.ae.data.message.MonitorPoolDataUpdate ( monitorPoolId, addedOrUpdated, removed, full ); }
Example 17
Source File: FolderDataUpdate.java From neoscada with Eclipse Public License 1.0 | 4 votes |
@Override public org.eclipse.scada.da.data.message.FolderDataUpdate decodeMessage ( final BinaryContext _context, final IoBuffer _data ) throws Exception { // message code { final int messageCode = _data.getInt (); if ( messageCode != MESSAGE_CODE ) { throw new IllegalStateException ( String.format ( "Expected messageCode %s but found %s", MESSAGE_CODE, messageCode ) ); } } final byte numberOfFields = _data.get (); // decode attributes java.util.List<String> location = null; java.util.List<org.eclipse.scada.da.data.BrowserEntry> addedOrModified = null; java.util.Set<String> removed = null; boolean full = false; logger.trace ( "Decoding {} fields", numberOfFields ); for ( int i = 0; i < numberOfFields; i++ ) { final byte fieldNumber = _data.get (); switch ( fieldNumber ) { case 1: { location = _context.decodeStringList ( _data ); } break; case 2: { addedOrModified = org.eclipse.scada.da.protocol.ngp.codec.Structures.decodeListBrowserEntry ( _context, _data, true ); } break; case 3: { removed = _context.decodeStringSet ( _data ); } break; case 4: { full = _context.decodePrimitiveBoolean ( _data ); } break; default: logger.warn ( "Received unknown field number: {}", fieldNumber ); break; } } // create object return new org.eclipse.scada.da.data.message.FolderDataUpdate ( location, addedOrModified, removed, full ); }
Example 18
Source File: DSRemotingClient.java From red5-client with Apache License 2.0 | 4 votes |
/** * Decode response received from remoting server. * * @param data * Result data to decode * @return Object deserialized from byte buffer data */ private Object decodeResult(IoBuffer data) { log.debug("decodeResult - data limit: {}", (data != null ? data.limit() : 0)); processHeaders(data); Input input = new Input(data); String target = null; byte b = data.get(); //look for SOH if (b == 0) { log.debug("NUL: {}", b); //0 log.debug("SOH: {}", data.get()); //1 } else if (b == 1) { log.debug("SOH: {}", b); //1 } int targetUriLength = data.getShort(); log.debug("targetUri length: {}", targetUriLength); target = input.readString(targetUriLength); log.debug("NUL: {}", data.get()); //0 //should be junk bytes ff, ff, ff, ff int count = data.getInt(); if (count == -1) { log.debug("DC1: {}", data.get()); //17 count = 1; } else { data.position(data.position() - 4); count = data.getShort(); } if (count != 1) { throw new RuntimeException("Expected exactly one result but got " + count); } String[] targetParts = target.split("[/]"); if (targetParts.length > 1) { log.debug("Result sequence number: {}", targetParts[1]); target = targetParts[2]; } else { target = target.substring(1); } log.debug("Target: {}", target); if ("onResult".equals(target)) { //read return value return input.readObject(); } else if ("onStatus".equals(target)) { //read return value return input.readObject(); } //read return value return Deserializer.deserialize(input, Object.class); }
Example 19
Source File: ServerProtocolHTTPDecoder.java From seed with Apache License 2.0 | 4 votes |
@Override public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { byte[] message = new byte[in.limit()]; in.get(message); String fullMessage = StringUtils.toEncodedString(message, Charset.forName(SeedConstants.DEFAULT_CHARSET)); Token token = new Token(); token.setBusiCharset(SeedConstants.DEFAULT_CHARSET); token.setBusiType(Token.BUSI_TYPE_HTTP); token.setFullMessage(fullMessage); if(fullMessage.startsWith("GET")){ if(fullMessage.startsWith("GET / HTTP/1.1\r\n") || fullMessage.startsWith("GET / HTTP/1.0\r\n")){ token.setBusiCode("/"); }else if(fullMessage.startsWith("GET /favicon.ico HTTP/1.1\r\n") || fullMessage.startsWith("GET /favicon.ico HTTP/1.0\r\n")){ token.setBusiCode("/favicon.ico"); }else{ //GET /login?aa=bb&cc=dd&ee=ff HTTP/1.1 if(fullMessage.substring(4, fullMessage.indexOf("\r\n")).contains("?")){ token.setBusiCode(fullMessage.substring(4, fullMessage.indexOf("?"))); token.setBusiMessage(fullMessage.substring(fullMessage.indexOf("?")+1, this.getHTTPVersionPosition(fullMessage)-1)); //GET /login HTTP/1.1 }else{ token.setBusiCode(fullMessage.substring(4, this.getHTTPVersionPosition(fullMessage)-1)); } } }else if(fullMessage.startsWith("POST")){ //先获取到请求报文头中的Content-Length int contentLength = 0; if(fullMessage.contains("Content-Length:")){ String msgLenFlag = fullMessage.substring(fullMessage.indexOf("Content-Length:") + 15); if(msgLenFlag.contains("\r\n")){ contentLength = Integer.parseInt(msgLenFlag.substring(0, msgLenFlag.indexOf("\r\n")).trim()); if(contentLength > 0){ token.setBusiMessage(fullMessage.split("\r\n\r\n")[1]); } } } //POST /login?aa=bb&cc=dd&ee=ff HTTP/1.1 //特别说明一下:此时报文体本应该是空的,即Content-Length=0,但不能排除对方偏偏在报文体中也传了参数 //特别说明一下:所以这里的处理手段是busiMessage=请求URL中的参数串 + "`" + 报文体中的参数串(如果存在报文体的话) if(fullMessage.substring(5, fullMessage.indexOf("\r\n")).contains("?")){ token.setBusiCode(fullMessage.substring(5, fullMessage.indexOf("?"))); String urlParam = fullMessage.substring(fullMessage.indexOf("?")+1, this.getHTTPVersionPosition(fullMessage)-1); if(contentLength > 0){ token.setBusiMessage(urlParam + "`" + fullMessage.split("\r\n\r\n")[1]); }else{ token.setBusiMessage(urlParam); } //POST /login HTTP/1.1 }else{ token.setBusiCode(fullMessage.substring(5, this.getHTTPVersionPosition(fullMessage)-1)); } } out.write(token); return MessageDecoderResult.OK; }
Example 20
Source File: ProtocolDecoderImpl.java From game-server with MIT License | 2 votes |
/** * 不包括消息长度 * * @param length a int. * @param ib a {@link org.apache.mina.core.buffer.IoBuffer} object. * @param out a {@link org.apache.mina.filter.codec.ProtocolDecoderOutput} object. */ protected void decodeBytes(int length, IoBuffer ib, ProtocolDecoderOutput out) { byte[] bytes = new byte[length]; ib.get(bytes); out.write(bytes); }