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:net.openhft.fix.transport.test.NettyFrameDecoderTest.java

License:Apache License

@Test
public void testDecode() {
    ByteBuf message = newLogonMessage();
    ByteBuf msgcopy = message.copy();
    EmbeddedChannel channel = new EmbeddedChannel(new NettyFrameDecoder());

    // raw write write
    Assert.assertTrue(channel.writeInbound(message));
    Assert.assertTrue(channel.finish());

    // read//from w  w w.j a v  a2s  . c  o m
    byte[] result = (byte[]) channel.readInbound();
    Assert.assertNotNull(result);

    if (msgcopy.hasArray()) {
        Assert.assertArrayEquals(msgcopy.array(), result);
    }
}

From source file:org.aotorrent.common.protocol.tracker.HTTPTrackerResponse.java

License:Apache License

public ByteBuf toTransmit() throws IOException, InvalidBEncodingException {
    Map<String, BEncodeValue> responseMap = Maps.newHashMap();

    responseMap.put("interval", new BEncodeValue(interval));
    responseMap.put("min_interval", new BEncodeValue(interval));
    responseMap.put("tracker id", new BEncodeValue(trackerId));
    responseMap.put("complete", new BEncodeValue(complete));
    responseMap.put("incomplete", new BEncodeValue(incomplete));

    ByteBuf peersEncoded = Unpooled.buffer(peers.size() * 6);
    for (InetSocketAddress peer : peers) {
        peersEncoded.writeBytes(peer.getAddress().getAddress());
        peersEncoded.writeShort(peer.getPort());
    }//from   w  ww  .  j  a  v  a  2s.  c om

    responseMap.put("peers", new BEncodeValue(
            new String(peersEncoded.array(), Charset.forName(Torrent.DEFAULT_TORRENT_ENCODING))));

    return BEncodeWriter.writeOut(responseMap);
}

From source file:org.apache.activemq.artemis.core.io.mapped.MappedFile.java

License:Apache License

/**
 * Writes a sequence of bytes to this file from the given buffer.
 * <p>/*ww w . j  a  va2s .c o m*/
 * <p> Bytes are written starting at this file's current position,
 */
public void write(ByteBuf src, int srcStart, int srcLength) throws IOException {
    final int nextPosition = this.position + srcLength;
    checkCapacity(nextPosition);
    final long destAddress = this.address + this.position;
    if (src.hasMemoryAddress()) {
        final long srcAddress = src.memoryAddress() + srcStart;
        PlatformDependent.copyMemory(srcAddress, destAddress, srcLength);
    } else if (src.hasArray()) {
        final byte[] srcArray = src.array();
        PlatformDependent.copyMemory(srcArray, srcStart, destAddress, srcLength);
    } else {
        throw new IllegalArgumentException("unsupported byte buffer");
    }
    rawMovePositionAndLength(nextPosition);
}

From source file:org.apache.activemq.artemis.core.protocol.proton.plug.ProtonSessionIntegrationCallback.java

License:Apache License

@Override
public void serverSend(final Receiver receiver, final Delivery delivery, String address, int messageFormat,
        ByteBuf messageEncoded) throws Exception {
    EncodedMessage encodedMessage = new EncodedMessage(messageFormat, messageEncoded.array(),
            messageEncoded.arrayOffset(), messageEncoded.writerIndex());

    ServerMessage message = manager.getConverter().inbound(encodedMessage);
    //use the address on the receiver if not null, if null let's hope it was set correctly on the message
    if (address != null) {
        message.setAddress(new SimpleString(address));
    }//w w w .j  a va 2s . co  m

    serverSession.send(message, false);

    manager.getServer().getStorageManager().afterCompleteOperations(new IOAsyncTask() {
        @Override
        public void done() {
            synchronized (connection.getLock()) {
                delivery.settle();
                connection.flush();
            }
        }

        @Override
        public void onError(int errorCode, String errorMessage) {
            synchronized (connection.getLock()) {
                receiver.setCondition(
                        new ErrorCondition(AmqpError.ILLEGAL_STATE, errorCode + ":" + errorMessage));
                connection.flush();
            }
        }
    });
}

