Example usage for io.netty.buffer ByteBuf capacity

List of usage examples for io.netty.buffer ByteBuf capacity

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf capacity.

Prototype

public abstract int capacity();

Source Link

Document

Returns the number of bytes (octets) this buffer can contain.

Usage

From source file:org.traccar.protocol.NoranProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;/*from w  ww  . jav  a 2 s  . c o  m*/

    buf.readUnsignedShortLE(); // length
    int type = buf.readUnsignedShortLE();

    if (type == MSG_SHAKE_HAND && channel != null) {

        ByteBuf response = Unpooled.buffer(13);
        response.writeCharSequence("\r\n*KW", StandardCharsets.US_ASCII);
        response.writeByte(0);
        response.writeShortLE(response.capacity());
        response.writeShortLE(MSG_SHAKE_HAND_RESPONSE);
        response.writeByte(1); // status
        response.writeCharSequence("\r\n", StandardCharsets.US_ASCII);

        channel.writeAndFlush(new NetworkMessage(response, remoteAddress));

    } else if (type == MSG_UPLOAD_POSITION || type == MSG_UPLOAD_POSITION_NEW || type == MSG_CONTROL_RESPONSE
            || type == MSG_ALARM) {

        boolean newFormat = false;
        if (type == MSG_UPLOAD_POSITION && buf.readableBytes() == 48
                || type == MSG_ALARM && buf.readableBytes() == 48
                || type == MSG_CONTROL_RESPONSE && buf.readableBytes() == 57) {
            newFormat = true;
        }

        Position position = new Position(getProtocolName());

        if (type == MSG_CONTROL_RESPONSE) {
            buf.readUnsignedIntLE(); // GIS ip
            buf.readUnsignedIntLE(); // GIS port
        }

        position.setValid(BitUtil.check(buf.readUnsignedByte(), 0));

        short alarm = buf.readUnsignedByte();
        switch (alarm) {
        case 1:
            position.set(Position.KEY_ALARM, Position.ALARM_SOS);
            break;
        case 2:
            position.set(Position.KEY_ALARM, Position.ALARM_OVERSPEED);
            break;
        case 3:
            position.set(Position.KEY_ALARM, Position.ALARM_GEOFENCE_EXIT);
            break;
        case 9:
            position.set(Position.KEY_ALARM, Position.ALARM_POWER_OFF);
            break;
        default:
            break;
        }

        if (newFormat) {
            position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedIntLE()));
            position.setCourse(buf.readFloatLE());
        } else {
            position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte()));
            position.setCourse(buf.readUnsignedShortLE());
        }
        position.setLongitude(buf.readFloatLE());
        position.setLatitude(buf.readFloatLE());

        if (!newFormat) {
            long timeValue = buf.readUnsignedIntLE();
            DateBuilder dateBuilder = new DateBuilder().setYear((int) BitUtil.from(timeValue, 26))
                    .setMonth((int) BitUtil.between(timeValue, 22, 26))
                    .setDay((int) BitUtil.between(timeValue, 17, 22))
                    .setHour((int) BitUtil.between(timeValue, 12, 17))
                    .setMinute((int) BitUtil.between(timeValue, 6, 12))
                    .setSecond((int) BitUtil.to(timeValue, 6));
            position.setTime(dateBuilder.getDate());
        }

        ByteBuf rawId;
        if (newFormat) {
            rawId = buf.readSlice(12);
        } else {
            rawId = buf.readSlice(11);
        }
        String id = rawId.toString(StandardCharsets.US_ASCII).replaceAll("[^\\p{Print}]", "");
        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id);
        if (deviceSession == null) {
            return null;
        }
        position.setDeviceId(deviceSession.getDeviceId());

        if (newFormat) {
            DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
            position.setTime(dateFormat.parse(buf.readSlice(17).toString(StandardCharsets.US_ASCII)));
            buf.readByte();
        }

        if (!newFormat) {
            position.set(Position.PREFIX_IO + 1, buf.readUnsignedByte());
            position.set(Position.KEY_FUEL_LEVEL, buf.readUnsignedByte());
        } else if (type == MSG_UPLOAD_POSITION_NEW) {
            position.set(Position.PREFIX_TEMP + 1, buf.readShortLE());
            position.set(Position.KEY_ODOMETER, buf.readFloatLE());
        }

        return position;
    }

    return null;
}

From source file:org.traccar.protocol.NoranProtocolEncoder.java

License:Apache License

