@Override
  public InboundEndpoint getEndpoint() throws Exception {
    UdpConnector connector = new UdpConnector(muleContext);
    connector.initialise();

    EndpointBuilder builder = new EndpointURIEndpointBuilder("udp://localhost:10100", muleContext);
    builder.setConnector(connector);
    return muleContext.getEndpointFactory().getInboundEndpoint(builder);
  }
Example #2
0
  public void testJaxenFilterConfig() throws Exception {
    EndpointBuilder epb = muleContext.getRegistry().lookupEndpointBuilder("test.ep2");

    InboundEndpoint ep = epb.buildInboundEndpoint();
    assertNotNull(ep.getFilter());
    assertTrue(ep.getFilter() instanceof JaxenFilter);
    JaxenFilter filter = (JaxenFilter) ep.getFilter();
    assertEquals("/car:foo/car:bar", filter.getPattern());
    assertEquals(5, filter.getNamespaces().size());
    assertEquals("http://car.com", filter.getNamespaces().get("car"));
  }
Example #3
0
  protected Destination getReplyToDestination(
      Message message, Session session, MuleEvent event, boolean remoteSync, boolean topic)
      throws JMSException, EndpointException, InitialisationException {
    Destination replyTo = null;

    // Some JMS implementations might not support the ReplyTo property.
    if (isHandleReplyTo(message, event)) {

      Object tempReplyTo = event.getMessage().removeProperty(JmsConstants.JMS_REPLY_TO);
      if (tempReplyTo == null) {
        // It may be a Mule URI or global endpoint Ref
        tempReplyTo = event.getMessage().removeProperty(MuleProperties.MULE_REPLY_TO_PROPERTY);
        if (tempReplyTo != null) {
          int i = tempReplyTo.toString().indexOf("://");
          if (i > -1) {
            tempReplyTo = tempReplyTo.toString().substring(i + 3);
          } else {
            EndpointBuilder epb =
                event.getMuleContext().getRegistry().lookupEndpointBuilder(tempReplyTo.toString());
            if (epb != null) {
              tempReplyTo = epb.buildOutboundEndpoint().getEndpointURI().getAddress();
            }
          }
        }
      }
      if (tempReplyTo != null) {
        if (tempReplyTo instanceof Destination) {
          replyTo = (Destination) tempReplyTo;
        } else {
          // TODO AP should this drill-down be moved into the resolver as well?
          boolean replyToTopic = false;
          String reply = tempReplyTo.toString();
          int i = reply.indexOf(":");
          if (i > -1) {
            // TODO MULE-1409 this check will not work for ActiveMQ 4.x,
            // as they have temp-queue://<destination> and temp-topic://<destination> URIs
            // Extract to a custom resolver for ActiveMQ4.x
            // The code path can be exercised, e.g. by a LoanBrokerESBTestCase
            String qtype = reply.substring(0, i);
            replyToTopic = JmsConstants.TOPIC_PROPERTY.equalsIgnoreCase(qtype);
            reply = reply.substring(i + 1);
          }
          replyTo =
              connector.getJmsSupport().createDestination(session, reply, replyToTopic, endpoint);
        }
      }
      // Are we going to wait for a return event ?
      if (remoteSync && replyTo == null && !disableTemporaryDestinations) {
        replyTo = connector.getJmsSupport().createTemporaryDestination(session, topic);
      }
    }
    return replyTo;
  }
