Example usage for org.eclipse.jface.dialogs ProgressMonitorDialog run

List of usage examples for org.eclipse.jface.dialogs ProgressMonitorDialog run

Introduction

In this page you can find the example usage for org.eclipse.jface.dialogs ProgressMonitorDialog run.

Prototype

@Override
public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
        throws InvocationTargetException, InterruptedException 

Source Link

Document

This implementation of IRunnableContext#run(boolean, boolean, IRunnableWithProgress) runs the given IRunnableWithProgress using the progress monitor for this progress dialog and blocks until the runnable has been run, regardless of the value of fork.

Usage

From source file:org.eclipse.emf.ecore.xcore.ui.ConvertToEcoreActionDelegate.java

License:Open Source License

@Override
public void run(IAction action) {
    final IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();

    final XPackage inputXPackage = getInputXPackage(
            (IStructuredSelection) workbenchWindow.getSelectionService().getSelection());
    final Resource inputResource = inputXPackage.eResource();

    URI ecoreOutputResourceURI = inputResource.getURI().trimFileExtension().appendFileExtension("ecore");
    final ResourceSet resourceSet = inputResource.getResourceSet();
    final Resource ecoreOutputResource = resourceSet.createResource(ecoreOutputResourceURI);
    URI genModelOutputResourceURI = inputResource.getURI().trimFileExtension().appendFileExtension("genmodel");
    final Resource genModelOutputResource = resourceSet.createResource(genModelOutputResourceURI);

    ProgressMonitorDialog dialog = new ProgressMonitorDialog(workbenchWindow.getShell());
    try {/*from  w  w  w. j a va  2  s  .  c  o m*/
        dialog.run(false, true, new WorkspaceModifyOperation() {
            @Override
            protected void execute(IProgressMonitor progressMonitor) {
                try {
                    progressMonitor.beginTask("", 1);

                    // outputResource.getContents().add(new XcoreEcoreBuilder().getEPackage(inputXPackage));
                    Resource ecoreXcore = resourceSet.getResource(
                            URI.createURI("platform:/plugin/org.eclipse.emf.ecore/model/Ecore.xcore"), false);
                    if (ecoreXcore != null) {
                        Resource ecore = resourceSet.createResource(
                                URI.createURI("platform:/plugin/org.eclipse.emf.ecore/model/Ecore.ecore"));
                        ecore.getContents().add(ecoreXcore.getContents().get(2));
                    }

                    ecoreOutputResource.getContents().add((EPackage) EcoreUtil
                            .getObjectByType(inputResource.getContents(), EcorePackage.Literals.EPACKAGE));
                    genModelOutputResource.getContents().add((GenModel) EcoreUtil
                            .getObjectByType(inputResource.getContents(), GenModelPackage.Literals.GEN_MODEL));

                    try {
                        ecoreOutputResource.save(null);
                        genModelOutputResource.save(null);

                        IFile ecoreFile = getFile(ecoreOutputResource);
                        IFile genModelFile = getFile(genModelOutputResource);
                        IWorkbenchPage workbenchPage = workbenchWindow.getActivePage();

                        final IWorkbenchPart activePart = workbenchPage.getActivePart();
                        if (activePart instanceof ISetSelectionTarget) {
                            final ISelection targetSelection = new StructuredSelection(ecoreFile);
                            workbenchWindow.getShell().getDisplay().asyncExec(new Runnable() {
                                public void run() {
                                    ((ISetSelectionTarget) activePart).selectReveal(targetSelection);
                                }
                            });
                        }

                        try {
                            workbenchPage.openEditor(new FileEditorInput(ecoreFile),
                                    workbenchWindow.getWorkbench().getEditorRegistry()
                                            .getDefaultEditor(ecoreFile.getFullPath().toString(),
                                                    Platform.getContentTypeManager()
                                                            .getContentType(EcorePackage.eCONTENT_TYPE))
                                            .getId());
                            workbenchPage.openEditor(new FileEditorInput(genModelFile),
                                    workbenchWindow.getWorkbench().getEditorRegistry()
                                            .getDefaultEditor(genModelFile.getFullPath().toString(),
                                                    Platform.getContentTypeManager()
                                                            .getContentType(GenModelPackage.eCONTENT_TYPE))
                                            .getId());
                        } catch (PartInitException pie) {
                            XcoreActivator.getInstance().getLog().log(new Status(IStatus.WARNING,
                                    "org.eclipse.emf.ecore.xcore.ui", 0, pie.getLocalizedMessage(), pie));
                        }
                    } catch (IOException ioe) {
                        XcoreActivator.getInstance().getLog().log(new Status(IStatus.WARNING,
                                "org.eclipse.emf.ecore.xcore.ui", 0, ioe.getLocalizedMessage(), ioe));
                    }
                } finally {
                    progressMonitor.done();
                }
            }
        });
    } catch (InterruptedException ie) {
        // ignore
    } catch (InvocationTargetException ite) {
        XcoreActivator.getInstance().getLog().log(new Status(IStatus.WARNING, "org.eclipse.emf.ecore.xcore.ui",
                0, ite.getLocalizedMessage(), ite));
    }
}

