protected List getMessages() throws Exception { QueueSession qs = connector.getQueueSession(); Queue queue = qs.getQueue(endpoint.getEndpointURI().getAddress()); UMOEvent event = (UMOEvent) queue.poll(connector.getQueueTimeout()); if (event != null) { routeMessage(new MuleMessage(event.getTransformedMessage(), event.getMessage())); } return null; }
public int compare(Object o1, Object o2) { UMOEvent event1 = (UMOEvent) o1; UMOEvent event2 = (UMOEvent) o2; if (event1.getMessage().getCorrelationSequence() > event2.getMessage().getCorrelationSequence()) { return 1; } else { return -1; } }
protected String getIdForEvent(UMOEvent event) throws MessagingException { try { MessageDigest md = MessageDigest.getInstance(messageDigestAlgorithm); return (String) byteArrayToHexString.transform( md.digest((byte[]) objectToByteArray.transform(event.getMessage().getPayload()))); } catch (NoSuchAlgorithmException nsa) { throw new RoutingException(event.getMessage(), event.getEndpoint(), nsa); } catch (TransformerException te) { throw new RoutingException(event.getMessage(), event.getEndpoint(), te); } }
protected UMOMessage aggregateEvents(EventGroup events) throws RoutingException { StringBuffer newPayload = new StringBuffer(); UMOEvent event = null; for (Iterator iterator = events.getEvents().iterator(); iterator.hasNext(); ) { event = (UMOEvent) iterator.next(); try { newPayload.append(event.getMessageAsString()).append(" "); } catch (UMOException e) { throw new RoutingException(event.getMessage(), event.getEndpoint(), e); } } return new MuleMessage(newPayload.toString(), event.getProperties()); }
/* * (non-Javadoc) * * @see org.mule.umo.UMOEventListener#onEvent(org.mule.umo.UMOEvent) */ public void onEvent(UMOEvent event) throws UMOException { if (connector.isQueueEvents()) { QueueSession queueSession = connector.getQueueSession(); Queue queue = queueSession.getQueue(endpoint.getEndpointURI().getAddress()); try { queue.put(event); } catch (InterruptedException e) { throw new MuleException( CoreMessages.interruptedQueuingEventFor(this.endpoint.getEndpointURI()), e); } } else { UMOMessage msg = new MuleMessage(event.getTransformedMessage(), event.getMessage()); synchronized (lock) { routeMessage(msg); } } }
/* * (non-Javadoc) * * @see org.mule.providers.AbstractMessageDispatcher#doDispatch(org.mule.umo.UMOEvent) */ protected void doDispatch(UMOEvent event) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Dispatch event: " + event); } UMOImmutableEndpoint endpoint = event.getEndpoint(); String writeStmt = endpoint.getEndpointURI().getAddress(); String str; if ((str = this.connector.getQuery(endpoint, writeStmt)) != null) { writeStmt = str; } if (StringUtils.isEmpty(writeStmt)) { throw new IllegalArgumentException("Write statement should not be null"); } if (!"insert".equalsIgnoreCase(writeStmt.substring(0, 6)) && !"update".equalsIgnoreCase(writeStmt.substring(0, 6)) && !"delete".equalsIgnoreCase(writeStmt.substring(0, 6))) { throw new IllegalArgumentException( "Write statement should be an insert / update / delete sql statement"); } List paramNames = new ArrayList(); writeStmt = JdbcUtils.parseStatement(writeStmt, paramNames); Object[] paramValues = JdbcUtils.getParams(endpoint, paramNames, event.getTransformedMessage()); UMOTransaction tx = TransactionCoordination.getInstance().getTransaction(); Connection con = null; try { con = this.connector.getConnection(); int nbRows = connector.createQueryRunner().update(con, writeStmt, paramValues); if (nbRows != 1) { logger.warn("Row count for write should be 1 and not " + nbRows); } if (tx == null) { JdbcUtils.commitAndClose(con); } logger.debug("Event dispatched succesfuly"); } catch (Exception e) { logger.debug("Error dispatching event: " + e.getMessage(), e); if (tx == null) { JdbcUtils.rollbackAndClose(con); } throw e; } }
public void route(UMOEvent event) throws RoutingException { UMOResponseRouter router = null; for (Iterator iterator = getRouters().iterator(); iterator.hasNext(); ) { router = (UMOResponseRouter) iterator.next(); router.process(event); // Update stats if (getStatistics().isEnabled()) { getStatistics().incrementRoutedMessage(event.getEndpoint()); } } }
/** * This method is invoked if the shouldAggregate method is called and returns true. Once this * method returns an aggregated message the event group is removed from the router * * @param events the event group for this request * @return an aggregated message * @throws org.mule.routing.AggregationException if the aggregation fails. in this scenario the * whole event group is removed and passed to the exception handler for this componenet */ protected UMOMessage aggregateEvents(EventGroup events) throws AggregationException { List eventList = IteratorUtils.toList(events.iterator(), events.size()); UMOEvent firstEvent = (UMOEvent) eventList.get(0); Collections.sort(eventList, SequenceComparator.getInstance()); ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); try { for (Iterator iterator = eventList.iterator(); iterator.hasNext(); ) { UMOEvent event = (UMOEvent) iterator.next(); baos.write(event.getMessageAsBytes()); } UMOMessage message = new MuleMessage(baos.toByteArray(), firstEvent.getMessage()); message.setCorrelationGroupSize(-1); message.setCorrelationSequence(-1); return message; } catch (Exception e) { throw new AggregationException(events, firstEvent.getEndpoint(), e); } finally { IOUtils.closeQuietly(baos); } }
protected UMOMessage doSend(UMOEvent event) throws Exception { sendMessage(event); if (useRemoteSync(event)) { Message response; if (groupChat != null) { response = groupChat.nextMessage(event.getTimeout()); } else { response = chat.nextMessage(event.getTimeout()); } if (response != null) { if (logger.isDebugEnabled()) { logger.debug("Got a response from chat: " + chat); } return new MuleMessage(connector.getMessageAdapter(response)); } } return null; }
protected void sendMessage(UMOEvent event) throws Exception { if (chat == null && groupChat == null) { UMOMessage msg = event.getMessage(); boolean group = msg.getBooleanProperty(XmppConnector.XMPP_GROUP_CHAT, false); String nickname = msg.getStringProperty(XmppConnector.XMPP_NICKNAME, "mule"); String recipient = event.getEndpoint().getEndpointURI().getPath().substring(1); if (group) { groupChat = new GroupChat(xmppConnection, recipient); if (!groupChat.isJoined()) { groupChat.join(nickname); } } else { chat = new Chat(xmppConnection, recipient); } } Object msgObj = event.getMessage().getPayload(); Message message; // avoid duplicate transformation if (!(msgObj instanceof Message)) { message = (Message) event.getTransformedMessage(); } else { message = (Message) msgObj; } if (logger.isTraceEnabled()) { logger.trace("Transformed packet: " + message.toXML()); } if (chat != null) { chat.sendMessage(message); } else { groupChat.sendMessage(message); } if (logger.isDebugEnabled()) { logger.debug("Packet successfully sent"); } }
/* (non-Javadoc) * @see org.mule.umo.provider.UMOConnectorSession#dispatch(org.mule.umo.UMOEvent) */ public void doDispatch(UMOEvent event) throws Exception { try { String endpoint = event.getEndpoint().getEndpointURI().getAddress(); Object data = event.getTransformedMessage(); String filename = (String) event.getProperty(FileConnector.PROPERTY_FILENAME); if (filename == null) { String outPattern = (String) event.getProperty(FileConnector.PROPERTY_OUTPUT_PATTERN); if (outPattern == null) { outPattern = connector.getOutputPattern(); } filename = generateFilename(event, outPattern); } if (filename == null) { throw new IOException("Filename is null"); } File file = Utility.createFile(endpoint + "/" + filename); byte[] buf; if (data instanceof byte[]) { buf = (byte[]) data; } else { buf = data.toString().getBytes(); } logger.info("Writing file to: " + file.getAbsolutePath()); FileOutputStream fos = new FileOutputStream(file, connector.isOutputAppend()); try { fos.write(buf); } finally { fos.close(); } } catch (Exception e) { getConnector().handleException(e); } }
public synchronized UMOMessage catchMessage( UMOMessage message, UMOSession session, boolean synchronous) throws RoutingException { UMOEvent event = RequestContext.getEvent(); try { event = new MuleEvent(message, event.getEndpoint(), session.getComponent(), event); if (synchronous) { statistics.incrementRoutedMessage(event.getEndpoint()); logger.info( "Event being routed from catch all strategy for endpoint: " + RequestContext.getEvent().getEndpoint()); return session.getComponent().sendEvent(event); } else { statistics.incrementRoutedMessage(event.getEndpoint()); session.getComponent().dispatchEvent(event); return null; } } catch (UMOException e) { throw new ComponentRoutingException( event.getMessage(), event.getEndpoint(), session.getComponent(), e); } }
/* (non-Javadoc) * @see org.mule.umo.provider.UMOConnectorSession#send(org.mule.umo.UMOEvent) */ public UMOMessage doSend(UMOEvent event) throws Exception { doDispatch(event); return event.getMessage(); }
private UMOMessage dispatchMessage(UMOEvent event) throws Exception { Session session = null; MessageProducer producer = null; MessageConsumer consumer = null; Destination replyTo = null; boolean transacted = false; boolean cached = false; boolean remoteSync = useRemoteSync(event); if (logger.isDebugEnabled()) { logger.debug( "dispatching on endpoint: " + event.getEndpoint().getEndpointURI() + ". Event id is: " + event.getId()); } try { // Retrieve the session from the current transaction. session = connector.getSessionFromTransaction(); if (session != null) { transacted = true; // If a transaction is running, we can not receive any messages // in the same transaction. if (remoteSync) { throw new IllegalTransactionStateException(new org.mule.config.i18n.Message("jms", 2)); } } // Should we be caching sessions? Note this is not part of the JMS spec. // and is turned off by default. else if (event .getMessage() .getBooleanProperty( JmsConstants.CACHE_JMS_SESSIONS_PROPERTY, connector.isCacheJmsSessions())) { cached = true; if (cachedSession != null) { session = cachedSession; } else { // Retrieve a session from the connector session = connector.getSession(event.getEndpoint()); cachedSession = session; } } else { // Retrieve a session from the connector session = connector.getSession(event.getEndpoint()); if (event.getEndpoint().getTransactionConfig().isTransacted()) { transacted = true; } } // Add a reference to the JMS session used so that an EventAwareTransformer // can later retrieve it. // TODO Figure out a better way to accomplish this: MULE-1079 // event.getMessage().setProperty(MuleProperties.MULE_JMS_SESSION, session); UMOEndpointURI endpointUri = event.getEndpoint().getEndpointURI(); // determine if endpointUri is a queue or topic // the format is topic:destination boolean topic = false; String resourceInfo = endpointUri.getResourceInfo(); topic = (resourceInfo != null && JmsConstants.TOPIC_PROPERTY.equalsIgnoreCase(resourceInfo)); // TODO MULE20 remove resource info support if (!topic) { topic = MapUtils.getBooleanValue( event.getEndpoint().getProperties(), JmsConstants.TOPIC_PROPERTY, false); } Destination dest = connector.getJmsSupport().createDestination(session, endpointUri.getAddress(), topic); producer = connector.getJmsSupport().createProducer(session, dest, topic); Object message = event.getTransformedMessage(); if (!(message instanceof Message)) { throw new DispatchException( new org.mule.config.i18n.Message( Messages.MESSAGE_NOT_X_IT_IS_TYPE_X_CHECK_TRANSFORMER_ON_X, "JMS message", message.getClass().getName(), connector.getName()), event.getMessage(), event.getEndpoint()); } Message msg = (Message) message; if (event.getMessage().getCorrelationId() != null) { msg.setJMSCorrelationID(event.getMessage().getCorrelationId()); } UMOMessage eventMsg = event.getMessage(); // Some JMS implementations might not support the ReplyTo property. if (connector.supportsProperty(JmsConstants.JMS_REPLY_TO)) { Object tempReplyTo = eventMsg.removeProperty(JmsConstants.JMS_REPLY_TO); if (tempReplyTo != null) { if (tempReplyTo instanceof Destination) { replyTo = (Destination) tempReplyTo; } else { boolean replyToTopic = false; String reply = tempReplyTo.toString(); int i = reply.indexOf(":"); if (i > -1) { String qtype = reply.substring(0, i); replyToTopic = "topic".equalsIgnoreCase(qtype); reply = reply.substring(i + 1); } replyTo = connector.getJmsSupport().createDestination(session, reply, replyToTopic); } } // Are we going to wait for a return event ? if (remoteSync && replyTo == null) { replyTo = connector.getJmsSupport().createTemporaryDestination(session, topic); } // Set the replyTo property if (replyTo != null) { msg.setJMSReplyTo(replyTo); } // Are we going to wait for a return event ? if (remoteSync) { consumer = connector.getJmsSupport().createConsumer(session, replyTo, topic); } } // QoS support String ttlString = (String) eventMsg.removeProperty(JmsConstants.TIME_TO_LIVE_PROPERTY); String priorityString = (String) eventMsg.removeProperty(JmsConstants.PRIORITY_PROPERTY); String persistentDeliveryString = (String) eventMsg.removeProperty(JmsConstants.PERSISTENT_DELIVERY_PROPERTY); long ttl = Message.DEFAULT_TIME_TO_LIVE; int priority = Message.DEFAULT_PRIORITY; boolean persistent = Message.DEFAULT_DELIVERY_MODE == DeliveryMode.PERSISTENT; if (ttlString != null) { ttl = Long.parseLong(ttlString); } if (priorityString != null) { priority = Integer.parseInt(priorityString); } if (persistentDeliveryString != null) { persistent = Boolean.valueOf(persistentDeliveryString).booleanValue(); } logger.debug("Sending message of type " + msg.getClass().getName()); if (consumer != null && topic) { // need to register a listener for a topic Latch l = new Latch(); ReplyToListener listener = new ReplyToListener(l); consumer.setMessageListener(listener); connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic); int timeout = event.getTimeout(); logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo); l.await(timeout, TimeUnit.MILLISECONDS); consumer.setMessageListener(null); listener.release(); Message result = listener.getMessage(); if (result == null) { logger.debug("No message was returned via replyTo destination"); return null; } else { UMOMessageAdapter adapter = connector.getMessageAdapter(result); return new MuleMessage(JmsMessageUtils.getObjectForMessage(result), adapter); } } else { connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic); if (consumer != null) { int timeout = event.getTimeout(); logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo); Message result = consumer.receive(timeout); if (result == null) { logger.debug("No message was returned via replyTo destination"); return null; } else { UMOMessageAdapter adapter = connector.getMessageAdapter(result); return new MuleMessage(JmsMessageUtils.getObjectForMessage(result), adapter); } } } return null; } finally { connector.closeQuietly(consumer); connector.closeQuietly(producer); // TODO I wonder if those temporary destinations also implement BOTH interfaces... // keep it 'simple' for now if (replyTo != null && (replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic)) { if (replyTo instanceof TemporaryQueue) { connector.closeQuietly((TemporaryQueue) replyTo); } else { // hope there are no more non-standard tricks from jms vendors here ;) connector.closeQuietly((TemporaryTopic) replyTo); } } // If the session is from the current transaction, it is up to the // transaction to close it. if (session != null && !cached && !transacted) { connector.closeQuietly(session); } } }
/** * Sets an Integer property associated with the current event. Calling this method is equivilent * to calling <code>event.getMessage().setIntProperty(..., ...)</code> * * @param name the property name or key * @param value the property value */ public void setIntProperty(String name, int value) { event.setIntProperty(name, value); }
MuleEventContext(UMOEvent event) { this.event = event; this.session = event.getSession(); }
public UMOEndpointURI getEndpointURI() { return event.getEndpoint().getEndpointURI(); }
/** * Sets a property associated with the current event. Calling this method is equivilent to calling * <code>event.getMessage().setProperty(..., ...)</code> * * @param name the property name or key * @param value the property value */ public void setProperty(String name, Object value) { event.setProperty(name, value); }
/** * An outputstream the can optionally be used write response data to an incoming message. * * @return an output strem if one has been made available by the message receiver that received * the message */ public OutputStream getOutputStream() { return event.getOutputStream(); }
/** * Returns the message payload for this event * * @return the message payload for this event */ public UMOMessage getMessage() { return event.getMessage(); }
/** * Returns a map of properties associated with the event * * @return a map of properties on the event */ public Map getProperties() { return event.getProperties(); }
/** * Sets a Double property associated with the current event. Calling this method is equivilent to * calling <code>event.getMessage().setDoubleProperty(..., ...)</code> * * @param name the property name or key * @param value the property value */ public void setDoubleProperty(String name, double value) { event.setDoubleProperty(name, value); }
/** * Sets a Long property associated with the current event. Calling this method is equivilent to * calling <code>event.getMessage().setLongProperty(..., ...)</code> * * @param name the property name or key * @param value the property value */ public void setLongProperty(String name, long value) { event.setLongProperty(name, value); }
/** * Gets a Boolean property associated with the current event. Calling this method is equivilent to * calling <code>event.getMessage().getbooleanProperty(..., ...)</code> * * @param name the property name * @param defaultValue a default value if the property doesn't exist in the event * @return the property value or the defaultValue if the property does not exist */ public boolean getBooleanProperty(String name, boolean defaultValue) { return event.getBooleanProperty(name, defaultValue); }
/** * Get the timeout value associated with the event * * @return the timeout for the event */ public int getTimeout() { return event.getTimeout(); }
/** * Reterns the conents of the message as a byte array. * * @return the conents of the message as a byte array * @throws org.mule.umo.UMOException if the message cannot be converted into an array of bytes */ public byte[] getMessageAsBytes() throws UMOException { return event.getMessageAsBytes(); }
protected String getId(Object obj) { UMOEvent event = (UMOEvent) obj; return event.getId(); }
/** * Returns the message transformed into it's recognised or expected format. The transformer used * is the one configured on the endpoint through which this event was received. * * @return the message transformed into it's recognised or expected format. * @throws org.mule.umo.transformer.TransformerException if a failure occurs in the transformer * @see org.mule.umo.transformer.UMOTransformer */ public Object getTransformedMessage() throws TransformerException { return event.getTransformedMessage(); }
/** * Determines whether the was sent synchrounously or not * * @return true if the event is synchronous */ public boolean isSynchronous() { return event.isSynchronous(); }
/** * Sets a Boolean property associated with the current event. Calling this method is equivilent to * calling <code>event.getMessage().setBooleanProperty(..., ...)</code> * * @param name the property name or key * @param value the property value */ public void setBooleanProperty(String name, boolean value) { event.setBooleanProperty(name, value); }