Example #4
0
  public Transformer getTransformer() throws Exception {
    Transformer trans = createObject(DomDocumentToXml.class);
    trans.setReturnClass(String.class);

    EndpointBuilder builder = new EndpointURIEndpointBuilder("test://test", muleContext);
    builder.setEncoding("US-ASCII");
    ImmutableEndpoint endpoint =
        muleContext.getRegistry().lookupEndpointFactory().getInboundEndpoint(builder);

    trans.setEndpoint(endpoint);
    return trans;
  }
  @Test
  public void cachesResolvedStaticEndpoints() throws Exception {
    OutboundEndpoint prototypeEndpoint = mock(OutboundEndpoint.class);
    when(prototypeEndpoint.getMuleContext()).thenReturn(muleContext);

    EndpointBuilder staticEndpointBuilder = mock(EndpointBuilder.class);
    when(staticEndpointBuilder.buildOutboundEndpoint()).thenReturn(prototypeEndpoint);

    EndpointBuilder endpointBuilder = mock(EndpointBuilder.class);
    when(endpointBuilder.buildOutboundEndpoint()).thenReturn(prototypeEndpoint);
    when(endpointBuilder.clone()).thenReturn(staticEndpointBuilder);

    DynamicOutboundEndpoint dynamicOutboundEndpoint =
        new DynamicOutboundEndpoint(
            endpointBuilder,
            new DynamicURIBuilder(new URIBuilder("test://localhost:#[header:port]", muleContext)));

    testOutboundEvent = createTestOutboundEvent();
    dynamicOutboundEndpoint.process(testOutboundEvent);
    dynamicOutboundEndpoint.process(testOutboundEvent);

    verify(endpointBuilder, times(1)).buildOutboundEndpoint();
  }
Example #6
0
  private MuleMessage dispatchMessage(MuleEvent 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()
              + ". MuleEvent id is: "
              + event.getId()
              + ". Outbound transformers are: "
              + event.getEndpoint().getTransformers());
    }

    try {
      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(
              JmsMessages.connectorDoesNotSupportSyncReceiveWhenTransacted());
        }
      }
      // 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 {
          session = connector.getSession(event.getEndpoint());
          cachedSession = session;
        }
      } else {
        session = connector.getSession(event.getEndpoint());
        if (event.getEndpoint().getTransactionConfig().isTransacted()) {
          transacted = true;
        }
      }

      boolean topic = connector.getTopicResolver().isTopic(event.getEndpoint(), true);

      Destination dest = connector.createDestinationMule3858Backport(session, endpoint);
      producer = connector.getJmsSupport().createProducer(session, dest, topic);

      Object message = event.transformMessage();
      if (!(message instanceof Message)) {
        throw new DispatchException(
            JmsMessages.checkTransformer("JMS message", message.getClass(), connector.getName()),
            event.getMessage(),
            event.getEndpoint());
      }

      Message msg = (Message) message;
      if (event.getMessage().getCorrelationId() != null) {
        msg.setJMSCorrelationID(event.getMessage().getCorrelationId());
      }

      MuleMessage 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) {
          // It may be a Mule URI or global endpoint Ref
          tempReplyTo = eventMsg.removeProperty(MuleProperties.MULE_REPLY_TO_PROPERTY);
          if (tempReplyTo != null) {
            if (tempReplyTo.toString().startsWith("jms://")) {
              tempReplyTo = tempReplyTo.toString().substring(6);
            } else {
              EndpointBuilder epb =
                  event
                      .getMuleContext()
                      .getRegistry()
                      .lookupEndpointBuilder(tempReplyTo.toString());
              if (epb != null) {
                tempReplyTo = epb.buildOutboundEndpoint().getEndpointURI().getAddress();
              }
            }
          }
        }
        if (tempReplyTo != null) {
          if (tempReplyTo instanceof Destination) {
            replyTo = (Destination) tempReplyTo;
          } else {
            // TODO AP should this drill-down be moved into the resolver as well?
            boolean replyToTopic = false;
            String reply = tempReplyTo.toString();
            int i = reply.indexOf(":");
            if (i > -1) {
              // TODO MULE-1409 this check will not work for ActiveMQ 4.x,
              // as they have temp-queue://<destination> and temp-topic://<destination> URIs
              // Extract to a custom resolver for ActiveMQ4.x
              // The code path can be exercised, e.g. by a LoanBrokerESBTestCase
              String qtype = reply.substring(0, i);
              replyToTopic = JmsConstants.TOPIC_PROPERTY.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) {
          try {
            consumer = connector.getJmsSupport().createConsumer(session, replyTo, topic);
          } catch (Exception e) {
            logger.warn(e);
          }
        }
      }

      // 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 =
          StringUtils.isNotBlank(ttlString)
              ? NumberUtils.toLong(ttlString)
              : Message.DEFAULT_TIME_TO_LIVE;
      int priority =
          StringUtils.isNotBlank(priorityString)
              ? NumberUtils.toInt(priorityString)
              : Message.DEFAULT_PRIORITY;
      boolean persistent =
          StringUtils.isNotBlank(persistentDeliveryString)
              ? BooleanUtils.toBoolean(persistentDeliveryString)
              : connector.isPersistentDelivery();

      if (connector.isHonorQosHeaders()) {
        int priorityProp =
            eventMsg.getIntProperty(JmsConstants.JMS_PRIORITY, Connector.INT_VALUE_NOT_SET);
        int deliveryModeProp =
            eventMsg.getIntProperty(JmsConstants.JMS_DELIVERY_MODE, Connector.INT_VALUE_NOT_SET);

        if (priorityProp != Connector.INT_VALUE_NOT_SET) {
          priority = priorityProp;
        }
        if (deliveryModeProp != Connector.INT_VALUE_NOT_SET) {
          persistent = deliveryModeProp == DeliveryMode.PERSISTENT;
        }
      }

      if (logger.isDebugEnabled()) {
        logger.debug("Sending message of type " + ClassUtils.getSimpleName(msg.getClass()));
      }

      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();

        if (logger.isDebugEnabled()) {
          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 {
          MessageAdapter adapter = connector.getMessageAdapter(result);
          return new DefaultMuleMessage(
              JmsMessageUtils.toObject(
                  result, connector.getSpecification(), endpoint.getEncoding()),
              adapter);
        }
      } else {
        connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic);
        if (consumer != null) {
          int timeout = event.getTimeout();

          if (logger.isDebugEnabled()) {
            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 {
            MessageAdapter adapter = connector.getMessageAdapter(result);
            return new DefaultMuleMessage(
                JmsMessageUtils.toObject(
                    result, connector.getSpecification(), endpoint.getEncoding()),
                adapter);
          }
        }
      }
      return null;
    } finally {
      connector.closeQuietly(producer);
      connector.closeQuietly(consumer);

      // TODO AP check if TopicResolver is to be utilized for temp destinations as well
      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);
      }
    }
  }
