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.component.seda;
018
019import java.util.concurrent.BlockingQueue;
020import java.util.concurrent.CountDownLatch;
021import java.util.concurrent.TimeUnit;
022
023import org.apache.camel.AsyncCallback;
024import org.apache.camel.Exchange;
025import org.apache.camel.ExchangeTimedOutException;
026import org.apache.camel.WaitForTaskToComplete;
027import org.apache.camel.impl.DefaultAsyncProducer;
028import org.apache.camel.support.SynchronizationAdapter;
029import org.apache.camel.util.ExchangeHelper;
030
031/**
032 * @version 
033 */
034public class SedaProducer extends DefaultAsyncProducer {
035    
036    /**
037     * @deprecated Better make use of the {@link SedaEndpoint#getQueue()} API which delivers the accurate reference to the queue currently being used.
038     */
039    @Deprecated
040    protected final BlockingQueue<Exchange> queue;
041    private final SedaEndpoint endpoint;
042    private final WaitForTaskToComplete waitForTaskToComplete;
043    private final long timeout;
044    private final boolean blockWhenFull;
045
046    /**
047     * @deprecated Use {@link #SedaProducer(SedaEndpoint, WaitForTaskToComplete, long, boolean) the other constructor}.
048     */
049    @Deprecated
050    public SedaProducer(SedaEndpoint endpoint, BlockingQueue<Exchange> queue, WaitForTaskToComplete waitForTaskToComplete, long timeout) {
051        this(endpoint, waitForTaskToComplete, timeout, false);
052    }
053
054    /**
055     * @deprecated Use {@link #SedaProducer(SedaEndpoint, WaitForTaskToComplete, long, boolean) the other constructor}.
056     */
057    @Deprecated
058    public SedaProducer(SedaEndpoint endpoint, BlockingQueue<Exchange> queue, WaitForTaskToComplete waitForTaskToComplete, long timeout, boolean blockWhenFull) {
059        this(endpoint, waitForTaskToComplete, timeout, blockWhenFull);
060    }
061
062    public SedaProducer(SedaEndpoint endpoint, WaitForTaskToComplete waitForTaskToComplete, long timeout, boolean blockWhenFull) {
063        super(endpoint);
064        this.queue = endpoint.getQueue();
065        this.endpoint = endpoint;
066        this.waitForTaskToComplete = waitForTaskToComplete;
067        this.timeout = timeout;
068        this.blockWhenFull = blockWhenFull;
069    }
070
071    @Override
072    public boolean process(final Exchange exchange, final AsyncCallback callback) {
073        WaitForTaskToComplete wait = waitForTaskToComplete;
074        if (exchange.getProperty(Exchange.ASYNC_WAIT) != null) {
075            wait = exchange.getProperty(Exchange.ASYNC_WAIT, WaitForTaskToComplete.class);
076        }
077
078        if (wait == WaitForTaskToComplete.Always
079            || (wait == WaitForTaskToComplete.IfReplyExpected && ExchangeHelper.isOutCapable(exchange))) {
080
081            // do not handover the completion as we wait for the copy to complete, and copy its result back when it done
082            Exchange copy = prepareCopy(exchange, false);
083
084            // latch that waits until we are complete
085            final CountDownLatch latch = new CountDownLatch(1);
086
087            // we should wait for the reply so install a on completion so we know when its complete
088            copy.addOnCompletion(new SynchronizationAdapter() {
089                @Override
090                public void onDone(Exchange response) {
091                    // check for timeout, which then already would have invoked the latch
092                    if (latch.getCount() == 0) {
093                        if (log.isTraceEnabled()) {
094                            log.trace("{}. Timeout occurred so response will be ignored: {}", this, response.hasOut() ? response.getOut() : response.getIn());
095                        }
096                        return;
097                    } else {
098                        if (log.isTraceEnabled()) {
099                            log.trace("{} with response: {}", this, response.hasOut() ? response.getOut() : response.getIn());
100                        }
101                        try {
102                            ExchangeHelper.copyResults(exchange, response);
103                        } finally {
104                            // always ensure latch is triggered
105                            latch.countDown();
106                        }
107                    }
108                }
109
110                @Override
111                public boolean allowHandover() {
112                    // do not allow handover as we want to seda producer to have its completion triggered
113                    // at this point in the routing (at this leg), instead of at the very last (this ensure timeout is honored)
114                    return false;
115                }
116
117                @Override
118                public String toString() {
119                    return "onDone at endpoint: " + endpoint;
120                }
121            });
122
123            log.trace("Adding Exchange to queue: {}", copy);
124            try {
125                addToQueue(copy);
126            } catch (SedaConsumerNotAvailableException e) {
127                exchange.setException(e);
128                callback.done(true);
129                return true;
130            }
131
132            if (timeout > 0) {
133                if (log.isTraceEnabled()) {
134                    log.trace("Waiting for task to complete using timeout (ms): {} at [{}]", timeout, endpoint.getEndpointUri());
135                }
136                // lets see if we can get the task done before the timeout
137                boolean done = false;
138                try {
139                    done = latch.await(timeout, TimeUnit.MILLISECONDS);
140                } catch (InterruptedException e) {
141                    // ignore
142                }
143                if (!done) {
144                    exchange.setException(new ExchangeTimedOutException(exchange, timeout));
145                    // remove timed out Exchange from queue
146                    endpoint.getQueue().remove(copy);
147                    // count down to indicate timeout
148                    latch.countDown();
149                }
150            } else {
151                if (log.isTraceEnabled()) {
152                    log.trace("Waiting for task to complete (blocking) at [{}]", endpoint.getEndpointUri());
153                }
154                // no timeout then wait until its done
155                try {
156                    latch.await();
157                } catch (InterruptedException e) {
158                    // ignore
159                }
160            }
161        } else {
162            // no wait, eg its a InOnly then just add to queue and return
163            // handover the completion so its the copy which performs that, as we do not wait
164            Exchange copy = prepareCopy(exchange, true);
165            log.trace("Adding Exchange to queue: {}", copy);
166            try {
167                addToQueue(copy);
168            } catch (SedaConsumerNotAvailableException e) {
169                exchange.setException(e);
170                callback.done(true);
171                return true;
172            }
173        }
174
175        // we use OnCompletion on the Exchange to callback and wait for the Exchange to be done
176        // so we should just signal the callback we are done synchronously
177        callback.done(true);
178        return true;
179    }
180
181    protected Exchange prepareCopy(Exchange exchange, boolean handover) {
182        // use a new copy of the exchange to route async (and use same message id)
183        Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, handover, true);
184        // set a new from endpoint to be the seda queue
185        copy.setFromEndpoint(endpoint);
186        return copy;
187    }
188
189    @Override
190    protected void doStart() throws Exception {
191        super.doStart();
192        endpoint.onStarted(this);
193    }
194
195    @Override
196    protected void doStop() throws Exception {
197        endpoint.onStopped(this);
198        super.doStop();
199    }
200
201    /**
202     * Strategy method for adding the exchange to the queue.
203     * <p>
204     * Will perform a blocking "put" if blockWhenFull is true, otherwise it will
205     * simply add which will throw exception if the queue is full
206     * 
207     * @param exchange the exchange to add to the queue
208     */
209    protected void addToQueue(Exchange exchange) throws SedaConsumerNotAvailableException {
210        BlockingQueue<Exchange> queue = null;
211        QueueReference queueReference = endpoint.getQueueReference();
212        if (queueReference != null) {
213            queue = queueReference.getQueue();
214        }
215        if (queue == null) {
216            throw new SedaConsumerNotAvailableException("No queue available on endpoint: " + endpoint, exchange);
217        }
218
219        if (endpoint.isFailIfNoConsumers() && !queueReference.hasConsumers()) {
220            throw new SedaConsumerNotAvailableException("No consumers available on endpoint: " + endpoint, exchange);
221        }
222        if (blockWhenFull) {
223            try {
224                queue.put(exchange);
225            } catch (InterruptedException e) {
226                // ignore
227                log.debug("Put interrupted, are we stopping? {}", isStopping() || isStopped());
228            }
229        } else {
230            queue.add(exchange);
231        }
232    }
233
234}