Java Code Examples for org.apache.mina.core.buffer.IoBuffer

The following are top voted examples for showing how to use org.apache.mina.core.buffer.IoBuffer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: directory-ldap-api   File: LdapProtocolDecoder.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void decode( IoSession session, IoBuffer in, ProtocolDecoderOutput out ) throws Exception
{
    @SuppressWarnings("unchecked")
    LdapMessageContainer<MessageDecorator<? extends Message>> messageContainer =
        ( LdapMessageContainer<MessageDecorator<? extends Message>> )
        session.getAttribute( LdapDecoder.MESSAGE_CONTAINER_ATTR );

    if ( session.containsAttribute( LdapDecoder.MAX_PDU_SIZE_ATTR ) )
    {
        int maxPDUSize = ( Integer ) session.getAttribute( LdapDecoder.MAX_PDU_SIZE_ATTR );

        messageContainer.setMaxPDUSize( maxPDUSize );
    }

    List<Message> decodedMessages = new ArrayList<>();
    ByteBuffer buf = in.buf();

    decode( buf, messageContainer, decodedMessages );

    for ( Message message : decodedMessages )
    {
        out.write( message );
    }
}
 
Example 2
Project: neoscada   File: DefaultBinaryContext.java   View source code 6 votes vote down vote up
@Override
public void encodeDoubleCollection ( final IoBuffer buffer, final byte fieldNumber, final Collection<Double> data ) throws Exception
{
    buffer.put ( fieldNumber );
    if ( data != null )
    {
        buffer.put ( TYPE_DOUBLE_LIST );
        buffer.putInt ( data.size () );
        for ( final Double entry : data )
        {
            buffer.putDouble ( entry );
        }
    }
    else
    {
        buffer.put ( TYPE_NULL );
    }
}
 
Example 3
Project: neoscada   File: DefaultBinaryContext.java   View source code 6 votes vote down vote up
private <T extends Collection<Map<String, String>>> T decodePropertiesCollection ( final IoBuffer buffer, final CollectionAllocator<Map<String, String>, T> allactor ) throws Exception
{
    final byte type = checkType ( buffer, TYPE_PROPERTIES_LIST, true );

    if ( type == TYPE_NULL )
    {
        return null;
    }
    else
    {
        final int items = buffer.getInt ();
        final T result = allactor.allocate ( items );
        fillPropertiesCollection ( buffer, items, result );
        return result;
    }
}
 
Example 4
Project: neoscada   File: DefaultIoEventSizeEstimator.java   View source code 6 votes vote down vote up
/**
 * Estimate the size of an Objecr in number of bytes
 * @param message The object to estimate
 * @return The estimated size of the object
 */
public int estimateSize(Object message) {
    if (message == null) {
        return 8;
    }

    int answer = 8 + estimateSize(message.getClass(), null);

    if (message instanceof IoBuffer) {
        answer += ((IoBuffer) message).remaining();
    } else if (message instanceof WriteRequest) {
        answer += estimateSize(((WriteRequest) message).getMessage());
    } else if (message instanceof CharSequence) {
        answer += ((CharSequence) message).length() << 1;
    } else if (message instanceof Iterable) {
        for (Object m : (Iterable<?>) message) {
            answer += estimateSize(m);
        }
    }

    return align(answer);
}
 
Example 5
Project: neoscada   File: ModbusRtuDecoder.java   View source code 6 votes vote down vote up
@Override
public synchronized void decode ( final IoSession session, final IoBuffer in, final ProtocolDecoderOutput out ) throws Exception
{
    IoBuffer currentFrame = (IoBuffer)session.getAttribute ( SESSION_KEY_CURRENT_FRAME );
    if ( currentFrame == null )
    {
        currentFrame = IoBuffer.allocate ( Constants.MAX_PDU_SIZE + Constants.RTU_HEADER_SIZE );
        session.setAttribute ( SESSION_KEY_CURRENT_FRAME, currentFrame );
    }
    logger.trace ( "decode () current frame = {} data = {}", currentFrame.toString (), currentFrame.getHexDump () );
    logger.trace ( "decode () new     frame = {} data = {}", in.toString (), in.getHexDump () );

    final int expectedSize = currentFrame.position () + in.remaining ();
    if ( expectedSize > MAX_SIZE + 1 )
    {
        throw new ModbusProtocolError ( String.format ( "received size (%s) exceeds max size (%s)", expectedSize, MAX_SIZE ) );
    }
    currentFrame.put ( in );

    tick ( session, out );
}
 
