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.RouteDefinition;
026import org.apache.camel.reifier.errorhandler.ErrorHandlerReifier;
027import org.apache.camel.spi.TransactedPolicy;
028import org.apache.camel.util.ObjectHelper;
029import org.slf4j.Logger;
030import org.slf4j.LoggerFactory;
031import org.springframework.transaction.PlatformTransactionManager;
032import org.springframework.transaction.support.TransactionTemplate;
033
034/**
035 * Wraps the processor in a Spring transaction
036 */
037public class SpringTransactionPolicy implements TransactedPolicy {
038    private static final Logger LOG = LoggerFactory.getLogger(SpringTransactionPolicy.class);
039    private TransactionTemplate template;
040    private String propagationBehaviorName;
041    private PlatformTransactionManager transactionManager;
042
043    /**
044     * Default constructor for easy spring configuration.
045     */
046    public SpringTransactionPolicy() {
047    }
048
049    public SpringTransactionPolicy(TransactionTemplate template) {
050        this.template = template;
051    }
052
053    public SpringTransactionPolicy(PlatformTransactionManager transactionManager) {
054        this.transactionManager = transactionManager;
055    }
056
057    @Override
058    public void beforeWrap(Route route, NamedNode definition) {
059    }
060
061    @Override
062    public Processor wrap(Route route, Processor processor) {
063        TransactionErrorHandler answer;
064
065        // the goal is to configure the error handler builder on the route as a transacted error handler,
066        // either its already a transacted or if not we replace it with a transacted one that we configure here
067        // and wrap the processor in the transacted error handler as we can have transacted routes that change
068        // propagation behavior, eg: from A required -> B -> requiresNew C (advanced use-case)
069        // if we should not support this we do not need to wrap the processor as we only need one transacted error handler
070
071        // find the existing error handler builder
072        RouteDefinition routeDefinition = (RouteDefinition) route.getRoute();
073        ErrorHandlerBuilder builder = (ErrorHandlerBuilder) routeDefinition.getErrorHandlerFactory();
074
075        // check if its a ref if so then do a lookup
076        if (builder instanceof ErrorHandlerBuilderRef) {
077            // its a reference to a error handler so lookup the reference
078            ErrorHandlerBuilderRef builderRef = (ErrorHandlerBuilderRef) builder;
079            String ref = builderRef.getRef();
080            // only lookup if there was explicit an error handler builder configured
081            // otherwise its just the "default" that has not explicit been configured
082            // and if so then we can safely replace that with our transacted error handler
083            if (ErrorHandlerReifier.isErrorHandlerFactoryConfigured(ref)) {
084                LOG.debug("Looking up ErrorHandlerBuilder with ref: {}", ref);
085                builder = (ErrorHandlerBuilder) ErrorHandlerReifier.lookupErrorHandlerFactory(route, ref);
086            }
087        }
088
089        if (builder != null && builder.supportTransacted()) {
090            // already a TX error handler then we are good to go
091            LOG.debug("The ErrorHandlerBuilder configured is already a TransactionErrorHandlerBuilder: {}", builder);
092            answer = createTransactionErrorHandler(route, processor, builder);
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                route.addErrorHandlerFactoryReference(builder, txBuilder);
108            }
109            answer = createTransactionErrorHandler(route, processor, txBuilder);
110
111            // set the route to use our transacted error handler builder
112            route.setErrorHandlerFactory(txBuilder);
113        }
114
115        // return with wrapped transacted error handler
116        return answer;
117    }
118
119    protected TransactionErrorHandler createTransactionErrorHandler(Route route, Processor processor, ErrorHandlerBuilder builder) {
120        TransactionErrorHandler answer;
121        try {
122            answer = (TransactionErrorHandler) ErrorHandlerReifier.reifier(route, builder).createErrorHandler(processor);
123        } catch (Exception e) {
124            throw RuntimeCamelException.wrapRuntimeCamelException(e);
125        }
126        return answer;
127    }
128
129    public TransactionTemplate getTransactionTemplate() {
130        if (template == null) {
131            ObjectHelper.notNull(transactionManager, "transactionManager");
132            template = new TransactionTemplate(transactionManager);
133            if (propagationBehaviorName != null) {
134                template.setPropagationBehaviorName(propagationBehaviorName);
135            }
136        }
137        return template;
138    }
139
140    public void setTransactionTemplate(TransactionTemplate template) {
141        this.template = template;
142    }
143
144    public void setTransactionManager(PlatformTransactionManager transactionManager) {
145        this.transactionManager = transactionManager;
146    }
147
148    public PlatformTransactionManager getTransactionManager() {
149        return transactionManager;
150    }
151
152    public void setPropagationBehaviorName(String propagationBehaviorName) {
153        this.propagationBehaviorName = propagationBehaviorName;
154    }
155
156    public String getPropagationBehaviorName() {
157        return propagationBehaviorName;
158    }
159}