protected void doDispatch(MuleEvent event) throws MuleException { // Dispatching event to the service if (stats.isEnabled()) { stats.incReceivedEventASync(); } if (logger.isDebugEnabled()) { logger.debug( "Service: " + name + " has received asynchronous event on: " + event.getEndpoint().getEndpointURI()); } // Block until we can queue the next event try { enqueue(event); if (stats.isEnabled()) { stats.incQueuedEvent(); } } catch (Exception e) { FailedToQueueEventException e1 = new FailedToQueueEventException( CoreMessages.interruptedQueuingEventFor(this.getName()), event.getMessage(), this, e); handleException(e1); } if (logger.isTraceEnabled()) { logger.trace("MuleEvent added to queue for: " + name); } }
// @Override public MuleEvent[] process(MuleEvent event) throws MessagingException { String eventComponentName = event.getService().getName(); if (!assignedComponentName.equals(eventComponentName)) { IllegalArgumentException iex = new IllegalArgumentException( "This receiver is assigned to service: " + assignedComponentName + " but has received an event for service: " + eventComponentName + ". Please check your config to make sure each service" + "has its own instance of IdempotentReceiver."); throw new RoutingException(event.getMessage(), event.getEndpoint(), iex); } Object id = this.getIdForEvent(event); try { if (idStore.storeId(id)) { return new MuleEvent[] {event}; } else { return null; } } catch (Exception e) { throw new RoutingException( CoreMessages.failedToWriteMessageToStore(id, assignedComponentName), event.getMessage(), event.getEndpoint(), e); } }
@Override protected MuleEvent aggregateEvents(EventGroup events) throws AggregationException { StringBuilder aggregateResponse = new StringBuilder(); MuleEvent event = null; try { for (Iterator<MuleEvent> iterator = events.iterator(); iterator.hasNext(); ) { event = iterator.next(); try { MuleMessage message = event.getMessage(); System.out.println( "//TODO: HOUSSOU message => " + message + "type => " + message.getClass()); doAggregate(aggregateResponse, message); } catch (Exception e) { throw new AggregationException(events, null, e); } } System.out.println("//TODO: HOUSSOU aggregateResponse => " + aggregateResponse); return new DefaultMuleEvent( new DefaultMuleMessage(aggregateResponse, events.toMessageCollection().getMuleContext()), events.getMessageCollectionEvent()); } catch (ObjectStoreException e) { throw new AggregationException(events, null); } }
protected <T, U> void runFlowWithPayload(String flowName, T expect, U payload) throws Exception { Flow flow = lookupFlowConstruct(flowName); MuleEvent event = AbstractMuleTestCase.getTestEvent(payload); MuleEvent responseEvent = flow.process(event); assertEquals(expect, responseEvent.getMessage().getPayload()); }
public void dispatchEvent(MuleEvent event) throws MuleException { if (stopping.get() || stopped.get()) { throw new ServiceException(CoreMessages.componentIsStopped(name), event.getMessage(), this); } // Dispatching event to an inbound endpoint // in the DefaultMuleSession#dispatchEvent ImmutableEndpoint endpoint = event.getEndpoint(); if (endpoint instanceof OutboundEndpoint) { try { ((OutboundEndpoint) endpoint).dispatch(event); } catch (Exception e) { throw new DispatchException(event.getMessage(), event.getEndpoint(), e); } return; } if (logger.isDebugEnabled()) { logger.debug( "Service: " + name + " has received asynchronous event on: " + event.getEndpoint().getEndpointURI()); } // Dispatching event to the service if (stats.isEnabled()) { stats.incReceivedEventASync(); } doDispatch(event); }
@Override protected final void authenticateInbound(MuleEvent event) throws SecurityException, CryptoFailureException, EncryptionStrategyNotFoundException, UnknownAuthenticationTypeException { String userHeader = (String) getCredentialsAccessor().getCredentials(event); if (userHeader == null) { throw new CredentialsNotSetException(event, event.getSession().getSecurityContext(), this); } Credentials user = new MuleCredentials(userHeader, getSecurityManager()); Authentication authentication; try { authentication = getSecurityManager().authenticate(new DefaultMuleAuthentication(user, event)); } catch (Exception e) { // Authentication failed if (logger.isDebugEnabled()) { logger.debug( "Authentication request for user: "******" failed: " + e.toString()); } throw new UnauthorisedException(CoreMessages.authFailedForUser(user.getUsername()), event, e); } // Authentication success if (logger.isDebugEnabled()) { logger.debug("Authentication success: " + authentication.toString()); } SecurityContext context = getSecurityManager().createSecurityContext(authentication); context.setAuthentication(authentication); event.getSession().setSecurityContext(context); }
@Test public void testDispatchNotification() throws Exception { TestEndpointMessageNotificationListener listener = new TestEndpointMessageNotificationListener(2); muleContext.registerListener(listener); OutboundEndpoint endpoint = createOutboundEndpoint(null, null, null, null, MessageExchangePattern.ONE_WAY, null); MuleEvent outboundEvent = createTestOutboundEvent(); endpoint.process(outboundEvent); assertEventDispatched(); assertTrue(listener.latch.await(RECEIVE_TIMEOUT, TimeUnit.MILLISECONDS)); assertEquals(2, listener.messageNotificationList.size()); assertEquals( EndpointMessageNotification.MESSAGE_DISPATCH_BEGIN, listener.messageNotificationList.get(0).getAction()); assertEquals( EndpointMessageNotification.MESSAGE_DISPATCH_END, listener.messageNotificationList.get(1).getAction()); assertTrue(listener.messageNotificationList.get(0).getSource() instanceof MuleMessage); assertTrue(listener.messageNotificationList.get(1).getSource() instanceof MuleMessage); assertEquals( outboundEvent.getMessage().getPayload(), listener.messageNotificationList.get(0).getSource().getPayload()); assertEquals( outboundEvent.getMessage().getPayload(), listener.messageNotificationList.get(1).getSource().getPayload()); }
// This method is used when the service invoked synchronously. It should really // be used independantly of if the service is invoked synchronously when we are // using an out-only outbound message exchange pattern protected MuleMessage sendToOutboundRouter(MuleEvent event, MuleMessage result) throws MessagingException { if (event.isStopFurtherProcessing()) { logger.debug( "MuleEvent stop further processing has been set, no outbound routing will be performed."); } if (result != null && !event.isStopFurtherProcessing()) { if (getOutboundRouter().hasEndpoints()) { // Here we need to use a copy of the message instance because there // is an inbound response so that transformers executed as part of // the outbound phase do not affect the inbound response. MULE-3307 MuleMessage outboundReturnMessage = getOutboundRouter() .route(new DefaultMuleMessage(result), event.getSession(), event.isSynchronous()); if (outboundReturnMessage != null) { result = outboundReturnMessage; } } else { logger.debug( "Outbound router on service '" + getName() + "' doesn't have any endpoints configured."); } } return result; }
protected void doDispatch(MuleEvent event) throws MuleException { if (logger.isDebugEnabled()) { logger.debug( MessageFormat.format( "Service: {0} has received asynchronous event on: {1}", name, event.getEndpoint().getEndpointURI())); } // Block until we can queue the next event try { if (stats.isEnabled()) { synchronized (queueStatsGuard) { enqueue(event); stats.incQueuedEvent(); } } else { // just enqueue without any hit for synchronization enqueue(event); } } catch (Exception e) { FailedToQueueEventException e1 = new FailedToQueueEventException( CoreMessages.interruptedQueuingEventFor(this.getName()), event.getMessage(), this, e); handleException(e1); } if (logger.isTraceEnabled()) { logger.trace("MuleEvent added to queue for: " + name); } }
@Test public void testDetour_notChainExecution_whenUsingProperty() throws Exception { MuleEvent initialEvent = getTestEvent(ORIGINAL_PAYLOAD_VALUE); MuleEvent resultEvent = runFlow("detourOnProperty", initialEvent); assertThat(resultEvent.getMessage().getPayloadAsString(), is(ORIGINAL_PAYLOAD_VALUE)); }
private Object getUser(MuleEvent event) { Object user = event .getMuleContext() .getExpressionManager() .evaluate(this.getUserExpression(), event.getMessage()); return user; }
/** * Run the flow specified by name and assert equality on the expected output * * @param flowName The name of the flow to run * @param expect The expected output */ protected <T> void runFlowAndExpect(String flowName, T expect) throws Exception { Flow flow = lookupFlowConstruct(flowName); MuleEvent event = AbstractMuleTestCase.getTestEvent(null); MuleEvent responseEvent = flow.process(event); if (expect != null) { assertEquals(expect, responseEvent.getMessage().getPayload()); } }
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; }
@Override public void onNotification(final AsyncMessageNotification notification) { if (notification.getAction() == AsyncMessageNotification.PROCESS_ASYNC_SCHEDULED) { asyncScheduledEvent = (MuleEvent) notification.getSource(); ((DefaultMuleMessage) asyncScheduledEvent.getMessage()) .assertAccess(ThreadSafeAccess.WRITE); } else if (notification.getAction() == AsyncMessageNotification.PROCESS_ASYNC_COMPLETE) { asyncCompleteEvent = (MuleEvent) notification.getSource(); ((DefaultMuleMessage) asyncCompleteEvent.getMessage()).assertAccess(ThreadSafeAccess.WRITE); } latch.countDown(); }
/** * Dispatches an event asynchronously to a endpointUri via a mule server. the Url determines where * to dispathc the event to, this can be in the form of * * @param url the Mule url used to determine the destination and transport of the message * @param payload the object that is the payload of the event * @param messageProperties any properties to be associated with the payload. In the case of Jms * you could set the JMSReplyTo property in these properties. * @throws org.mule.api.MuleException */ public void dispatch(String url, Object payload, Map messageProperties) throws MuleException { MuleMessage message = new DefaultMuleMessage(payload, messageProperties); MuleEvent event = getEvent(message, url, false); try { event.getSession().dispatchEvent(event); } catch (MuleException e) { throw e; } catch (Exception e) { throw new DispatchException( ClientMessages.failedToDispatchClientEvent(), event.getMessage(), event.getEndpoint(), e); } }
@Test public void testSessionScope() throws Exception { MuleEvent e = getTestEvent("testing"); e.getSession().setProperty("SESSION_PROP", "Value1"); RequestContext.setEvent(e); MessagePropertiesContext mpc = new MessagePropertiesContext(); assertEquals("Value1", mpc.getProperty("SESSION_PROP", PropertyScope.SESSION)); // test case insensitivity assertEquals("Value1", mpc.getProperty("SESSION_prop", PropertyScope.SESSION)); assertNull(mpc.getProperty("SESSION_X", PropertyScope.SESSION)); }
protected void doDispatch(MuleEvent event) throws Exception { Object data = event.transformMessage(); if (!(data instanceof Message)) { throw new DispatchException( CoreMessages.transformUnexpectedType(data.getClass(), Message.class), event.getMessage(), event.getEndpoint()); } else { // Check the message for any unset data and use defaults sendMailMessage((Message) data); } }
// This method is used when the service invoked asynchronously. It should really // be used independantly of if the service is invoked asynchronously when we are // using an out-in or out-optional-in outbound message exchange pattern protected void dispatchToOutboundRouter(MuleEvent event, MuleMessage result) throws MessagingException { if (event.isStopFurtherProcessing()) { logger.debug( "MuleEvent stop further processing has been set, no outbound routing will be performed."); } if (result != null && !event.isStopFurtherProcessing()) { if (getOutboundRouter().hasEndpoints()) { // Here we can use the same message instance because there is no inbound response. getOutboundRouter().route(result, event.getSession(), event.isSynchronous()); } } }
@Override public MuleEvent process(MuleEvent event) throws MuleException { HttpRestRequest request = getHttpRestRequest(event); String path = request.getResourcePath(); MuleEvent handled = handleEvent(event, path); if (handled != null) { return handled; } // check for raml descriptor request if (path.equals(getApi().getUri()) && ActionType.GET.toString().equals(request.getMethod().toUpperCase()) && request.getAdapter().getAcceptableResponseMediaTypes().contains(APPLICATION_RAML)) { String raml = config.getApikitRaml(event); event.getMessage().setPayload(raml); event.getMessage().setOutboundProperty(HttpConstants.HEADER_CONTENT_TYPE, APPLICATION_RAML); event.getMessage().setOutboundProperty(HttpConstants.HEADER_CONTENT_LENGTH, raml.length()); event.getMessage().setOutboundProperty("Access-Control-Allow-Origin", "*"); return event; } URIPattern uriPattern; URIResolver uriResolver; path = path.isEmpty() ? "/" : path; try { uriPattern = getUriPatternCache().get(path); uriResolver = getUriResolverCache().get(path); } catch (ExecutionException e) { if (e.getCause() instanceof MuleRestException) { throw (MuleRestException) e.getCause(); } throw new DefaultMuleException(e); } Resource resource = getRoutingTable().get(uriPattern); if (resource.getAction(request.getMethod()) == null) { throw new MethodNotAllowedException(resource.getUri(), request.getMethod()); } ResolvedVariables resolvedVariables = uriResolver.resolve(uriPattern); processUriParameters(resolvedVariables, resource, event); Flow flow = getFlow(resource, request.getMethod()); if (flow == null) { throw new ApikitRuntimeException("Flow not found for resource: " + resource); } return request.process(flow, resource.getAction(request.getMethod())); }
@Override public MuleEvent process(MuleEvent event) throws MuleException { try { String address2Use = expressionManager.parse(addressExpression, event.getMessage()); ClientMessage msg = writeBodyToMessage(event.getMessage().getPayload(), clientSession); if (StringUtils.isNotBlank(event.getMessage().getCorrelationId())) { msg.putStringProperty(JMS_CORRELATION_ID, event.getMessage().getCorrelationId()); } for (Map.Entry<String, String> e : headerExpressions.entrySet()) { Object value2Use = expressionManager.evaluate(e.getValue(), event.getMessage()); msg.putObjectProperty(e.getKey(), value2Use); } for (String prop : event.getMessage().getOutboundPropertyNames()) { msg.putObjectProperty(prop, event.getMessage().getOutboundProperty(prop)); } producer.send(address2Use, msg); Map<String, Object> props = new HashMap<String, Object>(); props.put("hornetq.address", address2Use); event.getMessage().addProperties(props, PropertyScope.INBOUND); return event; } catch (Exception e) { throw new MessagingException(event, e); } }
// @Override public boolean isMatch(MuleEvent event) throws MessagingException { if (idStore == null) { // we need to load this on the first request as we need the service name synchronized (this) { this.initialize(event); } } try { return !idStore.containsId(this.getIdForEvent(event)); } catch (Exception ex) { throw new RoutingException(event.getMessage(), event.getEndpoint(), ex); } }
/** * Sends an object (payload) synchronous to the given url and returns a MuleMessage response back. * * @param url the Mule url used to determine the destination and transport of the message * @param payload the object that is the payload of the event * @param messageProperties any properties to be associated with the payload. In the case of Jms * you could set the JMSReplyTo property in these properties. * @return a umomessage response. * @throws org.mule.api.MuleException */ public MuleMessage send(String url, Object payload, Map messageProperties) throws MuleException { MuleMessage message = new DefaultMuleMessage(payload, messageProperties); MuleEvent event = getEvent(message, url, true); MuleMessage response; try { response = event.getSession().sendEvent(event); } catch (MuleException e) { throw e; } catch (Exception e) { throw new DispatchException( ClientMessages.failedToDispatchClientEvent(), event.getMessage(), event.getEndpoint(), e); } return response; }
@Test public void testDefaultFlowRequestResponse() throws Exception { OutboundEndpoint endpoint = createOutboundEndpoint( null, null, null, null, MessageExchangePattern.REQUEST_RESPONSE, null); testOutboundEvent = createTestOutboundEvent(); MuleEvent result = endpoint.process(testOutboundEvent); assertEventSent(); assertSame(responseMessage, result.getMessage()); assertEqualMessages(responseMessage, result.getMessage()); }
public void testResponseEventsCleanedUp() throws Exception { // relax access to get to the responseEvents RelaxedResponseAggregator aggregator = new RelaxedResponseAggregator(); MuleEvent event = getTestEvent("message1"); final MuleMessage message = event.getMessage(); final String id = message.getUniqueId(); message.setCorrelationId(id); message.setCorrelationGroupSize(1); aggregator.process(event); aggregator.getResponse(message); Map responseEvents = aggregator.getResponseEvents(); assertTrue("Response events should be cleaned up.", responseEvents.isEmpty()); }
@Category({RegressionTests.class}) @Test public void testRemoveObjects() { try { MessageProcessor flow = lookupFlowConstruct("remove-objects"); MuleEvent response = flow.process(getTestEvent(testObjects)); flow = lookupFlowConstruct("find-objects"); response = flow.process(getTestEvent(testObjects)); MongoCollection payload = (MongoCollection) response.getMessage().getPayload(); assertTrue(payload.isEmpty()); } catch (Exception e) { e.printStackTrace(); fail(); } }
@Override public MuleEvent process(MuleEvent event) throws MuleException { MuleMessage message = event.getMessage(); List messageList = (List) message.getPayload(); logger.info("message.getPayload() => {}", messageList); return event; }
@Test public void testTimeoutSetOnEvent() throws Exception { int testTimeout = 999; OutboundEndpoint endpoint = createOutboundEndpoint( null, null, null, null, MessageExchangePattern.REQUEST_RESPONSE, null); testOutboundEvent = createTestOutboundEvent(); testOutboundEvent .getMessage() .setOutboundProperty(MuleProperties.MULE_EVENT_TIMEOUT_PROPERTY, testTimeout); MuleEvent response = endpoint.process(testOutboundEvent); assertEquals(testTimeout, response.getTimeout()); }
private MuleEvent invokeInternal(MuleEvent event) throws MuleException { // Ensure we have event in ThreadLocal OptimizedRequestContext.unsafeSetEvent(event); if (logger.isTraceEnabled()) { logger.trace( String.format( "Invoking %s component for service %s", this.getClass().getName(), flowConstruct.getName())); } if (!lifecycleManager.getState().isStarted() || lifecycleManager.getState().isStopping()) { throw new LifecycleException(CoreMessages.isStopped(flowConstruct.getName()), this); } // Invoke component implementation and gather statistics try { fireComponentNotification( event.getMessage(), ComponentMessageNotification.COMPONENT_PRE_INVOKE); long startTime = 0; if (statistics.isEnabled()) { startTime = System.currentTimeMillis(); } Object result = doInvoke(event); if (statistics.isEnabled()) { statistics.addExecutionTime(System.currentTimeMillis() - startTime); } MuleEvent resultEvent = createResultEvent(event, result); // Components only have access to the original event, so propogate the // stop further processing resultEvent.setStopFurtherProcessing(event.isStopFurtherProcessing()); fireComponentNotification( resultEvent.getMessage(), ComponentMessageNotification.COMPONENT_POST_INVOKE); return resultEvent; } catch (MuleException me) { throw me; } catch (Exception e) { throw new ComponentException(CoreMessages.failedToInvoke(this.toString()), event, this, e); } }
@Test public void testCatchDispatchExceptionSync() throws Exception { OutboundEndpoint endpoint = createTestOutboundEndpoint(null, null); InterceptingMessageProcessor mp = new ExceptionHandlingMessageProcessor(); mp.setListener(new ExceptionThrowingMessageProcessr()); MuleEvent event = createTestOutboundEvent(exceptionListener); MuleEvent resultEvent = mp.process(event); assertNotNull(resultEvent); assertNotNull("exception expected", resultEvent.getMessage().getExceptionPayload()); assertTrue( resultEvent.getMessage().getExceptionPayload().getException() instanceof IllegalStateException); assertEquals(NullPayload.getInstance(), resultEvent.getMessage().getPayload()); assertNotNull(exceptionListener.sensedException); }
protected MessageConsumer createReplyToConsumer( Message currentMessage, MuleEvent event, Session session, Destination replyTo, boolean topic) throws JMSException { String selector = null; // Only used by topics String durableName = null; // If we're not using if (!(replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic)) { String jmsCorrelationId = currentMessage.getJMSCorrelationID(); if (jmsCorrelationId == null) { jmsCorrelationId = currentMessage.getJMSMessageID(); } selector = "JMSCorrelationID='" + jmsCorrelationId + "'"; if (logger.isDebugEnabled()) { logger.debug("ReplyTo Selector is: " + selector); } } // We need to set the durableName and Selector if using topics if (topic) { String tempDurable = (String) event.getEndpoint().getProperties().get(JmsConstants.DURABLE_PROPERTY); boolean durable = connector.isDurable(); if (tempDurable != null) { durable = Boolean.valueOf(tempDurable); } // Get the durable subscriber name if there is one durableName = (String) event.getEndpoint().getProperties().get(JmsConstants.DURABLE_NAME_PROPERTY); if (durableName == null && durable && topic) { durableName = "mule." + connector.getName() + "." + event.getEndpoint().getEndpointURI().getAddress(); if (logger.isDebugEnabled()) { logger.debug( "Jms Connector for this receiver is durable but no durable name has been specified. Defaulting to: " + durableName); } } } return connector .getJmsSupport() .createConsumer(session, replyTo, selector, connector.isNoLocal(), null, topic, endpoint); }