Example 6
Project: neoscada   File: IntegerDecodingState.java   View source code 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 7
Project: neoscada   File: DefaultIoFilterChain.java   View source code 6 votes vote down vote up
@Override
public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
    AbstractIoSession s = (AbstractIoSession) session;
    if (!(message instanceof IoBuffer)) {
        s.increaseReadMessages(System.currentTimeMillis());
    } else if (!((IoBuffer) message).hasRemaining()) {
        s.increaseReadMessages(System.currentTimeMillis());
    }

    try {
        session.getHandler().messageReceived(s, message);
    } finally {
        if (s.getConfig().isUseReadOperation()) {
            s.offerReadFuture(message);
        }
    }
}
 
Example 8
Project: neoscada   File: SizeTest.java   View source code 6 votes vote down vote up
public long getSize ()
{
    long size = 0;
    for ( final Object data : this.queue )
    {
        if ( data instanceof IoBuffer )
        {
            size += ( (IoBuffer)data ).remaining ();
        }
        else
        {
            throw new IllegalArgumentException ( "Can only handle IoBuffers" );
        }
    }
    return size;
}
 
Example 9
Project: neoscada   File: Socks4LogicHandler.java   View source code 6 votes vote down vote up
/**
 * Handle a SOCKS4/SOCKS4a response from the proxy server. Test
 * the response buffer reply code and call {@link #setHandshakeComplete()}
 * if access is granted.
 * 
 * @param buf the buffer holding the server response data.
 * @throws exception if server response is malformed or if request is rejected
 * by the proxy server.
 */
protected void handleResponse(final IoBuffer buf) throws Exception {
    byte first = buf.get(0);

    if (first != 0) {
        throw new Exception("Socks response seems to be malformed");
    }

    byte status = buf.get(1);

    // Consumes all the response data from the buffer
    buf.position(buf.position() + SocksProxyConstants.SOCKS_4_RESPONSE_SIZE);

    if (status == SocksProxyConstants.V4_REPLY_REQUEST_GRANTED) {
        setHandshakeComplete();
    } else {
        throw new Exception("Proxy handshake failed - Code: 0x" + ByteUtilities.asHex(new byte[] { status }) + " ("
                + SocksProxyConstants.getReplyCodeAsString(status) + ")");
    }
}
 
Example 10
Project: neoscada   File: ProtocolDecoderImpl.java   View source code 6 votes vote down vote up
private boolean processBrowseAdded ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws ProtocolCodecException
{
    final int len = messageLength ( data );
    if ( len < 0 )
    {
        return false;
    }

    final int count = data.getUnsignedShort ();

    final List<BrowseAdded.Entry> entries = new ArrayList<BrowseAdded.Entry> ( count );

    for ( int i = 0; i < count; i++ )
    {
        entries.add ( decodeBrowserAddEntry ( data, session ) );
    }

    out.write ( new BrowseAdded ( entries ) );

    return true;
}
 
Example 11
Project: neoscada   File: AbstractIoSession.java   View source code 6 votes vote down vote up
/**
 * TODO Add method documentation
 */
public final void increaseWrittenMessages(WriteRequest request, long currentTime) {
    Object message = request.getMessage();
    if (message instanceof IoBuffer) {
        IoBuffer b = (IoBuffer) message;
        if (b.hasRemaining()) {
            return;
        }
    }

    writtenMessages++;
    lastWriteTime = currentTime;
    if (getService() instanceof AbstractIoService) {
        ((AbstractIoService) getService()).getStatistics().increaseWrittenMessages(currentTime);
    }

    decreaseScheduledWriteMessages();
}
 
Example 12
Project: neoscada   File: DefaultBinaryContext.java   View source code 6 votes vote down vote up
private <T extends Collection<Long>> T decodeLongCollection ( final IoBuffer buffer, final CollectionAllocator<Long, T> allactor ) throws Exception
{
    final byte type = checkType ( buffer, TYPE_LONG_LIST, true );

    if ( type == TYPE_NULL )
    {
        return null;
    }
    else
    {
        final int items = buffer.getInt ();
        final T result = allactor.allocate ( items );
        fillLongCollection ( buffer, items, result );
        return result;
    }
}
 
