From 4b25ec5f531447139205b7211f94979b5036ac0a Mon Sep 17 00:00:00 2001 From: Phillipus Date: Fri, 8 Sep 2023 14:16:40 +0100 Subject: [PATCH] Add IRunnable class --- .../editor/ui/components/IRunnable.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 com.archimatetool.editor/src/com/archimatetool/editor/ui/components/IRunnable.java diff --git a/com.archimatetool.editor/src/com/archimatetool/editor/ui/components/IRunnable.java b/com.archimatetool.editor/src/com/archimatetool/editor/ui/components/IRunnable.java new file mode 100644 index 000000000..b1da1acbb --- /dev/null +++ b/com.archimatetool.editor/src/com/archimatetool/editor/ui/components/IRunnable.java @@ -0,0 +1,58 @@ +package com.archimatetool.editor.ui.components; + +import java.lang.reflect.InvocationTargetException; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.operation.IRunnableContext; + +/** + * An IRunnableContext and IRunnableWithProgress wrapper that catches and re-throws any Exceptions. Example: + * + *
+ *   ProgressMonitorDialog dialog = ...;
+ *   try {
+ *       IRunnable.run(dialog, monitor -> {
+ *           // do stuff...
+ *           monitor.setTaskName("New task");
+ *       }, true);
+ *   }
+ *   catch(Exception ex) {
+ *       ex.printStackTrace();
+ *   } 
+ * 
+ * + * @author Phillip Beauvoir + */ +public interface IRunnable { + + void run(IProgressMonitor monitor) throws Exception; + + /** + * Run the Runnable, catching any Exceptions and re-throwing them + * @param fork true if the runnable should be run in a separate thread and false to run in the same thread + */ + static void run(IRunnableContext context, IRunnable runnable, boolean fork) throws Exception { + Exception[] exception = new Exception[1]; + + try { + context.run(fork, true, monitor -> { + try { + runnable.run(monitor); + } + catch(Exception ex) { + exception[0] = ex; + } + }); + } + catch(InvocationTargetException ex) { + exception[0] = new Exception(ex.getTargetException()); // we want the target exception + } + catch(InterruptedException ex) { + exception[0] = ex; + } + + if(exception[0] != null) { + throw exception[0]; + } + } +} \ No newline at end of file