Author: davsclaus
Date: Wed Apr 18 11:23:54 2012
New Revision: 1327447
URL: http://svn.apache.org/viewvc?rev=1327447&view=rev
Log:
CAMEL-5178: File consumer should use exception handler to handle all component
specific exceptions. Add example how to plugin a custom exception handler and
send that to a Camel route so Camel routing onException can deal with the
exception. Reduce the out of the box logging exception handler to WARN level.
Added:
camel/trunk/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerCustomExceptionHandlerTest.java
Modified:
camel/trunk/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConsumer.java
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/LoggingExceptionHandler.java
Modified:
camel/trunk/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConsumer.java
URL:
http://svn.apache.org/viewvc/camel/trunk/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConsumer.java?rev=1327447&r1=1327446&r2=1327447&view=diff
==============================================================================
---
camel/trunk/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConsumer.java
(original)
+++
camel/trunk/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConsumer.java
Wed Apr 18 11:23:54 2012
@@ -260,10 +260,11 @@ public abstract class GenericFileConsume
return;
}
} catch (Exception e) {
- if (log.isDebugEnabled()) {
- log.debug(endpoint + " cannot begin processing file: " + file
+ " due to: " + e.getMessage(), e);
- }
+ // remove file from the in progress list due to failure
endpoint.getInProgressRepository().remove(absoluteFileName);
+
+ String msg = endpoint + " cannot begin processing file: " + file +
" due to: " + e.getMessage();
+ handleException(msg, e);
return;
}
@@ -311,7 +312,9 @@ public abstract class GenericFileConsume
// from in progress when it takes over and processes the file,
which may happen
// by another thread at a later time. So its only safe to remove
it if there was an exception)
endpoint.getInProgressRepository().remove(absoluteFileName);
- handleException(e);
+
+ String msg = "Error processing file " + file + " due to " +
e.getMessage();
+ handleException(msg, e);
}
}
@@ -336,6 +339,7 @@ public abstract class GenericFileConsume
if (log.isDebugEnabled()) {
log.debug(endpoint + " error custom processing: " + file + "
due to: " + e.getMessage() + ". This exception will be ignored.", e);
}
+ handleException(e);
} finally {
// always remove file from the in progress list as its no longer
in progress
// use the original file name that was used to add it to the
repository
Modified:
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java
URL:
http://svn.apache.org/viewvc/camel/trunk/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java?rev=1327447&r1=1327446&r2=1327447&view=diff
==============================================================================
---
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java
(original)
+++
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java
Wed Apr 18 11:23:54 2012
@@ -100,4 +100,15 @@ public class DefaultConsumer extends Ser
Throwable newt = (t == null) ? new IllegalArgumentException("Handling
[null] exception") : t;
getExceptionHandler().handleException(newt);
}
+
+ /**
+ * Handles the given exception using the {@link #getExceptionHandler()}
+ *
+ * @param message additional message about the exception
+ * @param t the exception to handle
+ */
+ protected void handleException(String message, Throwable t) {
+ Throwable newt = (t == null) ? new IllegalArgumentException("Handling
[null] exception") : t;
+ getExceptionHandler().handleException(message, newt);
+ }
}
Modified:
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/LoggingExceptionHandler.java
URL:
http://svn.apache.org/viewvc/camel/trunk/camel-core/src/main/java/org/apache/camel/impl/LoggingExceptionHandler.java?rev=1327447&r1=1327446&r2=1327447&view=diff
==============================================================================
---
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/LoggingExceptionHandler.java
(original)
+++
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/LoggingExceptionHandler.java
Wed Apr 18 11:23:54 2012
@@ -28,7 +28,7 @@ import org.slf4j.LoggerFactory;
* A default implementation of {@link ExceptionHandler} which uses a {@link
org.apache.camel.processor.CamelLogger} to
* log the exception.
* <p/>
- * This implementation will by default log the exception with stack trace at
ERROR level.
+ * This implementation will by default log the exception with stack trace at
WARN level.
*
* @version
*/
@@ -36,7 +36,7 @@ public class LoggingExceptionHandler imp
private final CamelLogger logger;
public LoggingExceptionHandler(Class<?> ownerType) {
- this(new CamelLogger(LoggerFactory.getLogger(ownerType),
LoggingLevel.ERROR));
+ this(new CamelLogger(LoggerFactory.getLogger(ownerType),
LoggingLevel.WARN));
}
public LoggingExceptionHandler(Class<?> ownerType, LoggingLevel level) {
@@ -59,7 +59,7 @@ public class LoggingExceptionHandler imp
try {
String msg =
CamelExchangeException.createExceptionMessage(message, exchange, exception);
if (isCausedByRollbackExchangeException(exception)) {
- // do not log stacktrace for intended rollbacks
+ // do not log stack trace for intended rollbacks
logger.log(msg);
} else {
if (exception != null) {
Added:
camel/trunk/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerCustomExceptionHandlerTest.java
URL:
http://svn.apache.org/viewvc/camel/trunk/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerCustomExceptionHandlerTest.java?rev=1327447&view=auto
==============================================================================
---
camel/trunk/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerCustomExceptionHandlerTest.java
(added)
+++
camel/trunk/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerCustomExceptionHandlerTest.java
Wed Apr 18 11:23:54 2012
@@ -0,0 +1,172 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file;
+
+import java.io.IOException;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.JndiRegistry;
+import org.apache.camel.spi.ExceptionHandler;
+
+/**
+ *
+ */
+public class FileConsumerCustomExceptionHandlerTest extends ContextTestSupport
{
+
+ private MyReadLockStrategy myReadLockStrategy = new MyReadLockStrategy();
+ private MyExceptionHandler myExceptionHandler = new MyExceptionHandler();
+
+ public void testCustomExceptionHandler() throws Exception {
+ myExceptionHandler.setTemplate(context.createProducerTemplate());
+
+ getMockEndpoint("mock:result").expectedMessageCount(2);
+ getMockEndpoint("mock:error").expectedBodiesReceived("Error Forced to
simulate no space on device");
+
+ template.sendBodyAndHeader("file:target/nospace", "Hello World",
Exchange.FILE_NAME, "hello.txt");
+ template.sendBodyAndHeader("file:target/nospace", "Bye World",
Exchange.FILE_NAME, "bye.txt");
+
+ assertMockEndpointsSatisfied();
+
+ assertEquals("Should pickup bye.txt file 2 times", 2,
myReadLockStrategy.getCounter());
+ }
+
+ @Override
+ protected JndiRegistry createRegistry() throws Exception {
+ JndiRegistry jndi = super.createRegistry();
+ jndi.bind("myExceptionHandler", myExceptionHandler);
+ jndi.bind("myReadLockStrategy", myReadLockStrategy);
+ return jndi;
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ // to handle any IOException being thrown
+ onException(IOException.class)
+ .handled(true)
+ .log("IOException occurred due: ${exception.message}")
+ // as we handle the exception we can send it to
direct:file-error,
+ // where we could send out alerts or whatever we want
+ .to("direct:file-error");
+
+ // special route that handles file errors
+ from("direct:file-error")
+ .log("File error route triggered to deal with exception
${exception?.class}")
+ // as this is based on unit test just transform a message
and send it to a mock
+ .transform().simple("Error ${exception.message}")
+ .to("mock:error");
+
+ // this is the file route that pickup files, notice how we use
our custom exception handler on the consumer
+ // the exclusiveReadLockStrategy is only configured because
this is from an unit test, so we use that to simulate exceptions
+
from("file:target/nospace?exclusiveReadLockStrategy=#myReadLockStrategy&consumer.exceptionHandler=#myExceptionHandler")
+ .convertBodyTo(String.class)
+ .to("mock:result");
+ }
+ };
+ }
+
+ // START SNIPPET: e1
+ /**
+ * Custom {@link ExceptionHandler} to be used on the file consumer, to send
+ * exceptions to a Camel route, to let Camel deal with the error.
+ */
+ private class MyExceptionHandler implements ExceptionHandler {
+
+ private ProducerTemplate template;
+
+ /**
+ * We use a producer template to send a message to the Camel route
+ */
+ public void setTemplate(ProducerTemplate template) {
+ this.template = template;
+ }
+
+ @Override
+ public void handleException(Throwable exception) {
+ handleException(exception.getMessage(), exception);
+ }
+
+ @Override
+ public void handleException(String message, Throwable exception) {
+ handleException(exception.getMessage(), null, exception);
+ }
+
+ @Override
+ public void handleException(final String message, final Exchange
originalExchange, final Throwable exception) {
+ // send the message to the special direct:file-error endpoint,
which will trigger exception handling
+ //
+ template.send("direct:file-error", new Processor() {
+ @Override
+ public void process(Exchange exchange) throws Exception {
+ // set an exception on the message from the start so the
error handling is triggered
+ exchange.setException(exception);
+ exchange.getIn().setBody(message);
+ }
+ });
+ }
+ }
+ // END SNIPPET: e1
+
+
+ // used for simulating exception during acquiring a lock on the file
+ private class MyReadLockStrategy implements
GenericFileExclusiveReadLockStrategy {
+
+ private int counter;
+
+ @Override
+ public void prepareOnStartup(GenericFileOperations operations,
GenericFileEndpoint endpoint) throws Exception {
+ // noop
+ }
+
+ @Override
+ public boolean acquireExclusiveReadLock(GenericFileOperations
operations, GenericFile file, Exchange exchange) throws Exception {
+ if (file.getFileNameOnly().equals("bye.txt")) {
+ if (counter++ == 0) {
+ // force an exception on acquire attempt for the bye.txt
file, on the first attempt
+ throw new IOException("Forced to simulate no space on
device");
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public void releaseExclusiveReadLock(GenericFileOperations operations,
GenericFile file, Exchange exchange) throws Exception {
+ // noop
+ }
+
+ @Override
+ public void setTimeout(long timeout) {
+ // noop
+ }
+
+ @Override
+ public void setCheckInterval(long checkInterval) {
+ // noop
+ }
+
+ public int getCounter() {
+ return counter;
+ }
+ }
+}