Example 13
Project: neoscada   File: COTPFilter.java   View source code 6 votes vote down vote up
/**
 * Handle data transmission
 * 
 * @param nextFilter
 * @param session
 * @param writeRequest
 */
private void handleDT ( final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest )
{
    final DataTPDU userData = (DataTPDU)writeRequest.getMessage ();
    final IoBuffer data = IoBuffer.allocate ( userData.getData ().remaining () + 3 );

    data.put ( (byte)0x02 ); // header length
    data.put ( (byte) ( COMMAND_DATA << 4 ) );

    final byte seq = (byte)0x80; // bit 8 to 1 (last packet)... bit 7..1 to zero (packet #0)

    data.put ( seq );

    data.put ( userData.getData () );

    data.flip ();

    nextFilter.filterWrite ( session, new WriteRequestWrapper ( writeRequest ) {
        @Override
        public Object getMessage ()
        {
            return data;
        }
    } );
}
 
Example 14
Project: neoscada   File: CompositeByteArray.java   View source code 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 15
Project: neoscada   File: StartBrowse.java   View source code 5 votes vote down vote up
@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 16
Project: jforgame   File: MessageEncoder.java   View source code 5 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
	CodecContext context = (CodecContext) session.getAttribute(SessionProperties.CODEC_CONTEXT);
	if (context == null) {
		context = new CodecContext();
		session.setAttribute(SessionProperties.CODEC_CONTEXT, context);
	}
	IoBuffer buffer = writeMessage((Message) message);
	out.write(buffer);
}
 
Example 17
Project: neoscada   File: DefaultBinaryContext.java   View source code 5 votes vote down vote up
protected void inlineEncodeVariantMap ( final IoBuffer buffer, final Map<String, Variant> data ) throws Exception
{
    buffer.putInt ( data.size () );
    for ( final Map.Entry<String, Variant> entry : data.entrySet () )
    {
        buffer.putPrefixedString ( entry.getKey (), STRING_PREFIX_LEN, this.encoder );
        inlineEncodeVariant ( buffer, entry.getValue () );
    }
}
 
Example 18
Project: jforgame   File: HttpServer.java   View source code 5 votes vote down vote up
@Override
public void sessionOpened(IoSession session) throws Exception {
	String ipAddr = SessionManager.INSTANCE.getRemoteIp(session);
	if (!isInWhiteIps(ipAddr)) {
		logger.error("非法后台登录,remoteIp=[{}]", ipAddr);
		byte[] body = "too young too simple".getBytes("UTF-8");
		IoBuffer out = IoBuffer.allocate(body.length);
		out.put(body);
		out.flip();
		session.write(out);
		session.close(false);
	}
}
 
Example 19
Project: jforgame   File: HttpServer.java   View source code 5 votes vote down vote up
@Override
public void messageReceived(IoSession session, Object message)
		throws Exception {
	if (message instanceof HttpRequest) {
		// 请求,解码器将请求转换成HttpRequest对象
		HttpRequest request = (HttpRequest) message;
		HttpCommandResponse commandResponse = handleCommand(request);
		// 响应HTML
		String responseHtml = new Gson().toJson(commandResponse);
		byte[] responseBytes = responseHtml.getBytes("UTF-8");
		int contentLength = responseBytes.length;

		// 构造HttpResponse对象,HttpResponse只包含响应的status line和header部分
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Content-Type", "text/html; charset=utf-8");
		headers.put("Content-Length", Integer.toString(contentLength));
		HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SUCCESS_OK, headers);

		// 响应BODY
		IoBuffer responseIoBuffer = IoBuffer.allocate(contentLength);
		responseIoBuffer.put(responseBytes);
		responseIoBuffer.flip();

		session.write(response); // 响应的status line和header部分
		session.write(responseIoBuffer); // 响应body部分
	}
}
 
Example 20
Project: neoscada   File: PrefixedStringDecoder.java   View source code 5 votes vote down vote up
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (in.prefixedDataAvailable(prefixLength, maxDataLength)) {
        String msg = in.getPrefixedString(prefixLength, charset.newDecoder());
        out.write(msg);
        return true;
    }

    return false;
}
 
