Example usage for javax.jms Message getLongProperty

List of usage examples for javax.jms Message getLongProperty

Introduction

In this page you can find the example usage for javax.jms Message getLongProperty.

Prototype


long getLongProperty(String name) throws JMSException;

Source Link

Document

Returns the value of the long property with the specified name.

Usage

From source file:org.fcrepo.integration.jms.observer.HeadersJMSIT.java

private static Long getTimestamp(final Message msg) throws JMSException {
    return msg.getLongProperty(TIMESTAMP_HEADER_NAME);
}

From source file:com.fusesource.forge.jmstest.tests.simple.SimpleConsumer.java

protected void run() {
    Connection con = null;/*  ww w  .ja v a2  s .  co  m*/
    Session session = null;
    final CountDownLatch latch = new CountDownLatch(Integer.MAX_VALUE);
    try {
        con = getConnection();
        session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination dest = getDestinationProvider().getDestination(session, "queue:TEST");
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message msg) {
                String grp = null;
                long nr = 0L;
                try {
                    grp = msg.getStringProperty("JMSXGroupID");
                    nr = msg.getLongProperty("MsgNr");
                } catch (JMSException jme) {
                }
                log().info("Received Message Group=(" + grp + ") MsgNr=" + nr);
                latch.countDown();
            }
        });
        con.start();
        latch.await();
        con.close();
    } catch (Exception e) {
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:springchat.jms.NewTextMessage.java

@Override
public void onMessage(Message jms) {
    MessageDto dto = new MessageDto();
    try {/* www. j a v a  2  s  . c  o  m*/
        dto.setContent(jms.getStringProperty("message"));
        dto.setFrom(jms.getStringProperty("user"));
        dto.setTimestamp(jms.getLongProperty("date"));
    } catch (JMSException e) {
        throw new UnmanagedException(e);
    }
    MessageEntity bean = messagesService.save(dto.getTimestamp(), dto.getFrom(), dto.getContent());
    dto.setId(bean.getUid());
    connections.sendToAll("text", dto);
}

From source file:springchat.test.NewTextMessageTest.java

@Test
public void testOnMessage() throws JMSException {
    final long uid = 10l;
    final String content = "Hi there!";
    final String user = "boto";
    final long timestamp = System.currentTimeMillis();

    Message jmsMessage = EasyMock.createNiceMock(Message.class);
    EasyMock.expect(jmsMessage.getStringProperty("message")).andReturn(content).once();
    EasyMock.expect(jmsMessage.getStringProperty("user")).andReturn(user).once();
    EasyMock.expect(jmsMessage.getLongProperty("date")).andReturn(timestamp).once();

    MessageEntity entityMessage = new MessageEntity();
    entityMessage.setUid(uid);//from   w w  w . j  a  va2  s. co m
    entityMessage.setDate(new Date(timestamp));
    entityMessage.setMessage(content);
    entityMessage.setUser(user);

    EasyMock.expect(messagesService.save(timestamp, user, content)).andReturn(entityMessage).once();

    connections.sendToAll(EasyMock.anyObject(String.class), EasyMock.anyObject(MessageDto.class));
    EasyMock.expectLastCall().andDelegateTo(new ConnectionsService() {
        @Override
        public void addSession(WebSocketSession session) {
            Assert.fail();
        }

        @Override
        public void removeSession(WebSocketSession session) {
            Assert.fail();
        }

        @Override
        public void sendToAll(String typeName, Object data) {
            Assert.assertEquals(MessageDto.class, data.getClass());
            Assert.assertEquals(uid, MessageDto.class.cast(data).getId().longValue());
        }
    });

    EasyMock.replay(messagesService, connections, jmsMessage);
    newTextMessage.onMessage(jmsMessage);
    EasyMock.verify(messagesService, connections, jmsMessage);
}

From source file:com.fusesource.forge.jmstest.executor.BenchmarkConsumer.java

public void onMessage(Message message) {
    // TODO: simulate slow subscriber with wait(n)
    try {//from w w  w.  j  av a  2  s. c om
        long now = System.currentTimeMillis();
        long latency = now - message.getLongProperty("SendTime");
        if (getMsgCounterProbe() != null) {
            getMsgCounterProbe().increment();
        }
        if (getLatencyProbe() != null) {
            getLatencyProbe().addValue(new Double(latency));
        }
        if (getMsgSizeProbe() != null) {
            getMsgSizeProbe().addValue(new Double(getMessageSize(message)));
        }
    } catch (JMSException e) {
        log().warn("SendTime not available in message properties", e);
    }
}

From source file:com.amalto.core.server.routing.DefaultRoutingEngine.java

@Override
public void consume(final Message message) {
    try {//from  w  w w  . ja  va 2s.co  m
        @SuppressWarnings("unchecked")
        String[] rules = getRulesList(message);
        final String pk = message.getStringProperty(JMS_PK_PROPERTY);
        final String type = message.getStringProperty(JMS_TYPE_PROPERTY);
        final String container = message.getStringProperty(JMS_CONTAINER_PROPERTY);
        final long timeScheduled = message.getLongProperty(JMS_SCHEDULED);
        final String routingOrderId = message.getJMSMessageID();
        for (int ruleIndex = 0; ruleIndex < rules.length; ruleIndex++) {
            String rule = rules[ruleIndex];
            final RoutingRulePOJO routingRule = routingRules.getRoutingRule(new RoutingRulePOJOPK(rule));
            // Apparently rule is not (yet) deployed onto this system's DB instance, but... that 's
            // rather unexpected since all nodes in cluster are supposed to share same system DB.
            if (routingRule == null) {
                throw new RuntimeException(
                        "Cannot execute rule(s) " + rules + ": routing rule '" + rule + "' can not be found.");
            }
            SecurityConfig.invokeSynchronousPrivateInternal(new Runnable() {
                @Override
                public void run() {
                    // execute all rules synchronously
                    final ItemPOJOPK itemPOJOPK = new ItemPOJOPK(new DataClusterPOJOPK(container), type,
                            pk.split("\\."));
                    applyRule(itemPOJOPK, routingRule, routingOrderId, timeScheduled);
                }
            });
        }
        // acknowledge message once all rules are executed
        message.acknowledge();
    } catch (Exception e) {
        throw new RuntimeException("Unable to process message.", e);
    }
}

From source file:org.apache.axis2.transport.jms.JMSUtils.java

/**
 * Extract transport level headers for JMS from the given message into a Map
 *
 * @param message the JMS message/*w w w.  ja v a2  s . co m*/
 * @return a Map of the transport headers
 */
public static Map<String, Object> getTransportHeaders(Message message) {
    // create a Map to hold transport headers
    Map<String, Object> map = new HashMap<String, Object>();

    // correlation ID
    try {
        if (message.getJMSCorrelationID() != null) {
            map.put(JMSConstants.JMS_COORELATION_ID, message.getJMSCorrelationID());
        }
    } catch (JMSException ignore) {
    }

    // set the delivery mode as persistent or not
    try {
        map.put(JMSConstants.JMS_DELIVERY_MODE, Integer.toString(message.getJMSDeliveryMode()));
    } catch (JMSException ignore) {
    }

    // destination name
    try {
        if (message.getJMSDestination() != null) {
            Destination dest = message.getJMSDestination();
            map.put(JMSConstants.JMS_DESTINATION,
                    dest instanceof Queue ? ((Queue) dest).getQueueName() : ((Topic) dest).getTopicName());
        }
    } catch (JMSException ignore) {
    }

    // expiration
    try {
        map.put(JMSConstants.JMS_EXPIRATION, Long.toString(message.getJMSExpiration()));
    } catch (JMSException ignore) {
    }

    // if a JMS message ID is found
    try {
        if (message.getJMSMessageID() != null) {
            map.put(JMSConstants.JMS_MESSAGE_ID, message.getJMSMessageID());
        }
    } catch (JMSException ignore) {
    }

    // priority
    try {
        map.put(JMSConstants.JMS_PRIORITY, Long.toString(message.getJMSPriority()));
    } catch (JMSException ignore) {
    }

    // redelivered
    try {
        map.put(JMSConstants.JMS_REDELIVERED, Boolean.toString(message.getJMSRedelivered()));
    } catch (JMSException ignore) {
    }

    // replyto destination name
    try {
        if (message.getJMSReplyTo() != null) {
            Destination dest = message.getJMSReplyTo();
            map.put(JMSConstants.JMS_REPLY_TO,
                    dest instanceof Queue ? ((Queue) dest).getQueueName() : ((Topic) dest).getTopicName());
        }
    } catch (JMSException ignore) {
    }

    // priority
    try {
        map.put(JMSConstants.JMS_TIMESTAMP, Long.toString(message.getJMSTimestamp()));
    } catch (JMSException ignore) {
    }

    // message type
    try {
        if (message.getJMSType() != null) {
            map.put(JMSConstants.JMS_TYPE, message.getJMSType());
        }
    } catch (JMSException ignore) {
    }

    // any other transport properties / headers
    Enumeration<?> e = null;
    try {
        e = message.getPropertyNames();
    } catch (JMSException ignore) {
    }

    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = (String) e.nextElement();
            try {
                map.put(headerName, message.getStringProperty(headerName));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, message.getBooleanProperty(headerName));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, message.getIntProperty(headerName));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, message.getLongProperty(headerName));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, message.getDoubleProperty(headerName));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, message.getFloatProperty(headerName));
            } catch (JMSException ignore) {
            }
        }
    }

    return map;
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

