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