Example 21
Project: neoscada   File: DefaultBinaryContext.java   View source code 5 votes vote down vote up
private void fillVariantMapCollection ( final IoBuffer buffer, final int items, final Collection<Map<String, Variant>> data ) throws Exception
{
    for ( int i = 0; i < items; i++ )
    {
        data.add ( inlineDecodeVariantMap ( buffer ) );
    }
}
 
Example 22
Project: neoscada   File: Socks4LogicHandler.java   View source code 5 votes vote down vote up
/**
 * Handle incoming data during the handshake process. Should consume only the
 * handshake data from the buffer, leaving any extra data in place.
 * 
 * @param nextFilter the next filter
 * @param buf the server response data buffer
 */
public void messageReceived(final NextFilter nextFilter, final IoBuffer buf) {
    try {
        if (buf.remaining() >= SocksProxyConstants.SOCKS_4_RESPONSE_SIZE) {
            handleResponse(buf);
        }
    } catch (Exception ex) {
        closeSession("Proxy handshake failed: ", ex);
    }
}
 
Example 23
Project: neoscada   File: StopBrowse.java   View source code 5 votes vote down vote up
@Override
public org.eclipse.scada.ae.data.message.StopBrowse 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

    logger.trace ( "Decoding {} fields", numberOfFields );

    for ( int i = 0; i < numberOfFields; i++ )
    {

        final byte fieldNumber = _data.get ();
        switch ( fieldNumber )
        {
            default:
                logger.warn ( "Received unknown field number: {}", fieldNumber );
                break;
        }

    }

    // create object
    return new org.eclipse.scada.ae.data.message.StopBrowse ();
}
 
Example 24
Project: neoscada   File: StopBrowse.java   View source code 5 votes vote down vote up
@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 25
Project: neoscada   File: Structures.java   View source code 5 votes vote down vote up
protected static void inlineEncodeEventInformation ( final BinaryContext context, final IoBuffer data, final org.eclipse.scada.ae.data.EventInformation value ) throws Exception
{
    // number of fields
    data.put ( (byte)4 );

    // encode attributes
    context.encodeString ( data, (byte)1, value.getId () );
    context.encodePrimitiveLong ( data, (byte)2, value.getSourceTimestamp () );
    context.encodePrimitiveLong ( data, (byte)3, value.getEntryTimestamp () );
    context.encodeVariantMap ( data, (byte)4, value.getAttributes () );

}
 
Example 26
Project: neoscada   File: AbstractAccessorVariable.java   View source code 5 votes vote down vote up
@Override
protected NotifyFuture<WriteResult> handleWrite ( final Variant value )
{
    final MemoryRequestBlock block = this.block;
    if ( block == null )
    {
        return new InstantErrorFuture<> ( new IllegalStateException ( "Device is not connected" ) );
    }

    final T cvtValue = getValue ( value );
    if ( cvtValue != null )
    {
        final IoBuffer data = IoBuffer.allocate ( this.accessor.getBufferSize ( cvtValue ) );
        if ( this.order != null )
        {
            this.order.put ( data, this.accessor, cvtValue );
        }
        else
        {
            this.accessor.put ( data, cvtValue );
        }
        block.writeData ( toAddress ( this.index ), data.array () );
        return new InstantFuture<> ( WriteResult.OK );
    }
    else
    {
        return new InstantErrorFuture<> ( new IllegalArgumentException ( String.format ( "Can only write doubles: %s is not a double", value ) ) );
    }
}
 
Example 27
Project: neoscada   File: Structures.java   View source code 5 votes vote down vote up
public static void encodeUserInformation ( final BinaryContext context, final IoBuffer data, final byte fieldNumber, final org.eclipse.scada.core.data.UserInformation value ) throws Exception
{
    context.beginWriteStructure ( data, fieldNumber, value == null );

    if ( value != null )
    {
        inlineEncodeUserInformation ( context, data, value );
    }
}
 
Example 28
Project: neoscada   File: MemoryBlock.java   View source code 5 votes vote down vote up
public IoBuffer readData ( final int offset, final int length )
{
    this.readLock.lock ();
    try
    {
        return performRead ( offset, length );
    }
    finally
    {
        this.readLock.unlock ();
    }
}
 
