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.spi.annotations.JdkService;
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 */
037@JdkService(TransactedPolicy.class)
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    public void beforeWrap(RouteContext routeContext, NamedNode definition) {
059    }
060
061    public Processor wrap(RouteContext routeContext, Processor processor) {
062        TransactionErrorHandler answer;
063
064        // the goal is to configure the error handler builder on the route as a transacted error handler,
065        // either its already a transacted or if not we replace it with a transacted one that we configure here
066        // and wrap the processor in the transacted error handler as we can have transacted routes that change
067        // propagation behavior, eg: from A required -> B -> requiresNew C (advanced use-case)
068        // if we should not support this we do not need to wrap the processor as we only need one transacted error handler
069
070        // find the existing error handler builder
071        RouteDefinition route = (RouteDefinition) routeContext.getRoute();
072        ErrorHandlerBuilder builder = (ErrorHandlerBuilder) route.getErrorHandlerBuilder();
073
074        // check if its a ref if so then do a lookup
075        if (builder instanceof ErrorHandlerBuilderRef) {
076            // its a reference to a error handler so lookup the reference
077            ErrorHandlerBuilderRef builderRef = (ErrorHandlerBuilderRef) builder;
078            String ref = builderRef.getRef();
079            // only lookup if there was explicit an error handler builder configured
080            // otherwise its just the "default" that has not explicit been configured
081            // and if so then we can safely replace that with our transacted error handler
082            if (ErrorHandlerBuilderRef.isErrorHandlerBuilderConfigured(ref)) {
083                LOG.debug("Looking up ErrorHandlerBuilder with ref: {}", ref);
084                builder = (ErrorHandlerBuilder)ErrorHandlerBuilderRef.lookupErrorHandlerBuilder(routeContext, ref);
085            }
086        }
087
088        if (builder != null && builder.supportTransacted()) {
089            // already a TX error handler then we are good to go
090            LOG.debug("The ErrorHandlerBuilder configured is already a TransactionErrorHandlerBuilder: {}", builder);
091            answer = createTransactionErrorHandler(routeContext, processor, builder);
092            answer.setExceptionPolicy(builder.getExceptionPolicyStrategy());
093            // configure our answer based on the existing error handler
094            builder.configure(routeContext, answer);
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                txBuilder.setErrorHandlers(routeContext, builder.getErrorHandlers(routeContext));
110            }
111            answer = createTransactionErrorHandler(routeContext, processor, txBuilder);
112            answer.setExceptionPolicy(txBuilder.getExceptionPolicyStrategy());
113            // configure our answer based on the existing error handler
114            txBuilder.configure(routeContext, answer);
115
116            // set the route to use our transacted error handler builder
117            route.setErrorHandlerBuilder(txBuilder);
118        }
119
120        // return with wrapped transacted error handler
121        return answer;
122    }
123
124    protected TransactionErrorHandler createTransactionErrorHandler(RouteContext routeContext, Processor processor, ErrorHandlerBuilder builder) {
125        TransactionErrorHandler answer;
126        try {
127            answer = (TransactionErrorHandler) builder.createErrorHandler(routeContext, processor);
128        } catch (Exception e) {
129            throw RuntimeCamelException.wrapRuntimeCamelException(e);
130        }
131        return answer;
132    }
133
134    public TransactionTemplate getTransactionTemplate() {
135        if (template == null) {
136            ObjectHelper.notNull(transactionManager, "transactionManager");
137            template = new TransactionTemplate(transactionManager);
138            if (propagationBehaviorName != null) {
139                template.setPropagationBehaviorName(propagationBehaviorName);
140            }
141        }
142        return template;
143    }
144
145    public void setTransactionTemplate(TransactionTemplate template) {
146        this.template = template;
147    }
148
149    public void setTransactionManager(PlatformTransactionManager transactionManager) {
150        this.transactionManager = transactionManager;
151    }
152
153    public PlatformTransactionManager getTransactionManager() {
154        return transactionManager;
155    }
156
157    public void setPropagationBehaviorName(String propagationBehaviorName) {
158        this.propagationBehaviorName = propagationBehaviorName;
159    }
160
161    public String getPropagationBehaviorName() {
162        return propagationBehaviorName;
163    }
164}