Esempio n. 1
0
 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;
 }
Esempio n. 2
0
 /*
  * (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);
     }
   }
 }
Esempio n. 3
0
  /*
   * (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;
    }
  }
Esempio n. 4
0
  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");
    }
  }
Esempio n. 5
0
  /* (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);
    }
  }
Esempio n. 6
0
  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);
      }
    }
  }
Esempio n. 7
0
 /**
  * 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();
 }
Esempio n. 8
0
 public Object onCall(UMOEvent event) throws UMOException {
   return routeMessage(
       new MuleMessage(event.getTransformedMessage(), event.getMessage()), event.isSynchronous());
 }