Example 29
Project: neoscada   File: BufferedWriteFilter.java   View source code 5 votes vote down vote up
/**
 * Internal method that actually frees the {@link IoBuffer} that contains
 * the buffered data that has not been flushed.
 * 
 * @param session the session we operate on
 */
private void free(IoSession session) {
    IoBuffer buf = buffersMap.remove(session);
    if (buf != null) {
        buf.free();
    }
}
 
Example 30
Project: neoscada   File: DaveFilter.java   View source code 5 votes vote down vote up
/**
 * Encode the parameters section of the write request
 * 
 * @param message
 * @param data
 */
private void encodeWriteRequestsParameters ( final DaveWriteRequest message, final IoBuffer data )
{
    // -- Write Command
    data.put ( DaveCommandCodes.DAVE_WRITE.getCommandCode () );
    data.put ( (byte)message.getRequests ().size () ); // possibly the number of write requests

    for ( final DaveWriteRequest.Request request : message.getRequests () )
    {
        encodeAddress ( data, request );
    }
}
 
Example 31
Project: neoscada   File: Zlib.java   View source code 5 votes vote down vote up
/**
 * Compress the input. The result will be put in a new buffer.
 *  
 * @param inBuffer the buffer to be compressed. The contents are transferred
 * into a local byte array and the buffer is flipped and returned intact.
 * @return the buffer with the compressed data
 * @throws IOException if the compression of teh buffer failed for some reason
 * @throws IllegalStateException if the mode is not <code>MODE_DEFLATER</code>
 */
public IoBuffer deflate(IoBuffer inBuffer) throws IOException {
    if (mode == MODE_INFLATER) {
        throw new IllegalStateException("not initialized as DEFLATER");
    }

    byte[] inBytes = new byte[inBuffer.remaining()];
    inBuffer.get(inBytes).flip();

    // according to spec, destination buffer should be 0.1% larger
    // than source length plus 12 bytes. We add a single byte to safeguard
    // against rounds that round down to the smaller value
    int outLen = (int) Math.round(inBytes.length * 1.001) + 1 + 12;
    byte[] outBytes = new byte[outLen];

    synchronized (zStream) {
        zStream.next_in = inBytes;
        zStream.next_in_index = 0;
        zStream.avail_in = inBytes.length;
        zStream.next_out = outBytes;
        zStream.next_out_index = 0;
        zStream.avail_out = outBytes.length;

        int retval = zStream.deflate(JZlib.Z_SYNC_FLUSH);
        if (retval != JZlib.Z_OK) {
            outBytes = null;
            inBytes = null;
            throw new IOException("Compression failed with return value : " + retval);
        }

        IoBuffer outBuf = IoBuffer.wrap(outBytes, 0, zStream.next_out_index);

        return outBuf;
    }
}
 
Example 32
Project: neoscada   File: Structures.java   View source code 5 votes vote down vote up
public static void encodeCollectionResponse ( final BinaryContext context, final IoBuffer data, final byte fieldNumber, final Collection<org.eclipse.scada.core.data.Response> values ) throws Exception
{
    context.beginWriteStructureList ( data, fieldNumber, values );

    if ( values == null )
    {
        return;
    }

    for ( final org.eclipse.scada.core.data.Response entry : values )
    {
        inlineEncodeResponse ( context, data, entry );
    }
}
 
Example 33
Project: neoscada   File: ProtocolDecoderImpl.java   View source code 5 votes vote down vote up
/**
 * Decode a variant from the stream
 *
 * @return a decoded variant or <code>null</code> if the data type was
 *         {@link DataType#DEAD}
 * @throws ProtocolCodecException
 */
private Variant decodeVariant ( final IoSession session, final IoBuffer data ) throws ProtocolCodecException
{
    final byte b = data.get ();
    final DataType dataType = DataType.fromByte ( b );
    if ( dataType == null )
    {
        throw new ProtocolCodecException ( String.format ( "Data type %02x is unkown", b ) );
    }

    switch ( dataType )
    {
        case DEAD:
            return null;
        case NULL:
            return Variant.NULL;
        case BOOLEAN:
            return Variant.valueOf ( data.get () != 0x00 );
        case INT32:
            return Variant.valueOf ( data.getInt () );
        case INT64:
            return Variant.valueOf ( data.getInt () );
        case DOUBLE:
            return Variant.valueOf ( data.getDouble () );
        case STRING:
            try
            {
                return Variant.valueOf ( decodeString ( session, data ) );
            }
            catch ( final CharacterCodingException e )
            {
                throw new ProtocolCodecException ( e );
            }
        default:
            throw new ProtocolCodecException ( String.format ( "Data type %s is unkown", b ) );
    }
}
 
