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