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 */
017 package org.apache.camel.spring.spi;
018
019 import org.apache.camel.AsyncCallback;
020 import org.apache.camel.CamelContext;
021 import org.apache.camel.Exchange;
022 import org.apache.camel.Predicate;
023 import org.apache.camel.Processor;
024 import org.apache.camel.processor.Logger;
025 import org.apache.camel.processor.RedeliveryErrorHandler;
026 import org.apache.camel.processor.RedeliveryPolicy;
027 import org.apache.camel.processor.exceptionpolicy.ExceptionPolicyStrategy;
028 import org.apache.camel.util.ObjectHelper;
029 import org.springframework.transaction.TransactionDefinition;
030 import org.springframework.transaction.TransactionStatus;
031 import org.springframework.transaction.support.TransactionCallbackWithoutResult;
032 import org.springframework.transaction.support.TransactionTemplate;
033
034 /**
035 * The <a href="http://camel.apache.org/transactional-client.html">Transactional Client</a>
036 * EIP pattern.
037 *
038 * @version $Revision: 959519 $
039 */
040 public class TransactionErrorHandler extends RedeliveryErrorHandler {
041
042 private final TransactionTemplate transactionTemplate;
043
044 /**
045 * Creates the transaction error handler.
046 *
047 * @param camelContext the camel context
048 * @param output outer processor that should use this default error handler
049 * @param logger logger to use for logging failures and redelivery attempts
050 * @param redeliveryProcessor an optional processor to run before redelivery attempt
051 * @param redeliveryPolicy policy for redelivery
052 * @param handledPolicy policy for handling failed exception that are moved to the dead letter queue
053 * @param exceptionPolicyStrategy strategy for onException handling
054 * @param transactionTemplate the transaction template
055 */
056 public TransactionErrorHandler(CamelContext camelContext, Processor output, Logger logger, Processor redeliveryProcessor,
057 RedeliveryPolicy redeliveryPolicy, Predicate handledPolicy,
058 ExceptionPolicyStrategy exceptionPolicyStrategy, TransactionTemplate transactionTemplate) {
059 super(camelContext, output, logger, redeliveryProcessor, redeliveryPolicy, handledPolicy, null, null, false);
060 setExceptionPolicy(exceptionPolicyStrategy);
061 this.transactionTemplate = transactionTemplate;
062 }
063
064 public boolean supportTransacted() {
065 return true;
066 }
067
068 @Override
069 public String toString() {
070 if (output == null) {
071 // if no output then don't do any description
072 return "";
073 }
074 return "TransactionErrorHandler:"
075 + propagationBehaviorToString(transactionTemplate.getPropagationBehavior())
076 + "[" + getOutput() + "]";
077 }
078
079 @Override
080 public void process(Exchange exchange) throws Exception {
081 // we have to run this synchronously as Spring Transaction does *not* support
082 // using multiple threads to span a transaction
083 if (exchange.getUnitOfWork().isTransactedBy(transactionTemplate)) {
084 // already transacted by this transaction template
085 // so lets just let the error handler process it
086 processByErrorHandler(exchange);
087 } else {
088 // not yet wrapped in transaction so lets do that
089 // and then have it invoke the error handler from within that transaction
090 processInTransaction(exchange);
091 }
092 }
093
094 @Override
095 public boolean process(Exchange exchange, AsyncCallback callback) {
096 // invoke ths synchronous method as Spring Transaction does *not* support
097 // using multiple threads to span a transaction
098 try {
099 process(exchange);
100 } catch (Throwable e) {
101 exchange.setException(e);
102 }
103
104 // notify callback we are done synchronously
105 callback.done(true);
106 return true;
107 }
108
109 protected void processInTransaction(final Exchange exchange) throws Exception {
110 String id = ObjectHelper.getIdentityHashCode(transactionTemplate);
111 try {
112 // mark the beginning of this transaction boundary
113 exchange.getUnitOfWork().beginTransactedBy(transactionTemplate);
114
115 if (log.isDebugEnabled()) {
116 log.debug("Transaction begin (" + id + ") for ExchangeId: " + exchange.getExchangeId());
117 }
118
119 doInTransactionTemplate(exchange);
120
121 if (log.isDebugEnabled()) {
122 log.debug("Transaction commit (" + id + ") for ExchangeId: " + exchange.getExchangeId());
123 }
124 } catch (TransactionRollbackException e) {
125 // ignore as its just a dummy exception to force spring TX to rollback
126 if (log.isDebugEnabled()) {
127 log.debug("Transaction rollback (" + id + ") for ExchangeId: " + exchange.getExchangeId());
128 }
129 } catch (Exception e) {
130 log.warn("Transaction rollback (" + id + ") for ExchangeId: " + exchange.getExchangeId() + " due exception: " + e.getMessage());
131 exchange.setException(e);
132 } finally {
133 // mark the end of this transaction boundary
134 exchange.getUnitOfWork().endTransactedBy(transactionTemplate);
135 }
136 }
137
138
139 protected void doInTransactionTemplate(final Exchange exchange) {
140
141 // spring transaction template is working best with rollback if you throw it a runtime exception
142 // otherwise it may not rollback messages send to JMS queues etc.
143
144 transactionTemplate.execute(new TransactionCallbackWithoutResult() {
145 protected void doInTransactionWithoutResult(TransactionStatus status) {
146 // wrapper exception to throw if the exchange failed
147 // IMPORTANT: Must be a runtime exception to let Spring regard it as to do "rollback"
148 RuntimeException rce = null;
149
150 // and now let process the exchange by the error handler
151 processByErrorHandler(exchange);
152
153 // after handling and still an exception or marked as rollback only then rollback
154 if (exchange.getException() != null || exchange.isRollbackOnly()) {
155
156 // if it was a local rollback only then remove its marker so outer transaction
157 // wont rollback as well (Note: isRollbackOnly() also returns true for ROLLBACK_ONLY_LAST)
158 exchange.removeProperty(Exchange.ROLLBACK_ONLY_LAST);
159
160 // wrap exception in transacted exception
161 if (exchange.getException() != null) {
162 rce = ObjectHelper.wrapRuntimeCamelException(exchange.getException());
163 } else if (exchange.isRollbackOnly()) {
164 // create dummy exception to force spring transaction manager to rollback
165 rce = new TransactionRollbackException();
166 }
167
168 if (!status.isRollbackOnly()) {
169 status.setRollbackOnly();
170 }
171
172 // rethrow if an exception occurred
173 if (rce != null) {
174 throw rce;
175 }
176 }
177 }
178 });
179 }
180
181 /**
182 * Processes the {@link Exchange} using the error handler.
183 * <p/>
184 * This implementation will invoke ensure this occurs synchronously, that means if the async routing engine
185 * did kick in, then this implementation will wait for the task to complete before it continues.
186 *
187 * @param exchange the exchange
188 */
189 protected void processByErrorHandler(final Exchange exchange) {
190 // must invoke the async method with empty callback to have it invoke the
191 // super.processErrorHandler
192 // we are transacted so we have to route synchronously so don't worry about returned
193 // value from the process method
194 // and the camel routing engine will detect this is an transacted Exchange and route
195 // it fully synchronously so we don't have to wait here if we hit an async endpoint
196 // all that is taken care of in the camel-core
197 super.process(exchange, new AsyncCallback() {
198 public void done(boolean doneSync) {
199 // noop
200 }
201 });
202 }
203
204 private static String propagationBehaviorToString(int propagationBehavior) {
205 String rc;
206 switch (propagationBehavior) {
207 case TransactionDefinition.PROPAGATION_MANDATORY:
208 rc = "PROPAGATION_MANDATORY";
209 break;
210 case TransactionDefinition.PROPAGATION_NESTED:
211 rc = "PROPAGATION_NESTED";
212 break;
213 case TransactionDefinition.PROPAGATION_NEVER:
214 rc = "PROPAGATION_NEVER";
215 break;
216 case TransactionDefinition.PROPAGATION_NOT_SUPPORTED:
217 rc = "PROPAGATION_NOT_SUPPORTED";
218 break;
219 case TransactionDefinition.PROPAGATION_REQUIRED:
220 rc = "PROPAGATION_REQUIRED";
221 break;
222 case TransactionDefinition.PROPAGATION_REQUIRES_NEW:
223 rc = "PROPAGATION_REQUIRES_NEW";
224 break;
225 case TransactionDefinition.PROPAGATION_SUPPORTS:
226 rc = "PROPAGATION_SUPPORTS";
227 break;
228 default:
229 rc = "UNKNOWN";
230 }
231 return rc;
232 }
233
234 }