package no.uio.ifi.refaktor.handlers; import java.lang.reflect.InvocationTargetException; import no.uio.ifi.refaktor.change.changers.RefaktorChanger; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.handlers.HandlerUtil; public abstract class WorkspaceModificationHandler extends AbstractHandler { private RefaktorChanger changer; public WorkspaceModificationHandler() { super(); } protected abstract RefaktorChanger createChanger(); protected abstract String getTitle(); protected abstract String getMessage(); @Override public Object execute(ExecutionEvent event) throws ExecutionException { destroyChanger(); if (preconditionsAreMet(event) && userConfirms(event)) { try { modifyWorkspace(); } catch (InvocationTargetException e) { e.printStackTrace(); makeAndThrowExecutionException(e); } catch (InterruptedException e) { e.printStackTrace(); makeAndThrowExecutionException(e); } } return null; } private void makeAndThrowExecutionException(Throwable e) throws ExecutionException { throw new ExecutionException(this.getClass().getSimpleName() + " failed",e); } protected boolean preconditionsAreMet(ExecutionEvent event) throws ExecutionException { return true; } public void modifyWorkspace() throws ExecutionException, InvocationTargetException, InterruptedException { WorkspaceModifyOperation op = new WorkspaceModifyOperation() { @Override protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { getChanger().execute(monitor); } }; op.run(new NullProgressMonitor()); } protected boolean userConfirms(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); return MessageDialog.openQuestion(window.getShell(), getTitle(), getMessage()); } protected void destroyChanger() { changer = null; } protected RefaktorChanger getChanger() { if (changer == null) changer = createChanger(); return changer; } }