Search in sources :

Example 1 with MessageInfo

use of org.jaffa.modules.messaging.services.configdomain.MessageInfo in project jaffa-framework by jaffa-projects.

the class ConfigurationServiceTest method testGetMessageInfo.

/**
 * Test of getMessageInfo method, of class org.jaffa.modules.messaging.services.ConfigurationService.
 */
public void testGetMessageInfo() throws ClassNotFoundException {
    ConfigurationService configurationService = ConfigurationService.getInstance();
    assertNotNull("Should have received an instance of the ConfigurationService", configurationService);
    MessageInfo messageInfo = null;
    messageInfo = configurationService.getMessageInfo("org.jaffa.modules.messaging.services.Example1Message");
    assertNotNull("Should have received a MessageInfo object for org.jaffa.modules.messaging.services.Example1Message", messageInfo);
    assertEquals("org.jaffa.modules.messaging.services.Example1Message", messageInfo.getDataBean());
    assertEquals("jaffa/queue1", messageInfo.getQueueName());
    assertEquals("org.jaffa.modules.messaging.services.Example1Service", messageInfo.getToClass());
    assertEquals("process", messageInfo.getToMethod());
    assertNotNull("Should have received a LockCheck object", messageInfo.getLockCheck());
    assertNotNull("Should have received a LockCheck object with a List of param elements", messageInfo.getLockCheck().getParam());
    assertEquals("Should have received a LockCheck object with a List of 2 param elements", 2, messageInfo.getLockCheck().getParam().size());
    assertEquals("jaffa.locks.global", messageInfo.getLockCheck().getParam().get(0).getName());
    assertEquals("true", messageInfo.getLockCheck().getParam().get(0).getValue());
    assertFalse(messageInfo.getLockCheck().getParam().get(0).isExpression());
    assertEquals("jaffa.locks.asset", messageInfo.getLockCheck().getParam().get(1).getName());
    assertEquals("bean.assetId", messageInfo.getLockCheck().getParam().get(1).getValue());
    assertTrue(messageInfo.getLockCheck().getParam().get(1).isExpression());
    assertNotNull("Should have received a Header object", messageInfo.getHeader());
    assertNotNull("Should have received a Header object with a List of param elements", messageInfo.getHeader().getParam());
    assertEquals("Should have received a Header object with a List of 1 param elements", 1, messageInfo.getHeader().getParam().size());
    assertEquals("jaffa.locks.asset", messageInfo.getHeader().getParam().get(0).getName());
    assertEquals("bean.assetId", messageInfo.getHeader().getParam().get(0).getValue());
    assertTrue(messageInfo.getHeader().getParam().get(0).isExpression());
}
Also used : MessageInfo(org.jaffa.modules.messaging.services.configdomain.MessageInfo)

Example 2 with MessageInfo

use of org.jaffa.modules.messaging.services.configdomain.MessageInfo in project jaffa-framework by jaffa-projects.

the class JmsClientHelper method send.

/**
 * Writes a JMS Message to the destination, as defined in the configuration file.
 * @param inst An instance of this class. If passed, then the newly created Message will simply be cached to be sent later. Else it will be sent right away.
 * @param payload Any serializable object.
 * @param userId A header element in the JMS message will be set to this value.
 * @param scheduledTaskId A header element in the JMS message will be set to this value.
 * @return the MessageId.
 * @throws FrameworkException Indicates some system error.
 * @throws ApplicationExceptions Indicates application error(s).
 */
