Java Code Examples for org.apache.mina.core.buffer.IoBuffer#flip()
The following examples show how to use
org.apache.mina.core.buffer.IoBuffer#flip() .
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: MinaEncoder.java From grain with MIT License | 6 votes |
@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 2
Source File: ErrorGeneratingFilter.java From neoscada with Eclipse Public License 1.0 | 6 votes |
private IoBuffer insertBytesToNewIoBuffer(IoSession session, IoBuffer buffer) { if (insertByteProbability > rng.nextInt(1000)) { logger.info(buffer.getHexDump()); // where to insert bytes ? int pos = rng.nextInt(buffer.remaining()) - 1; // how many byte to insert ? int count = rng.nextInt(maxInsertByte - 1) + 1; IoBuffer newBuff = IoBuffer.allocate(buffer.remaining() + count); for (int i = 0; i < pos; i++) newBuff.put(buffer.get()); for (int i = 0; i < count; i++) { newBuff.put((byte) (rng.nextInt(256))); } while (buffer.remaining() > 0) { newBuff.put(buffer.get()); } newBuff.flip(); logger.info("Inserted " + count + " bytes."); logger.info(newBuff.getHexDump()); return newBuff; } return null; }
Example 3
Source File: ServerProtocolEncoder.java From seed with Apache License 2.0 | 5 votes |
@Override public void encode(IoSession session, String message, ProtocolEncoderOutput out) throws Exception { IoBuffer buffer = IoBuffer.allocate(100).setAutoExpand(true); buffer.putString(message, Charset.forName(SeedConstants.DEFAULT_CHARSET).newEncoder()); buffer.flip(); out.write(buffer); }
Example 4
Source File: DaveFilter.java From neoscada with Eclipse Public License 1.0 | 5 votes |
@Override public void sessionOpened ( final NextFilter nextFilter, final IoSession session ) throws Exception { logger.info ( "Sending hello" ); final byte[] data = new byte[] { // 0x00, 0x00, // (byte)0xff, (byte)0xff,// 0x00, 0x08, // plen 0x00, 0x00, // dlen (byte)0xf0, 0x00, // 0x00, 0x01, // 0x00, 0x01, // (byte)0xFF, (byte)0xFF // our PDU }; final IoBuffer buffer = IoBuffer.allocate ( 0 ).setAutoExpand ( true ); buffer.put ( PACKET_START_MAGIC ); buffer.put ( (byte)0x01 ); // type buffer.put ( data ); buffer.flip (); session.write ( new DataTPDU ( buffer ) ); nextFilter.sessionOpened ( session ); }
Example 5
Source File: VmPipeFilterChain.java From neoscada with Eclipse Public License 1.0 | 5 votes |
private Object getMessageCopy(Object message) { Object messageCopy = message; if (message instanceof IoBuffer) { IoBuffer rb = (IoBuffer) message; rb.mark(); IoBuffer wb = IoBuffer.allocate(rb.remaining()); wb.put(rb); wb.flip(); rb.reset(); messageCopy = wb; } return messageCopy; }
Example 6
Source File: StartBrowse.java From neoscada with Eclipse Public License 1.0 | 5 votes |
@Override public IoBuffer encodeMessage ( final BinaryContext context, final Object objectMessage ) throws Exception { final IoBuffer data = IoBuffer.allocate ( 5 ); data.putInt ( MESSAGE_CODE ); data.put ( (byte)0 ); // number of fields data.flip (); return data; }
Example 7
Source File: IoSessionOutputStream.java From cxf with Apache License 2.0 | 5 votes |
@Override public void write(int b) throws IOException { IoBuffer buf = IoBuffer.allocate(1); buf.put((byte) b); buf.flip(); write(buf); }
Example 8
Source File: BaseRTMPTConnection.java From red5-client with Apache License 2.0 | 5 votes |
protected IoBuffer foldPendingMessages(int targetSize) { if (pendingMessages.isEmpty()) { return null; } IoBuffer result = IoBuffer.allocate(2048); result.setAutoExpand(true); // We'll have to create a copy here to avoid endless recursion List<Packet> toNotify = new LinkedList<Packet>(); while (!pendingMessages.isEmpty()) { PendingData pendingMessage = pendingMessages.remove(); result.put(pendingMessage.getBuffer()); if (pendingMessage.getPacket() != null) { toNotify.add(pendingMessage.getPacket()); } if ((result.position() > targetSize)) { break; } } for (Packet message : toNotify) { try { handler.messageSent(this, message); } catch (Exception e) { log.error("Could not notify stream subsystem about sent message", e); } } result.flip(); writtenBytes.addAndGet(result.limit()); return result; }
Example 9
Source File: ModbusExport.java From neoscada with Eclipse Public License 1.0 | 5 votes |
protected Object makeData ( final BaseMessage message, final IoBuffer data ) { data.flip (); logger.trace ( "Create data message - data: {}", data ); //$NON-NLS-1$ return new ReadResponse ( message.getTransactionId (), message.getUnitIdentifier (), message.getFunctionCode (), data ); }
Example 10
Source File: HexTool.java From mapleLemon with GNU General Public License v2.0 | 5 votes |
public static String toString(IoBuffer buf) { buf.flip(); byte[] arr = new byte[buf.remaining()]; buf.get(arr); String ret = toString(arr); buf.flip(); buf.put(arr); return ret; }
Example 11
Source File: AbstractTcpClient.java From util with Apache License 2.0 | 5 votes |
/** * 功能:向服务端传送数据。 * @author 朱志杰 QQ:862990787 * Sep 5, 2013 10:30:05 AM * @param str */ public void write(String str){ TcpClientTest t=new TcpClientTest(); IoBuffer buffer = IoBuffer.allocate(str.getBytes().length); buffer.put(str.getBytes()); buffer.flip(); t.write(buffer); }
Example 12
Source File: BufferedWriteFilter.java From neoscada with Eclipse Public License 1.0 | 5 votes |
/** * Internal method that actually flushes the buffered data. * * @param nextFilter the {@link NextFilter} of this filter * @param session the session where buffer will be written * @param buf the data to write * @throws Exception if a write operation fails */ private void internalFlush(NextFilter nextFilter, IoSession session, IoBuffer buf) throws Exception { IoBuffer tmp = null; synchronized (buf) { buf.flip(); tmp = buf.duplicate(); buf.clear(); } logger.debug("Flushing buffer: {}", tmp); nextFilter.filterWrite(session, new DefaultWriteRequest(tmp)); }
Example 13
Source File: TestNTGVisitorPositive.java From sailfish-core with Apache License 2.0 | 4 votes |
/** * Test case Integer data type */ @Test public void testNTGVisitorEncode_IntegerField() { Integer value = Integer.MAX_VALUE; int offset = 0 ; int length = 4; String fldName = "FieldInteger"; String fldNamespace = "NTG"; String fldDescr = "Description " + fldName; Map<String, IAttributeStructure> protocolAttributes = new HashMap<>(); protocolAttributes.put(NTGProtocolAttribute.Offset.toString(), new AttributeStructure( NTGProtocolAttribute.Offset.toString(), Integer.toString(offset), offset, JavaType.JAVA_LANG_INTEGER)); protocolAttributes.put(NTGProtocolAttribute.Format.toString(), new AttributeStructure( NTGProtocolAttribute.Format.toString(), NTGFieldFormat.S.toString(), NTGFieldFormat.S.toString(), JavaType.JAVA_LANG_STRING)); protocolAttributes.put(NTGProtocolAttribute.Length.toString(), new AttributeStructure( NTGProtocolAttribute.Length.toString(), Integer.toString(length), length, JavaType.JAVA_LANG_INTEGER)); IFieldStructure mockSimpleField = new FieldStructure(fldName, fldNamespace, fldDescr, null, protocolAttributes, null, JavaType.JAVA_LANG_INTEGER, false, false, false, null); ByteBuffer bb = ByteBuffer.wrap(new byte[length]); bb.order( ByteOrder.LITTLE_ENDIAN); bb.putInt(value); try { IFieldStructure fldStruct = new FieldStructure(fldName, fldNamespace, fldDescr, null, protocolAttributes, null, JavaType.JAVA_LANG_INTEGER, true, false, false, value.toString()) ; NTGVisitorEncode visitor = new NTGVisitorEncode(); visitor.visit(mockSimpleField.getName(), value, fldStruct, false); IoBuffer ioBuffer = visitor.getBuffer(); for( int i = 0 ; i < bb.array().length; i++ ) { logger.trace("Symbol at index [{}]. Expected [{}], actual [{}].", i, bb.array()[i], ioBuffer.array()[i]); Assert.assertEquals(String.format("NTGVisitor.visit(Integer) failed. " + "Error at index [%d]. Expected [%x], actual [%x].", i, bb.array()[i], ioBuffer.array()[i]), bb.array()[i], ioBuffer.array()[i]); } IoBuffer copy = ioBuffer.duplicate(); copy.order(ByteOrder.LITTLE_ENDIAN); copy.flip(); Integer restored = copy.getInt(); Assert.assertEquals( value, restored ); logger.info("Visitor: method visit(Integer) PASSED."); } catch(Exception ex) { ex.printStackTrace(); logger.error(ex.getMessage(),ex); Assert.fail(ex.getMessage()); } }
Example 14
Source File: ConnectorTest.java From game-server with MIT License | 4 votes |
private void testConnector0(IoSession session) throws InterruptedException { EchoConnectorHandler handler = (EchoConnectorHandler) session .getHandler(); IoBuffer readBuf = handler.readBuf; readBuf.clear(); WriteFuture writeFuture = null; for (int i = 0; i < COUNT; i++) { IoBuffer buf = IoBuffer.allocate(DATA_SIZE); buf.limit(DATA_SIZE); fillWriteBuffer(buf, i); buf.flip(); writeFuture = session.write(buf); if (session.getService().getTransportMetadata().isConnectionless()) { // This will align message arrival order in connectionless transport types waitForResponse(handler, (i + 1) * DATA_SIZE); } } writeFuture.awaitUninterruptibly(); waitForResponse(handler, DATA_SIZE * COUNT); // Assert data //// Please note that BufferOverflowException can be thrown //// in SocketIoProcessor if there was a read timeout because //// we share readBuf. readBuf.flip(); LOGGER.info("readBuf: " + readBuf); assertEquals(DATA_SIZE * COUNT, readBuf.remaining()); IoBuffer expectedBuf = IoBuffer.allocate(DATA_SIZE * COUNT); for (int i = 0; i < COUNT; i++) { expectedBuf.limit((i + 1) * DATA_SIZE); fillWriteBuffer(expectedBuf, i); } expectedBuf.position(0); isEquals(expectedBuf, readBuf); }
Example 15
Source File: TestNTGVisitorPositive.java From sailfish-core with Apache License 2.0 | 4 votes |
/** * Test case Double data type */ @Test public void testNTGVisitorEncode_DoubleField() { Double value = (double) (Integer.MAX_VALUE/10000); int offset = 0 ; int length = 8; String fldName = "FieldDouble"; String fldNamespace = "NTG"; String fldDescr = "Description " + fldName; Map<String, IAttributeStructure> protocolAttributes = new HashMap<>(); protocolAttributes.put(NTGProtocolAttribute.Offset.toString(), new AttributeStructure( NTGProtocolAttribute.Offset.toString(), Integer.toString(offset), offset, JavaType.JAVA_LANG_INTEGER)); protocolAttributes.put(NTGProtocolAttribute.Format.toString(), new AttributeStructure( NTGProtocolAttribute.Format.toString(), NTGFieldFormat.S.toString(), NTGFieldFormat.S.toString(), JavaType.JAVA_LANG_STRING)); protocolAttributes.put(NTGProtocolAttribute.Length.toString(), new AttributeStructure( NTGProtocolAttribute.Length.toString(), Integer.toString(length), length, JavaType.JAVA_LANG_INTEGER)); IFieldStructure mockSimpleField = new FieldStructure(fldName, fldNamespace, fldDescr, null, protocolAttributes, null, JavaType.JAVA_LANG_DOUBLE, false, false, false, null); ByteBuffer bb = ByteBuffer.wrap(new byte[length]); bb.order( ByteOrder.LITTLE_ENDIAN); BigDecimal baseValue = new BigDecimal( value ); BigDecimal baseScaled = baseValue.setScale( 8, BigDecimal.ROUND_HALF_UP ); BigDecimal multiplied = baseScaled.multiply( new BigDecimal(Math.pow(10, 8))) ; bb.putLong(multiplied.longValue()); try { IFieldStructure fldStruct = new FieldStructure(fldName, fldNamespace, fldDescr, null, protocolAttributes, null, JavaType.JAVA_LANG_DOUBLE, true, false, false, value.toString()) ; NTGVisitorEncode visitor = new NTGVisitorEncode(); visitor.visit(mockSimpleField.getName(), value, fldStruct, false); IoBuffer ioBuffer = visitor.getBuffer(); for( int i = 0 ; i < bb.array().length; i++ ) { logger.trace("Symbol at index [{}]. Expected [{}], actual [{}].", i, bb.array()[i], ioBuffer.array()[i]); Assert.assertEquals(String.format("NTGVisitor.visit(Double) failed. " + "Error at index [%d]. Expected [%x], actual [%x].", i, bb.array()[i], ioBuffer.array()[i]), bb.array()[i], ioBuffer.array()[i]); } IoBuffer copy = ioBuffer.duplicate(); copy.order(ByteOrder.LITTLE_ENDIAN); copy.flip(); Double restored = copy.getLong() /Math.pow(10, 8); Assert.assertEquals( value, restored ); logger.info("Visitor: method visit(Double) PASSED."); } catch(Exception ex) { ex.printStackTrace(); logger.error(ex.getMessage(),ex); Assert.fail(ex.getMessage()); } }
Example 16
Source File: TextLineDecoder.java From neoscada with Eclipse Public License 1.0 | 4 votes |
/** * 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 17
Source File: RTMPMinaProtocolDecoder.java From red5-server-common with Apache License 2.0 | 4 votes |
/** {@inheritDoc} */ public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws ProtocolCodecException { // get the connection from the session String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID); log.trace("Session id: {}", sessionId); // connection verification routine @SuppressWarnings("unchecked") IConnectionManager<RTMPConnection> connManager = (IConnectionManager<RTMPConnection>) ((WeakReference<?>) session.getAttribute(RTMPConnection.RTMP_CONN_MANAGER)).get(); RTMPConnection conn = (RTMPConnection) connManager.getConnectionBySessionId(sessionId); RTMPConnection connLocal = (RTMPConnection) Red5.getConnectionLocal(); if (connLocal == null || !conn.getSessionId().equals(connLocal.getSessionId())) { if (log.isDebugEnabled() && connLocal != null) { log.debug("Connection local didn't match session"); } } if (conn != null) { // set the connection to local if its referred to by this session Red5.setConnectionLocal(conn); // copy data range from incoming if (log.isTraceEnabled()) { log.trace("Incoming: in.position {}, in.limit {}, in.remaining {}", new Object[] { in.position(), in.limit(), in.remaining() }); } byte[] arr = new byte[in.remaining()]; in.get(arr); // create a buffer and store it on the session IoBuffer buf = (IoBuffer) session.getAttribute("buffer"); if (buf == null) { buf = IoBuffer.allocate(arr.length); buf.setAutoExpand(true); session.setAttribute("buffer", buf); } // copy incoming into buffer buf.put(arr); // flip so we can read buf.flip(); if (log.isTraceEnabled()) { //log.trace("Buffer before: {}", Hex.encodeHexString(arr)); log.trace("Buffers info before: buf.position {}, buf.limit {}, buf.remaining {}", new Object[] { buf.position(), buf.limit(), buf.remaining() }); } // get the connections decoder lock final Semaphore lock = conn.getDecoderLock(); try { // acquire the decoder lock lock.acquire(); // construct any objects from the decoded bugger List<?> objects = decoder.decodeBuffer(conn, buf); log.trace("Decoded: {}", objects); if (objects != null) { int writeCount = 0; for (Object object : objects) { out.write(object); writeCount++; } log.trace("Wrote {} objects", writeCount); } } catch (Exception e) { log.error("Error during decode", e); } finally { lock.release(); // clear local Red5.setConnectionLocal(null); } if (log.isTraceEnabled()) { //log.trace("Buffer after: {}", Hex.encodeHexString(Arrays.copyOfRange(buf.array(), buf.position(), buf.limit()))); log.trace("Buffers info after: buf.position {}, buf.limit {}, buf.remaining {}", new Object[] { buf.position(), buf.limit(), buf.remaining() }); } } else { log.debug("Closing and skipping decode for unregistered connection: {}", sessionId); session.closeNow(); log.debug("Session closing: {} reading: {} writing: {}", session.isClosing(), session.isReadSuspended(), session.isWriteSuspended()); } }
Example 18
Source File: HandshakeRequest.java From red5-websocket with Apache License 2.0 | 4 votes |
public HandshakeRequest(IoBuffer req) { this.req = req; req.flip(); }
Example 19
Source File: RTMPMinaCodecFactory.java From red5-client with Apache License 2.0 | 4 votes |
@Override public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws ProtocolCodecException { log.trace("decode buffer position: {}", in.position()); // 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); Red5.setConnectionLocal(conn); byte[] arr = new byte[in.remaining()]; in.get(arr); // create a buffer and store it on the session IoBuffer buf = (IoBuffer) session.getAttribute("buffer"); if (buf == null) { buf = IoBuffer.allocate(arr.length); buf.setAutoExpand(true); session.setAttribute("buffer", buf); } // copy incoming into buffer buf.put(arr); // flip so we can read buf.flip(); final Semaphore lock = conn.getDecoderLock(); try { // acquire the decoder lock lock.acquire(); // construct any objects from the decoded buffer List<?> objects = getDecoder().decodeBuffer(conn, buf); log.trace("Decoded: {}", objects); if (objects != null) { for (Object object : objects) { log.trace("Writing {} to decoder output: {}", object, out); out.write(object); } } log.trace("Input buffer position: {}", in.position()); } catch (Exception e) { log.error("Error during decode", e); } finally { lock.release(); Red5.setConnectionLocal(null); } }
Example 20
Source File: MP3Reader.java From red5-io with Apache License 2.0 | 4 votes |
/** * Creates file metadata object * * @return Tag */ private ITag createFileMeta() { log.debug("createFileMeta"); // create tag for onMetaData event IoBuffer in = IoBuffer.allocate(1024); in.setAutoExpand(true); Output out = new Output(in); out.writeString("onMetaData"); Map<Object, Object> props = new HashMap<Object, Object>(); props.put("audiocodecid", IoConstants.FLAG_FORMAT_MP3); props.put("canSeekToEnd", true); // set id3 meta data if it exists if (metaData != null) { if (metaData.artist != null) { props.put("artist", metaData.artist); } if (metaData.album != null) { props.put("album", metaData.album); } if (metaData.songName != null) { props.put("songName", metaData.songName); } if (metaData.genre != null) { props.put("genre", metaData.genre); } if (metaData.year != null) { props.put("year", metaData.year); } if (metaData.track != null) { props.put("track", metaData.track); } if (metaData.comment != null) { props.put("comment", metaData.comment); } if (metaData.duration != null) { props.put("duration", metaData.duration); } if (metaData.channels != null) { props.put("channels", metaData.channels); } if (metaData.sampleRate != null) { props.put("samplerate", metaData.sampleRate); } if (metaData.hasCoverImage()) { Map<Object, Object> covr = new HashMap<>(1); covr.put("covr", new Object[] { metaData.getCovr() }); props.put("tags", covr); } //clear meta for gc metaData = null; } log.debug("Metadata properties map: {}", props); // check for duration if (!props.containsKey("duration")) { // generate it from framemeta if (frameMeta != null) { props.put("duration", frameMeta.timestamps[frameMeta.timestamps.length - 1] / 1000.0); } else { log.debug("Frame meta was null"); } } // set datarate if (dataRate > 0) { props.put("audiodatarate", dataRate); } out.writeMap(props); in.flip(); // meta-data ITag result = new Tag(IoConstants.TYPE_METADATA, 0, in.limit(), null, prevSize); result.setBody(in); return result; }