From source file:org.apache.activemq.artemis.message.CoreMessageTest.java

License:Apache License

private CoreMessage decodeMessage() {

    ByteBuf newBuffer = Unpooled.buffer(BYTE_ENCODE.capacity());
    newBuffer.writeBytes(BYTE_ENCODE, 0, BYTE_ENCODE.writerIndex());

    CoreMessage coreMessage = internalDecode(newBuffer);

    int encodeSize = coreMessage.getEncodeSize();

    Assert.assertEquals(newBuffer.capacity(), encodeSize);

    Assert.assertEquals(ADDRESS, coreMessage.getAddressSimpleString());

    Assert.assertEquals(PROP1_VALUE.toString(), coreMessage.getStringProperty(PROP1_NAME));

    ByteBuf destinedBuffer = Unpooled.buffer(BYTE_ENCODE.array().length);
    coreMessage.sendBuffer(destinedBuffer, 0);

    byte[] destinedArray = destinedBuffer.array();
    byte[] sourceArray = BYTE_ENCODE.array();

    CoreMessage newDecoded = internalDecode(Unpooled.wrappedBuffer(destinedArray));

    Assert.assertEquals(encodeSize, newDecoded.getEncodeSize());

    Assert.assertArrayEquals(sourceArray, destinedArray);

    return coreMessage;
}

From source file:org.apache.activemq.artemis.message.CoreMessageTest.java

License:Apache License

@Test
public void testPassThroughMultipleThreads() throws Throwable {
    CoreMessage coreMessage = new CoreMessage();
    coreMessage.receiveBuffer(BYTE_ENCODE);

    LinkedList<Throwable> errors = new LinkedList<>();

    Thread[] threads = new Thread[50];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(() -> {
            try {
                for (int j = 0; j < 50; j++) {
                    Assert.assertEquals(ADDRESS, coreMessage.getAddressSimpleString());
                    Assert.assertEquals(PROP1_VALUE.toString(), coreMessage.getStringProperty(PROP1_NAME));

                    ByteBuf destinedBuffer = Unpooled.buffer(BYTE_ENCODE.array().length);
                    coreMessage.sendBuffer(destinedBuffer, 0);

                    byte[] destinedArray = destinedBuffer.array();
                    byte[] sourceArray = BYTE_ENCODE.array();

                    Assert.assertArrayEquals(sourceArray, destinedArray);

                    Assert.assertEquals(TEXT,
                            TextMessageUtil.readBodyText(coreMessage.getReadOnlyBodyBuffer()).toString());
                }//from   ww  w .j ava2 s. c  o  m
            } catch (Throwable e) {
                e.printStackTrace();
                errors.add(e);
            }
        });
    }

    for (Thread t : threads) {
        t.start();
    }

    for (Thread t : threads) {
        t.join();
    }

    for (Throwable e : errors) {
        throw e;
    }

}

From source file:org.apache.activemq.artemis.protocol.amqp.broker.AMQPSessionCallback.java

License:Apache License

public void serverSend(final Transaction transaction, final Receiver receiver, final Delivery delivery,
        String address, int messageFormat, ByteBuf messageEncoded) throws Exception {
    EncodedMessage encodedMessage = new EncodedMessage(messageFormat, messageEncoded.array(),
            messageEncoded.arrayOffset(), messageEncoded.writerIndex());

    ServerMessage message = manager.getConverter().inbound(encodedMessage);
    //use the address on the receiver if not null, if null let's hope it was set correctly on the message
    if (address != null) {
        message.setAddress(new SimpleString(address));
    }/*from   w  w  w.  jav  a2 s  .co m*/

    recoverContext();

    PagingStore store = manager.getServer().getPagingManager().getPageStore(message.getAddress());
    if (store.isRejectingMessages()) {
        // We drop pre-settled messages (and abort any associated Tx)
        if (delivery.remotelySettled()) {
            if (transaction != null) {
                String amqpAddress = delivery.getLink().getTarget().getAddress();
                ActiveMQException e = new ActiveMQAMQPResourceLimitExceededException(
                        "Address is full: " + amqpAddress);
                transaction.markAsRollbackOnly(e);
            }
        } else {
            rejectMessage(delivery);
        }
    } else {
        serverSend(transaction, message, delivery, receiver);
    }
}

