Example usage for io.netty.buffer ByteBuf array

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

Introduction

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

Prototype

public abstract byte[] array();

Source Link

Document

Returns the backing byte array of this buffer.

Usage

From source file:com.vethrfolnir.game.network.mu.packets.MuReadPacket.java

License:Open Source License

protected void shiftC(ByteBuf buff, int pos) {
    byte b = buff.array()[pos];
    b &= 0x7F;/*from  w w  w.  j  a v  a  2 s  . c o  m*/
    b |= 0x80;
    buff.array()[pos] = b;
}

From source file:com.vethrfolnir.game.network.mu.packets.MuWritePacket.java

License:Open Source License

public void shiftC(ByteBuf buff, int pos) {
    byte b = buff.array()[pos];
    b &= 0x7F;//www. ja va  2s .  co m
    b |= 0x80;
    buff.array()[pos] = b;
}

From source file:com.vethrfolnir.game.network.mu.received.MovedToLocation.java

License:Open Source License

@Override
public void read(MuClient client, ByteBuf buff, Object... params) {
    GameObject entity = client.getEntity();
    Positioning positioning = entity.get(PlayerMapping.Positioning);

    int origianlX = readC(buff);
    int origianlY = readC(buff);

    int offset = buff.readerIndex();
    byte[] data = buff.array();

    int pack = data[offset];
    int stepCount = (pack & 0x0F) + 1; // ... seriously now ...
    int heading = (pack & 0xF0) >> 4;

    int x = origianlX, y = origianlY;

    int TableIndex = 0;
    for (int i = 1; i < stepCount; i++) {
        if ((i % 2) == 1)
            TableIndex = data[offset + (i + 1) / 2] >> 4;
        else// w w w  .  j av  a 2s. c om
            TableIndex = data[offset + (i + 1) / 2] & 0x0F;

        x += stepDirections[TableIndex * 2];
        y += stepDirections[TableIndex * 2 + 1];
    }

    PlayerState state = entity.get(PlayerMapping.PlayerState);

    // Cheap yet effective, for now
    int distance = (int) MuUtils.distanceSquared(positioning.getX(), positioning.getY(), x, y);

    if (!state.isGM() && (distance > 10 && !positioning.moveFlag())) {
        client.close();
    }

    positioning.moveTo(x, y, heading);
    //System.out.println(getClass().getSimpleName()+": player "+entity.getName()+" "+x+" X "+y+" Y from[x "+origianlX+" y "+origianlY+"]  Heading: "+(heading)+". Step Count: "+stepCount);
}

From source file:com.yahoo.pulsar.broker.admin.BrokerStats.java

License:Apache License

@GET
@Path("/destinations")
@ApiOperation(value = "Get all the destination stats by namesapce", response = OutputStream.class, responseContainer = "OutputStream") // https://github.com/swagger-api/swagger-ui/issues/558
                                                                                                                                       // map
                                                                                                                                       // support
                                                                                                                                       // missing
@ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission") })
public StreamingOutput getDestinations2() throws Exception {
    // Ensure super user access only
    validateSuperUserAccess();/*from ww  w  .  jav a 2s . c o  m*/
    return new StreamingOutput() {
        public void write(OutputStream output) throws IOException, WebApplicationException {
            ByteBuf statsBuf = null;
            try {
                statsBuf = pulsar().getBrokerService().getDimensionMetrics();
                output.write(statsBuf.array(), statsBuf.arrayOffset(), statsBuf.readableBytes());
            } catch (Exception e) {
                throw new WebApplicationException(e);
            } finally {
                ReferenceCountUtil.release(statsBuf);
            }
        }
    };
}

From source file:com.yahoo.pulsar.broker.admin.PersistentTopics.java

License:Apache License

@GET
@Path("/{property}/{cluster}/{namespace}/{destination}/subscription/{subName}/position/{messagePosition}")
@ApiOperation(value = "Peek nth message on a topic subscription.")
@ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"),
        @ApiResponse(code = 404, message = "Topic, subscription or the message position does not exist") })
