Java Examples for org.fusesource.hawtbuf.Buffer

The following java examples will help you to understand the usage of org.fusesource.hawtbuf.Buffer. These source code samples are taken from different open source projects.

Example 1
Project: mqtt-client-master  File: CallbackConnection.java View source code
public CallbackConnection listener(final Listener original) {
    if (original instanceof ExtendedListener) {
        this.listener = (ExtendedListener) original;
    } else {
        this.listener = new ExtendedListener() {

            public void onPublish(UTF8Buffer topic, Buffer body, final Callback<Callback<Void>> ack) {
                original.onPublish(topic, body, new Runnable() {

                    public void run() {
                        ack.onSuccess(null);
                    }
                });
            }

            public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) {
                original.onPublish(topic, body, ack);
            }

            public void onConnected() {
                original.onConnected();
            }

            public void onDisconnected() {
                original.onDisconnected();
            }

            public void onFailure(Throwable value) {
                original.onFailure(value);
            }
        };
    }
    return this;
}
Example 2
Project: activemq-master  File: MQTTProtocolConverter.java View source code
public PUBLISH convertMessage(ActiveMQMessage message) throws IOException, JMSException, DataFormatException {
    PUBLISH result = new PUBLISH();
    // packet id is set in MQTTSubscription
    QoS qoS;
    if (message.propertyExists(QOS_PROPERTY_NAME)) {
        int ordinal = message.getIntProperty(QOS_PROPERTY_NAME);
        qoS = QoS.values()[ordinal];
    } else {
        qoS = message.isPersistent() ? QoS.AT_MOST_ONCE : QoS.AT_LEAST_ONCE;
    }
    result.qos(qoS);
    if (message.getBooleanProperty(RetainedMessageSubscriptionRecoveryPolicy.RETAINED_PROPERTY)) {
        result.retain(true);
    }
    String topicName;
    synchronized (mqttTopicMap) {
        topicName = mqttTopicMap.get(message.getJMSDestination());
        if (topicName == null) {
            String amqTopicName = findSubscriptionStrategy().onSend(message.getDestination());
            topicName = MQTTProtocolSupport.convertActiveMQToMQTT(amqTopicName);
            mqttTopicMap.put(message.getJMSDestination(), topicName);
        }
    }
    result.topicName(new UTF8Buffer(topicName));
    if (message.getDataStructureType() == ActiveMQTextMessage.DATA_STRUCTURE_TYPE) {
        ActiveMQTextMessage msg = (ActiveMQTextMessage) message.copy();
        msg.setReadOnlyBody(true);
        String messageText = msg.getText();
        if (messageText != null) {
            result.payload(new Buffer(messageText.getBytes("UTF-8")));
        }
    } else if (message.getDataStructureType() == ActiveMQBytesMessage.DATA_STRUCTURE_TYPE) {
        ActiveMQBytesMessage msg = (ActiveMQBytesMessage) message.copy();
        msg.setReadOnlyBody(true);
        byte[] data = new byte[(int) msg.getBodyLength()];
        msg.readBytes(data);
        result.payload(new Buffer(data));
    } else if (message.getDataStructureType() == ActiveMQMapMessage.DATA_STRUCTURE_TYPE) {
        ActiveMQMapMessage msg = (ActiveMQMapMessage) message.copy();
        msg.setReadOnlyBody(true);
        Map<String, Object> map = msg.getContentMap();
        if (map != null) {
            result.payload(new Buffer(map.toString().getBytes("UTF-8")));
        }
    } else {
        ByteSequence byteSequence = message.getContent();
        if (byteSequence != null && byteSequence.getLength() > 0) {
            if (message.isCompressed()) {
                Inflater inflater = new Inflater();
                inflater.setInput(byteSequence.data, byteSequence.offset, byteSequence.length);
                byte[] data = new byte[4096];
                int read;
                ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
                while ((read = inflater.inflate(data)) != 0) {
                    bytesOut.write(data, 0, read);
                }
                byteSequence = bytesOut.toByteSequence();
                bytesOut.close();
            }
            result.payload(new Buffer(byteSequence.data, byteSequence.offset, byteSequence.length));
        }
    }
    LOG.trace("ActiveMQ-->MQTT:MQTT_MSGID:{} client:{} connection:{} ActiveMQ_MSGID:{}", result.messageId(), clientId, connectionInfo.getConnectionId(), message.getMessageId());
    return result;
}
Example 3
Project: fuse-extra-master  File: DescribedType.java View source code
protected void createStaticBlock() {
    for (Object obj : type.getEncodingOrDescriptorOrFieldOrChoiceOrDoc()) {
        if (obj instanceof Descriptor) {
            Descriptor desc = (Descriptor) obj;
            int mods = JMod.PUBLIC | JMod.STATIC | JMod.FINAL;
            SYMBOLIC_ID = cls().field(mods, Buffer.class, "SYMBOLIC_ID", _new(cm.ref(AsciiBuffer.class)).arg(desc.getName()));
            SYMBOLIC_ID_SIZE = cls().field(mods, Long.class, "SYMBOLIC_ID_SIZE", generator.registry().cls().staticInvoke("instance").invoke("sizer").invoke("sizeOfSymbol").arg(ref("SYMBOLIC_ID")));
            String[] code = desc.getCode().split(":");
            String category = code[0];
            String descriptorId = code[1];
            category = category.substring(2);
            descriptorId = descriptorId.substring(2);
            //CATEGORY = cls().field(mods, long.class, "CATEGORY", JExpr.lit(Integer.parseInt(category.substring(2), 16)));
            //DESCRIPTOR_ID = cls().field(mods, long.class, "DESCRIPTOR_ID", JExpr.lit(Integer.parseInt(descriptorId.substring(2), 16)));
            //NUMERIC_ID = cls().field(mods, cm.LONG, "NUMERIC_ID", JExpr.direct("CATEGORY << 32 | DESCRIPTOR_ID"));
            NUMERIC_ID = cls().field(mods, BigInteger.class, "NUMERIC_ID", _new(cm.ref("java.math.BigInteger")).arg(lit(category + descriptorId)).arg(lit(16)));
            NUMERIC_ID_SIZE = cls().field(mods, Long.class, "NUMERIC_ID_SIZE", generator.registry().cls().staticInvoke("instance").invoke("sizer").invoke("sizeOfULong").arg(ref("NUMERIC_ID")));
            SYMBOLIC_CONSTRUCTOR = cls().field(mods, cm.ref(generator.getMarshaller() + ".DescribedConstructor"), "SYMBOLIC_CONSTRUCTOR", _new(cm.ref(generator.getMarshaller() + ".DescribedConstructor")).arg(ref("SYMBOLIC_ID")));
            NUMERIC_CONSTRUCTOR = cls().field(mods, cm.ref(generator.getMarshaller() + ".DescribedConstructor"), "NUMERIC_CONSTRUCTOR", _new(cm.ref(generator.getMarshaller() + ".DescribedConstructor")).arg(ref("NUMERIC_ID")));
            CONSTRUCTOR = cls().field(mods, cm.ref(generator.getMarshaller() + ".DescribedConstructor"), "CONSTRUCTOR");
            cls().init().add(generator.registry().cls().staticInvoke("instance").invoke("getFormatCodeMap").invoke("put").arg(ref("NUMERIC_ID")).arg(cls().dotclass()));
            cls().init().add(generator.registry().cls().staticInvoke("instance").invoke("getSymbolicCodeMap").invoke("put").arg(ref("SYMBOLIC_ID")).arg(cls().dotclass()));
            JConditional block = cls().init()._if(cm.ref("java.lang.Boolean").staticInvoke("parseBoolean").arg(cm.ref("java.lang.System").staticInvoke("getProperty").arg(lit(generator.getCodecPackagePrefix() + ".UseSymbolicID"))));
            block._then().assign(ref("CONSTRUCTOR"), ref("SYMBOLIC_CONSTRUCTOR"));
            block._else().assign(ref("CONSTRUCTOR"), ref("NUMERIC_CONSTRUCTOR"));
        }
    }
}
Example 4
Project: atmosphere-stomp-master  File: ApolloTest.java View source code
/**
     * Tests decode.
     */
