001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.processor;
018
019import java.net.URISyntaxException;
020import java.util.HashMap;
021
022import org.apache.camel.AsyncCallback;
023import org.apache.camel.AsyncProcessor;
024import org.apache.camel.AsyncProducerCallback;
025import org.apache.camel.CamelContext;
026import org.apache.camel.Endpoint;
027import org.apache.camel.EndpointAware;
028import org.apache.camel.Exchange;
029import org.apache.camel.ExchangePattern;
030import org.apache.camel.Producer;
031import org.apache.camel.ServicePoolAware;
032import org.apache.camel.Traceable;
033import org.apache.camel.impl.InterceptSendToEndpoint;
034import org.apache.camel.impl.ProducerCache;
035import org.apache.camel.spi.IdAware;
036import org.apache.camel.support.ServiceSupport;
037import org.apache.camel.util.AsyncProcessorConverterHelper;
038import org.apache.camel.util.AsyncProcessorHelper;
039import org.apache.camel.util.EndpointHelper;
040import org.apache.camel.util.EventHelper;
041import org.apache.camel.util.ObjectHelper;
042import org.apache.camel.util.ServiceHelper;
043import org.apache.camel.util.StopWatch;
044import org.apache.camel.util.URISupport;
045import org.slf4j.Logger;
046import org.slf4j.LoggerFactory;
047
048/**
049 * Processor for forwarding exchanges to a static endpoint destination.
050 *
051 * @see SendDynamicProcessor
052 */
053public class SendProcessor extends ServiceSupport implements AsyncProcessor, Traceable, EndpointAware, IdAware {
054    protected static final Logger LOG = LoggerFactory.getLogger(SendProcessor.class);
055    protected transient String traceLabelToString;
056    protected final CamelContext camelContext;
057    protected final ExchangePattern pattern;
058    protected ProducerCache producerCache;
059    protected AsyncProcessor producer;
060    protected Endpoint destination;
061    protected ExchangePattern destinationExchangePattern;
062    protected String id;
063    protected volatile long counter;
064
065    public SendProcessor(Endpoint destination) {
066        this(destination, null);
067    }
068
069    public SendProcessor(Endpoint destination, ExchangePattern pattern) {
070        ObjectHelper.notNull(destination, "destination");
071        this.destination = destination;
072        this.camelContext = destination.getCamelContext();
073        this.pattern = pattern;
074        try {
075            this.destinationExchangePattern = null;
076            this.destinationExchangePattern = EndpointHelper.resolveExchangePatternFromUrl(destination.getEndpointUri());
077        } catch (URISyntaxException e) {
078            throw ObjectHelper.wrapRuntimeCamelException(e);
079        }
080        ObjectHelper.notNull(this.camelContext, "camelContext");
081    }
082
083    @Override
084    public String toString() {
085        return "sendTo(" + destination + (pattern != null ? " " + pattern : "") + ")";
086    }
087
088    public String getId() {
089        return id;
090    }
091
092    public void setId(String id) {
093        this.id = id;
094    }
095
096    /**
097     * @deprecated not longer supported.
098     */
099    @Deprecated
100    public void setDestination(Endpoint destination) {
101    }
102
103    public String getTraceLabel() {
104        if (traceLabelToString == null) {
105            traceLabelToString = URISupport.sanitizeUri(destination.getEndpointUri());
106        }
107        return traceLabelToString;
108    }
109
110    @Override
111    public Endpoint getEndpoint() {
112        return destination;
113    }
114
115    public void process(final Exchange exchange) throws Exception {
116        AsyncProcessorHelper.process(this, exchange);
117    }
118
119    public boolean process(Exchange exchange, final AsyncCallback callback) {
120        if (!isStarted()) {
121            exchange.setException(new IllegalStateException("SendProcessor has not been started: " + this));
122            callback.done(true);
123            return true;
124        }
125
126        // we should preserve existing MEP so remember old MEP
127        // if you want to permanently to change the MEP then use .setExchangePattern in the DSL
128        final ExchangePattern existingPattern = exchange.getPattern();
129
130        counter++;
131
132        // if we have a producer then use that as its optimized
133        if (producer != null) {
134
135            // record timing for sending the exchange using the producer
136            final StopWatch watch = new StopWatch();
137
138            final Exchange target = configureExchange(exchange, pattern);
139
140            EventHelper.notifyExchangeSending(exchange.getContext(), target, destination);
141            LOG.debug(">>>> {} {}", destination, exchange);
142
143            boolean sync = true;
144            try {
145                sync = producer.process(exchange, new AsyncCallback() {
146                    @Override
147                    public void done(boolean doneSync) {
148                        try {
149                            // restore previous MEP
150                            target.setPattern(existingPattern);
151                            // emit event that the exchange was sent to the endpoint
152                            long timeTaken = watch.stop();
153                            EventHelper.notifyExchangeSent(target.getContext(), target, destination, timeTaken);
154                        } finally {
155                            callback.done(doneSync);
156                        }
157                    }
158                });
159            } catch (Throwable throwable) {
160                exchange.setException(throwable);
161                callback.done(sync);
162            }
163
164            return sync;
165        }
166
167        // send the exchange to the destination using the producer cache for the non optimized producers
168        return producerCache.doInAsyncProducer(destination, exchange, pattern, callback, new AsyncProducerCallback() {
169            public boolean doInAsyncProducer(Producer producer, AsyncProcessor asyncProducer, final Exchange exchange,
170                                             ExchangePattern pattern, final AsyncCallback callback) {
171                final Exchange target = configureExchange(exchange, pattern);
172                LOG.debug(">>>> {} {}", destination, exchange);
173                return asyncProducer.process(target, new AsyncCallback() {
174                    public void done(boolean doneSync) {
175                        // restore previous MEP
176                        target.setPattern(existingPattern);
177                        // signal we are done
178                        callback.done(doneSync);
179                    }
180                });
181            }
182        });
183    }
184    
185    public Endpoint getDestination() {
186        return destination;
187    }
188
189    public ExchangePattern getPattern() {
190        return pattern;
191    }
192
193    protected Exchange configureExchange(Exchange exchange, ExchangePattern pattern) {
194        // destination exchange pattern overrides pattern
195        if (destinationExchangePattern != null) {
196            exchange.setPattern(destinationExchangePattern);
197        } else if (pattern != null) {
198            exchange.setPattern(pattern);
199        }
200        // set property which endpoint we send to
201        exchange.setProperty(Exchange.TO_ENDPOINT, destination.getEndpointUri());
202        return exchange;
203    }
204
205    public long getCounter() {
206        return counter;
207    }
208
209    public void reset() {
210        counter = 0;
211    }
212
213    protected void doStart() throws Exception {
214        if (producerCache == null) {
215            // use a single producer cache as we need to only hold reference for one destination
216            // and use a regular HashMap as we do not want a soft reference store that may get re-claimed when low on memory
217            // as we want to ensure the producer is kept around, to ensure its lifecycle is fully managed,
218            // eg stopping the producer when we stop etc.
219            producerCache = new ProducerCache(this, camelContext, new HashMap<String, Producer>(1));
220            // do not add as service as we do not want to manage the producer cache
221        }
222        ServiceHelper.startService(producerCache);
223
224        // the destination could since have been intercepted by a interceptSendToEndpoint so we got to
225        // lookup this before we can use the destination
226        Endpoint lookup = camelContext.hasEndpoint(destination.getEndpointKey());
227        if (lookup instanceof InterceptSendToEndpoint) {
228            if (LOG.isDebugEnabled()) {
229                LOG.debug("Intercepted sending to {} -> {}",
230                        URISupport.sanitizeUri(destination.getEndpointUri()), URISupport.sanitizeUri(lookup.getEndpointUri()));
231            }
232            destination = lookup;
233        }
234        // warm up the producer by starting it so we can fail fast if there was a problem
235        // however must start endpoint first
236        ServiceHelper.startService(destination);
237
238        // this SendProcessor is used a lot in Camel (eg every .to in the route DSL) and therefore we
239        // want to optimize for regular producers, by using the producer directly instead of the ProducerCache
240        // Only for pooled and non singleton producers we have to use the ProducerCache as it supports these
241        // kind of producer better (though these kind of producer should be rare)
242
243        Producer producer = producerCache.acquireProducer(destination);
244        if (producer instanceof ServicePoolAware || !producer.isSingleton()) {
245            // no we cannot optimize it - so release the producer back to the producer cache
246            // and use the producer cache for sending
247            producerCache.releaseProducer(destination, producer);
248        } else {
249            // yes we can optimize and use the producer directly for sending
250            this.producer = AsyncProcessorConverterHelper.convert(producer);
251        }
252    }
253
254    protected void doStop() throws Exception {
255        ServiceHelper.stopServices(producerCache, producer);
256    }
257
258    protected void doShutdown() throws Exception {
259        ServiceHelper.stopAndShutdownServices(producerCache, producer);
260    }
261}