private ByteBuf encodeContent(String content) {

    ByteBuf buf = Unpooled.buffer(12 + 56);

    buf.writeCharSequence("\r\n*KW", StandardCharsets.US_ASCII);
    buf.writeByte(0);/* w  w  w  .  j a v  a  2 s.  com*/
    buf.writeShortLE(buf.capacity());
    buf.writeShortLE(NoranProtocolDecoder.MSG_CONTROL);
    buf.writeInt(0); // gis ip
    buf.writeShortLE(0); // gis port
    buf.writeBytes(content.getBytes(StandardCharsets.US_ASCII));
    buf.writerIndex(buf.writerIndex() + 50 - content.length());
    buf.writeCharSequence("\r\n", StandardCharsets.US_ASCII);

    return buf;
}

From source file:org.traccar.protocol.T800xProtocolDecoder.java

License:Apache License

private void sendResponse(Channel channel, short header, int type, int index, ByteBuf imei, int alarm) {
    if (channel != null) {
        ByteBuf response = Unpooled.buffer(alarm > 0 ? 16 : 15);
        response.writeShort(header);//from   ww  w. ja va2  s . c  o  m
        response.writeByte(type);
        response.writeShort(response.capacity()); // length
        response.writeShort(index);
        response.writeBytes(imei);
        if (alarm > 0) {
            response.writeByte(alarm);
        }
        channel.writeAndFlush(new NetworkMessage(response, channel.remoteAddress()));
    }
}

From source file:org.traccar.protocol.TeltonikaProtocolDecoder.java

License:Apache License

private void decodeSerial(Channel channel, SocketAddress remoteAddress, Position position, ByteBuf buf) {

    getLastLocation(position, null);//w w  w .  ja  va 2s  .  com

    int type = buf.readUnsignedByte();
    if (type == 0x0D) {

        buf.readInt(); // length
        int subtype = buf.readUnsignedByte();
        if (subtype == 0x01) {

            long photoId = buf.readUnsignedInt();
            ByteBuf photo = Unpooled.buffer(buf.readInt());
            photos.put(photoId, photo);
            sendImageRequest(channel, remoteAddress, photoId, 0, Math.min(IMAGE_PACKET_MAX, photo.capacity()));

        } else if (subtype == 0x02) {

            long photoId = buf.readUnsignedInt();
            buf.readInt(); // offset
            ByteBuf photo = photos.get(photoId);
            photo.writeBytes(buf, buf.readUnsignedShort());
            if (photo.writableBytes() > 0) {
                sendImageRequest(channel, remoteAddress, photoId, photo.writerIndex(),
                        Math.min(IMAGE_PACKET_MAX, photo.writableBytes()));
            } else {
                String uniqueId = Context.getIdentityManager().getById(position.getDeviceId()).getUniqueId();
                photos.remove(photoId);
                try {
                    position.set(Position.KEY_IMAGE,
                            Context.getMediaManager().writeFile(uniqueId, photo, "jpg"));
                } finally {
                    photo.release();
                }
            }

        }

    } else {

        position.set(Position.KEY_TYPE, type);

        int length = buf.readInt();
        boolean readable = true;
        for (int i = 0; i < length; i++) {
            byte b = buf.getByte(buf.readerIndex() + i);
            if (b < 32 && b != '\r' && b != '\n') {
                readable = false;
                break;
            }
        }

        if (readable) {
            position.set(Position.KEY_RESULT, buf.readSlice(length).toString(StandardCharsets.US_ASCII));
        } else {
            position.set(Position.KEY_RESULT, ByteBufUtil.hexDump(buf.readSlice(length)));
        }
    }
}

From source file:ratpack.groovy.template.internal.TextTemplateCompiler.java

License:Apache License

public CompiledTextTemplate compile(ByteBuf templateSource, String name)
        throws CompilationFailedException, IOException {
    ByteBuf scriptSource = byteBufAllocator.buffer(templateSource.capacity());
    parser.parse(templateSource, scriptSource);

    String scriptSourceString = scriptSource.toString(CharsetUtil.UTF_8);
    scriptSource.release();//from   w  w w .ja  va2  s.  c  o m

    if (verbose && logger.isInfoEnabled()) {
        logger.info("\n-- script source --\n" + scriptSourceString + "\n-- script end --\n");
    }

    try {
        Class<DefaultTextTemplateScript> scriptClass = scriptEngine.compile(name, scriptSourceString);
        return new CompiledTextTemplate(name, scriptClass);
    } catch (Exception e) {
        throw new InvalidTemplateException(name, "compilation failure", e);
    }
}

From source file:ratpack.groovy.templating.internal.TemplateCompiler.java

License:Apache License

public CompiledTemplate compile(ByteBuf templateSource, String name)
        throws CompilationFailedException, IOException {
    ByteBuf scriptSource = byteBufAllocator.buffer(templateSource.capacity());
    parser.parse(templateSource, scriptSource);

    String scriptSourceString = scriptSource.toString(CharsetUtil.UTF_8);
    scriptSource.release();/*from w  ww . j  a v  a  2 s  . c  o  m*/

    if (verbose && logger.isInfoEnabled()) {
        logger.info("\n-- script source --\n" + scriptSourceString + "\n-- script end --\n");
    }

    try {
        Class<DefaultTemplateScript> scriptClass = scriptEngine.compile(name, scriptSourceString);
        return new CompiledTemplate(name, scriptClass);
    } catch (Exception e) {
        throw new InvalidTemplateException(name, "compilation failure", e);
    }
}