From source file:org.eclipse.emf.ecore.xcore.ui.ConvertToXcoreActionDelegate.java

License:Open Source License

@Override
public void run(IAction action) {
    final IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();

    final EPackage inputEPackage = getInputEPackage(
            (IStructuredSelection) workbenchWindow.getSelectionService().getSelection());
    final Resource inputResource = inputEPackage.eResource();

    URI outputResourceURI = inputResource.getURI().trimFileExtension().appendFileExtension("xcore");
    final Resource outputResource = inputResource.getResourceSet().createResource(outputResourceURI);

    ProgressMonitorDialog dialog = new ProgressMonitorDialog(workbenchWindow.getShell());
    try {/*from  w  w w  .  j  av  a 2s.  c  om*/
        dialog.run(false, true, new WorkspaceModifyOperation() {
            @Override
            protected void execute(IProgressMonitor progressMonitor) {
                try {
                    progressMonitor.beginTask("", 1);

                    Resource genModelResource = inputResource.getResourceSet().getResources().get(0);
                    GenModel inputGenModel = null;
                    if (genModelResource != inputResource) {
                        inputGenModel = (GenModel) genModelResource.getContents().get(0);
                        inputGenModel.reconcile();
                        final GenModel genModel = GenModelFactory.eINSTANCE.createGenModel();
                        genModel.initialize(Collections.singleton(inputEPackage));
                        genModelResource.getContents().add(genModel);
                        genModelInitializer.initialize(genModel);
                        new Object() {
                            void visit(GenBase genBase1, GenBase genBase2) {
                                if (genBase1.eClass() == genBase2.eClass()) {
                                    for (EAttribute eAttribute : genBase1.eClass().getEAllAttributes()) {
                                        // TODO
                                        if (!eAttribute.isMany() && genBase1.eIsSet(eAttribute)) {
                                            Object value1 = genBase1.eGet(eAttribute);
                                            Object value2 = genBase2.eGet(eAttribute);
                                            if (value1 == null ? value2 != null : !value1.equals(value2)) {
                                                EModelElement eModelElement = genBase2.getEcoreModelElement();
                                                if (eModelElement == null) {
                                                    eModelElement = genModel.getGenPackages().get(0)
                                                            .getEcorePackage();
                                                }
                                                EcoreUtil.setAnnotation(eModelElement, GenModelPackage.eNS_URI,
                                                        eAttribute.getName(), EcoreUtil.convertToString(
                                                                eAttribute.getEAttributeType(), value1));
                                            }
                                            for (Iterator<EObject> i = genBase1.eContents()
                                                    .iterator(), j = genBase2.eContents().iterator(); i
                                                            .hasNext() && j.hasNext();) {
                                                EObject content1 = i.next();
                                                EObject content2 = j.next();
                                                if (content1 instanceof GenBase
                                                        && content2 instanceof GenBase) {
                                                    visit((GenBase) content1, (GenBase) content2);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }.visit(inputGenModel, genModel);
                    } else {
                        // TODO what about no GenModel?
                        // We'd want to create one and use that...
                    }

                    EcoreXcoreBuilder ecoreXcoreBuilder = ecoreXcoreBuilderProvider.get();
                    ecoreXcoreBuilder.initialize(inputGenModel);
                    XPackage xPackage = ecoreXcoreBuilder.getXPackage(inputEPackage);
                    outputResource.getContents().add(xPackage);
                    outputResource.getContents().add(inputGenModel);
                    outputResource.getContents().add(inputEPackage);
                    GenPackage ecoreGenPackage = inputGenModel.getEcoreGenPackage();
                    if (ecoreGenPackage != null) {
                        outputResource.getContents().add(ecoreGenPackage.getGenModel());
                    }
                    GenPackage xmlTypeGenPackage = inputGenModel.getXMLTypeGenPackage();
                    if (xmlTypeGenPackage != null) {
                        outputResource.getContents().add(xmlTypeGenPackage.getGenModel());
                    }
                    GenPackage xmlNamespaceGenPackage = inputGenModel.getXMLNamespaceGenPackage();
                    if (xmlNamespaceGenPackage != null) {
                        outputResource.getContents().add(xmlNamespaceGenPackage.getGenModel());
                    }
                    ecoreXcoreBuilder.link();
                    genModelBuilder.buildMap(inputGenModel);

                    ImportManager importManager = new ImportManager(
                            inputGenModel.getGenPackages().get(0).getInterfacePackageName()) {
                        @Override
                        protected boolean shouldImport(String packageName, String shortName,
                                String importName) {
                            return true;
                        }
                    };
                    for (Iterator<EObject> i = inputEPackage.eAllContents(); i.hasNext();) {
                        EObject eObject = i.next();
                        if (eObject instanceof EGenericType) {
                            EGenericType eGenericType = (EGenericType) eObject;
                            EClassifier eClassifier = eGenericType.getEClassifier();
                            if (eClassifier != null) {
                                GenClassifier genClassifier = inputGenModel.findGenClassifier(eClassifier);
                                String qualifiedName = genClassifier.getGenPackage().getInterfacePackageName()
                                        + "." + eClassifier.getName();
                                importManager.addImport(qualifiedName);
                            }
                        }
                    }
                    for (String qualifiedName : importManager.getImports()) {
                        XImportDirective xImportDirective = XcoreFactory.eINSTANCE.createXImportDirective();
                        xImportDirective.setImportedNamespace(qualifiedName);
                        xPackage.getImportDirectives().add(xImportDirective);
                    }

                    try {
                        Map<Object, Object> options = new HashMap<Object, Object>();
                        SaveOptions.newBuilder().format().noValidation().getOptions().addTo(options);
                        outputResource.save(options);

                        IFile file = getFile(outputResource);
                        IWorkbenchPage workbenchPage = workbenchWindow.getActivePage();

                        final IWorkbenchPart activePart = workbenchPage.getActivePart();
                        if (activePart instanceof ISetSelectionTarget) {
                            final ISelection targetSelection = new StructuredSelection(file);
                            workbenchWindow.getShell().getDisplay().asyncExec(new Runnable() {
                                public void run() {
                                    ((ISetSelectionTarget) activePart).selectReveal(targetSelection);
                                }
                            });
                        }

                        try {
                            workbenchPage
                                    .openEditor(new FileEditorInput(file),
                                            workbenchWindow.getWorkbench().getEditorRegistry()
                                                    .getDefaultEditor(file.getFullPath().toString(),
                                                            Platform.getContentTypeManager()
                                                                    .getContentType("org.eclipse.emf.ecore"))
                                                    .getId());
                        } catch (PartInitException pie) {
                            XcoreActivator.getInstance().getLog().log(new Status(IStatus.WARNING,
                                    "org.eclipse.emf.ecore.xcore.ui", 0, pie.getLocalizedMessage(), pie));
                        }
                    } catch (IOException ioe) {
                        XcoreActivator.getInstance().getLog().log(new Status(IStatus.WARNING,
                                "org.eclipse.emf.ecore.xcore.ui", 0, ioe.getLocalizedMessage(), ioe));
                    }
                } finally {
                    progressMonitor.done();
                }
            }
        });
    } catch (InterruptedException ie) {
        // ignore
    } catch (InvocationTargetException ite) {
        XcoreActivator.getInstance().getLog().log(new Status(IStatus.WARNING, "org.eclipse.emf.ecore.xcore.ui",
                0, ite.getLocalizedMessage(), ite));
    }
}

From source file:org.eclipse.emf.mapping.ecore2ecore.action.MapToEcoreActionDelegate.java

License:Open Source License

@Override
public void run(IAction action) {
    final IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    Object selection = ((IStructuredSelection) workbenchWindow.getSelectionService().getSelection())
            .getFirstElement();//ww w. j a v  a2  s.c o  m
    final IFile selectedEcoreFile = selection instanceof IFile
            && FILE_EXTENSIONS.contains(((IFile) selection).getFileExtension()) ? (IFile) selection : null;

    ViewerFilter viewerFilter = new ViewerFilter() {
        @Override
        public boolean select(Viewer viewer, Object parentElement, Object element) {
            if (element instanceof IFile) {
                IFile file = (IFile) element;
                return FILE_EXTENSIONS.contains(file.getFileExtension()) && (selectedEcoreFile == null
                        || !selectedEcoreFile.getFullPath().equals(file.getFullPath()));
            }
            return true;
        }
    };

    final IFile[] files = WorkspaceResourceDialog.openFileSelection(workbenchWindow.getShell(), null,
            Ecore2EcoreEditorPlugin.INSTANCE.getString("_UI_SelectOutputEcoreModels_label"), true, null,
            Collections.singletonList(viewerFilter));

    if (files.length > 0) {
        final EPackage inputEPackage = getInputEPackage(
                (IStructuredSelection) workbenchWindow.getSelectionService().getSelection());
        final Resource inputResource = inputEPackage.eResource();

        ProgressMonitorDialog dialog = new ProgressMonitorDialog(workbenchWindow.getShell());

        try {
            dialog.run(false, true, new WorkspaceModifyOperation() {
                @Override
                protected void execute(IProgressMonitor progressMonitor) {
                    try {
                        progressMonitor.beginTask("", files.length);

                        for (int i = 0; i < files.length; i++) {
                            Resource outputResource = inputResource.getResourceSet().getResource(
                                    URI.createPlatformResourceURI(files[i].getFullPath().toString(), true),
                                    true);
                            EPackage outputEPackage = (EPackage) EcoreUtil.getObjectByType(
                                    outputResource.getContents(), EcorePackage.Literals.EPACKAGE);

                            String base = inputResource.getURI().trimFileExtension().lastSegment() + "_2_"
                                    + outputResource.getURI().trimFileExtension().lastSegment();
                            URI mappingURI = outputResource.getURI().trimSegments(1).appendSegment(base)
                                    .appendFileExtension(ECORE2ECORE_FILE_EXTENSION);

                            Resource mappingResource = inputResource.getResourceSet()
                                    .createResource(mappingURI);

                            progressMonitor.subTask(MessageFormat.format(
                                    Ecore2EcoreEditorPlugin.INSTANCE
                                            .getString("_UI_BuildingMappingFromTo_message"),
                                    new Object[] { inputResource.getURI().lastSegment(),
                                            outputResource.getURI().lastSegment() }));

                            mappingResource.getContents().add(createMappingRoot(inputEPackage, outputEPackage));

                            try {
                                mappingResource.save(null);

                                IFile file = getFile(mappingResource);
                                IWorkbenchPage workbenchPage = workbenchWindow.getActivePage();

                                final IWorkbenchPart activePart = workbenchPage.getActivePart();
                                if (activePart instanceof ISetSelectionTarget) {
                                    final ISelection targetSelection = new StructuredSelection(file);
                                    workbenchWindow.getShell().getDisplay().asyncExec(new Runnable() {
                                        public void run() {
                                            ((ISetSelectionTarget) activePart).selectReveal(targetSelection);
                                        }
                                    });
                                }

                                try {
                                    workbenchPage.openEditor(new FileEditorInput(file),
                                            workbenchWindow.getWorkbench().getEditorRegistry()
                                                    .getDefaultEditor(file.getFullPath().toString()).getId());
                                } catch (PartInitException pie) {
                                    Ecore2EcoreEditorPlugin.INSTANCE.log(pie);
                                }
                            } catch (IOException ioe) {
                                Ecore2EcoreEditorPlugin.INSTANCE.log(ioe);
                            }
                        }
                    } finally {
                        progressMonitor.done();
                    }
                }
            });
        } catch (InterruptedException ie) {
            // ignore
        } catch (InvocationTargetException ite) {
            Ecore2EcoreEditorPlugin.INSTANCE.log(ite);
        }
    }
}

From source file:org.eclipse.epf.export.msp.ExportMSPXMLService.java

License:Open Source License

private void generateOperatonRun(Process process, Project project, MethodConfiguration config)
        throws InvocationTargetException, InterruptedException {
    final Process fprocess = process;
    final Project fproject = project;
    final MethodConfiguration fconfig = config;

    IRunnableWithProgress op = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException {
            try {
                monitor.beginTask(ExportMSPResources.exportMSPWizard_title, IProgressMonitor.UNKNOWN);

                generate(fprocess, fproject, fconfig);
            } catch (Exception e) {
                throw new InvocationTargetException(e);
            } finally {
                monitor.done();/* w w  w.  jav  a2 s . c  om*/
            }
        }
    };
    ProgressMonitorDialog pmDialog = new ProgressMonitorDialog(Display.getCurrent().getActiveShell());
    pmDialog.run(true, false, op);
}

From source file:org.eclipse.epf.importing.services.CommandLinePluginImporter.java

License:Open Source License

public boolean execute(String[] args) {
    if (!super.execute(args)) {
        return false;
    }/*from  w  w  w  .  j ava 2s . co m*/
    try {
        loadInputFile();
        WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
            public void execute(IProgressMonitor monitor) {
                try {
                    monitor.setTaskName("Openning base library and preparing import ...");//$NON-NLS-1$"
                    XMILibraryUtil.openMethodLibrary(baseLibPath);

                    File importLibFolder = new File(importLibPath);

                    PluginImportData data = new PluginImportData();
                    data.llData.setLibName(importLibFolder.getName());
                    data.llData.setParentFolder(importLibFolder.getAbsolutePath());
                    final PluginImportingService service = new PluginImportingService(data);
                    service.validate(null);

                    List importPlugins = data.getPlugins();
                    for (int i = 0; i < importPlugins.size(); i++) {
                        PluginInfo info = (PluginInfo) importPlugins.get(i);
                        info.selected = selectedPlugins.isEmpty() || selectedPlugins.contains(info.name);
                    }

                    service.performImport(monitor);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    monitor.done();
                }
            }
        };

        ProgressMonitorDialog pmDialog = new ProgressMonitorDialog(Display.getCurrent().getActiveShell());
        pmDialog.run(true, false, operation);

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.eclipse.epf.library.ui.LibraryUIManager.java

License:Open Source License

public static boolean upgradeLibrary(final File libFile, final UpgradeCallerInfo callerInfo) {
    final StringBuffer errMsg = new StringBuffer();
    final boolean[] cancelFlagHolder = { false };

    // Do the work within an operation because this is a long running
    // activity that modifies the workbench.
    WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
        public void execute(IProgressMonitor monitor) {
            monitor.beginTask(LibraryUIResources.upgradingLibraryTask_name, 10);
            monitor.worked(1);//from  w w w . j  a  v a  2 s. c  o m
            try {
                MappingUtil.migrate(libFile.getAbsolutePath(), monitor, callerInfo);
            } catch (OperationCanceledException e) {
                cancelFlagHolder[0] = true;
            } catch (Exception e) {
                LibraryUIPlugin.getDefault().getLogger().logError(e);
                if (DEBUG) {
                    e.printStackTrace();
                }
                String msg = e.getMessage();
                if (msg == null) {
                    msg = LibraryUIResources.upgradeLibraryError_msg;
                }
                errMsg.append(msg);
            } finally {
                monitor.done();
            }
        }
    };

    try {
        // Run the operation and display the progress.
        ProgressMonitorDialog pmDialog = new ProgressMonitorDialog(Display.getCurrent().getActiveShell()) {
            protected Point getInitialSize() {
                Point calculatedSize = super.getInitialSize();
                if (calculatedSize.x < 675) {
                    calculatedSize.x = 675;
                }
                return calculatedSize;
            }
        };
        pmDialog.run(true, false, operation);
        if (cancelFlagHolder[0]) {
            return false;
        } else if (errMsg.length() > 0) {
            IStatus status = new Status(IStatus.ERROR, LibraryUIPlugin.PLUGIN_ID, 0, "", null) {//$NON-NLS-1$
                public IStatus[] getChildren() {
                    IStatus[] ret = new Status[1];
                    IStatus cs = new Status(IStatus.ERROR, LibraryUIPlugin.PLUGIN_ID, 0, errMsg.toString(),
                            null);
                    ret[0] = cs;
                    return ret;
                }

                public boolean isMultiStatus() {
                    return true;
                }
            };

            LibraryUIPlugin.getDefault().getMsgDialog().displayError(
                    LibraryUIResources.upgradeLibraryDialog_title, LibraryUIResources.upgradeLibraryError_msg,
                    status);

            return false;
        }
        return true;
    } catch (Exception e) {
        LibraryUIPlugin.getDefault().getLogger().logError(e);
        if (DEBUG) {
            e.printStackTrace();
        }
        LibraryUIPlugin.getDefault().getMsgDialog().displayError(LibraryUIResources.upgradeLibraryDialog_title,
                LibraryUIResources.upgradeLibraryError_msg);
        return false;
    }

}

From source file:org.eclipse.epf.library.ui.wizards.LibraryBackupUtil.java

License:Open Source License

private void doBackup(final Shell shell, final File libPath, ILibraryService service) {
    path = null;//from   w w  w  .ja v  a2s. c om
    final ILibraryService fservice = service;

    SafeUpdateController.syncExec(new Runnable() {
        public void run() {
            Shell s = shell;
            if (s == null) {
                s = MsgBox.getDefaultShell();
            }

            if (s == null) {
                s = new Shell(MsgBox.getDisplay());
            }

            String title = LibraryUIResources.backupLibraryDialog_title;
            String message = LibraryUIResources.backupLibraryDialog_text;
            String backupPath = libPath.getAbsolutePath() + ".backup"; //$NON-NLS-1$   

            LibraryBackupDialog dlg = new LibraryBackupDialog(s, title, message, backupPath);

            if (dlg.open() == Dialog.OK) {
                path = dlg.getPath();
            }

            ProgressMonitorDialog pmDialog = new ProgressMonitorDialog(s);
            IRunnableWithProgress op = new IRunnableWithProgress() {
                public void run(IProgressMonitor monitor) throws InvocationTargetException {
                    monitor.beginTask(LibraryUIResources.backingUpLibraryTask_name, IProgressMonitor.UNKNOWN);
                    if (path != null) {
                        if (fservice == null) {
                            backup(libPath, new File(path));
                        } else {
                            fservice.getCurrentLibraryManager().backupMethodLibrary(path);
                        }
                    }
                }
            };

            try {
                pmDialog.run(true, false, op);
            } catch (Exception e) {
                LibraryUIPlugin.getDefault().getLogger().logError(e);
            }
        }
    });

}

From source file:org.eclipse.equinox.p2.ui.RepositoryManipulationPage.java

License:Open Source License

void refreshRepository() {
    final MetadataRepositoryElement[] selected = getSelectedElements();
    final ProvisionException[] fail = new ProvisionException[1];
    final boolean[] remove = new boolean[1];
    remove[0] = false;/*w  w  w  . ja v  a  2  s  . c  o m*/
    if (selected.length != 1)
        return;
    final URI location = selected[0].getLocation();
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
    try {
        dialog.run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                monitor.beginTask(
                        NLS.bind(ProvUIMessages.RepositoryManipulationPage_ContactingSiteMessage, location),
                        100);
                try {
                    // Batch the events for this operation so that any events on reload (discovery, etc.) will be ignored
                    // in the UI as they happen.
                    ui.signalRepositoryOperationStart();
                    tracker.clearRepositoryNotFound(location);
                    // If the managers don't know this repo, refreshing it will not work.
                    // We temporarily add it, but we must remove it in case the user cancels out of this page.
                    if (!includesRepo(tracker.getKnownRepositories(ui.getSession()), location)) {
                        remove[0] = true;
                        // We don't want to use the tracker here because it ensures that additions are
                        // reported as user events to be responded to.  We don't want, for example, the
                        // install wizard to change combo selections based on what is done here.
                        ProvUI.getMetadataRepositoryManager(ui.getSession()).addRepository(location);
                        ProvUI.getArtifactRepositoryManager(ui.getSession()).addRepository(location);
                    }
                    // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=312332
                    // We assume repository colocation here.  Ideally we should not do this, but the
                    // RepositoryTracker API is swallowing the refresh errors.
                    SubMonitor sub = SubMonitor.convert(monitor, 200);
                    try {
                        ProvUI.getMetadataRepositoryManager(ui.getSession()).refreshRepository(location,
                                sub.newChild(100));
                    } catch (ProvisionException e) {
                        fail[0] = e;
                    }
                    try {
                        ProvUI.getArtifactRepositoryManager(ui.getSession()).refreshRepository(location,
                                sub.newChild(100));
                    } catch (ProvisionException e) {
                        // Failure in the artifact repository.  We will not report this because the user has no separate visibility
                        // of the artifact repository.  We should log the error.  If this repository fails during a download, the error
                        // will be reported at that time to the user, when it matters.  This also prevents false error reporting when
                        // a metadata repository didn't actually have a colocated artifact repository.
                        LogHelper.log(e);
                    }
                } catch (OperationCanceledException e) {
                    // Catch canceled login attempts
                    fail[0] = new ProvisionException(new Status(IStatus.CANCEL, ProvUIActivator.PLUGIN_ID,
                            ProvUIMessages.RepositoryManipulationPage_RefreshOperationCanceled, e));
                } finally {
                    // Check if the monitor was canceled
                    if (fail[0] == null && monitor.isCanceled())
                        fail[0] = new ProvisionException(new Status(IStatus.CANCEL, ProvUIActivator.PLUGIN_ID,
                                ProvUIMessages.RepositoryManipulationPage_RefreshOperationCanceled));
                    // If we temporarily added a repo so we could read it, remove it.
                    if (remove[0]) {
                        ProvUI.getMetadataRepositoryManager(ui.getSession()).removeRepository(location);
                        ProvUI.getArtifactRepositoryManager(ui.getSession()).removeRepository(location);
                    }
                    ui.signalRepositoryOperationComplete(null, false);
                }
            }
        });
    } catch (InvocationTargetException e) {
        // nothing to report
    } catch (InterruptedException e) {
        // nothing to report
    }
    if (fail[0] != null) {
        // If the repo was not found, tell ProvUI that we will be reporting it.
        // We are going to report problems directly to the status manager because we
        // do not want the automatic repo location editing to kick in.
        if (fail[0].getStatus().getCode() == ProvisionException.REPOSITORY_NOT_FOUND) {
            tracker.addNotFound(location);
        }
        if (!fail[0].getStatus().matches(IStatus.CANCEL)) {
            // An error is only shown if the dialog was not canceled
            ProvUI.handleException(fail[0], null, StatusManager.SHOW);
        }
    } else {
        // Confirm that it was successful
        MessageDialog.openInformation(getShell(), ProvUIMessages.RepositoryManipulationPage_TestConnectionTitle,
                NLS.bind(ProvUIMessages.RepositoryManipulationPage_TestConnectionSuccess,
                        URIUtil.toUnencodedString(location)));
    }
    repositoryViewer.update(selected[0], null);
    setDetails();
}

From source file:org.eclipse.equinox.p2.ui.RevertProfilePage.java

License:Open Source License

boolean revert() {
    final IProfile snapshot = getSelectedSnapshot();
    if (snapshot == null)
        return false;
    final IProvisioningPlan[] plan = new IProvisioningPlan[1];
    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) {
            IProfile currentProfile;/* w w w  .  j a v  a  2 s  .c o  m*/
            IProfileRegistry registry = ProvUI.getProfileRegistry(getSession());
            IPlanner planner = (IPlanner) getSession().getProvisioningAgent().getService(IPlanner.SERVICE_NAME);
            currentProfile = registry.getProfile(profileId);
            plan[0] = planner.getDiffPlan(currentProfile, snapshot, monitor);
        }
    };
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
    try {
        dialog.run(true, true, runnable);
    } catch (InvocationTargetException e) {
        ProvUI.handleException(e.getCause(), null, StatusManager.SHOW | StatusManager.LOG);
    } catch (InterruptedException e) {
        // nothing to report
    }
    // the dialog does not throw OperationCanceledException so we have to
    // check the monitor
    if (dialog.getProgressMonitor().isCanceled())
        return false;

    boolean reverted = false;
    if (plan[0] != null) {
        if (plan[0].getStatus().isOK()) {
            // We use a default provisioning context (all repos) because we have no other
            // way currently to figure out which sites the user wants to contact
            ProfileModificationJob op = new ProfileModificationJob(
                    ProvUIMessages.RevertDialog_RevertOperationLabel, getSession(), profileId, plan[0],
                    new ProvisioningContext(getSession().getProvisioningAgent()));
            // we want to force a restart (not allow apply changes)
            op.setRestartPolicy(ProvisioningJob.RESTART_ONLY);
            getProvisioningUI().schedule(op, StatusManager.SHOW | StatusManager.LOG);
            reverted = true;
        } else if (plan[0].getStatus().getSeverity() != IStatus.CANCEL) {
            ProvUI.reportStatus(plan[0].getStatus(), StatusManager.LOG | StatusManager.SHOW);
            // This message has no effect in an installation dialog
            // setMessage(ProvUIMessages.ProfileModificationWizardPage_UnexpectedError, IMessageProvider.ERROR);
        }
    }
    return reverted;
}

