@Override public void onMessage(Message message) { try { ObjectMessage objectMessage = (ObjectMessage) message; HandlingEventRegistrationAttempt attempt = (HandlingEventRegistrationAttempt) objectMessage.getObject(); handlingEventService.registerHandlingEvent( attempt.getCompletionTime(), attempt.getTrackingId(), attempt.getVoyageNumber(), attempt.getUnLocode(), attempt.getType()); } catch (JMSException | CannotCreateHandlingEventException e) { // Poison messages will be placed on dead-letter queue. throw new RuntimeException("Error occurred processing message", e); // } catch (JMSException e) { // logger.log(Level.SEVERE, e.getMessage(), e); } }
@Test public void onMessageErrorHandling() throws Exception { // given PayloadStub payload = new PayloadStub(); payload.setExecuteCauseException(true); TaskMessage taskMessage = new TaskMessage(HandlerStub.class, payload); ObjectMessage messageMock = mock(ObjectMessage.class); when(messageMock.getObject()).thenReturn(taskMessage); // when listener.onMessage(messageMock); // then assertTrue(payload.isHandledErrorSuccessfully()); }
@Test public void onMessageErrorHandlingFailed() throws Exception { // given PayloadStub payload = new PayloadStub(); payload.setExecuteCauseException(true); payload.setHandleErrorCauseException(true); TaskMessage taskMessage = new TaskMessage(HandlerStub.class, payload); ObjectMessage messageMock = mock(ObjectMessage.class); when(messageMock.getObject()).thenReturn(taskMessage); // when listener.onMessage(messageMock); // then assertTrue(payload.isExecuted()); assertFalse(payload.isExecutedSuccessfully()); assertTrue(payload.isErrorHandled()); assertFalse(payload.isHandledErrorSuccessfully()); }
@Test public void onMessageInvalidMessageObjectInstance() throws Exception { // given listener = spy(listener); Serializable wrongMessage = mock(Serializable.class); ObjectMessage messageMock = mock(ObjectMessage.class); when(messageMock.getObject()).thenReturn(wrongMessage); // when listener.onMessage(messageMock); // then verify(listener, times(1)).logIllegalArgumentExceptionError( any(IllegalArgumentException.class)); }
private void sendObjectMsgSingleSession(List<? extends Serializable> objectsToSend) throws JMSException { Session session = null; Connection conn = null; try { conn = qFactory.createConnection(); session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); for (Serializable objectToSend : objectsToSend) { ObjectMessage msg = session.createObjectMessage(); msg.setObject(objectToSend); producer.send(msg); } } finally { closeSession(session); closeConnection(conn); } }
/** * Publish message. * * @param event the event * @throws JMSException the jMS exception */ public void publishMessage(final BasicEvent event) throws JMSException { if (System.currentTimeMillis() > lastFailureTimestamp) { publishedCounter.incrementAndGet(); int shard = (int) (event.getManifestId() % poolsize); try { producers[shard].send(session -> { ObjectMessage message = session.createObjectMessage(event); message.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); message.setLongProperty("ciId", event.getCiId()); message.setLongProperty("manifestId", event.getManifestId()); message.setStringProperty("source", event.getSource()); if (logger.isDebugEnabled()) { logger.debug("Published: ciId:" + event.getCiId() + "; source:" + event.getSource()); } return message; }); lastFailureTimestamp = -1; } catch (JmsException exception) { logger.warn("There was an error sending a message. Discarding messages for " + mqConnectionThreshold + " ms"); lastFailureTimestamp = System.currentTimeMillis() + mqConnectionThreshold; } } }
/** * takes the jms message */ public void onMessage(Message msg) { try { if (msg instanceof ObjectMessage) { BasicEvent event = (BasicEvent)((ObjectMessage)msg).getObject(); if (logger.isDebugEnabled() || cisToLog.contains(event.getCiId())) { logger.info(gson.toJson(event)); } sensorHeartBeat.timeStampIt(event.getChannel()); sensorHeartBeat.timeStampIt(BasicEvent.DEFAULT_CHANNEL); sensor.sendCEPEvent(event); } msg.acknowledge(); } catch (JMSException e) { logger.info("caught Exception in onMessage",e); } }
@Test /*exception shall not come out, we force it * but the code eats it */ public void testOnMessageExceptionCase() throws Exception{ SensorListener listen = new SensorListener(); Sensor sensorThrower = mock(Sensor.class); listen.setSensor(sensorThrower); listen.setSensorHeartBeat(mock(SensorHeartBeat.class)); ObjectMessage msg = mock(ObjectMessage.class); doThrow(new JMSException("mock")).when(msg).acknowledge(); BasicEvent event = mock(BasicEvent.class); when(msg.getObject()).thenReturn(event); listen.onMessage(msg); }
/** * sends an Object message instead of Text; should be ok * it will get logged */ @Test public void onObjectMessage() { ObjectMessage objectMessage = mock(ObjectMessage.class); NotificationMessage notificationMessage = new NotificationMessage(); notificationMessage.setTimestamp(1L); notificationMessage.setText("mock-text"); try { when(objectMessage.getObject()).thenReturn(notificationMessage); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Sends a message to the myWMS application inside the application * server. * * @param mfcMessage the message to be send * @throws JMSException * @throws NamingException */ public void send(MFCMessage mfcMessage) throws JMSException, NamingException { // create the jms session QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); // lookup of the jms queue over jndi Queue outputQueue = (Queue) context.lookup("queue/" + OUTPUT_QUEUE_NAME); // create the message publisher QueueSender sender = session.createSender(outputQueue); ObjectMessage objectMessage = session.createObjectMessage(); objectMessage.setObject(mfcMessage); objectMessage.setJMSTimestamp(System.currentTimeMillis()); sender.send(objectMessage); sender.close(); session.close(); }
public void onMessage(Message msg) { try { ObjectMessage om = (ObjectMessage)msg; String operation = om.getStringProperty("operation"); Object obj = om.getObject(); String rashodCode = om.getStringProperty("rashodCode"); log.info("onMessage:" +operation+ "operation"); if (obj instanceof Record) { Record rec = (Record)obj; if ("add".equals(operation)) { indexer.add(rec, rashodCode); log.info("Record added, ID: " + rec.getRecordID()); } else if ("update".equals(operation)) { indexer.update(rec, rashodCode); log.info("Record updated, ID: " + rec.getRecordID()); } } else if ((obj instanceof Integer) && "delete".equals(operation)) { Integer recID = (Integer)obj; indexer.delete(recID); log.info("Record deleted, ID: " + recID); } } catch (JMSException e) { log.fatal(e); } }
/** * {@inheritDoc} */ @Override public void onMessage(final Message message) { if (message instanceof ObjectMessage) { final ObjectMessage msg = (ObjectMessage) message; try { final Serializable object = msg.getObject(); if (object instanceof EmailMessage) { send((EmailMessage) object); } else { throw new IWSException(IWSErrors.ERROR, "Not a proper e-mail message."); } } catch (JMSException e) { throw new IWSException(IWSErrors.ERROR, "Sending the email message failed.", e); } } }
@JmsListener(destination = Queue.EMAIL_QUEUE, containerFactory = "jmsContainerFactory") public void receiveMessage(Message message) { if (message instanceof ObjectMessage) { ObjectMessage objectMessage = (ObjectMessage) message; try { if (objectMessage.getObject() instanceof EmailJmsMessage) { try { EmailJmsMessage emailJmsMessage = (EmailJmsMessage) objectMessage.getObject(); emailMessage.sendEmail(emailJmsMessage.getHtml(), emailJmsMessage.getAttachments(), emailJmsMessage.getRecipient(), emailJmsMessage.getSubject()); } catch (Exception e) { logger.error("Email messaging exception", e); } } } catch (JMSException ex) { logger.error("JMSException thrown during Email JMS message acknowledgment:", ex); } } else { logger.error("JMS: not an object message - nothing to do"); } }
@Override public void to(JmsDestination target) { try { Connection connection = connectionFactory.createConnection(); connection.start(); Session session = createFunction.apply(connection); Destination destination = target.createDestination(session); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.PERSISTENT); if (this.expirationTime != null) { producer.setTimeToLive(this.expirationTime); } ObjectMessage message = session.createObjectMessage(object); producer.send(message); session.close(); connection.close(); } catch (JMSException e) { logger.error("Error while sending object to AMQ destination", e); } }
@Override public void onMessage(Message message) { ObjectMessage msg = (ObjectMessage) message; try { Order order = (Order) msg.getObject(); System.out.println("Got message from queue receiver==>" + order); // Send response OrderResponse orderResponse = new OrderResponse(); orderResponse.setItemCode(order.getItemCode()); orderResponse.setOrderQuantity(order.getQuantity()); ReorderResponseMessageSender.sendMessage(orderResponse); } catch (JMSException | NamingException e) { e.printStackTrace(); } }
public static void sendMessage(Order order) throws NamingException, JMSException { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF); properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(USERNAME, PASSWORD)); properties.put(QUEUE_NAME_PREFIX + REORDER_REQUEST_QUEUE, REORDER_REQUEST_QUEUE); InitialContext ctx = new InitialContext(properties); // Lookup connection factory QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME); queueConnection = connFactory.createQueueConnection(); queueConnection.start(); queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); // Send message Queue queue = (Queue) ctx.lookup(REORDER_REQUEST_QUEUE); // create the message to send ObjectMessage message = queueSession.createObjectMessage(order); javax.jms.QueueSender queueSender = queueSession.createSender(queue); queueSender.send(message); queueSender.close(); queueSession.close(); queueConnection.close(); }
private Message jmsReceiveRequest(HttpSession session, Object hwid, String sn, long w) throws JMSException { MessageConsumer consumer = (MessageConsumer) session.getAttribute("consumer"); if (consumer == null) { // consumer = queuesession.createConsumer(queue, "OUI='" + oui + "' AND SN='" + sn + "'"); //String filter = "OUI='" + oui + "' AND SN='" + sn + "'"; String filter = "HWID='" + /*hw.getId()*/ hwid + "' AND SN='" + sn + "'"; consumer = _jms.createConsumer(filter); session.setAttribute("consumer", consumer); //log(lastInform, Level.FINEST, "Created consumer: " + filter); } ObjectMessage jm = (w == 0) ? (ObjectMessage) consumer.receiveNoWait() : (ObjectMessage) consumer.receive(w); if (jm != null) { return (Message) jm.getObject(); } return null; }
public Object Receive(String filter, long timeoutReceive) throws JMSException { System.out.println("CLIENT: Creating cosumer: " + filter + "'"); MessageConsumer consumer = queuesession.createConsumer(queue, filter); Message mrcv; if ((mrcv = consumer.receive(timeoutReceive)) != null) { Object rm1; try { rm1 = ((ObjectMessage) mrcv).getObject(); //System.out.println("RCV1: " + mrcv.getJMSCorrelationID() + " req=" + rm1.name); return rm1; } catch (MessageFormatException e) { System.out.println("MessageFormatException: " + e.getMessage()); mrcv.acknowledge(); } } return null; }
public static MessageProcessor produce(Message message, RunnerTerminator runnerTerminator) throws JMSException { MessageProcessor processor = null; if (message instanceof ObjectMessage) { Object object = ((ObjectMessage) message).getObject(); if (object instanceof ProcessingErrorMessage) { processor = new ProcessingErrorMessageProcessor((ProcessingErrorMessage) object, runnerTerminator); } else if (object instanceof FinishedSuiteProcessingMessage) { processor = new SuiteFinishedProcessor((FinishedSuiteProcessingMessage) object, runnerTerminator); } else if (object instanceof ProgressMessage) { processor = new ProgressMessageProcessor((ProgressMessage) object); } else if (object instanceof FatalErrorMessage) { processor = new FatalErrorMessageProcessor((FatalErrorMessage) object, runnerTerminator); } else { processor = new UnexpectedMessageProcessor(object); } } return processor; }
public static <T> T getFromMessage(Message message, Class<T> tClass) throws JMSException { T result; if (message instanceof ObjectMessage) { final Serializable object = ((ObjectMessage) message).getObject(); if (tClass.isInstance(object)) { result = tClass.cast(object); } else { LOGGER.error("Invalid message object type: {}", object); result = null; } } else { LOGGER.error("Invalid message type: {}", message); result = null; } return result; }
private void processUrlsAndGroupToPackages(Deque<MessageWithDestination> messagesQueue, Test test) throws JMSException { int msgIndex = 0; final int totalUrls = test.getUrls().size(); List<Url> urlsToSend = Lists.newArrayList(); for (Url testUrl : test.getUrls()) { msgIndex++; urlsToSend.add(testUrl); if (msgIndex % urlPackageSize == 0 || msgIndex == totalUrls) { final CollectorJobData data = new CollectorJobData(suite.get().getCompany(), suite.get().getProject(), suite.get().getName(), test.getName(), urlsToSend, test.getProxy()); ObjectMessage message = session.createObjectMessage(data); message.setJMSCorrelationID(correlationId); messagesQueue.add(new MessageWithDestination(getQueueOut(), message, urlsToSend.size())); urlsToSend.clear(); } } }
@Test public void onMessage_whenError_expectObserversNotified() throws Exception { ObjectMessage message = Mockito.mock(ObjectMessage.class); Url url = Mockito.mock(Url.class); CollectorResultData collectorResultData = CollectorResultData .createErrorResult(url, ProcessingError .collectingError("error"), "jmsID001", "testNameExample"); when(message.getObject()).thenReturn(collectorResultData); when(message.getJMSCorrelationID()).thenReturn(CORRELATION_ID); when(message.getJMSMessageID()).thenReturn("jmsID0001"); tested.onMessage(message); //onError verify(observer, times(1)).update(Matchers.<Observable>any(), any()); //finishTask verify(changeObserver, times(1)).informChangesCompleted(); verify(consumer, times(1)).close(); }
@Test public void testConsumeObjectMessage() throws Exception { endpoint.expectedMessageCount(1); jmsTemplate.setPubSubDomain(false); jmsTemplate.send("test.object", new MessageCreator() { public Message createMessage(Session session) throws JMSException { ObjectMessage msg = session.createObjectMessage(); MyUser user = new MyUser(); user.setName("Claus"); msg.setObject(user); return msg; } }); endpoint.assertIsSatisfied(); assertCorrectObjectReceived(); }
@Override public void onMessage(Message message) { ObjectMessage objectMessage = (ObjectMessage) message; try { Serializable body = objectMessage.getObject(); if( body instanceof CardHolder){ CardHolder cardHolder = (CardHolder) body; automationEngine.examine(cardHolder); } else if( body instanceof Notification){ Notification notification = (Notification) body; automationEngine.executeActions(notification); } else if(body instanceof BoardRule){ BoardRule timerNotification = (BoardRule) body; automationEngine.executeActions(timerNotification); }else { logger.warn("JMS Message Contained Invalid Body"); } } catch (Exception e) { logger.error("JMS Exception on Event Reception",e); } }
public static void publish(String destination, Serializable object, String contentType) throws Exception { BindingRegistry reg = server.getRegistry(); ConnectionFactory factory = (ConnectionFactory) reg.lookup("ConnectionFactory"); Connection conn = factory.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination dest = session.createQueue(destination); try { Assert.assertNotNull("Destination was null", dest); MessageProducer producer = session.createProducer(dest); ObjectMessage message = session.createObjectMessage(); if (contentType != null) { message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType); } message.setObject(object); producer.send(message); } finally { conn.close(); } }
@Test public void sendMessage_checkCloseOnException() throws Exception { MockitoAnnotations.initMocks(this); doReturn(Boolean.TRUE).when(sender).checkJMSResources(); Connection conn = mock(Connection.class); doReturn(conn).when(factory).createConnection(); Session session = mock(Session.class); doReturn(session).when(conn).createSession(eq(false), eq(Session.AUTO_ACKNOWLEDGE)); MessageProducer producer = mock(MessageProducer.class); doReturn(producer).when(session).createProducer(eq(queue)); ObjectMessage om = mock(ObjectMessage.class); doReturn(om).when(session).createObjectMessage(); doNothing().when(om).setObject(caughtMessage.capture()); doThrow(new JMSException("test caused")).when(producer).send( any(Message.class)); try { sender.sendMessage(objectMessage); fail(); } catch (JMSException e) { verify(session, times(1)).close(); verify(conn, times(1)).close(); } }
@Override protected String extractString(JMSBindingData binding) throws Exception { Message content = binding.getMessage(); if (content instanceof TextMessage) { return TextMessage.class.cast(content).getText(); } else if (content instanceof BytesMessage) { BytesMessage sourceBytes = BytesMessage.class.cast(content); if (sourceBytes.getBodyLength() > Integer.MAX_VALUE) { throw JCAMessages.MESSAGES.theSizeOfMessageContentExceedsBytesThatIsNotSupportedByThisOperationSelector("" + Integer.MAX_VALUE); } byte[] bytearr = new byte[(int)sourceBytes.getBodyLength()]; sourceBytes.readBytes(bytearr); return new String(bytearr); } else if (content instanceof ObjectMessage) { ObjectMessage sourceObj = ObjectMessage.class.cast(content); return String.class.cast(sourceObj.getObject()); } else if (content instanceof MapMessage) { MapMessage sourceMap = MapMessage.class.cast(content); return sourceMap.getString(KEY); } else { return content.getStringProperty(KEY); } }
/** * This implementation converts a TextMessage back to a String, a * ByteMessage back to a byte array, a MapMessage back to a Map, * and an ObjectMessage back to a Serializable object. Returns * the plain Message object in case of an unknown message type. * * @return payload * @throws javax.jms.JMSException */ @Override public Object convert(Message message) throws JMSException { if (message instanceof TextMessage) { return ((TextMessage)message).getText(); } else if (message instanceof StreamMessage) { return ((StreamMessage)message).readString(); } else if (message instanceof BytesMessage) { return extractByteArrayFromMessage((BytesMessage)message); } else if (message instanceof MapMessage) { return extractMapFromMessage((MapMessage)message); } else if (message instanceof ObjectMessage) { return extractSerializableFromMessage((ObjectMessage)message); } else { return message; } }
public final void onMessage(final Message message) { try { if (message instanceof ObjectMessage) { final ObjectMessage objectMessage = (ObjectMessage) message; final LoggingEvent event = (LoggingEvent) objectMessage.getObject(); final Logger remoteLogger = Logger.getLogger(event.getLoggerName()); remoteLogger.callAppenders(event); } else { logger.warn("Received message is of type " + message.getJMSType() + ", was expecting ObjectMessage."); } } catch (final JMSException e) { logger.error("Exception thrown while processing incoming message.", e); } }
public static void print(Message msg) throws JMSException { log.info(".print received message: " + msg.getJMSMessageID()); if (msg instanceof ObjectMessage) { ObjectMessage objMsg = (ObjectMessage) msg; log.info(".print object: " + objMsg.getObject().toString()); } else { MapMessage mapMsg = (MapMessage) msg; HashMap map = new HashMap(); Enumeration en = mapMsg.getMapNames(); while (en.hasMoreElements()) { String property = (String) en.nextElement(); Object mapObject = mapMsg.getObject(property); map.put(property, mapObject); } log.info(".print map: " + map); } }
private void sendObjectMessageUsingCoreJms(String queueName, Serializable object) throws Exception { Connection jmsConn = null; try { jmsConn = coreCf.createConnection(); Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); ObjectMessage objectMessage = session.createObjectMessage(object); Queue queue = session.createQueue(queueName); MessageProducer producer = session.createProducer(queue); producer.send(objectMessage); } finally { if (jmsConn != null) { jmsConn.close(); } } }
public void onMessage(javax.jms.Message message) { ILoggingEvent event; try { if (message instanceof ObjectMessage) { ObjectMessage objectMessage = (ObjectMessage) message; event = (ILoggingEvent) objectMessage.getObject(); Logger log = (Logger) LoggerFactory.getLogger(event.getLoggerName()); log.callAppenders(event); } else { logger.warn("Received message is of type " + message.getJMSType() + ", was expecting ObjectMessage."); } } catch (JMSException jmse) { logger.error("Exception thrown while processing incoming message.", jmse); } }
/** * This method called by {@link AppenderBase#doAppend} method to do most * of the real appending work. */ public void append(ILoggingEvent event) { if (!isStarted()) { return; } try { ObjectMessage msg = queueSession.createObjectMessage(); Serializable so = pst.transform(event); msg.setObject(so); queueSender.send(msg); successiveFailureCount = 0; } catch (Exception e) { successiveFailureCount++; if (successiveFailureCount > SUCCESSIVE_FAILURE_LIMIT) { stop(); } addError("Could not send message in JMSQueueAppender [" + name + "].", e); } }
/** * This method called by {@link AppenderBase#doAppend} method to do most * of the real appending work. */ public void append(ILoggingEvent event) { if (!isStarted()) { return; } try { ObjectMessage msg = topicSession.createObjectMessage(); Serializable so = pst.transform(event); msg.setObject(so); topicPublisher.publish(msg); successiveFailureCount = 0; } catch (Exception e) { successiveFailureCount++; if (successiveFailureCount > SUCCESSIVE_FAILURE_LIMIT) { stop(); } addError("Could not publish message in JMSTopicAppender [" + name + "].", e); } }