Example #7
0
  @SuppressWarnings("unchecked")
  protected void registerReceiverWithMuleService(MessageReceiver receiver, EndpointURI ep)
      throws MuleException {
    CxfMessageReceiver cxfReceiver = (CxfMessageReceiver) receiver;
    Server server = cxfReceiver.getServer();

    uriToServer.put(server.getEndpoint().getEndpointInfo().getAddress(), server);

    // TODO MULE-2228 Simplify this API
    SedaService c = new SedaService();

    String uniqueServiceName = createServiceName(server.getEndpoint());
    c.setName(uniqueServiceName);

    c.setModel(muleContext.getRegistry().lookupSystemModel());

    CxfServiceComponent svcComponent = new CxfServiceComponent(this, (CxfMessageReceiver) receiver);
    svcComponent.setBus(bus);

    c.setComponent(new DefaultJavaComponent(new SingletonObjectFactory(svcComponent)));

    // No determine if the endpointUri requires a new connector to be
    // registed in the case of http we only need to register the new
    // endpointUri if the port is different
    String endpoint = receiver.getEndpointURI().getAddress();
    String scheme = ep.getScheme().toLowerCase();

    InboundEndpoint originalEndpoint = receiver.getEndpoint();
    boolean sync = originalEndpoint.isSynchronous();

    // If we are using sockets then we need to set the endpoint name appropiately
    // and if using http/https
    // we need to default to POST and set the Content-Type
    if (scheme.equals("http")
        || scheme.equals("https")
        || scheme.equals("ssl")
        || scheme.equals("tcp")
        || scheme.equals("servlet")) {
      originalEndpoint.getProperties().put(HttpConnector.HTTP_METHOD_PROPERTY, "POST");
      originalEndpoint.getProperties().put(HttpConstants.HEADER_CONTENT_TYPE, "text/xml");
    }

    QName serviceName = server.getEndpoint().getEndpointInfo().getName();

    EndpointBuilder protocolEndpointBuilder = new EndpointURIEndpointBuilder(endpoint, muleContext);
    protocolEndpointBuilder.setSynchronous(sync);
    protocolEndpointBuilder.setName(ep.getScheme() + ":" + serviceName.getLocalPart());
    protocolEndpointBuilder.setTransactionConfig(originalEndpoint.getTransactionConfig());

    EndpointBuilder receiverEndpointBuilder =
        new EndpointURIEndpointBuilder(originalEndpoint, muleContext);

    // Apply the transformers to the correct endpoint
    EndpointBuilder transformerEndpoint;
    if (cxfReceiver.isApplyTransformersToProtocol()) {
      transformerEndpoint = protocolEndpointBuilder;
      receiverEndpointBuilder.setTransformers(Collections.emptyList());
      receiverEndpointBuilder.setResponseTransformers(Collections.emptyList());
    } else {
      transformerEndpoint = receiverEndpointBuilder;
    }

    // Ensure that the transformers aren't empty before setting them. Otherwise Mule will get
    // confused
    // and won't add the default transformers.
    if (originalEndpoint.getTransformers() != null
        && !originalEndpoint.getTransformers().isEmpty()) {
      transformerEndpoint.setTransformers(originalEndpoint.getTransformers());
    }

    if (originalEndpoint.getResponseTransformers() != null
        && !originalEndpoint.getResponseTransformers().isEmpty()) {
      transformerEndpoint.setResponseTransformers(originalEndpoint.getResponseTransformers());
    }

    // apply the filters to the correct endpoint
    EndpointBuilder filterEndpoint;
    if (cxfReceiver.isApplyFiltersToProtocol()) {
      filterEndpoint = protocolEndpointBuilder;
      receiverEndpointBuilder.setFilter(null);
    } else {
      filterEndpoint = receiverEndpointBuilder;
    }
    filterEndpoint.setFilter(originalEndpoint.getFilter());

    // apply the security filter to the correct endpoint
    EndpointBuilder secFilterEndpoint;
    if (cxfReceiver.isApplySecurityToProtocol()) {
      secFilterEndpoint = protocolEndpointBuilder;
      receiverEndpointBuilder.setSecurityFilter(null);
    } else {
      secFilterEndpoint = receiverEndpointBuilder;
    }
    secFilterEndpoint.setSecurityFilter(originalEndpoint.getSecurityFilter());

    String connectorName = (String) originalEndpoint.getProperty(CxfConstants.PROTOCOL_CONNECTOR);
    if (connectorName != null) {
      protocolEndpointBuilder.setConnector(
          muleContext.getRegistry().lookupConnector(connectorName));
    }

    InboundEndpoint protocolEndpoint =
        muleContext
            .getRegistry()
            .lookupEndpointFactory()
            .getInboundEndpoint(protocolEndpointBuilder);

    InboundEndpoint receiverEndpoint =
        muleContext
            .getRegistry()
            .lookupEndpointFactory()
            .getInboundEndpoint(receiverEndpointBuilder);

    receiver.setEndpoint(receiverEndpoint);

    c.setInboundRouter(new DefaultInboundRouterCollection());
    c.getInboundRouter().addEndpoint(protocolEndpoint);
    services.add(c);
  }