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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#setAutoExpand() . 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: ByteArray.java    From red5-io with Apache License 2.0 6 votes vote down vote up
/**
 * Decompress contents using zlib.
 */
public void uncompress() {
    data.position(0);
    byte[] buffer = new byte[8192];
    IoBuffer tmp = IoBuffer.allocate(0);
    tmp.setAutoExpand(true);
    try (InflaterInputStream inflater = new InflaterInputStream(data.asInputStream())) {
        while (inflater.available() > 0) {
            int decompressed = inflater.read(buffer);
            if (decompressed <= 0) {
                // Finished decompression
                break;
            }
            tmp.put(buffer, 0, decompressed);
        }
    } catch (IOException e) {
        tmp.free();
        throw new RuntimeException("could not uncompress data", e);
    }
    data.free();
    data = tmp;
    data.flip();
    prepareIO();
}
 
Example 2
Source File: ProtocolEncoderImpl.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
protected IoBuffer createMessage ( final IoSession session, final byte command, final boolean longMessage )
{
    final IoBuffer data = IoBuffer.allocate ( 3 );
    data.setAutoExpand ( true );

    if ( Sessions.isLittleEndian ( session ) )
    {
        data.order ( ByteOrder.LITTLE_ENDIAN );
    }

    data.put ( (byte)0x12 );
    data.put ( (byte)0x02 );
    data.put ( command );
    if ( longMessage )
    {
        data.putShort ( (short)0 );
    }
    return data;
}
 
Example 3
Source File: ObjectSerializationEncoder.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    if (!(message instanceof Serializable)) {
        throw new NotSerializableException();
    }

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

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

    buf.flip();
    out.write(buf);
}
 
Example 4
Source File: TPKTFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the session buffer and create one of necessary
 * 
 * @param session
 *            the session
 * @return the session buffer
 */
private IoBuffer getSessionBuffer ( final IoSession session )
{
    IoBuffer buffer = (IoBuffer)session.getAttribute ( SESSION_BUFFER_ATTR );
    if ( buffer == null )
    {
        buffer = IoBuffer.allocate ( 0 );
        buffer.setAutoExpand ( true );
        session.setAttribute ( SESSION_BUFFER_ATTR, buffer );
    }
    return buffer;
}
 
Example 5
Source File: ObjectSerializationOutputStream.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public void writeObject(Object obj) throws IOException {
    IoBuffer buf = IoBuffer.allocate(64, false);
    buf.setAutoExpand(true);
    buf.putObject(obj);

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

    out.write(buf.array(), 0, buf.position());
}
 
Example 6
Source File: ScreenVideo2.java    From red5-io with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public IoBuffer getKeyframe() {
    IoBuffer result = IoBuffer.allocate(blockDataSize + 11);
    result.setAutoExpand(true);
    // Header
    result.put((byte) (FLV_FRAME_KEY | VideoCodec.SCREEN_VIDEO2.getId()));
    // Frame size
    result.putShort((short) widthInfo);
    result.putShort((short) heightInfo);
    // reserved (6) has iframeimage (1) has palleteinfo (1)
    result.put(specInfo1);
    // Get compressed blocks
    byte[] tmpData = new byte[blockDataSize];
    int pos = 0;
    for (int idx = 0; idx < blockCount; idx++) {
        int size = blockSize[idx];
        if (size == 0) {
            // this should not happen: no data for this block
            return null;
        }
        result.putShort((short) (size + 1));
        // IMAGEFORMAT
        // reserved(3) color depth(2) has diff blocks(1)
        // ZlibPrimeCompressCurrent(1) ZlibPrimeCompressPrevious (1)
        result.put(specInfo2);
        System.arraycopy(blockData, pos, tmpData, 0, size);
        result.put(tmpData, 0, size);
        pos += blockDataSize;
    }
    result.rewind();
    return result;
}
 