From source file:ratpack.sse.internal.ServerSentEventDecoder.java

License:Apache License

public void decode(ByteBuf in, ByteBufAllocator bufferAllocator, Action<Event<?>> eventAction)
        throws Exception {
    ByteBuf currentLineBuffer = null;//from   w ww  . j  a  v  a  2 s  .c o m
    String eventData = null;
    String eventType = null;
    String eventId = null;
    FieldName currentFieldType = null;
    State state = State.ReadLine;

    try {
        while (in.isReadable()) {
            final int readerIndexAtStart = in.readerIndex();

            switch (state) {
            case ReadLine:
                final int endOfLineStartIndex = scanAndFindEndOfLine(in);

                if (-1 == endOfLineStartIndex) { // End of line not found, set readIndex to the end
                    in.readerIndex(in.capacity());
                } else {
                    final int bytesAvailableInThisLine = endOfLineStartIndex - readerIndexAtStart;

                    if (bytesAvailableInThisLine == 0) {
                        state = State.DispatchEvent;
                    } else {
                        currentLineBuffer = bufferAllocator.buffer(bytesAvailableInThisLine,
                                bytesAvailableInThisLine);
                        in.readBytes(currentLineBuffer, bytesAvailableInThisLine);
                        state = State.ReadFieldName;
                    }
                }

                break;
            case DispatchEvent:
                eventAction.execute(new DefaultEvent<>().id(eventId).event(eventType).data(eventData));

                eventId = null;
                eventType = null;
                eventData = null;

                state = State.SkipTillEOL;

                break;
            case ReadFieldName:
                int indexOfColon = scanAndFindColon(currentLineBuffer);
                if (-1 == indexOfColon) { // No colon found, use the whole line as the field name, and the empty string as the field value.
                    indexOfColon = currentLineBuffer.capacity();
                }

                if (1 == indexOfColon) { // Line starts with a colon, ignore
                    state = State.ReadLine;
                    currentLineBuffer.release();
                } else {
                    ByteBuf fieldNameBuffer = bufferAllocator.buffer(indexOfColon, indexOfColon);
                    currentLineBuffer.readBytes(fieldNameBuffer, indexOfColon);
                    state = State.SkipColonAndWhiteSpaces; // We have read the field name, next we should skip colon & WS.

                    try {
                        currentFieldType = readCurrentFieldTypeFromBuffer(fieldNameBuffer);
                    } finally {
                        if (null == currentFieldType) {
                            state = State.SkipTillEOL; // Ignore this event completely.
                        }
                        fieldNameBuffer.release();
                    }
                }

                break;
            case SkipColonAndWhiteSpaces:
                skipColonAndWhiteSpaces(currentLineBuffer);
                state = State.ReadFieldValue;

                break;
            case SkipTillEOL:
                skipTilEOL(in);
                state = State.ReadLine;
                break;
            case ReadFieldValue:
                final int bytesAvailableInThisValue = currentLineBuffer.readableBytes();
                ByteBuf currentFieldValue = bufferAllocator.buffer(bytesAvailableInThisValue,
                        bytesAvailableInThisValue);
                currentLineBuffer.readBytes(currentFieldValue, bytesAvailableInThisValue);
                state = State.SkipTillEOL;

                switch (currentFieldType) {
                case Data:
                    if (null == eventData) {
                        eventData = currentFieldValue.toString(UTF_8);
                    } else {
                        eventData = eventData + LINE_FEED + currentFieldValue.toString(UTF_8);
                    }
                    break;
                case Id:
                    eventId = currentFieldValue.toString(UTF_8);
                    break;
                case Event:
                    eventType = currentFieldValue.toString(UTF_8);
                    break;
                }

                currentFieldValue.release();
                currentLineBuffer.release();

                break;

            }

        }
    } finally {
        in.release();
    }
}

From source file:ratpack.sse.internal.ServerSentEventDecoder.java

License:Apache License

private static boolean skipTillFirstMatching(ByteBuf byteBuf, byte thing) {
    int i = byteBuf.indexOf(byteBuf.readerIndex(), byteBuf.capacity(), thing);
    if (-1 == i) {
        return false;
    } else {//from   w  w  w  . j a v a  2 s. c o  m
        byteBuf.readByte();
        return true;
    }
}

From source file:reactor.ipc.netty.http.client.HttpClientFormEncoder.java

License:Open Source License

