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