private static String send(JmsClientHelper inst, Object payload, String userId, String scheduledTaskId) throws FrameworkException, ApplicationExceptions {
    Session session = inst != null ? inst.m_session : null;
    try {
        if (log.isDebugEnabled())
            log.debug("Input to send is userId=" + userId + ", scheduledTaskId=" + scheduledTaskId + ", payload=" + payload);
        if (userId == null) {
            // If the input userId is null, then use SecurityManager.getPrincipal().getName()
            if (SecurityManager.getPrincipal() != null)
                userId = SecurityManager.getPrincipal().getName();
        }
        if (userId == null || userId.length() == 0) {
            log.error("Error in locating the user id info for " + payload.getClass().getName());
            throw new JaffaMessagingFrameworkException(JaffaMessagingFrameworkException.USERID_NOT_FOUND, new Object[] { payload.getClass().getName() });
        }
        // Reads the MessageInfo for the className of the input payload
        MessageInfo messageInfo = null;
        try {
            messageInfo = ConfigurationService.getInstance().getMessageInfo(payload.getClass().getName());
            if (messageInfo == null)
                throw new JaffaMessagingFrameworkException(JaffaMessagingFrameworkException.MESSAGE_INFO_MISSING, new Object[] { payload.getClass().getName() });
        } catch (ClassNotFoundException e) {
            log.error("Error in locating the Message info for " + payload.getClass().getName(), e);
            throw new JaffaMessagingFrameworkException(JaffaMessagingFrameworkException.MESSAGE_INFO_MISSING, new Object[] { payload.getClass().getName() }, e);
        }
        // Invokes the LockingService, to ensure that no locks exist if specified in the MessageInfo
        LockingService.checkLock(payload, messageInfo);
        // Process the payload if RULE_POST_IMMEDIATE is true
        Boolean postImmediate = Parser.parseBoolean((String) ContextManagerFactory.instance().getProperty(RULE_POST_IMMEDIATE));
        if (postImmediate != null && postImmediate.booleanValue()) {
            if (log.isDebugEnabled())
                log.debug("jaffa.messaging.postImmediate=true");
            if (log.isDebugEnabled())
                log.debug("Rule '" + RULE_POST_IMMEDIATE + "' is enabled. Will process the payload immediately");
            // Process the payload
            JaffaMessageConsumer.processPayload(messageInfo, payload, userId, scheduledTaskId, null);
            // Return a null since no message has been created.
            return null;
        } else {
            if (log.isDebugEnabled())
                log.debug("jaffa.messaging.postImmediate=false");
            // Create a Session, if not passed
            if (inst == null) {
                final Connection connection = JaffaConnectionFactory.obtainConnection();
                session = obtainSession(connection, false);
            }
            // Marshals the payload into XML
            String xml = marshalPayload(payload);
            // Obtain the destination from the payload, if it implements IHasDestinationName.
            // Fallback to the static message config, if the payload does not provide any destination.
            String queueName = payload instanceof IHasDestinationName ? ((IHasDestinationName) payload).getQueueName() : null;
            if (log.isDebugEnabled())
                log.debug("Destination from the payload: queueName=" + queueName);
            if (queueName == null) {
                queueName = messageInfo.getQueueName();
                if (log.isDebugEnabled())
                    log.debug("Fallback to the static message config: queueName=" + queueName);
            }
            String topicName = payload instanceof IHasDestinationName ? ((IHasDestinationName) payload).getTopicName() : null;
            if (topicName == null)
                topicName = messageInfo.getTopicName();
            // Creates the JMS Message and sets the standard properties
            Message message = session.createTextMessage(xml);
            message.setStringProperty(JmsBrowser.HEADER_USER_ID, userId);
            message.setStringProperty(JmsBrowser.HEADER_SCHEDULED_TASK_ID, scheduledTaskId);
            message.setStringProperty(JmsBrowser.HEADER_DATA_BEAN_CLASS_NAME, payload.getClass().getName());
            if (queueName != null)
                message.setStringProperty(JmsBrowser.HEADER_ORIGINAL_QUEUE_NAME, queueName);
            // Sets the header elements as defined in the configuration file.
            if (messageInfo.getHeader() != null && messageInfo.getHeader().getParam() != null) {
                for (Param param : messageInfo.getHeader().getParam()) {
                    Object value = InitialContextFactrory.obtainParamValue(param, payload);
                    message.setObjectProperty(param.getName(), value);
                }
            }
            // Sets additional header elements if the payload implements the IHasHeaderParams interface
            if (payload instanceof IHasHeaderParams) {
                HeaderParam[] headerParams = ((IHasHeaderParams) payload).getHeaderParams();
                if (headerParams != null) {
                    for (HeaderParam headerParam : headerParams) message.setStringProperty(headerParam.getName(), headerParam.getValue());
                }
            }
            // Sets additional header elements if the payload has header params.
            if (payload instanceof EventMessage) {
                List<org.jaffa.soa.services.event.HeaderParam> headerParams = ((EventMessage) payload).getHeaderParams();
                if (headerParams != null) {
                    for (org.jaffa.soa.services.event.HeaderParam headerParam : headerParams) {
                        message.setStringProperty(headerParam.getName(), headerParam.getValue());
                    }
                }
            }
            if ((queueName == null || 0 == queueName.length()) && (topicName == null || 0 == topicName.length())) {
                return message.getJMSMessageID();
            }
            // Sends the Message for a local Session only. The Message will be sent later when part of a transaction
            if (inst == null) {
                if (queueName != null && 0 < queueName.length())
                    send(session, message, queueName);
                if (topicName != null && 0 < topicName.length())
                    send(session, message, topicName);
            } else {
                if (inst.m_messages == null)
                    inst.m_messages = new LinkedHashMap<Message, String>();
                if (queueName != null && 0 < queueName.length())
                    inst.m_messages.put(message, queueName);
                if (topicName != null && 0 < topicName.length())
                    inst.m_messages.put(message, topicName);
            }
            // Return the message id
            return message.getJMSMessageID();
        }
    } catch (JMSException e) {
        log.error("Error in sending the message", e);
        throw new JaffaMessagingFrameworkException(JaffaMessagingFrameworkException.SEND_ERROR, null, e);
    } finally {
        if (inst == null && session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                log.warn("Error in closing a JMS Session", e);
            }
        }
    }
}
Also used : ObjectMessage(javax.jms.ObjectMessage) Message(javax.jms.Message) TextMessage(javax.jms.TextMessage) EventMessage(org.jaffa.soa.services.event.EventMessage) Connection(javax.jms.Connection) JMSException(javax.jms.JMSException) MessageInfo(org.jaffa.modules.messaging.services.configdomain.MessageInfo) EventMessage(org.jaffa.soa.services.event.EventMessage) Param(org.jaffa.modules.messaging.services.configdomain.Param) Session(javax.jms.Session)

