Search in sources :

Example 1 with Param

use of org.jaffa.modules.messaging.services.configdomain.Param 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 2 with Param

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

the class LoggingService method setLoggingContext.

/**
 * Adds the appropriate elements to the Message Driven Context (MDC) of Log4J, as specified in the input messageConfig.
 * @param payload Any serializable object.
 * @param messageInfo the corresponding MessageInfo object, as specified in the configuration file.
 * @param userId the userId to be added to the MDC.
 * @param scheduledTaskId the scheduledTaskId to be added to the MDC.
 * @param messageId the messageId to be added to the MDC.
 */
public static void setLoggingContext(Object payload, MessageInfo messageInfo, String userId, String scheduledTaskId, String messageId) {
    // Push the current MDC context into the thread-level stack
    Map<String, Object> currentLoggingContext = MDC.getContext() != null ? new HashMap<String, Object>(MDC.getContext()) : new HashMap<String, Object>();
    Stack<Map<String, Object>> stack = t_loggingContext.get();
    if (stack == null) {
        stack = new Stack<Map<String, Object>>();
        t_loggingContext.set(stack);
    }
    stack.push(currentLoggingContext);
    // Add elements to the MDC, based on the presence of loggingNames in the header information of the MessageConfig
    if (messageInfo.getHeader() != null && messageInfo.getHeader().getParam() != null) {
        for (Param param : messageInfo.getHeader().getParam()) {
            if (param.getLoggingName() != null) {
                String key = param.getLoggingName().value();
                try {
                    Object value = InitialContextFactrory.obtainParamValue(param, payload);
                    if (value != null)
                        MDC.put(key, value);
                    else
                        MDC.remove(key);
                } catch (Exception e) {
                    if (log.isDebugEnabled())
                        log.debug("Error in obtaining value for the LoggingName " + key, e);
                }
            }
        }
    }
    // Add some standard elements to the MDC
    if (userId != null)
        MDC.put(BusinessEventLogMeta.LOGGED_BY, userId);
    if (scheduledTaskId != null)
        MDC.put(BusinessEventLogMeta.SCHEDULED_TASK_ID, scheduledTaskId);
    if (messageId != null)
        MDC.put(BusinessEventLogMeta.MESSAGE_ID, messageId);
}
Also used : Param(org.jaffa.modules.messaging.services.configdomain.Param) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with Param

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

the class JndiJmsManager method populateJmsConfig.

/**
 * Pre fills the jmsconfig with the environment values
 * @param jmsConfig
 */
private void populateJmsConfig(JmsConfig jmsConfig) {
    if (jmsConfig != null && jmsConfig.getJndiContext() != null && System.getProperty("java.naming.provider.url") != null && System.getProperty("java.naming.provider.url").length() > 0) {
        for (Param param : jmsConfig.getJndiContext().getParam()) {
            if ("java.naming.provider.url".equals(param.getName())) {
                param.setValue(System.getProperty("java.naming.provider.url"));
            }
        }
        jmsConfig.setUser(System.getProperty("activemq.broker.jms.user"));
        jmsConfig.setPassword(System.getProperty("activemq.broker.jms.password"));
    }
}
Also used : Param(org.jaffa.modules.messaging.services.configdomain.Param)

Example 4 with Param

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

the class InitialContextFactrory method createInitialContext.

/**
 * Creates an InitialContext.
 *
 * @throws FrameworkException
 *           in case any internal error occurs.
 * @throws ApplicationExceptions
 *           Indicates application error(s).
 */
private void createInitialContext() throws FrameworkException, ApplicationExceptions {
    try {
        if (context == null) {
            JmsConfig jmsConfig = ConfigurationService.getInstance().getJmsConfig();
            if (jmsConfig.getJndiContext() != null && jmsConfig.getJndiContext().getParam() != null) {
                Properties properties = new Properties();
                for (Param param : jmsConfig.getJndiContext().getParam()) properties.put(param.getName(), obtainParamValue(param));
                context = new InitialContext(properties);
            } else
                context = new InitialContext();
        }
    } catch (NamingException e) {
        LOGGER.error("Error in creating a JNDI InitialContext", e);
        throw new JaffaMessagingFrameworkException(JaffaMessagingFrameworkException.INITIAL_CONTEXT_ERROR, null, e);
    }
}
Also used : Param(org.jaffa.modules.messaging.services.configdomain.Param) NamingException(javax.naming.NamingException) JmsConfig(org.jaffa.modules.messaging.services.configdomain.JmsConfig) Properties(java.util.Properties) InitialContext(javax.naming.InitialContext)