From source file:org.eclipse.ffs.internal.ui.add.WizardFileSystemResourceImportPage1.java

License:Open Source License

/**
 * Update the tree to only select those elements that match the selected types
 *///from   ww  w. j  a v a2  s .  c o m
protected void setupSelectionsBasedOnSelectedTypes() {
    ProgressMonitorDialog dialog = new ProgressMonitorJobsDialog(getContainer().getShell());
    final Map selectionMap = new Hashtable();

    final IElementFilter filter = new IElementFilter() {

        public void filterElements(Collection files, IProgressMonitor monitor) throws InterruptedException {
            if (files == null) {
                throw new InterruptedException();
            }
            Iterator filesList = files.iterator();
            while (filesList.hasNext()) {
                if (monitor.isCanceled()) {
                    throw new InterruptedException();
                }
                checkFile(filesList.next());
            }
        }

        public void filterElements(Object[] files, IProgressMonitor monitor) throws InterruptedException {
            if (files == null) {
                throw new InterruptedException();
            }
            for (int i = 0; i < files.length; i++) {
                if (monitor.isCanceled()) {
                    throw new InterruptedException();
                }
                checkFile(files[i]);
            }
        }

        private void checkFile(Object fileElement) {
            MinimizedFileSystemElement file = (MinimizedFileSystemElement) fileElement;
            if (isExportableExtension(file.getFileNameExtension())) {
                List elements = new ArrayList();
                FileSystemElement parent = file.getParent();
                if (selectionMap.containsKey(parent)) {
                    elements = (List) selectionMap.get(parent);
                }
                elements.add(file);
                selectionMap.put(parent, elements);
            }
        }

    };

    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(final IProgressMonitor monitor) throws InterruptedException {
            monitor.beginTask(DataTransferMessages.ImportPage_filterSelections, IProgressMonitor.UNKNOWN);
            getSelectedResources(filter, monitor);
        }
    };

    try {
        dialog.run(true, true, runnable);
    } catch (InvocationTargetException exception) {
        //Couldn't start. Do nothing.
        return;
    } catch (InterruptedException exception) {
        //Got interrupted. Do nothing.
        return;
    }
    // make sure that all paint operations caused by closing the progress 
    // dialog get flushed, otherwise extra pixels will remain on the screen until 
    // updateSelections is completed
    getShell().update();
    // The updateSelections method accesses SWT widgets so cannot be executed
    // as part of the above progress dialog operation since the operation forks
    // a new process.   
    if (selectionMap != null) {
        updateSelections(selectionMap);
    }
}