Example usage for io.netty.buffer ByteBuf getShort

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

Introduction

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

Prototype

public abstract short getShort(int index);

Source Link

Document

Gets a 16-bit short integer at the specified absolute index in this buffer.

Usage

From source file:com.couchbase.client.core.endpoint.binary.BinaryHandler.java

License:Open Source License

@Override
protected CouchbaseResponse decodeResponse(final ChannelHandlerContext ctx,
        final FullBinaryMemcacheResponse msg) throws Exception {
    BinaryRequest request = currentRequest();
    ResponseStatus status = convertStatus(msg.getStatus());

    CouchbaseResponse response;//from  w  ww  .j a v a 2 s . c  om
    ByteBuf content = msg.content().copy();
    long cas = msg.getCAS();
    String bucket = request.bucket();
    if (request instanceof GetRequest || request instanceof ReplicaGetRequest) {
        int flags = 0;
        if (msg.getExtrasLength() > 0) {
            final ByteBuf extrasReleased = msg.getExtras();
            final ByteBuf extras = ctx.alloc().buffer(msg.getExtrasLength());
            extras.writeBytes(extrasReleased, extrasReleased.readerIndex(), extrasReleased.readableBytes());
            flags = extras.getInt(0);
            extras.release();
        }
        response = new GetResponse(status, cas, flags, bucket, content, request);
    } else if (request instanceof GetBucketConfigRequest) {
        response = new GetBucketConfigResponse(status, bucket, content,
                ((GetBucketConfigRequest) request).hostname());
    } else if (request instanceof InsertRequest) {
        response = new InsertResponse(status, cas, bucket, content, request);
    } else if (request instanceof UpsertRequest) {
        response = new UpsertResponse(status, cas, bucket, content, request);
    } else if (request instanceof ReplaceRequest) {
        response = new ReplaceResponse(status, cas, bucket, content, request);
    } else if (request instanceof RemoveRequest) {
        response = new RemoveResponse(status, bucket, content, request);
    } else if (request instanceof CounterRequest) {
        response = new CounterResponse(status, bucket, msg.content().readLong(), cas, request);
    } else if (request instanceof UnlockRequest) {
        response = new UnlockResponse(status, bucket, content, request);
    } else if (request instanceof TouchRequest) {
        response = new TouchResponse(status, bucket, content, request);
    } else if (request instanceof ObserveRequest) {
        byte observed = content.getByte(content.getShort(2) + 4);
        response = new ObserveResponse(status, observed, ((ObserveRequest) request).master(), bucket, content,
                request);
    } else if (request instanceof AppendRequest) {
        response = new AppendResponse(status, cas, bucket, content, request);
    } else if (request instanceof PrependRequest) {
        response = new PrependResponse(status, cas, bucket, content, request);
    } else {
        throw new IllegalStateException(
                "Unhandled request/response pair: " + request.getClass() + "/" + msg.getClass());
    }

    return response;
}

From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java

License:Apache License

/**
 * Helper method to decode all other response messages.
 *
 * @param request the current request./*from w ww  .j  a  v  a 2  s  .  co  m*/
 * @param msg the current response message.
 * @param status the response status code.
 * @return the decoded response or null if none did match.
 */
