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.Route;
022import org.apache.camel.RuntimeCamelException;
023import org.apache.camel.builder.ErrorHandlerBuilder;
024import org.apache.camel.builder.ErrorHandlerBuilderRef;
025import org.apache.camel.model.ModelCamelContext;
026import org.apache.camel.model.RouteDefinition;
027import org.apache.camel.model.errorhandler.ErrorHandlerHelper;
028import org.apache.camel.spi.TransactedPolicy;
029import org.apache.camel.util.ObjectHelper;
030import org.slf4j.Logger;
031import org.slf4j.LoggerFactory;
032import org.springframework.transaction.PlatformTransactionManager;
033import org.springframework.transaction.support.TransactionTemplate;
034
035/**
036 * Wraps the processor in a Spring transaction
037 */
038public class SpringTransactionPolicy implements TransactedPolicy {
039    private static final Logger LOG = LoggerFactory.getLogger(SpringTransactionPolicy.class);
040    private TransactionTemplate template;
041    private String propagationBehaviorName;
042    private PlatformTransactionManager transactionManager;
043
044    /**
045     * Default constructor for easy spring configuration.
046     */
047    public SpringTransactionPolicy() {
048    }
049
050    public SpringTransactionPolicy(TransactionTemplate template) {
051        this.template = template;
052    }
053
054    public SpringTransactionPolicy(PlatformTransactionManager transactionManager) {
055        this.transactionManager = transactionManager;
056    }
057
058    @Override
059    public void beforeWrap(Route route, NamedNode definition) {
060    }
061
062    @Override
063    public Processor wrap(Route route, Processor processor) {
064        TransactionErrorHandler answer;
065
066        // the goal is to configure the error handler builder on the route as a transacted error handler,
067        // either its already a transacted or if not we replace it with a transacted one that we configure here
068        // and wrap the processor in the transacted error handler as we can have transacted routes that change
069        // propagation behavior, eg: from A required -> B -> requiresNew C (advanced use-case)
070        // if we should not support this we do not need to wrap the processor as we only need one transacted error handler
071
072        // find the existing error handler builder
073        RouteDefinition routeDefinition = (RouteDefinition) route.getRoute();
074        ErrorHandlerBuilder builder = (ErrorHandlerBuilder) routeDefinition.getErrorHandlerFactory();
075
076        // check if its a ref if so then do a lookup
077        if (builder instanceof ErrorHandlerBuilderRef) {
078            // its a reference to a error handler so lookup the reference
079            ErrorHandlerBuilderRef builderRef = (ErrorHandlerBuilderRef) builder;
080            String ref = builderRef.getRef();
081            // only lookup if there was explicit an error handler builder configured
082            // otherwise its just the "default" that has not explicit been configured
083            // and if so then we can safely replace that with our transacted error handler
084            if (ErrorHandlerHelper.isErrorHandlerFactoryConfigured(ref)) {
085                LOG.debug("Looking up ErrorHandlerBuilder with ref: {}", ref);
086                builder = (ErrorHandlerBuilder) ErrorHandlerHelper.lookupErrorHandlerFactory(route, ref, true);
087            }
088        }
089
090        if (builder != null && builder.supportTransacted()) {
091            // already a TX error handler then we are good to go
092            LOG.debug("The ErrorHandlerBuilder configured is already a TransactionErrorHandlerBuilder: {}", builder);
093            answer = createTransactionErrorHandler(route, processor, builder);
094        } else {
095            // no transaction error handler builder configure so create a temporary one as we got all
096            // the needed information form the configured builder anyway this allow us to use transacted
097            // routes anyway even though the error handler is not transactional, eg ease of configuration
098            if (builder != null) {
099                LOG.debug("The ErrorHandlerBuilder configured is not a TransactionErrorHandlerBuilder: {}", builder);
100            } else {
101                LOG.debug("No ErrorHandlerBuilder configured, will use default TransactionErrorHandlerBuilder settings");
102            }
103            TransactionErrorHandlerBuilder txBuilder = new TransactionErrorHandlerBuilder();
104            txBuilder.setTransactionTemplate(getTransactionTemplate());
105            txBuilder.setSpringTransactionPolicy(this);
106            if (builder != null) {
107                // use error handlers from the configured builder
108                route.addErrorHandlerFactoryReference(builder, txBuilder);
109            }
110            answer = createTransactionErrorHandler(route, processor, txBuilder);
111
112            // set the route to use our transacted error handler builder
113            route.setErrorHandlerFactory(txBuilder);
114        }
115
116        // return with wrapped transacted error handler
117        return answer;
118    }
119
120    protected TransactionErrorHandler createTransactionErrorHandler(
121            Route route, Processor processor, ErrorHandlerBuilder builder) {
122        TransactionErrorHandler answer;
123        try {
124            ModelCamelContext mcc = route.getCamelContext().adapt(ModelCamelContext.class);
125            answer = (TransactionErrorHandler) mcc.getModelReifierFactory().createErrorHandler(route, builder, 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}