Example 34
Project: neoscada   File: Structures.java   View source code 5 votes vote down vote up
public static void encodeHistoricalItemInformation ( final BinaryContext context, final IoBuffer data, final byte fieldNumber, final org.eclipse.scada.hd.data.HistoricalItemInformation value ) throws Exception
{
    context.beginWriteStructure ( data, fieldNumber, value == null );

    if ( value != null )
    {
        inlineEncodeHistoricalItemInformation ( context, data, value );
    }
}
 
Example 35
Project: neoscada   File: Structures.java   View source code 5 votes vote down vote up
protected static void fillAttributeWriteResultEntryCollection ( final BinaryContext context, final IoBuffer data, final int items, final Collection<org.eclipse.scada.da.data.AttributeWriteResultEntry> values ) throws Exception
{
    for ( int i = 0; i < items; i++ )
    {
        values.add ( inlindeDecodeAttributeWriteResultEntry ( context, data ) );
    }
}
 
Example 36
Project: AeroStory   File: GMPacketDecoder.java   View source code 5 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    byte decryptedPacket[] = new byte[in.limit()];
    in.get(decryptedPacket, 0, in.limit());
    out.write(decryptedPacket);
    return true;
}
 
Example 37
Project: neoscada   File: Structures.java   View source code 5 votes vote down vote up
public static void encodeBrowserEntry ( final BinaryContext context, final IoBuffer data, final byte fieldNumber, final org.eclipse.scada.ae.data.BrowserEntry value ) throws Exception
{
    context.beginWriteStructure ( data, fieldNumber, value == null );

    if ( value != null )
    {
        inlineEncodeBrowserEntry ( context, data, value );
    }
}
 
Example 38
Project: neoscada   File: Structures.java   View source code 5 votes vote down vote up
protected static void inlineEncodeValueEntry ( final BinaryContext context, final IoBuffer data, final org.eclipse.scada.hd.data.ValueEntry value ) throws Exception
{
    // number of fields
    data.put ( (byte)2 );

    // encode attributes
    context.encodeString ( data, (byte)1, value.getValueType () );
    context.encodeDoubleCollection ( data, (byte)2, value.getValues () );

}
 
Example 39
Project: neoscada   File: Structures.java   View source code 5 votes vote down vote up
protected static void fillValueEntryCollection ( final BinaryContext context, final IoBuffer data, final int items, final Collection<org.eclipse.scada.hd.data.ValueEntry> values ) throws Exception
{
    for ( int i = 0; i < items; i++ )
    {
        values.add ( inlindeDecodeValueEntry ( context, data ) );
    }
}
 
Example 40
Project: neoscada   File: Structures.java   View source code 5 votes vote down vote up
protected static org.eclipse.scada.core.data.OperationParameters inlindeDecodeOperationParameters ( final BinaryContext _context, final IoBuffer _data ) throws Exception
{
    // number of fields
    final byte numberOfFields = _data.get ();

    // decode attributes

    org.eclipse.scada.core.data.UserInformation userInformation = null;
    java.util.Map<String, String> properties = null;

    logger.trace ( "Decoding {} fields", numberOfFields );

    for ( int i = 0; i < numberOfFields; i++ )
    {

        final byte fieldNumber = _data.get ();
        switch ( fieldNumber )
        {
            case 1:
            {
                userInformation = org.eclipse.scada.core.protocol.ngp.codec.Structures.decodeUserInformation ( _context, _data, true );
            }
                break;
            case 2:
            {
                properties = _context.decodeProperties ( _data );
            }
                break;
            default:
                logger.warn ( "Received unknown field number: {}", fieldNumber );
                break;
        }

    }

    // create object
    return new org.eclipse.scada.core.data.OperationParameters ( userInformation, properties );
}