Example 7
Source File: NIOConnection.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void deliver(Packet packet) throws UnauthorizedException {
    if (isClosed()) {
        backupDeliverer.deliver(packet);
    }
    else {
        boolean errorDelivering = false;
        IoBuffer buffer = IoBuffer.allocate(4096);
        buffer.setAutoExpand(true);
        try {
            buffer.putString(packet.getElement().asXML(), encoder.get());
            if (flashClient) {
                buffer.put((byte) '\0');
            }
            buffer.flip();
            
            ioSessionLock.lock();
            try {
                ioSession.write(buffer);
            } finally {
                ioSessionLock.unlock();
            }
        }
        catch (Exception e) {
            Log.debug("Error delivering packet:\n" + packet, e);
            errorDelivering = true;
        }
        if (errorDelivering) {
            close();
            // Retry sending the packet again. Most probably if the packet is a
            // Message it will be stored offline
            backupDeliverer.deliver(packet);
        }
        else {
            session.incrementServerPacketCount();
        }
    }
}
 
Example 8
Source File: MessageChannelCodecFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private Frame encodeCloseMessage ( final IoSession session, final CloseMessage message ) throws CharacterCodingException
{
    final IoBuffer data = IoBuffer.allocate ( 0 );
    data.setAutoExpand ( true );
    data.putString ( message.getMessage (), getCharsetEncoder ( session ) );
    data.put ( (byte)0x00 );
    data.putInt ( message.getCode () );

    data.flip ();

    return new Frame ( FrameType.CLOSE, data );
}
 
Example 9
Source File: BaseRTMPTConnection.java    From red5-client with Apache License 2.0 5 votes vote down vote up
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 10
Source File: MinaDecoder.java    From grain with MIT License 5 votes vote down vote up
private void storeRemainingInSession(IoBuffer buf, IoSession session) {
	IoBuffer remainingBuf = IoBuffer.allocate(buf.capacity());
	remainingBuf.setAutoExpand(true);
	remainingBuf.order(buf.order());
	remainingBuf.put(buf);
	session.setAttribute(BUFFER, remainingBuf);
}
 
Example 11
Source File: NIOConnection.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void deliverRawText0(String text){
    boolean errorDelivering = false;
    IoBuffer buffer = IoBuffer.allocate(text.length());
    buffer.setAutoExpand(true);
    try {
        //Charset charset = Charset.forName(CHARSET);
        //buffer.putString(text, charset.newEncoder());
        buffer.put(text.getBytes(StandardCharsets.UTF_8));
        if (flashClient) {
            buffer.put((byte) '\0');
        }
        buffer.flip();
        ioSessionLock.lock();
        try {
            ioSession.write(buffer);
        }
        finally {
            ioSessionLock.unlock();
        }
    }
    catch (Exception e) {
        Log.debug("Error delivering raw text:\n" + text, e);
        errorDelivering = true;
    }

    // Attempt to close the connection if delivering text fails.
    if (errorDelivering) {
        close();
    }
}
 
Example 12
Source File: ModbusRtuEncoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@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 );
}
 
Example 13
Source File: MinaProtocolEncoder.java    From jforgame with Apache License 2.0 5 votes vote down vote up
private IoBuffer writeMessage(Message message) {
		// ----------------消息协议格式-------------------------
		// packetLength | moduleId | cmd  | body
		// int             short     byte  byte[]

		IoBuffer buffer = IoBuffer.allocate(CodecContext.WRITE_CAPACITY);
		buffer.setAutoExpand(true);

		// 写入具体消息的内容
		IMessageEncoder msgEncoder = SerializerHelper.getInstance().getEncoder();
		byte[] body = msgEncoder.writeMessageBody(message);
		// 消息元信息常量3表示消息body前面的两个字段,一个short表示module,一个byte表示cmd,
		final int metaSize = 3;
		// 消息内容长度
		buffer.putInt(body.length + metaSize);
		short moduleId = message.getModule();
		byte cmd = message.getCmd();
		// 写入module类型
		buffer.putShort(moduleId);
		// 写入cmd类型
		buffer.put(cmd);
	
		buffer.put(body);
//		// 回到buff字节数组头部
		buffer.flip();

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

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

    buf.flip();
    out.write(buf);
}
 
