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     */
017    package org.apache.camel;
018    
019    import java.util.List;
020    import java.util.Map;
021    
022    import org.apache.camel.spi.Synchronization;
023    import org.apache.camel.spi.UnitOfWork;
024    
025    /**
026     * An Exchange is the message container holding the information during the entire routing of
027     * a {@link  Message} received by a {@link Consumer}. 
028     * <p/>
029     * During processing down the {@link Processor} chain, the {@link Exchange} provides access to the 
030     * current (not the original) request and response {@link Message} messages. The {@link Exchange} 
031     * also holds meta-data during its entire lifetime stored as properties accessible using the 
032     * various {@link #getProperty(String)} methods. The {@link #setProperty(String, Object)} is 
033     * used to store a property. For example you can use this to store security, SLA related 
034     * data or any other information deemed useful throughout processing. If an {@link Exchange} 
035     * failed during routing the {@link Exception} that caused the failure is stored and accessible 
036     * via the {@link #getException()} method.
037     * <p/>
038     * An Exchange is created when a {@link Consumer} receives a request. A new {@link Message} is
039     * created, the request is set as the body of the {@link Message} and depending on the {@link Consumer}
040     * other {@link Endpoint} and protocol related information is added as headers on the {@link Message}.
041     * Then an Exchange is created and the newly created {@link Message} is set as the in on the Exchange.
042     * Therefore an Exchange starts its life in a {@link Consumer}. The Exchange is then sent down the
043     * {@link Route} for processing along a {@link Processor} chain. The {@link Processor} as the name
044     * suggests is what processes the {@link Message} in the Exchange and Camel, in addition to 
045     * providing out-of-the-box a large number of useful processors, it also allows you to create your own. 
046     * The rule Camel uses is to take the out {@link Message} produced by the previous {@link Processor} 
047     * and set it as the in for the next {@link Processor}. If the previous {@link Processor} did not
048     * produce an out, then the in of the previous {@link Processor} is sent as the next in. At the
049     * end of the processing chain, depending on the {@link ExchangePattern Message Exchange Pattern} (or MEP)
050     * the last out (or in of no out available) is sent by the {@link Consumer} back to the original caller.
051     * <p/>
052     * Camel, in addition to providing out-of-the-box a large number of useful processors, it also allows 
053     * you to implement and use your own. When the Exchange is passed to a {@link Processor}, it always 
054     * contains an in {@link Message} and no out {@link Message}. The {@link Processor} <b>may</b> produce 
055     * an out, depending on the nature of the {@link Processor}. The in {@link Message} can be accessed 
056     * using the {@link #getIn()} method. Since the out message is null when entering the {@link Processor}, 
057     * the {@link #getOut()} method is actually a convenient factory method that will lazily instantiate a 
058     * {@link org.apache.camel.impl.DefaultMessage} which you could populate. As an alternative you could 
059     * also instantiate your specialized  {@link Message} and set it on the exchange using the 
060     * {@link #setOut(org.apache.camel.Message)} method. Please note that a {@link Message} contains not only 
061     * the body but also headers and attachments. If you are creating a new {@link Message} the headers and 
062     * attachments of the in {@link Message} are not automatically copied to the out by Camel and you'll have 
063     * to set the headers and attachments you need yourself. If your {@link Processor} is not producing a 
064     * different {@link Message} but only needs to slightly  modify the in, you can simply update the in 
065     * {@link Message} returned by {@link #getIn()}. 
066     * <p/>
067     * See this <a href="http://camel.apache.org/using-getin-or-getout-methods-on-exchange.html">FAQ entry</a> 
068     * for more details.
069     * 
070     */
071    public interface Exchange {
072    
073        String AUTHENTICATION                   = "CamelAuthentication";
074        String AUTHENTICATION_FAILURE_POLICY_ID = "CamelAuthenticationFailurePolicyId";
075        String ACCEPT_CONTENT_TYPE              = "CamelAcceptContentType";
076        String AGGREGATED_SIZE                  = "CamelAggregatedSize";
077        String AGGREGATED_TIMEOUT               = "CamelAggregatedTimeout";
078        String AGGREGATED_COMPLETED_BY          = "CamelAggregatedCompletedBy";
079        String AGGREGATED_CORRELATION_KEY       = "CamelAggregatedCorrelationKey";
080        String AGGREGATION_STRATEGY             = "CamelAggregationStrategy";
081        String AGGREGATION_COMPLETE_ALL_GROUPS  = "CamelAggregationCompleteAllGroups";
082        String ASYNC_WAIT                       = "CamelAsyncWait";
083    
084        String BATCH_INDEX                = "CamelBatchIndex";
085        String BATCH_SIZE                 = "CamelBatchSize";
086        String BATCH_COMPLETE             = "CamelBatchComplete";
087        String BEAN_METHOD_NAME           = "CamelBeanMethodName";
088        String BEAN_MULTI_PARAMETER_ARRAY = "CamelBeanMultiParameterArray";
089        String BINDING                    = "CamelBinding";
090        // do not prefix with Camel and use lower-case starting letter as its a shared key
091        // used across other Apache products such as AMQ, SMX etc.
092        String BREADCRUMB_ID              = "breadcrumbId";
093    
094        String CHARSET_NAME      = "CamelCharsetName";
095        String CREATED_TIMESTAMP = "CamelCreatedTimestamp";
096        String CONTENT_ENCODING  = "Content-Encoding";
097        String CONTENT_LENGTH    = "Content-Length";
098        String CONTENT_TYPE      = "Content-Type";
099        String CORRELATION_ID    = "CamelCorrelationId";
100    
101        String DATASET_INDEX             = "CamelDataSetIndex";
102        String DEFAULT_CHARSET_PROPERTY  = "org.apache.camel.default.charset";
103        String DESTINATION_OVERRIDE_URL = "CamelDestinationOverrideUrl";
104        String DISABLE_HTTP_STREAM_CACHE = "CamelDisableHttpStreamCache";
105        String DUPLICATE_MESSAGE         = "CamelDuplicateMessage";
106    
107        String EXCEPTION_CAUGHT           = "CamelExceptionCaught";
108        String EVALUATE_EXPRESSION_RESULT = "CamelEvaluateExpressionResult";
109        String ERRORHANDLER_HANDLED       = "CamelErrorHandlerHandled";
110        String EXTERNAL_REDELIVERED       = "CamelExternalRedelivered";
111    
112        String FAILURE_HANDLED      = "CamelFailureHandled";
113        String FAILURE_ENDPOINT     = "CamelFailureEndpoint";
114        String FILTER_NON_XML_CHARS = "CamelFilterNonXmlChars";
115        String FILE_LOCAL_WORK_PATH = "CamelFileLocalWorkPath";
116        String FILE_NAME            = "CamelFileName";
117        String FILE_NAME_ONLY       = "CamelFileNameOnly";
118        String FILE_NAME_PRODUCED   = "CamelFileNameProduced";
119        String FILE_PATH            = "CamelFilePath";
120        String FILE_PARENT          = "CamelFileParent";
121        String FILE_LAST_MODIFIED   = "CamelFileLastModified";
122        String FILTER_MATCHED       = "CamelFilterMatched";
123    
124        String GROUPED_EXCHANGE = "CamelGroupedExchange";
125        
126        String HTTP_BASE_URI           = "CamelHttpBaseUri";
127        String HTTP_CHARACTER_ENCODING = "CamelHttpCharacterEncoding";
128        String HTTP_METHOD             = "CamelHttpMethod";
129        String HTTP_PATH               = "CamelHttpPath";
130        String HTTP_PROTOCOL_VERSION   = "CamelHttpProtocolVersion";
131        String HTTP_QUERY              = "CamelHttpQuery";
132        String HTTP_RESPONSE_CODE      = "CamelHttpResponseCode";
133        String HTTP_URI                = "CamelHttpUri";
134        String HTTP_URL                = "CamelHttpUrl";
135        String HTTP_CHUNKED            = "CamelHttpChunked";
136        String HTTP_SERVLET_REQUEST    = "CamelHttpServletRequest";
137        String HTTP_SERVLET_RESPONSE   = "CamelHttpServletResponse";
138    
139        String INTERCEPTED_ENDPOINT = "CamelInterceptedEndpoint";
140        String INTERCEPT_SEND_TO_ENDPOINT_WHEN_MATCHED = "CamelInterceptSendToEndpointWhenMatched";
141    
142        String LANGUAGE_SCRIPT          = "CamelLanguageScript";
143        String LOG_DEBUG_BODY_MAX_CHARS = "CamelLogDebugBodyMaxChars";
144        String LOG_DEBUG_BODY_STREAMS   = "CamelLogDebugStreams";
145        String LOOP_INDEX               = "CamelLoopIndex";
146        String LOOP_SIZE                = "CamelLoopSize";
147    
148        String MAXIMUM_CACHE_POOL_SIZE     = "CamelMaximumCachePoolSize";
149        String MAXIMUM_ENDPOINT_CACHE_SIZE = "CamelMaximumEndpointCacheSize";
150        String MULTICAST_INDEX             = "CamelMulticastIndex";
151        String MULTICAST_COMPLETE          = "CamelMulticastComplete";
152    
153        String NOTIFY_EVENT = "CamelNotifyEvent";
154    
155        String ON_COMPLETION = "CamelOnCompletion";
156    
157        String PARENT_UNIT_OF_WORK = "CamelParentUnitOfWork";
158    
159        String RECEIVED_TIMESTAMP      = "CamelReceivedTimestamp";
160        String REDELIVERED             = "CamelRedelivered";
161        String REDELIVERY_COUNTER      = "CamelRedeliveryCounter";
162        String REDELIVERY_MAX_COUNTER  = "CamelRedeliveryMaxCounter";
163        String REDELIVERY_EXHAUSTED    = "CamelRedeliveryExhausted";
164        String REDELIVERY_DELAY        = "CamelRedeliveryDelay";
165        String ROLLBACK_ONLY           = "CamelRollbackOnly";
166        String ROLLBACK_ONLY_LAST      = "CamelRollbackOnlyLast";
167        String ROUTE_STOP              = "CamelRouteStop";
168    
169        String SOAP_ACTION        = "CamelSoapAction";
170        String SKIP_GZIP_ENCODING = "CamelSkipGzipEncoding";
171        String SLIP_ENDPOINT      = "CamelSlipEndpoint";
172        String SPLIT_INDEX        = "CamelSplitIndex";
173        String SPLIT_COMPLETE     = "CamelSplitComplete";
174        String SPLIT_SIZE         = "CamelSplitSize";
175    
176        String TIMER_COUNTER         = "CamelTimerCounter";
177        String TIMER_FIRED_TIME      = "CamelTimerFiredTime";
178        String TIMER_NAME            = "CamelTimerName";
179        String TIMER_PERIOD          = "CamelTimerPeriod";
180        String TIMER_TIME            = "CamelTimerTime";
181        String TO_ENDPOINT           = "CamelToEndpoint";
182        String TRACE_EVENT           = "CamelTraceEvent";
183        String TRACE_EVENT_NODE_ID   = "CamelTraceEventNodeId";
184        String TRACE_EVENT_TIMESTAMP = "CamelTraceEventTimestamp";
185        String TRACE_EVENT_EXCHANGE  = "CamelTraceEventExchange";
186        String TRANSFER_ENCODING     = "Transfer-Encoding";
187    
188        String UNIT_OF_WORK_EXHAUSTED    = "CamelUnitOfWorkExhausted";
189        String UNIT_OF_WORK_PROCESS_SYNC = "CamelUnitOfWorkProcessSync";
190    
191        String XSLT_FILE_NAME = "CamelXsltFileName";
192    
193        /**
194         * Returns the {@link ExchangePattern} (MEP) of this exchange.
195         *
196         * @return the message exchange pattern of this exchange
197         */
198        ExchangePattern getPattern();
199    
200        /**
201         * Allows the {@link ExchangePattern} (MEP) of this exchange to be customized.
202         *
203         * This typically won't be required as an exchange can be created with a specific MEP
204         * by calling {@link Endpoint#createExchange(ExchangePattern)} but it is here just in case
205         * it is needed.
206         *
207         * @param pattern  the pattern 
208         */
209        void setPattern(ExchangePattern pattern);
210    
211        /**
212         * Returns a property associated with this exchange by name
213         *
214         * @param name the name of the property
215         * @return the value of the given property or <tt>null</tt> if there is no property for
216         *         the given name
217         */
218        Object getProperty(String name);
219    
220        /**
221         * Returns a property associated with this exchange by name
222         *
223         * @param name the name of the property
224         * @param defaultValue the default value to return if property was absent
225         * @return the value of the given property or <tt>defaultValue</tt> if there is no
226         *         property for the given name
227         */
228        Object getProperty(String name, Object defaultValue);
229    
230        /**
231         * Returns a property associated with this exchange by name and specifying
232         * the type required
233         *
234         * @param name the name of the property
235         * @param type the type of the property
236         * @return the value of the given property or <tt>null</tt> if there is no property for
237         *         the given name or <tt>null</tt> if it cannot be converted to the given type
238         */
239        <T> T getProperty(String name, Class<T> type);
240    
241        /**
242         * Returns a property associated with this exchange by name and specifying
243         * the type required
244         *
245         * @param name the name of the property
246         * @param defaultValue the default value to return if property was absent
247         * @param type the type of the property
248         * @return the value of the given property or <tt>defaultValue</tt> if there is no property for
249         *         the given name or <tt>null</tt> if it cannot be converted to the given type
250         */
251        <T> T getProperty(String name, Object defaultValue, Class<T> type);
252    
253        /**
254         * Sets a property on the exchange
255         *
256         * @param name  of the property
257         * @param value to associate with the name
258         */
259        void setProperty(String name, Object value);
260    
261        /**
262         * Removes the given property on the exchange
263         *
264         * @param name of the property
265         * @return the old value of the property
266         */
267        Object removeProperty(String name);
268    
269        /**
270         * Returns all of the properties associated with the exchange
271         *
272         * @return all the headers in a Map
273         */
274        Map<String, Object> getProperties();
275    
276        /**
277         * Returns whether any properties has been set
278         *
279         * @return <tt>true</tt> if any properties has been set
280         */
281        boolean hasProperties();
282    
283        /**
284         * Returns the inbound request message
285         *
286         * @return the message
287         */
288        Message getIn();
289    
290        /**
291         * Returns the inbound request message as the given type
292         *
293         * @param type the given type
294         * @return the message as the given type or <tt>null</tt> if not possible to covert to given type
295         */
296        <T> T getIn(Class<T> type);
297    
298        /**
299         * Sets the inbound message instance
300         *
301         * @param in the inbound message
302         */
303        void setIn(Message in);
304    
305        /**
306         * Returns the outbound message, lazily creating one if one has not already
307         * been associated with this exchange.
308         * <p/>
309         * <br/><b>Important:</b> If you want to change the current message, then use {@link #getIn()} instead as it will
310         * ensure headers etc. is kept and propagated when routing continues. Bottom line end users should rarely use
311         * this method.
312         * <p/>
313         * <br/>If you want to test whether an OUT message have been set or not, use the {@link #hasOut()} method.
314         * <p/>
315         * See also the class java doc for this {@link Exchange} for more details and this
316         * <a href="http://camel.apache.org/using-getin-or-getout-methods-on-exchange.html">FAQ entry</a>.
317         *
318         * @return the response
319         * @see #getIn()
320         */
321        Message getOut();
322    
323        /**
324         * Returns the outbound request message as the given type
325         * <p/>
326         * <br/><b>Important:</b> If you want to change the current message, then use {@link #getIn()} instead as it will
327         * ensure headers etc. is kept and propagated when routing continues. Bottom line end users should rarely use
328         * this method.
329         * <p/>
330         * <br/>If you want to test whether an OUT message have been set or not, use the {@link #hasOut()} method.
331         * <p/>
332         * See also the class java doc for this {@link Exchange} for more details and this
333         * <a href="http://camel.apache.org/using-getin-or-getout-methods-on-exchange.html">FAQ entry</a>.
334         *
335         * @param type the given type
336         * @return the message as the given type or <tt>null</tt> if not possible to covert to given type
337         * @see #getIn(Class)
338         */
339        <T> T getOut(Class<T> type);
340    
341        /**
342         * Returns whether an OUT message has been set or not.
343         *
344         * @return <tt>true</tt> if an OUT message exists, <tt>false</tt> otherwise.
345         */
346        boolean hasOut();
347    
348        /**
349         * Sets the outbound message
350         *
351         * @param out the outbound message
352         */
353        void setOut(Message out);
354    
355        /**
356         * Returns the exception associated with this exchange
357         *
358         * @return the exception (or null if no faults)
359         */
360        Exception getException();
361    
362        /**
363         * Returns the exception associated with this exchange.
364         * <p/>
365         * Is used to get the caused exception that typically have been wrapped in some sort
366         * of Camel wrapper exception
367         * <p/>
368         * The strategy is to look in the exception hierarchy to find the first given cause that matches the type.
369         * Will start from the bottom (the real cause) and walk upwards.
370         *
371         * @param type the exception type
372         * @return the exception (or <tt>null</tt> if no caused exception matched)
373         */
374        <T> T getException(Class<T> type);
375    
376        /**
377         * Sets the exception associated with this exchange
378         * <p/>
379         * Camel will wrap {@link Throwable} into {@link Exception} type to
380         * accommodate for the {@link #getException()} method returning a plain {@link Exception} type.
381         *
382         * @param t  the caused exception
383         */
384        void setException(Throwable t);
385    
386        /**
387         * Returns true if this exchange failed due to either an exception or fault
388         *
389         * @return true if this exchange failed due to either an exception or fault
390         * @see Exchange#getException()
391         * @see Message#setFault(boolean)
392         * @see Message#isFault()
393         */
394        boolean isFailed();
395    
396        /**
397         * Returns true if this exchange is transacted
398         */
399        boolean isTransacted();
400    
401        /**
402         * Returns true if this exchange is an external initiated redelivered message (such as a JMS broker).
403         * <p/>
404         * <b>Important: </b> It is not always possible to determine if the message is a redelivery
405         * or not, and therefore <tt>null</tt> is returned. Such an example would be a JDBC message.
406         * However JMS brokers provides details if a message is redelivered.
407         *
408         * @return <tt>true</tt> if redelivered, <tt>false</tt> if not, <tt>null</tt> if not able to determine
409         */
410        Boolean isExternalRedelivered();
411    
412        /**
413         * Returns true if this exchange is marked for rollback
414         */
415        boolean isRollbackOnly();
416    
417        /**
418         * Returns the container so that a processor can resolve endpoints from URIs
419         *
420         * @return the container which owns this exchange
421         */
422        CamelContext getContext();
423    
424        /**
425         * Creates a copy of the current message exchange so that it can be
426         * forwarded to another destination
427         */
428        Exchange copy();
429    
430        /**
431         * Returns the endpoint which originated this message exchange if a consumer on an endpoint
432         * created the message exchange, otherwise this property will be <tt>null</tt>
433         */
434        Endpoint getFromEndpoint();
435    
436        /**
437         * Sets the endpoint which originated this message exchange. This method
438         * should typically only be called by {@link org.apache.camel.Endpoint} implementations
439         *
440         * @param fromEndpoint the endpoint which is originating this message exchange
441         */
442        void setFromEndpoint(Endpoint fromEndpoint);
443        
444        /**
445         * Returns the route id which originated this message exchange if a route consumer on an endpoint
446         * created the message exchange, otherwise this property will be <tt>null</tt>
447         */
448        String getFromRouteId();
449    
450        /**
451         * Sets the route id which originated this message exchange. This method
452         * should typically only be called by the internal framework.
453         *
454         * @param fromRouteId the from route id
455         */
456        void setFromRouteId(String fromRouteId);
457    
458        /**
459         * Returns the unit of work that this exchange belongs to; which may map to
460         * zero, one or more physical transactions
461         */
462        UnitOfWork getUnitOfWork();
463    
464        /**
465         * Sets the unit of work that this exchange belongs to; which may map to
466         * zero, one or more physical transactions
467         */
468        void setUnitOfWork(UnitOfWork unitOfWork);
469    
470        /**
471         * Returns the exchange id (unique)
472         */
473        String getExchangeId();
474    
475        /**
476         * Set the exchange id
477         */
478        void setExchangeId(String id);
479    
480        /**
481         * Adds a {@link org.apache.camel.spi.Synchronization} to be invoked as callback when
482         * this exchange is completed.
483         *
484         * @param onCompletion  the callback to invoke on completion of this exchange
485         */
486        void addOnCompletion(Synchronization onCompletion);
487    
488        /**
489         * Checks if the passed {@link org.apache.camel.spi.Synchronization} instance is
490         * already contained on this exchange.
491         *
492         * @param onCompletion  the callback instance that is being checked for
493         * @return <tt>true</tt>, if callback instance is already contained on this exchange, else <tt>false</tt>
494         */
495        boolean containsOnCompletion(Synchronization onCompletion);
496    
497        /**
498         * Handover all the on completions from this exchange to the target exchange.
499         *
500         * @param target the target exchange
501         */
502        void handoverCompletions(Exchange target);
503    
504        /**
505         * Handover all the on completions from this exchange
506         *
507         * @return the on completions
508         */
509        List<Synchronization> handoverCompletions();
510    
511    }