From source file:org.apache.activemq.artemis.protocol.amqp.converter.message.JMSMappingOutboundTransformerTest.java

License:Apache License

public EncodedMessage transform(ServerJMSMessage message) throws Exception {
    // Useful for testing but not recommended for real life use.
    ByteBuf nettyBuffer = Unpooled.buffer(1024);
    NettyWritable buffer = new NettyWritable(nettyBuffer);

    long messageFormat = transformer.transform(message, buffer);

    EncodedMessage encoded = new EncodedMessage(messageFormat, nettyBuffer.array(),
            nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(), nettyBuffer.readableBytes());

    return encoded;
}

From source file:org.apache.activemq.artemis.protocol.amqp.converter.ProtonMessageConverter.java

License:Apache License

@Override
public Object outbound(ServerMessage messageOutbound, int deliveryCount) throws Exception {
    // Useful for testing but not recommended for real life use.
    ByteBuf nettyBuffer = Unpooled.buffer(1024);
    NettyWritable buffer = new NettyWritable(nettyBuffer);
    long messageFormat = (long) outbound(messageOutbound, deliveryCount, buffer);

    EncodedMessage encoded = new EncodedMessage(messageFormat, nettyBuffer.array(),
            nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(), nettyBuffer.readableBytes());

    return encoded;
}

From source file:org.apache.activemq.artemis.protocol.amqp.proton.ProtonServerSenderContext.java

License:Apache License

/**
 * handle an out going message from ActiveMQ Artemis, send via the Proton Sender
 *//*from w  w w  .  ja  v  a2 s . co  m*/
public int deliverMessage(MessageReference messageReference, int deliveryCount, Connection transportConnection)
        throws Exception {

    if (closed) {
        return 0;
    }

    AMQPMessage message = CoreAmqpConverter.checkAMQP(messageReference.getMessage());
    sessionSPI.invokeOutgoing(message,
            (ActiveMQProtonRemotingConnection) transportConnection.getProtocolConnection());

    // presettle means we can settle the message on the dealer side before we send it, i.e.
    // for browsers
    boolean preSettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED;

    // we only need a tag if we are going to settle later
    byte[] tag = preSettle ? new byte[0] : protonSession.getTag();

    ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(message.getEncodeSize());
    try {
        message.sendBuffer(nettyBuffer, deliveryCount);

        int size = nettyBuffer.writerIndex();

        while (!connection.tryLock(1, TimeUnit.SECONDS)) {
            if (closed || sender.getLocalState() == EndpointState.CLOSED) {
                // If we're waiting on the connection lock, the link might be in the process of closing.  If this happens
                // we return.
                return 0;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Couldn't get lock on deliverMessage " + this);
                }
            }
        }

        try {
            final Delivery delivery;
            delivery = sender.delivery(tag, 0, tag.length);
            delivery.setMessageFormat((int) message.getMessageFormat());
            delivery.setContext(messageReference);

            // this will avoid a copy.. patch provided by Norman using buffer.array()
            sender.send(nettyBuffer.array(), nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(),
                    nettyBuffer.readableBytes());

            if (preSettle) {
                // Presettled means the client implicitly accepts any delivery we send it.
                sessionSPI.ack(null, brokerConsumer, messageReference.getMessage());
                delivery.settle();
            } else {
                sender.advance();
            }
            connection.flush();
        } finally {
            connection.unlock();
        }

        return size;
    } finally {
        nettyBuffer.release();
    }
}