Example 15
Source File: AACAudio.java    From red5-io with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public IoBuffer getDecoderConfiguration() {
    if (blockDataAACDCR == null) {
        return null;
    }
    IoBuffer result = IoBuffer.allocate(4);
    result.setAutoExpand(true);
    result.put(blockDataAACDCR);
    result.rewind();
    return result;
}
 
Example 16
Source File: ITCHVisitorEncode.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public ITCHVisitorEncode(IoBuffer buffer, ByteOrder byteOrder) {
	this.buffer = buffer;
	this.byteOrder = byteOrder;
	buffer.setAutoExpand(true);
	buffer.order(byteOrder);
}
 
Example 17
Source File: WebSocketServerTest.java    From red5-websocket with Apache License 2.0 4 votes vote down vote up
public void connect() {
    try {
        ConnectFuture future = connector.connect(new InetSocketAddress(host, port));
        future.awaitUninterruptibly();
        session = future.getSession();
        // write the handshake
        IoBuffer buf = IoBuffer.allocate(308);
        buf.setAutoExpand(true);
        buf.put("GET /default?encoding=text HTTP/1.1".getBytes());
        buf.put(Constants.CRLF);
        buf.put("Upgrade: websocket".getBytes());
        buf.put(Constants.CRLF);
        buf.put("Connection: Upgrade".getBytes());
        buf.put(Constants.CRLF);
        buf.put(String.format("%s: http://%s:%d", Constants.HTTP_HEADER_ORIGIN, host, port).getBytes());
        buf.put(Constants.CRLF);
        buf.put(String.format("%s: %s:%d", Constants.HTTP_HEADER_HOST, host, port).getBytes());
        buf.put(Constants.CRLF);
        buf.put(String.format("%s: dGhlIHNhbXBsZSBub25jZQ==", Constants.WS_HEADER_KEY).getBytes());
        buf.put(Constants.CRLF);
        buf.put("Sec-WebSocket-Version: 13".getBytes());
        buf.put(Constants.CRLF);
        if (cookie != null) {
            buf.put(String.format("Cookie: monster=%s", cookie).getBytes());
            buf.put(Constants.CRLF);
        }
        buf.put(Constants.CRLF);
        if (log.isDebugEnabled()) {
            log.debug("Handshake request length: {}", buf.limit());
        }
        HandshakeRequest request = new HandshakeRequest(buf);
        session.write(request);
        // create connection 
        WebSocketConnection conn = new WebSocketConnection(session);
        conn.setType(ConnectionType.WEB);
        conn.setConnected();
        // add connection to client side session
        session.setAttribute(Constants.CONNECTION, conn);
    } catch (Exception e) {
        log.error("Connection error", e);
    }
}
 
Example 18
Source File: RTMPClientProtocolEncoder.java    From red5-client with Apache License 2.0 4 votes vote down vote up
/**
 * Encode notification event and fill given byte buffer.
 *
 * @param out
 *            Byte buffer to fill
 * @param command
 *            Notification event
 */
