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.model;
018
019import java.lang.reflect.Method;
020import java.util.Map;
021import javax.xml.bind.annotation.XmlAccessType;
022import javax.xml.bind.annotation.XmlAccessorType;
023import javax.xml.bind.annotation.XmlAttribute;
024import javax.xml.bind.annotation.XmlRootElement;
025import javax.xml.bind.annotation.XmlTransient;
026
027import org.apache.camel.NoSuchBeanException;
028import org.apache.camel.Processor;
029import org.apache.camel.RuntimeCamelException;
030import org.apache.camel.Service;
031import org.apache.camel.processor.WrapProcessor;
032import org.apache.camel.spi.Metadata;
033import org.apache.camel.spi.Policy;
034import org.apache.camel.spi.RouteContext;
035import org.apache.camel.spi.TransactedPolicy;
036import org.apache.camel.util.CamelContextHelper;
037import org.apache.camel.util.ObjectHelper;
038import org.slf4j.Logger;
039import org.slf4j.LoggerFactory;
040
041/**
042 * Enables transaction on the route
043 *
044 * @version 
045 */
046@Metadata(label = "configuration")
047@XmlRootElement(name = "transacted")
048@XmlAccessorType(XmlAccessType.FIELD)
049public class TransactedDefinition extends OutputDefinition<TransactedDefinition> {
050
051    // TODO: Align this code with PolicyDefinition
052
053    // JAXB does not support changing the ref attribute from required to optional
054    // if we extend PolicyDefinition so we must make a copy of the class
055    @XmlTransient
056    public static final String PROPAGATION_REQUIRED = "PROPAGATION_REQUIRED";
057
058    private static final Logger LOG = LoggerFactory.getLogger(TransactedDefinition.class);
059
060    @XmlTransient
061    protected Class<? extends Policy> type = TransactedPolicy.class;
062    @XmlAttribute
063    protected String ref;
064    @XmlTransient
065    private Policy policy;
066
067    public TransactedDefinition() {
068    }
069
070    public TransactedDefinition(Policy policy) {
071        this.policy = policy;
072    }
073
074    @Override
075    public String toString() {
076        return "Transacted[" + description() + "]";
077    }
078    
079    protected String description() {
080        if (ref != null) {
081            return "ref:" + ref;
082        } else if (policy != null) {
083            return policy.toString();
084        } else {
085            return "";
086        }
087    }
088
089    @Override
090    public String getLabel() {
091        return "transacted[" + description() + "]";
092    }
093
094    @Override
095    public boolean isAbstract() {
096        return true;
097    }
098
099    @Override
100    public boolean isTopLevelOnly() {
101        // transacted is top level as we only allow have it configured once per route
102        return true;
103    }
104
105    public String getRef() {
106        return ref;
107    }
108
109    public void setRef(String ref) {
110        this.ref = ref;
111    }
112
113    /**
114     * Sets a policy type that this definition should scope within.
115     * <p/>
116     * Is used for convention over configuration situations where the policy
117     * should be automatic looked up in the registry and it should be based
118     * on this type. For instance a {@link org.apache.camel.spi.TransactedPolicy}
119     * can be set as type for easy transaction configuration.
120     * <p/>
121     * Will by default scope to the wide {@link Policy}
122     *
123     * @param type the policy type
124     */
125    public void setType(Class<? extends Policy> type) {
126        this.type = type;
127    }
128
129    /**
130     * Sets a reference to use for lookup the policy in the registry.
131     *
132     * @param ref the reference
133     * @return the builder
134     */
135    public TransactedDefinition ref(String ref) {
136        setRef(ref);
137        return this;
138    }
139
140    @Override
141    public Processor createProcessor(RouteContext routeContext) throws Exception {
142        Policy policy = resolvePolicy(routeContext);
143        ObjectHelper.notNull(policy, "policy", this);
144
145        // before wrap
146        policy.beforeWrap(routeContext, this);
147
148        // create processor after the before wrap
149        Processor childProcessor = this.createChildProcessor(routeContext, true);
150
151        // wrap
152        Processor target = policy.wrap(routeContext, childProcessor);
153
154        if (!(target instanceof Service)) {
155            // wrap the target so it becomes a service and we can manage its lifecycle
156            target = new WrapProcessor(target, childProcessor);
157        }
158        return target;
159    }
160
161    protected Policy resolvePolicy(RouteContext routeContext) {
162        if (policy != null) {
163            return policy;
164        }
165        return doResolvePolicy(routeContext, getRef(), type);
166    }
167
168    protected static Policy doResolvePolicy(RouteContext routeContext, String ref, Class<? extends Policy> type) {
169        // explicit ref given so lookup by it
170        if (ObjectHelper.isNotEmpty(ref)) {
171            return CamelContextHelper.mandatoryLookup(routeContext.getCamelContext(), ref, Policy.class);
172        }
173
174        // no explicit reference given from user so we can use some convention over configuration here
175
176        // try to lookup by scoped type
177        Policy answer = null;
178        if (type != null) {
179            // try find by type, note that this method is not supported by all registry
180            Map<String, ?> types = routeContext.lookupByType(type);
181            if (types.size() == 1) {
182                // only one policy defined so use it
183                Object found = types.values().iterator().next();
184                if (type.isInstance(found)) {
185                    return type.cast(found);
186                }
187            }
188        }
189
190        // for transacted routing try the default REQUIRED name
191        if (type == TransactedPolicy.class) {
192            // still not found try with the default name PROPAGATION_REQUIRED
193            answer = routeContext.lookup(PROPAGATION_REQUIRED, TransactedPolicy.class);
194        }
195
196        // this logic only applies if we are a transacted policy
197        // still no policy found then try lookup the platform transaction manager and use it as policy
198        if (answer == null && type == TransactedPolicy.class) {
199            Class<?> tmClazz = routeContext.getCamelContext().getClassResolver().resolveClass("org.springframework.transaction.PlatformTransactionManager");
200            if (tmClazz != null) {
201                // see if we can find the platform transaction manager in the registry
202                Map<String, ?> maps = routeContext.lookupByType(tmClazz);
203                if (maps.size() == 1) {
204                    // only one platform manager then use it as default and create a transacted
205                    // policy with it and default to required
206
207                    // as we do not want dependency on spring jars in the camel-core we use
208                    // reflection to lookup classes and create new objects and call methods
209                    // as this is only done during route building it does not matter that we
210                    // use reflection as performance is no a concern during route building
211                    Object transactionManager = maps.values().iterator().next();
212                    LOG.debug("One instance of PlatformTransactionManager found in registry: {}", transactionManager);
213                    Class<?> txClazz = routeContext.getCamelContext().getClassResolver().resolveClass("org.apache.camel.spring.spi.SpringTransactionPolicy");
214                    if (txClazz != null) {
215                        LOG.debug("Creating a new temporary SpringTransactionPolicy using the PlatformTransactionManager: {}", transactionManager);
216                        TransactedPolicy txPolicy = ObjectHelper.newInstance(txClazz, TransactedPolicy.class);
217                        Method method;
218                        try {
219                            method = txClazz.getMethod("setTransactionManager", tmClazz);
220                        } catch (NoSuchMethodException e) {
221                            throw new RuntimeCamelException("Cannot get method setTransactionManager(PlatformTransactionManager) on class: " + txClazz);
222                        }
223                        ObjectHelper.invokeMethod(method, txPolicy, transactionManager);
224                        return txPolicy;
225                    } else {
226                        // camel-spring is missing on the classpath
227                        throw new RuntimeCamelException("Cannot create a transacted policy as camel-spring.jar is not on the classpath!");
228                    }
229                } else {
230                    if (maps.isEmpty()) {
231                        throw new NoSuchBeanException(null, "PlatformTransactionManager");
232                    } else {
233                        throw new IllegalArgumentException("Found " + maps.size() + " PlatformTransactionManager in registry. "
234                                + "Cannot determine which one to use. Please configure a TransactionTemplate on the transacted policy.");
235                    }
236                }
237            }
238        }
239
240        return answer;
241    }
242
243}