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        String desc = description();
077        if (ObjectHelper.isEmpty(desc)) {
078            return "Transacted";
079        } else {
080            return "Transacted[" + desc + "]";
081        }
082    }
083    
084    protected String description() {
085        if (ref != null) {
086            return "ref:" + ref;
087        } else if (policy != null) {
088            return policy.toString();
089        } else {
090            return "";
091        }
092    }
093
094    @Override
095    public String getLabel() {
096        String desc = description();
097        if (ObjectHelper.isEmpty(desc)) {
098            return "transacted";
099        } else {
100            return "transacted[" + desc + "]";
101        }
102    }
103
104    @Override
105    public boolean isAbstract() {
106        return true;
107    }
108
109    @Override
110    public boolean isTopLevelOnly() {
111        // transacted is top level as we only allow have it configured once per route
112        return true;
113    }
114
115    public String getRef() {
116        return ref;
117    }
118
119    public void setRef(String ref) {
120        this.ref = ref;
121    }
122
123    /**
124     * Sets a policy type that this definition should scope within.
125     * <p/>
126     * Is used for convention over configuration situations where the policy
127     * should be automatic looked up in the registry and it should be based
128     * on this type. For instance a {@link org.apache.camel.spi.TransactedPolicy}
129     * can be set as type for easy transaction configuration.
130     * <p/>
131     * Will by default scope to the wide {@link Policy}
132     *
133     * @param type the policy type
134     */
135    public void setType(Class<? extends Policy> type) {
136        this.type = type;
137    }
138
139    /**
140     * Sets a reference to use for lookup the policy in the registry.
141     *
142     * @param ref the reference
143     * @return the builder
144     */
145    public TransactedDefinition ref(String ref) {
146        setRef(ref);
147        return this;
148    }
149
150    @Override
151    public Processor createProcessor(RouteContext routeContext) throws Exception {
152        Policy policy = resolvePolicy(routeContext);
153        ObjectHelper.notNull(policy, "policy", this);
154
155        // before wrap
156        policy.beforeWrap(routeContext, this);
157
158        // create processor after the before wrap
159        Processor childProcessor = this.createChildProcessor(routeContext, true);
160
161        // wrap
162        Processor target = policy.wrap(routeContext, childProcessor);
163
164        if (!(target instanceof Service)) {
165            // wrap the target so it becomes a service and we can manage its lifecycle
166            target = new WrapProcessor(target, childProcessor);
167        }
168        return target;
169    }
170
171    protected Policy resolvePolicy(RouteContext routeContext) {
172        if (policy != null) {
173            return policy;
174        }
175        return doResolvePolicy(routeContext, getRef(), type);
176    }
177
178    protected static Policy doResolvePolicy(RouteContext routeContext, String ref, Class<? extends Policy> type) {
179        // explicit ref given so lookup by it
180        if (ObjectHelper.isNotEmpty(ref)) {
181            return CamelContextHelper.mandatoryLookup(routeContext.getCamelContext(), ref, Policy.class);
182        }
183
184        // no explicit reference given from user so we can use some convention over configuration here
185
186        // try to lookup by scoped type
187        Policy answer = null;
188        if (type != null) {
189            // try find by type, note that this method is not supported by all registry
190            Map<String, ?> types = routeContext.lookupByType(type);
191            if (types.size() == 1) {
192                // only one policy defined so use it
193                Object found = types.values().iterator().next();
194                if (type.isInstance(found)) {
195                    return type.cast(found);
196                }
197            }
198        }
199
200        // for transacted routing try the default REQUIRED name
201        if (type == TransactedPolicy.class) {
202            // still not found try with the default name PROPAGATION_REQUIRED
203            answer = routeContext.lookup(PROPAGATION_REQUIRED, TransactedPolicy.class);
204        }
205
206        // this logic only applies if we are a transacted policy
207        // still no policy found then try lookup the platform transaction manager and use it as policy
208        if (answer == null && type == TransactedPolicy.class) {
209            Class<?> tmClazz = routeContext.getCamelContext().getClassResolver().resolveClass("org.springframework.transaction.PlatformTransactionManager");
210            if (tmClazz != null) {
211                // see if we can find the platform transaction manager in the registry
212                Map<String, ?> maps = routeContext.lookupByType(tmClazz);
213                if (maps.size() == 1) {
214                    // only one platform manager then use it as default and create a transacted
215                    // policy with it and default to required
216
217                    // as we do not want dependency on spring jars in the camel-core we use
218                    // reflection to lookup classes and create new objects and call methods
219                    // as this is only done during route building it does not matter that we
220                    // use reflection as performance is no a concern during route building
221                    Object transactionManager = maps.values().iterator().next();
222                    LOG.debug("One instance of PlatformTransactionManager found in registry: {}", transactionManager);
223                    Class<?> txClazz = routeContext.getCamelContext().getClassResolver().resolveClass("org.apache.camel.spring.spi.SpringTransactionPolicy");
224                    if (txClazz != null) {
225                        LOG.debug("Creating a new temporary SpringTransactionPolicy using the PlatformTransactionManager: {}", transactionManager);
226                        TransactedPolicy txPolicy = ObjectHelper.newInstance(txClazz, TransactedPolicy.class);
227                        Method method;
228                        try {
229                            method = txClazz.getMethod("setTransactionManager", tmClazz);
230                        } catch (NoSuchMethodException e) {
231                            throw new RuntimeCamelException("Cannot get method setTransactionManager(PlatformTransactionManager) on class: " + txClazz);
232                        }
233                        ObjectHelper.invokeMethod(method, txPolicy, transactionManager);
234                        return txPolicy;
235                    } else {
236                        // camel-spring is missing on the classpath
237                        throw new RuntimeCamelException("Cannot create a transacted policy as camel-spring.jar is not on the classpath!");
238                    }
239                } else {
240                    if (maps.isEmpty()) {
241                        throw new NoSuchBeanException(null, "PlatformTransactionManager");
242                    } else {
243                        throw new IllegalArgumentException("Found " + maps.size() + " PlatformTransactionManager in registry. "
244                                + "Cannot determine which one to use. Please configure a TransactionTemplate on the transacted policy.");
245                    }
246                }
247            }
248        }
249
250        return answer;
251    }
252
253}