@Override
protected void encodeCommand(IoBuffer out, ICommand command) {
    log.debug("encodeCommand - command: {}", command);
    RTMPConnection conn = (RTMPConnection) Red5.getConnectionLocal();
    Output output = new org.red5.io.amf.Output(out);
    final IServiceCall call = command.getCall();
    final boolean isPending = (call.getStatus() == Call.STATUS_PENDING);
    log.debug("Call: {} pending: {}", call, isPending);
    if (!isPending) {
        log.debug("Call has been executed, send result");
        Serializer.serialize(output, call.isSuccess() ? "_result" : "_error");
    } else {
        log.debug("This is a pending call, send request");
        // for request we need to use AMF3 for client mode if the connection is AMF3
        if (conn.getEncoding() == Encoding.AMF3) {
            output = new org.red5.io.amf3.Output(out);
        }
        final String action = (call.getServiceName() == null) ? call.getServiceMethodName() : call.getServiceName() + '.' + call.getServiceMethodName();
        Serializer.serialize(output, action);
    }
    if (command instanceof Invoke) {
        Serializer.serialize(output, Integer.valueOf(command.getTransactionId()));
        Serializer.serialize(output, command.getConnectionParams());
    }
    if (call.getServiceName() == null && "connect".equals(call.getServiceMethodName())) {
        // response to initial connect, always use AMF0
        output = new org.red5.io.amf.Output(out);
    } else {
        if (conn.getEncoding() == Encoding.AMF3) {
            output = new org.red5.io.amf3.Output(out);
        } else {
            output = new org.red5.io.amf.Output(out);
        }
    }
    if (!isPending && (command instanceof Invoke)) {
        IPendingServiceCall pendingCall = (IPendingServiceCall) call;
        if (!call.isSuccess()) {
            log.debug("Call was not successful");
            StatusObject status = generateErrorResult(StatusCodes.NC_CALL_FAILED, call.getException());
            pendingCall.setResult(status);
        }
        Object res = pendingCall.getResult();
        log.debug("Writing result: {}", res);
        Serializer.serialize(output, res);
    } else {
        log.debug("Writing params");
        final Object[] args = call.getArguments();
        if (args != null) {
            for (Object element : args) {
                Serializer.serialize(output, element);
            }
        }
    }
    if (command.getData() != null) {
        out.setAutoExpand(true);
        out.put(command.getData());
    }
}
 
Example 19
Source File: MP3Reader.java    From red5-io with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 20
Source File: MP4Reader.java    From red5-io with Apache License 2.0 4 votes vote down vote up
/**
 * Tag sequence MetaData, Video config, Audio config, remaining audio and video
 * 
 * Packet prefixes: 17 00 00 00 00 = Video extra data (first video packet) 17 01 00 00 00 = Video keyframe 27 01 00 00 00 = Video
 * interframe af 00 ... 06 = Audio extra data (first audio packet) af 01 = Audio frame
 * 
 * Audio extra data(s): af 00 = Prefix 11 90 4f 14 = AAC Main = aottype 0 // 11 90 12 10 = AAC LC = aottype 1 13 90 56 e5 a5 48 00 =
 * HE-AAC SBR = aottype 2 06 = Suffix
 * 
 * Still not absolutely certain about this order or the bytes - need to verify later
 */
private void createPreStreamingTags(int timestamp, boolean clear) {
    log.debug("Creating pre-streaming tags");
    if (clear) {
        firstTags.clear();
    }
    ITag tag = null;
    IoBuffer body = null;
    if (hasVideo) {
        //video tag #1
        body = IoBuffer.allocate(41);
        body.setAutoExpand(true);
        body.put(PREFIX_VIDEO_CONFIG_FRAME); //prefix
        if (videoDecoderBytes != null) {
            //because of other processing we do this check
            if (log.isDebugEnabled()) {
                log.debug("Video decoder bytes: {}", HexDump.byteArrayToHexString(videoDecoderBytes));
            }
            body.put(videoDecoderBytes);
        }
        tag = new Tag(IoConstants.TYPE_VIDEO, timestamp, body.position(), null, 0);
        body.flip();
        tag.setBody(body);
        //add tag
        firstTags.add(tag);
    }
    // TODO: Handle other mp4 container audio codecs like mp3
    // mp3 header magic number ((int & 0xffe00000) == 0xffe00000) 
    if (hasAudio) {
        //audio tag #1
        if (audioDecoderBytes != null) {
            //because of other processing we do this check
            if (log.isDebugEnabled()) {
                log.debug("Audio decoder bytes: {}", HexDump.byteArrayToHexString(audioDecoderBytes));
            }
            body = IoBuffer.allocate(audioDecoderBytes.length + 3);
            body.setAutoExpand(true);
            body.put(PREFIX_AUDIO_CONFIG_FRAME); //prefix
            body.put(audioDecoderBytes);
            body.put((byte) 0x06); //suffix
            tag = new Tag(IoConstants.TYPE_AUDIO, timestamp, body.position(), null, 0);
            body.flip();
            tag.setBody(body);
            //add tag
            firstTags.add(tag);
        } else {
            log.info("Audio decoder bytes were not available");
        }
    }
}