public Response peekNthMessage(@PathParam("property") String property, @PathParam("cluster") String cluster,
        @PathParam("namespace") String namespace, @PathParam("destination") @Encoded String destination,
        @PathParam("subName") String subName, @PathParam("messagePosition") int messagePosition,
        @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    destination = decode(destination);/*from ww  w . ja  v a 2s  .c o  m*/
    DestinationName dn = DestinationName.get(domain(), property, cluster, namespace, destination);
    PartitionedTopicMetadata partitionMetadata = getPartitionedTopicMetadata(property, cluster, namespace,
            destination, authoritative);
    if (partitionMetadata.partitions > 0) {
        throw new RestException(Status.METHOD_NOT_ALLOWED,
                "Peek messages on a partitioned topic is not allowed");
    }
    validateAdminOperationOnDestination(dn, authoritative);
    PersistentTopic topic = getTopicReference(dn);
    PersistentReplicator repl = null;
    PersistentSubscription sub = null;
    Entry entry = null;
    if (subName.startsWith(topic.replicatorPrefix)) {
        repl = getReplicatorReference(subName, topic);
    } else {
        sub = getSubscriptionReference(subName, topic);
    }
    try {
        if (subName.startsWith(topic.replicatorPrefix)) {
            entry = repl.peekNthMessage(messagePosition).get();
        } else {
            entry = sub.peekNthMessage(messagePosition).get();
        }
        checkNotNull(entry);
        PositionImpl pos = (PositionImpl) entry.getPosition();
        ByteBuf metadataAndPayload = entry.getDataBuffer();

        // moves the readerIndex to the payload
        MessageMetadata metadata = Commands.parseMessageMetadata(metadataAndPayload);

        ResponseBuilder responseBuilder = Response.ok();
        responseBuilder.header("X-Pulsar-Message-ID", pos.toString());
        for (KeyValue keyValue : metadata.getPropertiesList()) {
            responseBuilder.header("X-Pulsar-PROPERTY-" + keyValue.getKey(), keyValue.getValue());
        }
        if (metadata.hasPublishTime()) {
            responseBuilder.header("X-Pulsar-publish-time",
                    DATE_FORMAT.format(Instant.ofEpochMilli(metadata.getPublishTime())));
        }

        // Decode if needed
        CompressionCodec codec = CompressionCodecProvider.getCompressionCodec(metadata.getCompression());
        ByteBuf uncompressedPayload = codec.decode(metadataAndPayload, metadata.getUncompressedSize());

        // Copy into a heap buffer for output stream compatibility
        ByteBuf data = PooledByteBufAllocator.DEFAULT.heapBuffer(uncompressedPayload.readableBytes(),
                uncompressedPayload.readableBytes());
        data.writeBytes(uncompressedPayload);
        uncompressedPayload.release();

        StreamingOutput stream = new StreamingOutput() {

            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                output.write(data.array(), data.arrayOffset(), data.readableBytes());
                data.release();
            }
        };

        return responseBuilder.entity(stream).build();
    } catch (NullPointerException npe) {
        throw new RestException(Status.NOT_FOUND, "Message not found");
    } catch (Exception exception) {
        log.error("[{}] Failed to get message at position {} from {} {}", clientAppId(), messagePosition, dn,
                subName, exception);
        throw new RestException(exception);
    } finally {
        if (entry != null) {
            entry.release();
        }
    }
}

From source file:com.yahoo.pulsar.client.impl.MessageIdImpl.java

License:Apache License