Example 3 with MessageInfo

use of org.jaffa.modules.messaging.services.configdomain.MessageInfo in project jaffa-framework by jaffa-projects.

the class JaffaMessageConsumer method onMessageInternal.

/**
 * This method is invoked by the messaging system, when a message is received
 * into a Destination with which this MDB is registered. It'll invoke the
 * handler associated with the input Message's payload, as obtained from the
 * configuration file. In case of an error, the Message will be redirected to
 * the ErrorQueue. If an error is thrown while redirecting the Message to the
 * ErrorQueue, that error will be logged by the logging-system. When handling
 * a message published to a Topic, errors if any, will be logged only.
 *
 * @param aMessage
 *          the Message.
 */
private void onMessageInternal(final Message aMessage) {
    try {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Consuming the message " + aMessage);
        // we want to log the total processing time, get the start time
        final long startTime = System.nanoTime();
        // Reads the MessageConfig from the ConfigurationService, based on the
        // dataBeanClassName
        final String dataBeanClassName = aMessage.getStringProperty(JmsBrowser.HEADER_DATA_BEAN_CLASS_NAME);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("DataBean Class Name " + dataBeanClassName);
        final MessageInfo messageInfo = ConfigurationService.getInstance().getMessageInfo(dataBeanClassName);
        if (messageInfo == null)
            throw new JaffaMessagingFrameworkException(JaffaMessagingFrameworkException.MESSAGE_INFO_MISSING, new Object[] { dataBeanClassName });
        // Unmarshals the Message payload into a dataBean using the
        // dataBeanClassName
        final Object payload = JAXBHelper.unmarshalPayload(obtainMessageContents(aMessage), dataBeanClassName);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Obtained payload for the dataBean " + dataBeanClassName + '\n' + payload);
        // Reads the userId from the Message header
        String userId = aMessage.getStringProperty(JmsBrowser.HEADER_USER_ID);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("The userId is " + userId);
        // Reads the scheduledTaskId from the Message header
        final String scheduledTaskId = aMessage.getStringProperty(JmsBrowser.HEADER_SCHEDULED_TASK_ID);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("The scheduledTaskId is " + scheduledTaskId);
        // Reads the originalMessageId from the Message header
        String originalMessageId = aMessage.getStringProperty(JmsBrowser.HEADER_ORIGINAL_MESSAGE_ID);
        if (originalMessageId == null)
            originalMessageId = aMessage.getJMSMessageID();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("The originalMessageId is " + originalMessageId);
        // Process the payload
        processPayload(aMessage, messageInfo, payload, userId, scheduledTaskId, originalMessageId);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Message successfully consumed");
        // we want to log the total processing time, get the end time
        if (LOGGER.isInfoEnabled()) {
            final long endTime = System.nanoTime();
            final long duration = endTime - startTime;
            LOGGER.info("[" + originalMessageId + "]Total time to process the Message: " + duration + "ms");
        }
    } catch (Exception e) {
        // Just log the error
        LOGGER.error("Exception thrown while consuming the message. Message was: " + aMessage, e);
    }
}
Also used : FrameworkException(org.jaffa.exceptions.FrameworkException) MessagingException(javax.mail.MessagingException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UserSessionSetupException(org.jaffa.presentation.portlet.session.UserSessionSetupException) ApplicationException(org.jaffa.exceptions.ApplicationException) MessageInfo(org.jaffa.modules.messaging.services.configdomain.MessageInfo)

Example 4 with MessageInfo

use of org.jaffa.modules.messaging.services.configdomain.MessageInfo in project jaffa-framework by jaffa-projects.

the class TaskFinderComponent method viewFailedTasks.

/**
 * Calls the Jaffa.Messaging.QueueViewer component for viewing the failed tasks.
 * @throws ApplicationExceptions This will be thrown in case any invalid data has been set.
 * @throws FrameworkException Indicates some system error.
 * @return The FormKey for the QueueViewer screen.
 */
public FormKey viewFailedTasks(String scheduledTaskId, Object businessObject) throws ApplicationExceptions, FrameworkException {
    // Create a filter with the input scheduledTaskId
    String filter = new StringBuilder(JmsBrowser.HEADER_SCHEDULED_TASK_ID).append('=').append('\'').append(scheduledTaskId).append('\'').toString();
    // Figure out the appropriate queueName based on the businessObject, so that the QueueViewer displays the relevant columns
    String queueName = null;
    if (businessObject != null) {
        try {
            MessageInfo messageInfo = ConfigurationService.getInstance().getMessageInfo(businessObject.getClass().getName());
            if (messageInfo != null)
                queueName = messageInfo.getQueueName();
        } catch (ClassNotFoundException e) {
        // do nothing
        }
    }
    // Instantiate the QueueViewer
    QueueViewerComponent viewComponent = (QueueViewerComponent) run("Jaffa.Messaging.QueueViewer");
    viewComponent.setFilter(filter);
    if (queueName != null) {
        viewComponent.setQueue(queueName);
        viewComponent.setMessageMode(MessageModeEnum.ERROR);
    }
    viewComponent.setReturnToFormKey(FormKey.getCloseBrowserFormKey());
    return viewComponent.display();
}
Also used : QueueViewerComponent(org.jaffa.modules.messaging.components.queueviewer.ui.QueueViewerComponent) MessageInfo(org.jaffa.modules.messaging.services.configdomain.MessageInfo)

Example 5 with MessageInfo

use of org.jaffa.modules.messaging.services.configdomain.MessageInfo in project jaffa-framework by jaffa-projects.

the class ConfigurationServiceTest method testGetMessageInfoForChildClassWithNoDefinition.

/**
 * Test of getMessageInfo method, of class org.jaffa.modules.messaging.services.ConfigurationService.
 * This tries to read the MessageInfo for Example2Message, which is not defined.
 * Instead it expects to get the definition for Example2Message's base class BaseMessage.
 */
public void testGetMessageInfoForChildClassWithNoDefinition() throws ClassNotFoundException {
    ConfigurationService configurationService = ConfigurationService.getInstance();
    assertNotNull("Should have received an instance of the ConfigurationService", configurationService);
    MessageInfo messageInfo = null;
    messageInfo = configurationService.getMessageInfo("org.jaffa.modules.messaging.services.Example2Message");
    assertNotNull("Should have received a MessageInfo object for org.jaffa.modules.messaging.services.Example2Message", messageInfo);
    assertEquals("org.jaffa.modules.messaging.services.BaseMessage", messageInfo.getDataBean());
    assertEquals("jaffa/queue", messageInfo.getQueueName());
    assertEquals("org.jaffa.modules.messaging.services.BaseService", messageInfo.getToClass());
    assertEquals("process", messageInfo.getToMethod());
    assertNotNull("Should have received a LockCheck object", messageInfo.getLockCheck());
    assertNotNull("Should have received a LockCheck object with a List of param elements", messageInfo.getLockCheck().getParam());
    assertEquals("Should have received a LockCheck object with a List of 2 param elements", 2, messageInfo.getLockCheck().getParam().size());
    assertEquals("jaffa.locks.global", messageInfo.getLockCheck().getParam().get(0).getName());
    assertEquals("true", messageInfo.getLockCheck().getParam().get(0).getValue());
    assertFalse(messageInfo.getLockCheck().getParam().get(0).isExpression());
    assertEquals("jaffa.locks.asset", messageInfo.getLockCheck().getParam().get(1).getName());
    assertEquals("bean.assetId", messageInfo.getLockCheck().getParam().get(1).getValue());
    assertTrue(messageInfo.getLockCheck().getParam().get(1).isExpression());
    assertNotNull("Should have received a Header object", messageInfo.getHeader());
    assertNotNull("Should have received a Header object with a List of param elements", messageInfo.getHeader().getParam());
    assertEquals("Should have received a Header object with a List of 1 param elements", 1, messageInfo.getHeader().getParam().size());
    assertEquals("jaffa.locks.asset", messageInfo.getHeader().getParam().get(0).getName());
    assertEquals("bean.assetId", messageInfo.getHeader().getParam().get(0).getValue());
    assertTrue(messageInfo.getHeader().getParam().get(0).isExpression());
}
Also used : MessageInfo(org.jaffa.modules.messaging.services.configdomain.MessageInfo)

Aggregations

MessageInfo (org.jaffa.modules.messaging.services.configdomain.MessageInfo)8 JMSException (javax.jms.JMSException)2 FrameworkException (org.jaffa.exceptions.FrameworkException)2 Param (org.jaffa.modules.messaging.services.configdomain.Param)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Connection (javax.jms.Connection)1 InvalidSelectorException (javax.jms.InvalidSelectorException)1 Message (javax.jms.Message)1 ObjectMessage (javax.jms.ObjectMessage)1 Session (javax.jms.Session)1 TextMessage (javax.jms.TextMessage)1 MessagingException (javax.mail.MessagingException)1 ApplicationException (org.jaffa.exceptions.ApplicationException)1 QueueViewerComponent (org.jaffa.modules.messaging.components.queueviewer.ui.QueueViewerComponent)1 UOW (org.jaffa.persistence.UOW)1 UserSessionSetupException (org.jaffa.presentation.portlet.session.UserSessionSetupException)1 EventMessage (org.jaffa.soa.services.event.EventMessage)1