/**
 * Populate Mail with values from Message. This exclude the
 * {@link MimeMessage}// w  ww. j  a  va2  s  .  com
 *
 * @param message
 * @param mail
 * @throws JMSException
 */
protected void populateMail(Message message, MailImpl mail) throws JMSException {
    mail.setErrorMessage(message.getStringProperty(JAMES_MAIL_ERROR_MESSAGE));
    mail.setLastUpdated(new Date(message.getLongProperty(JAMES_MAIL_LAST_UPDATED)));
    mail.setName(message.getStringProperty(JAMES_MAIL_NAME));

    Optional.ofNullable(SerializationUtil
            .<PerRecipientHeaders>deserialize(message.getStringProperty(JAMES_MAIL_PER_RECIPIENT_HEADERS)))
            .ifPresent(mail::addAllSpecificHeaderForRecipient);

    List<MailAddress> rcpts = new ArrayList<>();
    String recipients = message.getStringProperty(JAMES_MAIL_RECIPIENTS);
    StringTokenizer recipientTokenizer = new StringTokenizer(recipients, JAMES_MAIL_SEPARATOR);
    while (recipientTokenizer.hasMoreTokens()) {
        String token = recipientTokenizer.nextToken();
        try {
            MailAddress rcpt = new MailAddress(token);
            rcpts.add(rcpt);
        } catch (AddressException e) {
            // Should never happen as long as the user does not modify the
            // the header by himself
            LOGGER.error("Unable to parse the recipient address {} for mail {}, so we ignore it", token,
                    mail.getName(), e);
        }
    }
    mail.setRecipients(rcpts);
    mail.setRemoteAddr(message.getStringProperty(JAMES_MAIL_REMOTEADDR));
    mail.setRemoteHost(message.getStringProperty(JAMES_MAIL_REMOTEHOST));

    String attributeNames = message.getStringProperty(JAMES_MAIL_ATTRIBUTE_NAMES);

    splitter.split(attributeNames).forEach(name -> setMailAttribute(message, mail, name));

    MaybeSender.getMailSender(message.getStringProperty(JAMES_MAIL_SENDER)).asOptional()
            .ifPresent(mail::setSender);
    mail.setState(message.getStringProperty(JAMES_MAIL_STATE));
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

@Override
@SuppressWarnings("unchecked")
public MailQueueIterator browse() throws MailQueueException {
    QueueBrowser browser = null;//from   w w w  .  j a v  a  2 s  . com
    try {
        browser = session.createBrowser(queue);

        Enumeration<Message> messages = browser.getEnumeration();
        QueueBrowser myBrowser = browser;

        return new MailQueueIterator() {

            @Override
            public void remove() {
                throw new UnsupportedOperationException("Read-only");
            }

            @Override
            public MailQueueItemView next() {
                while (hasNext()) {
                    try {
                        Message m = messages.nextElement();
                        return new MailQueueItemView(createMail(m), nextDeliveryDate(m));
                    } catch (MessagingException | JMSException e) {
                        LOGGER.error("Unable to browse queue", e);
                    }
                }

                throw new NoSuchElementException();
            }

            private ZonedDateTime nextDeliveryDate(Message m) throws JMSException {
                long nextDeliveryTimestamp = m.getLongProperty(JAMES_NEXT_DELIVERY);
                return Instant.ofEpochMilli(nextDeliveryTimestamp).atZone(ZoneId.systemDefault());
            }

            @Override
            public boolean hasNext() {
                return messages.hasMoreElements();
            }

            @Override
            public void close() {
                closeBrowser(myBrowser);
            }
        };

    } catch (Exception e) {
        closeBrowser(browser);

        LOGGER.error("Unable to browse queue {}", queueName, e);
        throw new MailQueueException("Unable to browse queue " + queueName, e);
    }
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public Message sendNextMessage(final CreateProducerCommand command) {
    Message sentMessage = null;
    MessageProvider messageProvider = _testMessageProviders.get(command.getMessageProviderName());
    if (messageProvider == null) {
        messageProvider = _defaultMessageProvider;
    }/*from w  w w.ja  va2 s  .  c o m*/

    final Session session = _testSessions.get(command.getSessionName());
    final MessageProducer producer = _testProducers.get(command.getParticipantName());
    try {
        sentMessage = messageProvider.nextMessage(session, command);
        int deliveryMode = producer.getDeliveryMode();
        int priority = producer.getPriority();
        long ttl = producer.getTimeToLive();
        if (messageProvider.isPropertySet(MessageProvider.PRIORITY)) {
            priority = sentMessage.getJMSPriority();
        }
        if (messageProvider.isPropertySet(MessageProvider.DELIVERY_MODE)) {
            deliveryMode = sentMessage.getJMSDeliveryMode();
        }
        if (messageProvider.isPropertySet(MessageProvider.TTL)) {
            ttl = sentMessage.getLongProperty(MessageProvider.TTL);
        }
        producer.send(sentMessage, deliveryMode, priority, ttl);
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create and send message with producer: "
                + command.getParticipantName() + " on session: " + command.getSessionName(), jmse);
    }
    return sentMessage;
}