1
2
3
4
5
6
7
8
9
10
11 package org.mule.transport.polling;
12
13 import org.mule.DefaultMuleEvent;
14 import org.mule.DefaultMuleMessage;
15 import org.mule.api.MuleEvent;
16 import org.mule.api.MuleMessage;
17 import org.mule.api.construct.FlowConstruct;
18 import org.mule.api.endpoint.ImmutableEndpoint;
19 import org.mule.api.endpoint.InboundEndpoint;
20 import org.mule.api.endpoint.OutboundEndpoint;
21 import org.mule.api.lifecycle.CreateException;
22 import org.mule.api.lifecycle.InitialisationException;
23 import org.mule.api.processor.MessageProcessor;
24 import org.mule.api.transport.Connector;
25 import org.mule.config.i18n.CoreMessages;
26 import org.mule.session.DefaultMuleSession;
27 import org.mule.transport.AbstractConnector;
28 import org.mule.transport.AbstractPollingMessageReceiver;
29 import org.mule.util.StringUtils;
30
31 import java.util.Map;
32
33 public class MessageProcessorPollingMessageReceiver extends AbstractPollingMessageReceiver
34 {
35 public static final String SOURCE_MESSAGE_PROCESSOR_PROPERTY_NAME = "sourceMessageProcessor";
36
37 protected MessageProcessor sourceMessageProcessor;
38
39 public MessageProcessorPollingMessageReceiver(Connector connector,
40 FlowConstruct flowConstruct,
41 InboundEndpoint endpoint) throws CreateException
42 {
43 super(connector, flowConstruct, endpoint);
44 }
45
46 @Override
47 protected void doInitialise() throws InitialisationException
48 {
49 super.doInitialise();
50
51 sourceMessageProcessor = (MessageProcessor) endpoint.getProperty(SOURCE_MESSAGE_PROCESSOR_PROPERTY_NAME);
52
53 if (sourceMessageProcessor instanceof OutboundEndpoint
54 && !((OutboundEndpoint) sourceMessageProcessor).getExchangePattern().hasResponse())
55 {
56
57 throw new InitialisationException(CoreMessages.createStaticMessage(String.format(
58 "The endpoint %s does not return responses and therefore can't be used for polling.",
59 sourceMessageProcessor)), this);
60 }
61
62 Long tempPolling = (Long) endpoint.getProperties().get(AbstractConnector.PROPERTY_POLLING_FREQUENCY);
63 if (tempPolling != null)
64 {
65 setFrequency(tempPolling);
66 }
67 }
68
69 @Override
70 public void poll() throws Exception
71 {
72 MuleMessage request = new DefaultMuleMessage(StringUtils.EMPTY, (Map<String, Object>) null,
73 connector.getMuleContext());
74 ImmutableEndpoint ep = endpoint;
75 if (sourceMessageProcessor instanceof ImmutableEndpoint)
76 {
77 ep = (ImmutableEndpoint) sourceMessageProcessor;
78 }
79
80 MuleEvent event = new DefaultMuleEvent(request, ep, new DefaultMuleSession(flowConstruct,
81 connector.getMuleContext()));
82
83 MuleEvent sourceEvent = sourceMessageProcessor.process(event);
84 if (sourceEvent != null)
85 {
86 routeMessage(sourceEvent.getMessage());
87 }
88 else
89 {
90
91 logger.info(String.format("Polling of '%s' returned null, the flow will not be invoked.",
92 sourceMessageProcessor));
93 }
94 }
95
96 }