@Test
public void decodeClientFrameTest() {
    final long start = System.currentTimeMillis();
    for (final String frame : clientFrames) {
        final MessageRecord mr = new MessageRecord();
        mr.buffer_$eq(new Buffer(frame.getBytes()));
        StompFrameMessage sfm = StompCodec.decode(mr);
        final StompFrame sm = sfm.frame();
        logger.info(sm.action().toString());
    }
    final long ms = System.currentTimeMillis() - start;
    logger.info("Apollo decodes client frames in {}ms", ms);
}
Example 5
Project: hawtbuf-master  File: TextFormat.java View source code
/**
     * If the next token is a string, consume it, unescape it as a
     * {@link Buffer}, and return it.  Otherwise, throw a
     * {@link ParseException}.
     */
public Buffer consumeBuffer() throws ParseException {
    char quote = currentToken.length() > 0 ? currentToken.charAt(0) : '\0';
    if (quote != '\"' && quote != '\'') {
        throw parseException("Expected string.");
    }
    if (currentToken.length() < 2 || currentToken.charAt(currentToken.length() - 1) != quote) {
        throw parseException("String missing ending quote.");
    }
    try {
        String escaped = currentToken.substring(1, currentToken.length() - 1);
        Buffer result = unescapeBytes(escaped);
        nextToken();
        return result;
    } catch (InvalidEscapeSequence e) {
        throw parseException(e.getMessage());
    }
}
Example 6
Project: camel-master  File: MQTTEndpoint.java View source code
public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) {
    if (!consumers.isEmpty()) {
        Exchange exchange = createExchange();
        exchange.getIn().setBody(body.toByteArray());
        exchange.getIn().setHeader(MQTTConfiguration.MQTT_SUBSCRIBE_TOPIC, topic.toString());
        for (MQTTConsumer consumer : consumers) {
            consumer.processExchange(exchange);
        }
    }
    if (ack != null) {
        ack.run();
    }
}
Example 7
Project: hawtdb-master  File: HawtTxPageFile.java View source code
Buffer encode() {
    try {
        os.reset();
        os.write(magic);
        os.writeLong(base_revision);
        os.writeInt(page_size);
        os.writeInt(free_list_page);
        os.writeInt(pessimistic_recovery_page);
        os.writeInt(optimistic_recovery_page);
        int length = os.position();
        byte[] data = os.getData();
        CRC32 checksum = new CRC32();
        checksum.update(data, 0, length);
        os.position((FILE_HEADER_SIZE / 2) - 8);
        os.writeLong(checksum.getValue());
        System.arraycopy(data, 0, data, FILE_HEADER_SIZE / 2, length);
        os.position(FILE_HEADER_SIZE / 2 - 8);
        os.writeLong(checksum.getValue());
        return os.toBuffer();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 8
Project: spice-zapper-master  File: ZapperPayload.java View source code
protected byte[] createSegmentFooter() {
    SegmentFooter footer = new SegmentFooter();
    final Hash bodyHash = super.getHash();
    footer.addHashes(new org.sonatype.spice.zapper.internal.hawtbuf.Hash().setHashAlg(bodyHash.getHashAlgorithmIdentifier().stringValue()).setHashBytes(new Buffer(bodyHash.byteValue())));
    return footer.toFramedByteArray();
}
Example 9
Project: activemq-artemis-master  File: AmqpSupport.java View source code
/**
    * Conversion from Java ByteBuffer to a HawtBuf buffer.
    *
    * @param data the ByteBuffer instance to convert.
    * @return a new HawtBuf buffer converted from the given ByteBuffer.
    */
public static Buffer toBuffer(ByteBuffer data) {
    if (data == null) {
        return null;
    }
    Buffer rc;
    if (data.isDirect()) {
        rc = new Buffer(data.remaining());
        data.get(rc.data);
    } else {
        rc = new Buffer(data);
        data.position(data.position() + data.remaining());
    }
    return rc;
}
Example 10
Project: hawtdispatch-master  File: AbstractProtocolCodec.java View source code
protected Buffer readUntil(Byte octet, int max, String msg) throws ProtocolException {
    byte[] array = readBuffer.array();
    Buffer buf = new Buffer(array, readEnd, readBuffer.position() - readEnd);
    int pos = buf.indexOf(octet);
    if (pos >= 0) {
        int offset = readStart;
        readEnd += pos + 1;
        readStart = readEnd;
        int length = readEnd - offset;
        if (max >= 0 && length > max) {
            throw new ProtocolException(msg);
        }
        return new Buffer(array, offset, length);
    } else {
        readEnd += buf.length;
        if (max >= 0 && (readEnd - readStart) > max) {
            throw new ProtocolException(msg);
        }
        return null;
    }
}
Example 11
Project: iotcloud2-master  File: MQTTConsumer.java View source code
public void onPublish(UTF8Buffer topic, Buffer payload, Runnable onComplete) {
    final String uuid = UUID.randomUUID().toString();
    try {
        MQTTMessage message = new MQTTMessage(payload, topic.toString());
        messages.put(message);
        onComplete.run();
    } catch (InterruptedException e) {
        LOG.error("Failed to put the message to queue", e);
    }
}
Example 12
Project: mqtt-irc-bot-master  File: BotController.java View source code
@Override
public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) {
    final String channel = Iterables.getLast(Splitter.on("/").trimResults().split(topic.toString())).replace(mqttProperties.getMqttIrcChannelPrefix(), "#");
    ack.run();
    log.debug("Received message on topic {} with payload {}. Writing to IRC channel {}", topic.toString(), body.utf8().toString(), channel);
    bot.sendMessage(channel, body.utf8().toString());
}
Example 13
Project: mqtt-test-suit-master  File: Publishers.java View source code
public static void main(String[] args) throws Exception {
    Publishers main = new Publishers();
    // Process the arguments
    LinkedList<String> argl = new LinkedList<String>(Arrays.asList(args));
    while (!argl.isEmpty()) {
        try {
            String arg = argl.removeFirst();
            if ("--help".equals(arg)) {
                displayHelpAndExit(0);
            } else if ("-v".equals(arg)) {
                main.mqtt.setVersion(shift(argl));
            } else if ("-h".equals(arg)) {
                main.mqtt.setHost(shift(argl));
            } else if ("-k".equals(arg)) {
                main.mqtt.setKeepAlive(Short.parseShort(shift(argl)));
            } else if ("-c".equals(arg)) {
                main.mqtt.setCleanSession(false);
            } else if ("-i".equals(arg)) {
                main.mqtt.setClientId(shift(argl));
            } else if ("-u".equals(arg)) {
                main.mqtt.setUserName(shift(argl));
            } else if ("-p".equals(arg)) {
                main.mqtt.setPassword(shift(argl));
            } else if ("--will-topic".equals(arg)) {
                main.mqtt.setWillTopic(shift(argl));
            } else if ("--will-payload".equals(arg)) {
                main.mqtt.setWillMessage(shift(argl));
            } else if ("--will-qos".equals(arg)) {
                int v = Integer.parseInt(shift(argl));
                if (v > QoS.values().length) {
                    stderr("Invalid qos value : " + v);
                    displayHelpAndExit(1);
                }
                main.mqtt.setWillQos(QoS.values()[v]);
            } else if ("--will-retain".equals(arg)) {
                main.mqtt.setWillRetain(true);
            } else if ("-d".equals(arg)) {
                main.debug = true;
            } else if ("--client-count".equals(arg)) {
                main.clientCount = Integer.parseInt(shift(argl));
            } else if ("--msg-count".equals(arg)) {
                main.messageCount = Integer.parseInt(shift(argl));
            } else if ("--client-sleep".equals(arg)) {
                main.sleep = Long.parseLong(shift(argl));
            } else if ("-q".equals(arg)) {
                int v = Integer.parseInt(shift(argl));
                if (v > QoS.values().length) {
                    stderr("Invalid qos value : " + v);
                    displayHelpAndExit(1);
                }
                main.qos = QoS.values()[v];
            } else if ("-r".equals(arg)) {
                main.retain = true;
            } else if ("-t".equals(arg)) {
                main.topic = new UTF8Buffer(shift(argl));
            } else if ("-m".equals(arg)) {
                main.body = new UTF8Buffer(shift(argl) + "\n");
            } else if ("-z".equals(arg)) {
                main.body = new UTF8Buffer("");
            } else if ("-f".equals(arg)) {
                File file = new File(shift(argl));
                RandomAccessFile raf = new RandomAccessFile(file, "r");
                try {
                    byte data[] = new byte[(int) raf.length()];
                    raf.seek(0);
                    raf.readFully(data);
                    main.body = new Buffer(data);
                } finally {
                    raf.close();
                }
            } else if ("-pc".equals(arg)) {
                main.prefixCounter = true;
            } else {
                stderr("Invalid usage: unknown option: " + arg);
                displayHelpAndExit(1);
            }
        } catch (NumberFormatException e) {
            stderr("Invalid usage: argument not a number");
            displayHelpAndExit(1);
        }
    }
    if (main.topic == null) {
        stderr("Invalid usage: no topic specified.");
        displayHelpAndExit(1);
    }
    if (main.body == null) {
        stderr("Invalid usage: -z -m or -f must be specified.");
        displayHelpAndExit(1);
    }
    main.execute();
    System.exit(0);
}
Example 14
Project: Osomcom-Pocsag-BSC-master  File: MqttService.java View source code
// Callback for processing the published topics
public void onPublish(UTF8Buffer topic, Buffer message, Runnable arg2) {
    LOGGER.fine("Received MQTT message on topic '" + topic + "': " + message);
    final String tmp = message.toString();
    Runnable MqttMsgProcessorTask = new Runnable() {

        @Override
        public void run() {
            PocsagServices pocsagServices = new PocsagServices();
            PocsagMessage pocsagMsg = PocsagMessage.parseMqttString(tmp);
            pocsagServices.send(pocsagMsg);
        }
    };
    new Thread(MqttMsgProcessorTask).start();
    // Must be executed after processing the message
    arg2.run();
}
Example 15
Project: Osomcom-Pocsag-MSC-master  File: MqttService.java View source code
// Callback for processing the published topics
public void onPublish(UTF8Buffer topic, Buffer message, Runnable arg2) {
    LOGGER.fine("Received MQTT message on topic '" + topic + "': " + message);
    final String tmp = message.toString();
    Runnable MqttMsgProcessorTask = new Runnable() {

        @Override
        public void run() {
            Node node = new Node();
            NodeServices nodeServices = new NodeServices();
            node.setGroup(1);
            node.setName(tmp.substring(7, tmp.indexOf(':', 7)));
            node.setProtocol(Node.Protocol.MQTT);
            node.setLastPing(new Timestamp((new Date()).getTime()));
            nodeServices.createOrUpdateByName(node);
        }
    };
    new Thread(MqttMsgProcessorTask).start();
    // Must be executed after processing the message
    arg2.run();
}
Example 16
Project: beam-master  File: MqttIOTest.java View source code
@Test
public void testWrite() throws Exception {
    MQTT client = new MQTT();
    client.setHost("tcp://localhost:" + port);
    final BlockingConnection connection = client.blockingConnection();
    connection.connect();
    connection.subscribe(new Topic[] { new Topic(Buffer.utf8("WRITE_TOPIC"), QoS.AT_LEAST_ONCE) });
    final Set<String> messages = new HashSet<>();
    Thread subscriber = new Thread() {

        public void run() {
            try {
                for (int i = 0; i < 200; i++) {
                    Message message = connection.receive();
                    messages.add(new String(message.getPayload()));
                    message.ack();
                }
            } catch (Exception e) {
                LOG.error("Can't receive message", e);
            }
        }
    };
    subscriber.start();
    ArrayList<byte[]> data = new ArrayList<>();
    for (int i = 0; i < 200; i++) {
        data.add(("Test " + i).getBytes());
    }
    pipeline.apply(Create.of(data)).apply(MqttIO.write().withConnectionConfiguration(MqttIO.ConnectionConfiguration.create("tcp://localhost:" + port, "WRITE_TOPIC")));
    pipeline.run();
    subscriber.join();
    connection.disconnect();
    assertEquals(200, messages.size());
    for (int i = 0; i < 200; i++) {
        assertTrue(messages.contains("Test " + i));
    }
}
Example 17
Project: hawtjms-master  File: JmsStreamMessage.java View source code
/**
     * Reads a byte array field from the stream message into the specified
     * <CODE>byte[]</CODE> object (the read buffer).
     * <p/>
     * <p/>
     * To read the field value, <CODE>readBytes</CODE> should be successively
     * called until it returns a value less than the length of the read buffer.
     * The value of the bytes in the buffer following the last byte read is
     * undefined.
     * <p/>
     * <p/>
     * If <CODE>readBytes</CODE> returns a value equal to the length of the
     * buffer, a subsequent <CODE>readBytes</CODE> call must be made. If there
     * are no more bytes to be read, this call returns -1.
     * <p/>
     * <p/>
     * If the byte array field value is null, <CODE>readBytes</CODE> returns -1.
     * <p/>
     * <p/>
     * If the byte array field value is empty, <CODE>readBytes</CODE> returns 0.
     * <p/>
     * <p/>
     * Once the first <CODE>readBytes</CODE> call on a <CODE>byte[]</CODE> field
     * value has been made, the full value of the field must be read before it
     * is valid to read the next field. An attempt to read the next field before
     * that has been done will throw a <CODE>MessageFormatException</CODE>.
     * <p/>
     * <p/>
     * To read the byte field value into a new <CODE>byte[]</CODE> object, use
     * the <CODE>readObject</CODE> method.
     *
     * @param value
     *        the buffer into which the data is read
     * @return the total number of bytes read into the buffer, or -1 if there is
     *         no more data because the end of the byte field has been reached
     * @throws JMSException
     *         if the JMS provider fails to read the message due to some
     *         internal error.
     * @throws MessageEOFException
     *         if unexpected end of message stream has been reached.
     * @throws MessageFormatException
     *         if this type conversion is invalid.
     * @throws MessageNotReadableException
     *         if the message is in write-only mode.
     * @see #readObject()
     */
@Override
public int readBytes(byte[] value) throws JMSException {
    initializeReading();
    try {
        if (value == null) {
            throw new NullPointerException();
        }
        checkEndOfStream();
        if (remainingBytes == -1) {
            Object data = stream.get(index++);
            if (!(data instanceof Buffer)) {
                throw new MessageFormatException("Not a byte array");
            }
            bytes = (Buffer) data;
            remainingBytes = bytes.length();
        } else if (remainingBytes == 0) {
            remainingBytes = -1;
            bytes = null;
            return -1;
        }
        if (value.length <= remainingBytes) {
            // small buffer
            remainingBytes -= value.length;
            System.arraycopy(bytes.data, bytes.offset, value, 0, value.length);
            bytes.offset += value.length;
            return value.length;
        } else {
            // big buffer
            System.arraycopy(bytes.data, bytes.offset, value, 0, remainingBytes);
            remainingBytes = 0;
            return bytes.length();
        }
    } catch (Throwable e) {
        throw JmsExceptionSupport.createMessageFormatException(e);
    }
}
Example 18
Project: hawtjournal-master  File: Journal.java View source code
private void compactDataFile(DataFile currentFile, Location firstUserLocation) throws IOException {
    DataFile tmpFile = new DataFile(new File(currentFile.getFile().getParent(), filePrefix + currentFile.getDataFileId() + ".tmp" + fileSuffix), currentFile.getDataFileId());
    RandomAccessFile raf = tmpFile.openRandomAccessFile();
    try {
        Location currentUserLocation = firstUserLocation;
        WriteBatch batch = new WriteBatch(tmpFile, 0);
        batch.prepareBatch();
        while (currentUserLocation != null) {
            Buffer data = accessor.readLocation(currentUserLocation);
            WriteCommand write = new WriteCommand(new Location(currentUserLocation), data, true);
            batch.appendBatch(write);
            currentUserLocation = goToNextLocation(currentUserLocation, Location.USER_RECORD_TYPE, false);
        }
        batch.perform(raf, null, true);
    } finally {
        if (raf != null) {
            raf.close();
        }
    }
    if (currentFile.getFile().delete()) {
        accessor.dispose(currentFile);
        totalLength.addAndGet(-currentFile.getLength());
        totalLength.addAndGet(tmpFile.getLength());
        if (tmpFile.getFile().renameTo(currentFile.getFile())) {
            currentFile.setLength(tmpFile.getLength());
        } else {
            throw new IOException("Cannot rename file: " + tmpFile.getFile());
        }
    } else {
        throw new IOException("Cannot remove file: " + currentFile.getFile());
    }
}
Example 19
Project: signalk-server-java-master  File: SkStompEndpoint.java View source code
protected void send(final Exchange exchange, final AsyncCallback callback) {
    final StompFrame frame = new StompFrame(SEND);
    if (logger.isDebugEnabled())
        logger.debug("STOMP: sending :" + exchange);
    frame.addHeader(DESTINATION, StompFrame.encodeHeader(destination));
    Map<String, Object> headers = exchange.getIn().getHeaders();
    if (headers != null) {
        for (String key : headers.keySet()) {
            if (headers.get(key) instanceof String) {
                if (logger.isDebugEnabled())
                    logger.debug("STOMP: encode header :" + key + "=" + (String) headers.get(key));
                frame.addHeader(Buffer.ascii(key), StompFrame.encodeHeader((String) headers.get(key)));
            }
        }
    }
    frame.content(utf8(exchange.getIn().getBody().toString()));
    connection.getDispatchQueue().execute(new Task() {

        @Override
        public void run() {
            connection.send(frame, new Callback<Void>() {

                @Override
                public void onFailure(Throwable e) {
                    exchange.setException(e);
                    callback.done(false);
                }

                @Override
                public void onSuccess(Void v) {
                    callback.done(false);
                }
            });
        }
    });
}
Example 20
Project: Security-Monitoring-and-Notification-master  File: MQTTSubscriberService.java View source code
public void onPublish(UTF8Buffer topic, Buffer payload, Runnable ack) {
    Log.d(TAG, "on publish called");
    // You can now process a received message from a topic
    // I did not find documentation on this, 
    String fullPayLoad = new String(payload.data);
    Log.d(TAG, "String size is " + fullPayLoad.length() + " , and data size is " + payload.length);
    // but the payload seems to in fact consists of 0x32 0xlen (maybe more than a byte) 0x(topic) 0x(message number - in 2 bytes) 0x(message)   
    String receivedMesageTopic = topic.toString();
    // TODO: I should probably check if there are characters that needs to be scaped
    String[] fullPayLoadParts = fullPayLoad.split(receivedMesageTopic);
    Log.d(TAG, "fullpayload = " + fullPayLoad);
    if (fullPayLoadParts.length == 2) {
        // sometimes the payload includes the message ID (2 bytes), sometimes it doesnt....
        // if the first character is a "{" then it didnt
        String messagePayLoad;
        if (fullPayLoadParts[1].charAt(0) == '{')
            messagePayLoad = fullPayLoadParts[1];
        else
            messagePayLoad = fullPayLoadParts[1].substring(2);
        String val = this.insertMessage(messagePayLoad, receivedMesageTopic);
    // TODO: SEND AN UPDATE MESSAGE TO ACTIVITY
    }
    // Once process execute the ack runnable.
    ack.run();
}
Example 21
Project: mqtt-jmeter-master  File: ListenerforSubscribe.java View source code
@Override
public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) {
    //		String message = new String(body.getData());
    //		System.out.println("Received: "+message);
    count.getAndIncrement();
    ack.run();
}