private static CouchbaseResponse handleOtherResponseMessages(BinaryRequest request,
        FullBinaryMemcacheResponse msg, ResponseStatus status, boolean seqOnMutation, String remoteHostname) {
    CouchbaseResponse response = null;
    ByteBuf content = msg.content();
    long cas = msg.getCAS();
    short statusCode = msg.getStatus();
    String bucket = request.bucket();

    if (request instanceof UnlockRequest) {
        response = new UnlockResponse(status, statusCode, bucket, content, request);
    } else if (request instanceof TouchRequest) {
        response = new TouchResponse(status, statusCode, bucket, content, request);
    } else if (request instanceof AppendRequest) {
        MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(),
                request.partition());
        response = new AppendResponse(status, statusCode, cas, bucket, content, descr, request);
    } else if (request instanceof PrependRequest) {
        MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(),
                request.partition());
        response = new PrependResponse(status, statusCode, cas, bucket, content, descr, request);
    } else if (request instanceof KeepAliveRequest) {
        releaseContent(content);
        response = new KeepAliveResponse(status, statusCode, request);
    } else if (request instanceof CounterRequest) {
        long value = status.isSuccess() ? content.readLong() : 0;
        releaseContent(content);

        MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(),
                request.partition());
        response = new CounterResponse(status, statusCode, bucket, value, cas, descr, request);
    } else if (request instanceof StatRequest) {
        String key = new String(msg.getKey(), CHARSET);
        String value = content.toString(CHARSET);
        releaseContent(content);

        response = new StatResponse(status, statusCode, remoteHostname, key, value, bucket, request);
    } else if (request instanceof GetAllMutationTokensRequest) {
        // 2 bytes for partition ID, and 8 bytes for sequence number
        MutationToken[] mutationTokens = new MutationToken[content.readableBytes() / 10];
        for (int i = 0; i < mutationTokens.length; i++) {
            mutationTokens[i] = new MutationToken((long) content.readShort(), 0, content.readLong(),
                    request.bucket());
        }
        releaseContent(content);
        response = new GetAllMutationTokensResponse(mutationTokens, status, statusCode, bucket, request);
    } else if (request instanceof ObserveRequest) {
        byte observed = ObserveResponse.ObserveStatus.UNKNOWN.value();
        long observedCas = 0;
        if (status.isSuccess()) {
            short keyLength = content.getShort(2);
            observed = content.getByte(keyLength + 4);
            observedCas = content.getLong(keyLength + 5);
        }
        releaseContent(content);
        response = new ObserveResponse(status, statusCode, observed, ((ObserveRequest) request).master(),
                observedCas, bucket, request);
    } else if (request instanceof ObserveSeqnoRequest) {
        if (status.isSuccess()) {
            byte format = content.readByte();
            switch (format) {
            case 0:
                response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(),
                        content.readShort(), content.readLong(), content.readLong(), content.readLong(), status,
                        statusCode, bucket, request);
                break;
            case 1:
                response = new FailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(),
                        content.readShort(), content.readLong(), content.readLong(), content.readLong(),
                        content.readLong(), content.readLong(), status, statusCode, bucket, request);
                break;
            default:
                throw new IllegalStateException("Unknown format for observe-seq: " + format);
            }
        } else {
            response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), (short) 0,
                    0, 0, 0, status, statusCode, bucket, request);
        }
        releaseContent(content);
    }

    return response;
}

From source file:com.github.mrstampy.pprspray.core.streamer.util.MediaStreamerUtils.java

License:Open Source License

/**
 * Gets the short chunk.//www  .  j a va2 s  .co  m
 *
 * @param chunk
 *          the chunk
 * @return the short chunk
 */
protected static int getShortChunk(byte[] chunk) {
    ByteBuf buf = Unpooled.copiedBuffer(chunk);

    return buf.getShort(0);
}

From source file:com.tesora.dve.db.mysql.portal.protocol.MSPComSetOptionRequestMessage.java

License:Open Source License

@Override
protected Short unmarshall(ByteBuf source) {
    source.skipBytes(1);//toss message identifier
    return source.getShort(INDEX_OF_OPTIONFLAG);
}

From source file:com.yahoo.pulsar.common.api.Commands.java

License:Apache License