protected byte[] toByteArray(int batchIndex) {
    MessageIdData.Builder builder = MessageIdData.newBuilder();
    builder.setLedgerId(ledgerId);//from  w  w w. j a v a 2s  .  c  o m
    builder.setEntryId(entryId);
    if (partitionIndex >= 0) {
        builder.setPartition(partitionIndex);
    }

    if (batchIndex != -1) {
        builder.setBatchIndex(batchIndex);
    }

    MessageIdData msgId = builder.build();
    int size = msgId.getSerializedSize();
    ByteBuf serialized = Unpooled.buffer(size, size);
    ByteBufCodedOutputStream stream = ByteBufCodedOutputStream.get(serialized);
    try {
        msgId.writeTo(stream);
    } catch (IOException e) {
        // This is in-memory serialization, should not fail
        throw new RuntimeException(e);
    }

    msgId.recycle();
    builder.recycle();
    stream.recycle();
    return serialized.array();
}

From source file:com.yahoo.pulsar.common.compression.CompressionCodecZLib.java

License:Apache License

@Override
public ByteBuf encode(ByteBuf source) {
    byte[] array;
    int length = source.readableBytes();

    int sizeEstimate = (int) Math.ceil(source.readableBytes() * 1.001) + 14;
    ByteBuf compressed = PooledByteBufAllocator.DEFAULT.heapBuffer(sizeEstimate);

    int offset = 0;
    if (source.hasArray()) {
        array = source.array();
        offset = source.arrayOffset() + source.readerIndex();
    } else {//from  www . ja v  a  2s . c o m
        // If it's a direct buffer, we need to copy it
        array = new byte[length];
        source.getBytes(source.readerIndex(), array);
    }

    synchronized (deflater) {
        deflater.setInput(array, offset, length);
        while (!deflater.needsInput()) {
            deflate(compressed);
        }

        deflater.reset();
    }

    return compressed;
}

From source file:com.yahoo.pulsar.common.compression.CompressionCodecZLib.java

License:Apache License

private void deflate(ByteBuf out) {
    int numBytes;
    do {//from   w  w w.  java 2s .c o m
        int writerIndex = out.writerIndex();
        numBytes = deflater.deflate(out.array(), out.arrayOffset() + writerIndex, out.writableBytes(),
                Deflater.SYNC_FLUSH);
        out.writerIndex(writerIndex + numBytes);
    } while (numBytes > 0);
}

From source file:com.yahoo.pulsar.common.compression.CompressionCodecZLib.java

License:Apache License

@Override
public ByteBuf decode(ByteBuf encoded, int uncompressedLength) throws IOException {
    ByteBuf uncompressed = PooledByteBufAllocator.DEFAULT.heapBuffer(uncompressedLength, uncompressedLength);

    int len = encoded.readableBytes();

    byte[] array;
    int offset;/*from ww  w  . ja  v  a 2  s  . com*/
    if (encoded.hasArray()) {
        array = encoded.array();
        offset = encoded.arrayOffset() + encoded.readerIndex();
    } else {
        array = new byte[len];
        encoded.getBytes(encoded.readerIndex(), array);
        offset = 0;
    }

    int resultLength;
    synchronized (inflater) {
        inflater.setInput(array, offset, len);
        try {
            resultLength = inflater.inflate(uncompressed.array(), uncompressed.arrayOffset(),
                    uncompressedLength);
        } catch (DataFormatException e) {
            throw new IOException(e);
        }
        inflater.reset();
    }

    checkArgument(resultLength == uncompressedLength);

    uncompressed.writerIndex(uncompressedLength);
    return uncompressed;
}

From source file:com.yahoo.pulsar.common.compression.Crc32cChecksumTest.java

License:Apache License

@Test
public void testCrc32cHardware() {
    if (HARDWARE_CRC32C_HASH == null) {
        return;/* w  w w  .j ava  2 s . c om*/
    }

    ByteBuf payload = Unpooled.wrappedBuffer(inputBytes);

    // compute checksum using sse4.2 hw instruction
    int hw = HARDWARE_CRC32C_HASH.calculate(payload.array(), payload.arrayOffset() + payload.readerIndex(),
            payload.readableBytes());
    assertEquals(hw, expectedChecksum);
}