/**
 * From the current context (currentBuffer and currentData), returns the next
 * HttpChunk (if possible) trying to get sizeleft bytes more into the currentBuffer.
 * This is the Multipart version.//w  w  w.  j  a  v  a  2  s.c  o m
 *
 * @param sizeleft the number of bytes to try to get from currentData
 *
 * @return the next HttpChunk or null if not enough bytes were found
 *
 * @throws ErrorDataEncoderException if the encoding is in error
 */
HttpContent encodeNextChunkMultipart(int sizeleft) throws ErrorDataEncoderException {
    if (currentData == null) {
        return null;
    }
    ByteBuf buffer;
    if (currentData instanceof InternalAttribute) {
        buffer = ((InternalAttribute) currentData).toByteBuf();
        currentData = null;
    } else {
        if (currentData instanceof Attribute) {
            try {
                buffer = ((Attribute) currentData).getChunk(sizeleft);
            } catch (IOException e) {
                throw new ErrorDataEncoderException(e);
            }
        } else {
            try {
                buffer = ((HttpData) currentData).getChunk(sizeleft);
            } catch (IOException e) {
                throw new ErrorDataEncoderException(e);
            }
        }
        if (buffer.capacity() == 0) {
            // end for current InterfaceHttpData, need more data
            currentData = null;
            return null;
        }
    }
    if (currentBuffer == null) {
        currentBuffer = buffer;
    } else {
        currentBuffer = wrappedBuffer(currentBuffer, buffer);
    }
    if (currentBuffer.readableBytes() < chunkSize) {
        currentData = null;
        return null;
    }
    buffer = fillByteBuf();
    return new DefaultHttpContent(buffer);
}

From source file:reactor.ipc.netty.http.client.HttpClientFormEncoder.java

License:Open Source License

/**
 * From the current context (currentBuffer and currentData), returns the next
 * HttpChunk (if possible) trying to get sizeleft bytes more into the currentBuffer.
 * This is the UrlEncoded version./*www  . j  ava  2  s .  com*/
 *
 * @param sizeleft the number of bytes to try to get from currentData
 *
 * @return the next HttpChunk or null if not enough bytes were found
 *
 * @throws ErrorDataEncoderException if the encoding is in error
 */
HttpContent encodeNextChunkUrlEncoded(int sizeleft) throws ErrorDataEncoderException {
    if (currentData == null) {
        return null;
    }
    int size = sizeleft;
    ByteBuf buffer;

    // Set name=
    if (isKey) {
        String key = currentData.getName();
        buffer = wrappedBuffer(key.getBytes());
        isKey = false;
        if (currentBuffer == null) {
            currentBuffer = wrappedBuffer(buffer, wrappedBuffer("=".getBytes()));
            // continue
            size -= buffer.readableBytes() + 1;
        } else {
            currentBuffer = wrappedBuffer(currentBuffer, buffer, wrappedBuffer("=".getBytes()));
            // continue
            size -= buffer.readableBytes() + 1;
        }
        if (currentBuffer.readableBytes() >= chunkSize) {
            buffer = fillByteBuf();
            return new DefaultHttpContent(buffer);
        }
    }

    // Put value into buffer
    try {
        buffer = ((HttpData) currentData).getChunk(size);
    } catch (IOException e) {
        throw new ErrorDataEncoderException(e);
    }

    // Figure out delimiter
    ByteBuf delimiter = null;
    if (buffer.readableBytes() < size) {
        isKey = true;
        delimiter = iterator.hasNext() ? wrappedBuffer("&".getBytes()) : null;
    }

    // End for current InterfaceHttpData, need potentially more data
    if (buffer.capacity() == 0) {
        currentData = null;
        if (currentBuffer == null) {
            currentBuffer = delimiter;
        } else {
            if (delimiter != null) {
                currentBuffer = wrappedBuffer(currentBuffer, delimiter);
            } else {
                currentBuffer = wrappedBuffer(currentBuffer);
            }
        }
        if (currentBuffer.readableBytes() >= chunkSize) {
            buffer = fillByteBuf();
            return new DefaultHttpContent(buffer);
        }
        return null;
    }

    // Put it all together: name=value&
    if (currentBuffer == null) {
        if (delimiter != null) {
            currentBuffer = wrappedBuffer(buffer, delimiter);
        } else {
            currentBuffer = buffer;
        }
    } else {
        if (delimiter != null) {
            currentBuffer = wrappedBuffer(currentBuffer, buffer, delimiter);
        } else {
            currentBuffer = wrappedBuffer(currentBuffer, buffer);
        }
    }

    // end for current InterfaceHttpData, need more data
    if (currentBuffer.readableBytes() < chunkSize) {
        currentData = null;
        isKey = true;
        return null;
    }

    buffer = fillByteBuf();
    return new DefaultHttpContent(buffer);
}