public static boolean hasChecksum(ByteBuf buffer) {
    return buffer.getShort(buffer.readerIndex()) == magicCrc32c;
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

private static int getEncryptedPacketLength(ByteBuf buffer, int offset) {
    int packetLength = 0;

    // SSLv3 or TLS - Check ContentType
    boolean tls;/*w  ww .  j a  v a  2  s  . co m*/
    switch (buffer.getUnsignedByte(offset)) {
    case 20: // change_cipher_spec
    case 21: // alert
    case 22: // handshake
    case 23: // application_data
        tls = true;
        break;
    default:
        // SSLv2 or bad data
        tls = false;
    }

    if (tls) {
        // SSLv3 or TLS - Check ProtocolVersion
        int majorVersion = buffer.getUnsignedByte(offset + 1);
        if (majorVersion == 3) {
            // SSLv3 or TLS
            packetLength = buffer.getUnsignedShort(offset + 3) + 5;
            if (packetLength <= 5) {
                // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data)
                tls = false;
            }
        } else {
            // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data)
            tls = false;
        }
    }

    if (!tls) {
        // SSLv2 or bad data - Check the version
        boolean sslv2 = true;
        int headerLength = (buffer.getUnsignedByte(offset) & 0x80) != 0 ? 2 : 3;
        int majorVersion = buffer.getUnsignedByte(offset + headerLength + 1);
        if (majorVersion == 2 || majorVersion == 3) {
            // SSLv2
            if (headerLength == 2) {
                packetLength = (buffer.getShort(offset) & 0x7FFF) + 2;
            } else {
                packetLength = (buffer.getShort(offset) & 0x3FFF) + 3;
            }
            if (packetLength <= headerLength) {
                sslv2 = false;
            }
        } else {
            sslv2 = false;
        }

        if (!sslv2) {
            return -1;
        }
    }
    return packetLength;
}

From source file:io.reactiverse.pgclient.impl.codec.DataTypeCodec.java

License:Apache License

private static Short binaryDecodeINT2(int index, int len, ByteBuf buff) {
    return buff.getShort(index);
}

From source file:org.dcache.xrootd.protocol.messages.SigverRequest.java

License:Open Source License

public SigverRequest(ByteBuf buffer) {
    super(buffer, kXR_sigver);

    expectrid = buffer.getShort(4);
    version = buffer.getByte(6);//from w w w. j  a v  a2s  .com
    flags = buffer.getByte(7); // should == kXR_nodata if this is a write
    seqno = buffer.getLong(8);
    crypto = buffer.getByte(16);

    /*
     * skip reserved [bytes 17-19]
     */

    int dlen = buffer.getInt(20);
    signature = new byte[dlen];
    buffer.getBytes(24, signature);
}

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

License:Apache License

private Object decodeBasic(Channel channel, SocketAddress remoteAddress, ByteBuf buf) {

    int length = buf.readUnsignedByte();
    int dataLength = length - 5;
    int type = buf.readUnsignedByte();

    DeviceSession deviceSession = null;//from www .ja  va 2 s.co m
    if (type != MSG_LOGIN) {
        deviceSession = getDeviceSession(channel, remoteAddress);
        if (deviceSession == null) {
            return null;
        }
        if (deviceSession.getTimeZone() == null) {
            deviceSession.setTimeZone(getTimeZone(deviceSession.getDeviceId()));
        }
    }

    if (type == MSG_LOGIN) {

        String imei = ByteBufUtil.hexDump(buf.readSlice(8)).substring(1);
        buf.readUnsignedShort(); // type

        deviceSession = getDeviceSession(channel, remoteAddress, imei);
        if (deviceSession != null && deviceSession.getTimeZone() == null) {
            deviceSession.setTimeZone(getTimeZone(deviceSession.getDeviceId()));
        }

        if (dataLength > 10) {
            int extensionBits = buf.readUnsignedShort();
            int hours = (extensionBits >> 4) / 100;
            int minutes = (extensionBits >> 4) % 100;
            int offset = (hours * 60 + minutes) * 60;
            if ((extensionBits & 0x8) != 0) {
                offset = -offset;
            }
            if (deviceSession != null) {
                TimeZone timeZone = deviceSession.getTimeZone();
                if (timeZone.getRawOffset() == 0) {
                    timeZone.setRawOffset(offset * 1000);
                    deviceSession.setTimeZone(timeZone);
                }
            }

        }

        if (deviceSession != null) {
            sendResponse(channel, false, type, buf.getShort(buf.writerIndex() - 6), null);
        }

    } else if (type == MSG_HEARTBEAT) {

        Position position = new Position(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        getLastLocation(position, null);

        int status = buf.readUnsignedByte();
        position.set(Position.KEY_ARMED, BitUtil.check(status, 0));
        position.set(Position.KEY_IGNITION, BitUtil.check(status, 1));
        position.set(Position.KEY_CHARGE, BitUtil.check(status, 2));

        if (buf.readableBytes() >= 2 + 6) {
            position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.01);
        }
        if (buf.readableBytes() >= 1 + 6) {
            position.set(Position.KEY_RSSI, buf.readUnsignedByte());
        }

        sendResponse(channel, false, type, buf.getShort(buf.writerIndex() - 6), null);

        return position;

    } else if (type == MSG_ADDRESS_REQUEST) {

        String response = "NA&&NA&&0##";
        ByteBuf content = Unpooled.buffer();
        content.writeByte(response.length());
        content.writeInt(0);
        content.writeBytes(response.getBytes(StandardCharsets.US_ASCII));
        sendResponse(channel, true, MSG_ADDRESS_RESPONSE, 0, content);

    } else if (type == MSG_TIME_REQUEST) {

        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        ByteBuf content = Unpooled.buffer();
        content.writeByte(calendar.get(Calendar.YEAR) - 2000);
        content.writeByte(calendar.get(Calendar.MONTH) + 1);
        content.writeByte(calendar.get(Calendar.DAY_OF_MONTH));
        content.writeByte(calendar.get(Calendar.HOUR_OF_DAY));
        content.writeByte(calendar.get(Calendar.MINUTE));
        content.writeByte(calendar.get(Calendar.SECOND));
        sendResponse(channel, false, MSG_TIME_REQUEST, 0, content);

    } else if (type == MSG_X1_GPS || type == MSG_X1_PHOTO_INFO) {

        return decodeX1(channel, buf, deviceSession, type);

    } else if (type == MSG_WIFI || type == MSG_WIFI_2) {

        return decodeWifi(channel, buf, deviceSession, type);

    } else if (type == MSG_INFO) {

        Position position = new Position(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        getLastLocation(position, null);

        position.set(Position.KEY_POWER, buf.readShort() * 0.01);

        return position;

    } else {

        return decodeBasicOther(channel, buf, deviceSession, type, dataLength);

    }

    return null;
}

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

License:Apache License

private Object decodeBasicOther(Channel channel, ByteBuf buf, DeviceSession deviceSession, int type,
        int dataLength) {

    Position position = new Position(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    if (type == MSG_LBS_MULTIPLE || type == MSG_LBS_EXTEND || type == MSG_LBS_WIFI || type == MSG_LBS_2
            || type == MSG_WIFI_3) {//from   w  ww.  j  a v  a2s. com

        boolean longFormat = type == MSG_LBS_2 || type == MSG_WIFI_3;

        DateBuilder dateBuilder = new DateBuilder(deviceSession.getTimeZone())
                .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte())
                .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte());

        getLastLocation(position, dateBuilder.getDate());

        int mcc = buf.readUnsignedShort();
        int mnc = BitUtil.check(mcc, 15) ? buf.readUnsignedShort() : buf.readUnsignedByte();
        Network network = new Network();
        for (int i = 0; i < 7; i++) {
            int lac = longFormat ? buf.readInt() : buf.readUnsignedShort();
            int cid = longFormat ? (int) buf.readLong() : buf.readUnsignedMedium();
            int rssi = -buf.readUnsignedByte();
            if (lac > 0) {
                network.addCellTower(CellTower.from(BitUtil.to(mcc, 15), mnc, lac, cid, rssi));
            }
        }

        buf.readUnsignedByte(); // time leads

        if (type != MSG_LBS_MULTIPLE && type != MSG_LBS_2) {
            int wifiCount = buf.readUnsignedByte();
            for (int i = 0; i < wifiCount; i++) {
                String mac = ByteBufUtil.hexDump(buf.readSlice(6)).replaceAll("(..)", "$1:");
                network.addWifiAccessPoint(
                        WifiAccessPoint.from(mac.substring(0, mac.length() - 1), buf.readUnsignedByte()));
            }
        }

        position.setNetwork(network);

    } else if (type == MSG_STRING) {

        getLastLocation(position, null);

        int commandLength = buf.readUnsignedByte();

        if (commandLength > 0) {
            buf.readUnsignedByte(); // server flag (reserved)
            position.set(Position.KEY_RESULT,
                    buf.readSlice(commandLength - 1).toString(StandardCharsets.US_ASCII));
        }

    } else if (isSupported(type)) {

        if (hasGps(type)) {
            decodeGps(position, buf, false, deviceSession.getTimeZone());
        } else {
            getLastLocation(position, null);
        }

        if (hasLbs(type)) {
            decodeLbs(position, buf, hasStatus(type));
        }

        if (hasStatus(type)) {
            decodeStatus(position, buf);
        }

        if (type == MSG_GPS_LBS_1 && buf.readableBytes() == 2 + 6) {
            int mask = buf.readUnsignedShort();
            position.set(Position.KEY_IGNITION, BitUtil.check(mask, 8 + 7));
            position.set(Position.PREFIX_IN + 2, BitUtil.check(mask, 8 + 6));
            if (BitUtil.check(mask, 8 + 4)) {
                int value = BitUtil.to(mask, 8 + 1);
                if (BitUtil.check(mask, 8 + 1)) {
                    value = -value;
                }
                position.set(Position.PREFIX_TEMP + 1, value);
            } else {
                int value = BitUtil.to(mask, 8 + 2);
                if (BitUtil.check(mask, 8 + 5)) {
                    position.set(Position.PREFIX_ADC + 1, value);
                } else {
                    position.set(Position.PREFIX_ADC + 1, value * 0.1);
                }
            }
        }

        if (type == MSG_GPS_LBS_1 && buf.readableBytes() == 4 + 6) {
            position.set(Position.KEY_ODOMETER, buf.readUnsignedInt());
        }

        if (type == MSG_GPS_LBS_2 && buf.readableBytes() == 3 + 6) {
            position.set(Position.KEY_IGNITION, buf.readUnsignedByte() > 0);
            position.set(Position.KEY_EVENT, buf.readUnsignedByte()); // reason
            position.set(Position.KEY_ARCHIVE, buf.readUnsignedByte() > 0);
        }

    } else {

        if (dataLength > 0) {
            buf.skipBytes(dataLength);
        }
        if (type != MSG_COMMAND_0 && type != MSG_COMMAND_1 && type != MSG_COMMAND_2) {
            sendResponse(channel, false, type, buf.getShort(buf.writerIndex() - 6), null);
        }
        return null;

    }

    if (hasLanguage(type)) {
        buf.readUnsignedShort();
    }

    if (type == MSG_GPS_LBS_STATUS_3 || type == MSG_FENCE_MULTI) {
        position.set(Position.KEY_GEOFENCE, buf.readUnsignedByte());
    }

    sendResponse(channel, false, type, buf.getShort(buf.writerIndex() - 6), null);

    return position;
}