Example 5 with Param

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

the class JmsBrowser method invokeHandler.

/**
 * Invokes the intended handler. This Handler must implement the IMessageHandler Interface in order to be invoked.
 *
 * @param message
 * @param methodName
 * @throws JaffaMessagingFrameworkException
 */
private static void invokeHandler(Message message, String methodName) throws JaffaMessagingFrameworkException {
    UOW uow = null;
    try {
        // Reads the MessageConfig from the ConfigurationService, based on the dataBeanClassName
        String dataBeanClassName = message.getStringProperty(JmsBrowser.HEADER_DATA_BEAN_CLASS_NAME);
        MessageInfo messageInfo = ConfigurationService.getInstance().getMessageInfo(dataBeanClassName);
        if (messageInfo == null)
            throw new JaffaMessagingFrameworkException(JaffaMessagingFrameworkException.MESSAGE_INFO_MISSING, new Object[] { dataBeanClassName });
        // Obtain the handlerClass
        Class handlerClass = Class.forName(messageInfo.getToClass());
        if (IMessageHandler.class.isAssignableFrom(handlerClass)) {
            // Unmarshals the Message payload into a dataBean using the dataBeanClassName
            Object payload = JAXBHelper.unmarshalPayload(obtainMessageContents(message), dataBeanClassName);
            if (log.isDebugEnabled())
                log.debug("Obtained payload for the dataBean " + dataBeanClassName + '\n' + payload);
            Method handlerMethod = null;
            Object handlerObject = null;
            // Obtain the handler method
            try {
                handlerMethod = handlerClass.getMethod(methodName, new Class[] { UOW.class, Map.class, Object.class });
            } catch (NoSuchMethodException e) {
                // Hence use the dataBeanClass specified in the messageInfo to get the appropriate handlerMethod
                if (log.isDebugEnabled())
                    log.debug(methodName + " method not found in " + handlerClass.getName());
                return;
            }
            handlerObject = handlerClass.newInstance();
            uow = new UOW();
            Map<String, String> headerMap = new HashMap<String, String>();
            // Sets the header elements as defined in the configuration file.
            if (messageInfo.getHeader() != null && messageInfo.getHeader().getParam() != null) {
                for (Param param : messageInfo.getHeader().getParam()) {
                    String headerValue = (String) message.getObjectProperty(param.getName());
                    headerMap.put(param.getName(), headerValue);
                }
            }
            handlerMethod.invoke(handlerObject, new Object[] { uow, headerMap, payload });
            uow.commit();
        }
    } catch (Exception e) {
        // Just log the error
        log.error("Exception thrown while deleting the message. Message was: " + message, e);
        throw new JaffaMessagingFrameworkException(JaffaMessagingFrameworkException.DELETE_ERROR, null, e);
    } finally {
        if (uow != null) {
            try {
                uow.rollback();
            } catch (Exception e) {
                throw new JaffaMessagingFrameworkException(JaffaMessagingFrameworkException.DELETE_ERROR, null, e);
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) Method(java.lang.reflect.Method) FrameworkException(org.jaffa.exceptions.FrameworkException) JMSException(javax.jms.JMSException) InvalidSelectorException(javax.jms.InvalidSelectorException) MessageInfo(org.jaffa.modules.messaging.services.configdomain.MessageInfo) Param(org.jaffa.modules.messaging.services.configdomain.Param) UOW(org.jaffa.persistence.UOW) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Param (org.jaffa.modules.messaging.services.configdomain.Param)5 HashMap (java.util.HashMap)2 Map (java.util.Map)2 JMSException (javax.jms.JMSException)2 MessageInfo (org.jaffa.modules.messaging.services.configdomain.MessageInfo)2 Method (java.lang.reflect.Method)1 Properties (java.util.Properties)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 InitialContext (javax.naming.InitialContext)1 NamingException (javax.naming.NamingException)1 FrameworkException (org.jaffa.exceptions.FrameworkException)1 JmsConfig (org.jaffa.modules.messaging.services.configdomain.JmsConfig)1 UOW (org.jaffa.persistence.UOW)1 EventMessage (org.jaffa.soa.services.event.EventMessage)1