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.spring.spi;
018    
019    import org.apache.camel.Processor;
020    import org.apache.camel.builder.ErrorHandlerBuilder;
021    import org.apache.camel.builder.ErrorHandlerBuilderRef;
022    import org.apache.camel.model.ProcessorDefinition;
023    import org.apache.camel.spi.RouteContext;
024    import org.apache.camel.spi.TransactedPolicy;
025    import org.apache.camel.util.ObjectHelper;
026    import org.slf4j.Logger;
027    import org.slf4j.LoggerFactory;
028    import org.springframework.transaction.PlatformTransactionManager;
029    import org.springframework.transaction.support.TransactionTemplate;
030    
031    /**
032     * Wraps the processor in a Spring transaction
033     *
034     * @version 
035     */
036    public class SpringTransactionPolicy implements TransactedPolicy {
037        private static final transient Logger LOG = LoggerFactory.getLogger(SpringTransactionPolicy.class);
038        private TransactionTemplate template;
039        private String propagationBehaviorName;
040        private PlatformTransactionManager transactionManager;
041    
042        /**
043         * Default constructor for easy spring configuration.
044         */
045        public SpringTransactionPolicy() {
046        }
047    
048        public SpringTransactionPolicy(TransactionTemplate template) {
049            this.template = template;
050        }
051    
052        public SpringTransactionPolicy(PlatformTransactionManager transactionManager) {
053            this.transactionManager = transactionManager;
054        }
055    
056        public void beforeWrap(RouteContext routeContext, ProcessorDefinition<?> definition) {
057        }
058    
059        public Processor wrap(RouteContext routeContext, Processor processor) {
060            TransactionErrorHandler answer;
061    
062            // the goal is to configure the error handler builder on the route as a transacted error handler,
063            // either its already a transacted or if not we replace it with a transacted one that we configure here
064            // and wrap the processor in the transacted error handler as we can have transacted routes that change
065            // propagation behavior, eg: from A required -> B -> requiresNew C (advanced use-case)
066            // if we should not support this we do not need to wrap the processor as we only need one transacted error handler
067    
068            // find the existing error handler builder
069            ErrorHandlerBuilder builder = (ErrorHandlerBuilder)routeContext.getRoute().getErrorHandlerBuilder();
070    
071            // check if its a ref if so then do a lookup
072            if (builder instanceof ErrorHandlerBuilderRef) {
073                // its a reference to a error handler so lookup the reference
074                ErrorHandlerBuilderRef builderRef = (ErrorHandlerBuilderRef) builder;
075                String ref = builderRef.getRef();
076                // only lookup if there was explicit an error handler builder configured
077                // otherwise its just the "default" that has not explicit been configured
078                // and if so then we can safely replace that with our transacted error handler
079                if (ErrorHandlerBuilderRef.isErrorHandlerBuilderConfigured(ref)) {
080                    LOG.debug("Looking up ErrorHandlerBuilder with ref: {}", ref);
081                    builder = (ErrorHandlerBuilder)ErrorHandlerBuilderRef.lookupErrorHandlerBuilder(routeContext, ref);
082                }
083            }
084    
085            if (builder != null && builder.supportTransacted()) {
086                // already a TX error handler then we are good to go
087                LOG.debug("The ErrorHandlerBuilder configured is already a TransactionErrorHandlerBuilder: {}", builder);
088                answer = createTransactionErrorHandler(routeContext, processor, builder);
089                answer.setExceptionPolicy(builder.getExceptionPolicyStrategy());
090                // configure our answer based on the existing error handler
091                builder.configure(routeContext, answer);
092            } else {
093                // no transaction error handler builder configure so create a temporary one as we got all
094                // the needed information form the configured builder anyway this allow us to use transacted
095                // routes anyway even though the error handler is not transactional, eg ease of configuration
096                if (builder != null) {
097                    LOG.debug("The ErrorHandlerBuilder configured is not a TransactionErrorHandlerBuilder: {}", builder);
098                } else {
099                    LOG.debug("No ErrorHandlerBuilder configured, will use default TransactionErrorHandlerBuilder settings");
100                }
101                TransactionErrorHandlerBuilder txBuilder = new TransactionErrorHandlerBuilder();
102                txBuilder.setTransactionTemplate(getTransactionTemplate());
103                txBuilder.setSpringTransactionPolicy(this);
104                if (builder != null) {
105                    // use error handlers from the configured builder
106                    txBuilder.setErrorHandlers(builder.getErrorHandlers());
107                }
108                answer = createTransactionErrorHandler(routeContext, processor, txBuilder);
109                answer.setExceptionPolicy(txBuilder.getExceptionPolicyStrategy());
110                // configure our answer based on the existing error handler
111                txBuilder.configure(routeContext, answer);
112    
113                // set the route to use our transacted error handler builder
114                routeContext.getRoute().setErrorHandlerBuilder(txBuilder);
115            }
116    
117            // return with wrapped transacted error handler
118            return answer;
119        }
120    
121        protected TransactionErrorHandler createTransactionErrorHandler(RouteContext routeContext, Processor processor, ErrorHandlerBuilder builder) {
122            TransactionErrorHandler answer;
123            try {
124                answer = (TransactionErrorHandler) builder.createErrorHandler(routeContext, processor);
125            } catch (Exception e) {
126                throw ObjectHelper.wrapRuntimeCamelException(e);
127            }
128            return answer;
129        }
130    
131        public TransactionTemplate getTransactionTemplate() {
132            if (template == null) {
133                ObjectHelper.notNull(transactionManager, "transactionManager");
134                template = new TransactionTemplate(transactionManager);
135                if (propagationBehaviorName != null) {
136                    template.setPropagationBehaviorName(propagationBehaviorName);
137                }
138            }
139            return template;
140        }
141    
142        public void setTransactionTemplate(TransactionTemplate template) {
143            this.template = template;
144        }
145    
146        public void setTransactionManager(PlatformTransactionManager transactionManager) {
147            this.transactionManager = transactionManager;
148        }
149    
150        public PlatformTransactionManager getTransactionManager() {
151            return transactionManager;
152        }
153    
154        public void setPropagationBehaviorName(String propagationBehaviorName) {
155            this.propagationBehaviorName = propagationBehaviorName;
156        }
157    
158        public String getPropagationBehaviorName() {
159            return propagationBehaviorName;
160        }
161    }