Example usage for org.eclipse.jface.operation IRunnableWithProgress run

List of usage examples for org.eclipse.jface.operation IRunnableWithProgress run

Introduction

In this page you can find the example usage for org.eclipse.jface.operation IRunnableWithProgress run.

Prototype

public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException;

Source Link

Document

Runs this operation.

Usage

From source file:com.bdaum.zoom.core.internal.CoreActivator.java

License:Open Source License

private void convertDatabase(final Meta meta) {
    final IDbManager db = getDbManager();
    int catVersion = meta.getVersion();
    int supportedVersion = db.getVersion();
    if (catVersion > supportedVersion)
        Core.getCore().getDbFactory().getErrorHandler().fatalError(Messages.CoreActivator_unsupported_version,
                NLS.bind(Messages.CoreActivator_use_newer_version, Constants.APPLICATION_NAME,
                        db.getFileName()),
                (IAdaptable) db);//from w w  w .  j  av  a 2  s  .  co m
    else if (catVersion < supportedVersion) {
        IRunnableWithProgress runnable = new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                monitor.beginTask(Messages.CoreActivator_converting_cat, IProgressMonitor.UNKNOWN);
                monitor.subTask(Messages.CoreActivator_backing_up_cat);
                db.performBackup(0L, -1L, true);
                monitor.subTask(Messages.CoreActivator_converting_to_new_version);
                CatalogConverter.convert(db, monitor);
                logInfo(NLS.bind(Messages.CoreActivator_catalog_converted, db.getVersion()));
                monitor.done();
            }
        };
        IWorkbench workbench = PlatformUI.getWorkbench();
        Shell shell = workbench.getWorkbenchWindowCount() > 0 ? workbench.getWorkbenchWindows()[0].getShell()
                : null;
        if (shell != null) {
            shell.getDisplay().syncExec(() -> {
                try {
                    new ProgressMonitorDialog(shell).run(true, false, runnable);
                } catch (InvocationTargetException e1) {
                    logError(NLS.bind(Messages.CoreActivator_error_when_updating_to_version_n, db.getVersion()),
                            e1);
                } catch (InterruptedException e2) {
                    // should never happen
                }
            });
        } else
            try {
                runnable.run(new NullProgressMonitor());
            } catch (InvocationTargetException e) {
                logError(NLS.bind(Messages.CoreActivator_error_when_updating_to_version_n, db.getVersion()), e);
            } catch (InterruptedException e) {
                // should never happen
            }
    }
}

From source file:com.bdaum.zoom.db.internal.DbManager.java

License:Open Source License

public void pruneEmptySystemCollections() {
    if (!readOnly && hasDirtyCollection()) {
        IRunnableWithProgress runnable = new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                pruneEmptySystemCollections(monitor, false);
            }/*from w w  w  .  j a  va2s .  c  o m*/
        };
        try {
            IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
            if (workbenchWindow != null) {
                ProgressMonitorDialog dialog = new ProgressMonitorDialog(workbenchWindow.getShell());
                dialog.create();
                dialog.getShell().setText(Constants.APPLICATION_NAME);
                dialog.run(false, true, runnable);
            } else
                runnable.run(new NullProgressMonitor());
        } catch (InvocationTargetException e) {
            // ignore
        } catch (InterruptedException e) {
            // ignore
        }
    }
}

From source file:com.dubture.twig.ui.actions.TwigToggleLineCommentHandler.java

License:Open Source License

@Override
protected void processAction(final ITextEditor textEditor, final IStructuredDocument document,
        ITextSelection textSelection) {/*ww w.  j a v a 2  s.  c  o  m*/

    IStructuredModel model = null;
    DocumentRewriteSession session = null;
    boolean changed = false;

    try {
        // get text selection lines info
        int selectionStartLine = textSelection.getStartLine();
        int selectionEndLine = textSelection.getEndLine();

        int selectionEndLineOffset = document.getLineOffset(selectionEndLine);
        int selectionEndOffset = textSelection.getOffset() + textSelection.getLength();

        // adjust selection end line
        if ((selectionEndLine > selectionStartLine) && (selectionEndLineOffset == selectionEndOffset)) {
            selectionEndLine--;
            selectionEndLineOffset = document.getLineInformation(selectionEndLine).getOffset();
        }

        int selectionStartLineOffset = document.getLineOffset(selectionStartLine);
        ITypedRegion[] lineTypedRegions = document.computePartitioning(selectionStartLineOffset,
                selectionEndLineOffset - selectionStartLineOffset);

        if (lineTypedRegions != null && lineTypedRegions.length >= 1
                && (lineTypedRegions[0].getType().equals("org.eclipse.wst.html.HTML_DEFAULT")
                        || lineTypedRegions[0].getType().equals("com.dubture.twig.TWIG_DEFAULT"))) {

            // save the selection position since it will be changing
            Position selectionPosition = null;
            selectionPosition = new Position(textSelection.getOffset(), textSelection.getLength());
            document.addPosition(selectionPosition);

            model = StructuredModelManager.getModelManager().getModelForEdit(document);
            if (model != null) {
                // makes it so one undo will undo all the edits to the
                // document
                model.beginRecording(this, SSEUIMessages.ToggleComment_label,
                        SSEUIMessages.ToggleComment_description);

                // keeps listeners from doing anything until updates are all
                // done
                model.aboutToChangeModel();
                if (document instanceof IDocumentExtension4) {
                    session = ((IDocumentExtension4) document)
                            .startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
                }
                changed = true;

                // get the display for the editor if we can
                Display display = null;
                if (textEditor instanceof StructuredTextEditor) {
                    StructuredTextViewer viewer = ((StructuredTextEditor) textEditor).getTextViewer();
                    if (viewer != null) {
                        display = viewer.getControl().getDisplay();
                    }
                }

                // create the toggling operation
                IRunnableWithProgress toggleCommentsRunnable = new ToggleLinesRunnable(
                        model.getContentTypeIdentifier(), document, selectionStartLine, selectionEndLine,
                        display);

                // if toggling lots of lines then use progress monitor else
                // just
                // run the operation
                if ((selectionEndLine - selectionStartLine) > TOGGLE_LINES_MAX_NO_BUSY_INDICATOR
                        && display != null) {
                    ProgressMonitorDialog dialog = new ProgressMonitorDialog(display.getActiveShell());
                    dialog.run(false, true, toggleCommentsRunnable);
                } else {
                    toggleCommentsRunnable.run(new NullProgressMonitor());
                }
            }
        } else {
            org.eclipse.core.expressions.EvaluationContext evaluationContext = new org.eclipse.core.expressions.EvaluationContext(
                    null, "") {
                @Override
                public Object getVariable(String name) {
                    if (ISources.ACTIVE_EDITOR_NAME.equals(name)) {
                        return textEditor;
                    }
                    return null;
                }
            };
            org.eclipse.core.commands.ExecutionEvent executionEvent = new org.eclipse.core.commands.ExecutionEvent(
                    null, Collections.EMPTY_MAP, new Event(), evaluationContext);
            toggleLineCommentHandler.execute(executionEvent);
        }

    } catch (InvocationTargetException e) {
        Logger.logException("Problem running toggle comment progess dialog.", e); //$NON-NLS-1$
    } catch (InterruptedException e) {
        Logger.logException("Problem running toggle comment progess dialog.", e); //$NON-NLS-1$
    } catch (BadLocationException e) {
        Logger.logException("The given selection " + textSelection + " must be invalid", e); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (ExecutionException e) {
    } finally {
        // clean everything up
        if (session != null && document instanceof IDocumentExtension4) {
            ((IDocumentExtension4) document).stopRewriteSession(session);
        }

        if (model != null) {
            model.endRecording(this);
            if (changed) {
                model.changedModel();
            }
            model.releaseFromEdit();
        }
    }

}

From source file:com.github.haixing_hu.swt.window.ApplicationWindowEx.java

License:Open Source License

/**
 * This implementation of IRunnableContext#run(boolean, boolean,
 * IRunnableWithProgress) blocks until the runnable has been run,
 * regardless of the value of <code>fork</code>.
 * It is recommended that <code>fork</code> is set to
 * true in most cases. If <code>fork</code> is set to <code>false</code>,
 * the runnable will run in the UI thread and it is the runnable's
 * responsibility to call <code>Display.readAndDispatch()</code>
 * to ensure UI responsiveness.//from  w ww.  j  a va  2s  . c om
 */
@Override
public void run(final boolean fork, boolean cancelable, final IRunnableWithProgress runnable)
        throws InvocationTargetException, InterruptedException {
    try {
        operationInProgress = true;
        final StatusLineManager mgr = getStatusLineManager();
        if (mgr == null) {
            runnable.run(new NullProgressMonitor());
            return;
        }
        final boolean cancelWasEnabled = mgr.isCancelEnabled();

        final Control contents = getContents();
        final Display display = contents.getDisplay();
        final Shell shell = getShell();
        final boolean contentsWasEnabled = contents.getEnabled();
        MenuManagerEx manager = getMenuBarManager();
        Menu menuBar = null;
        if (manager != null) {
            menuBar = manager.getMenu();
            manager = null;
        }
        boolean menuBarWasEnabled = false;
        if (menuBar != null) {
            menuBarWasEnabled = menuBar.getEnabled();
        }

        final Control toolbarControl = getToolBarControl();
        boolean toolbarWasEnabled = false;
        if (toolbarControl != null) {
            toolbarWasEnabled = toolbarControl.getEnabled();
        }

        final Control coolbarControl = getCoolBarControl();
        boolean coolbarWasEnabled = false;
        if (coolbarControl != null) {
            coolbarWasEnabled = coolbarControl.getEnabled();
        }

        // Disable the rest of the shells on the current display
        final Shell[] shells = display.getShells();
        final boolean[] enabled = new boolean[shells.length];
        for (int i = 0; i < shells.length; i++) {
            final Shell current = shells[i];
            if (current == shell) {
                continue;
            }
            if ((current != null) && !current.isDisposed()) {
                enabled[i] = current.getEnabled();
                current.setEnabled(false);
            }
        }

        final Control currentFocus = display.getFocusControl();
        try {
            contents.setEnabled(false);
            if (menuBar != null) {
                menuBar.setEnabled(false);
            }
            if (toolbarControl != null) {
                toolbarControl.setEnabled(false);
            }
            if (coolbarControl != null) {
                coolbarControl.setEnabled(false);
            }
            mgr.setCancelEnabled(cancelable);
            final Exception[] holder = new Exception[1];
            BusyIndicator.showWhile(display, new Runnable() {
                @Override
                public void run() {
                    try {
                        ModalContext.run(runnable, fork, mgr.getProgressMonitor(), display);
                    } catch (final InvocationTargetException ite) {
                        holder[0] = ite;
                    } catch (final InterruptedException ie) {
                        holder[0] = ie;
                    }
                }
            });

            if (holder[0] != null) {
                if (holder[0] instanceof InvocationTargetException) {
                    throw (InvocationTargetException) holder[0];
                } else if (holder[0] instanceof InterruptedException) {
                    throw (InterruptedException) holder[0];
                }
            }
        } finally {
            operationInProgress = false;
            // Enable the rest of the shells on the current display
            for (int i = 0; i < shells.length; i++) {
                final Shell current = shells[i];
                if (current == shell) {
                    continue;
                }
                if ((current != null) && !current.isDisposed()) {
                    current.setEnabled(enabled[i]);
                }
            }
            if (!contents.isDisposed()) {
                contents.setEnabled(contentsWasEnabled);
            }
            if ((menuBar != null) && !menuBar.isDisposed()) {
                menuBar.setEnabled(menuBarWasEnabled);
            }
            if ((toolbarControl != null) && !toolbarControl.isDisposed()) {
                toolbarControl.setEnabled(toolbarWasEnabled);
            }
            if ((coolbarControl != null) && !coolbarControl.isDisposed()) {
                coolbarControl.setEnabled(coolbarWasEnabled);
            }
            mgr.setCancelEnabled(cancelWasEnabled);
            if ((currentFocus != null) && !currentFocus.isDisposed()) {
                // It's necessary to restore focus after reenabling the controls
                // because disabling them causes focus to jump elsewhere.
                // Use forceFocus rather than setFocus to avoid SWT's
                // search for children which can take focus, so focus
                // ends up back on the actual control that previously had it.
                currentFocus.forceFocus();
            }
        }
    } finally {
        operationInProgress = false;
    }
}

From source file:com.mentor.nucleus.bp.core.common.PersistableModelComponent.java

License:Open Source License

public void persist(IProgressMonitor monitor) throws CoreException {
    if (!isLoaded()) {
        // not loaded, ignore
        return;//from  ww w .  ja  v a2s .c o  m
    }

    // if the persistence version will change then persist the root component
    PersistenceManager.updatePersistenceVersion(this);

    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();

    IPath componentParentDirectory = getContainingDirectoryPath();
    IFolder containingFolder = workspaceRoot.getFolder(componentParentDirectory);
    if (!containingFolder.exists()) {
        if (!containingFolder.getParent().exists()) {
            // the persist is part of a deletion, and the parent has already
            // been deleted
            return;
        }
        containingFolder.create(true, true, monitor);
    }

    IFile file = getFile();

    persisting = true;
    // create an export-factory and have it perform the persistence
    AbstractModelExportFactory factory = AbstractModelExportFactory.getInstance();
    try {
        IRunnableWithProgress runnable = factory.create(componentRootME, file.getLocation().toString(), true);
        runnable.run(monitor);

        // get Eclipse to notice that the model's file has changed on disk
        containingFolder.refreshLocal(IFile.DEPTH_ONE, monitor);
    } catch (CoreException x) {
        CorePlugin.logError("Could not refresh persisted model file.", x);
    } catch (Exception e) {
        CorePlugin.logError("Could not persist model", e);
    } finally {
        persisting = false;
    }
}

From source file:com.mentor.nucleus.bp.core.ui.ConvertModel2UUIDAction.java

License:Open Source License

private void persistSingleFileModel(Ooaofooa mr, IFile file) {
    AbstractModelExportFactory factory = AbstractModelExportFactory.getInstance();

    try {/*from www. ja  va 2 s  . com*/
        IRunnableWithProgress runnable = factory.create(mr, file.getLocation().toString(), true);
        runnable.run(new NullProgressMonitor());
    } catch (Exception e) {
        CorePlugin.logError("Could not persist model", e);
    }

    // get Eclipse to notice that the model's file has changed on disk 
    try {
        file.refreshLocal(IFile.DEPTH_ZERO, new NullProgressMonitor());
    } catch (CoreException x) {
        CorePlugin.logError("Could not refresh persisted model file.", x);
    }

}

From source file:com.mentor.nucleus.bp.core.ui.CopyCutAction.java

License:Open Source License

public void run() {
    Clipboard cb = CorePlugin.getSystemClipboard();
    cb.clearContents();/*w  w  w . j a  v  a  2 s  .c  o m*/
    Object secondary = getSecondaryClipboardData();
    if (secondary != null && onlyIncludeSecondaryData()) {
        // this occurs when copy of element data is not
        // allowed, but image copy is
        cb.setContents(new Object[] { secondary }, new Transfer[] { getSecondaryTransfer() });
        return;
    }
    TransactionManager manager = getTransactionManager();
    Transaction transaction = null;
    int old_val = 0;
    try {
        // only start a transaction for a cut, this allows for
        // restoration via undo
        if (getActionType() == CUT_TYPE) {
            transaction = manager.startTransaction(transactioName,
                    new ModelRoot[] { Ooaofooa.getDefaultInstance(),
                            (ModelRoot) OoaofgraphicsUtil.getGraphicsRoot(Ooaofooa.DEFAULT_WORKING_MODELSPACE,
                                    OoaofgraphicsUtil.getGraphicsClass()) });
            Ooaofooa.beginSaveOperation();
            // only respond to DELETE events
            old_val = Ooaofooa.Enablemodelchangelistenersfor(Ooaofooa.getDefaultInstance(),
                    Modeleventnotification_c.DELTA_DELETE, Modeleventnotification_c.MODEL_ELEMENT_CHANGED);
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String streamContents = "";
        NonRootModelElement[] elements = getElementsToBeCopied(true);
        List<NonRootModelElement> elementList = Arrays.asList(elements);
        String packagingHeader = getPackagingHeaderFromElements(elementList);
        IRunnableWithProgress progress = CorePlugin.getStreamExportFactory().create(out, elements, true, false);
        progress.run(new NullProgressMonitor());
        out.close();
        streamContents = new String(out.toByteArray());
        streamContents = streamContents.replaceFirst("\n", "\n" + packagingHeader + "\n");
        if (secondary == null) {
            cb.setContents(new Object[] { streamContents }, new Transfer[] { TextTransfer.getInstance() });
        } else {
            cb.setContents(new Object[] { streamContents, secondary },
                    new Transfer[] { TextTransfer.getInstance(), getSecondaryTransfer() });
        }
        postRun();
    } catch (Exception e) {
        if (getActionType() == CUT_TYPE) {
            if (transaction != null && manager != null && manager.getActiveTransaction() == transaction) {
                manager.cancelTransaction(transaction, e);
                transaction = null;
            }
        }
        // log error
        CorePlugin.logError("Exception during cut/copy of selection.", e);
    } finally {
        if (transaction != null)
            manager.endTransaction(transaction);
        if (getActionType() == CUT_TYPE) {
            Ooaofooa.Enablemodelchangelistenersfor(Ooaofooa.getDefaultInstance(), old_val, old_val);
            Ooaofooa.endSaveOperation();
        }
    }
}

From source file:com.mentor.nucleus.bp.core.ui.NewDomainWizard.java

License:Open Source License

public boolean createDomain(IWizardContainer container, ProgressMonitorDialog dialog) {
    IProject project = (IProject) m_sys.getAdapter(IProject.class);
    String domainName = PersistenceManager.getDefaultInstance()
            .getUniqueNameOfParent(m_sys.getPersistableComponent(), m_domainName, null);
    final String id = Ooaofooa.createModelRootId(project, domainName, true);
    final Ooaofooa modelRoot = Ooaofooa.getInstance(id, false);
    String message = "";//$NON-NLS-1$
    if (container != null && dialog == null)
        dialog = new ProgressMonitorDialog(getShell());

    if (!m_useTemplate) {
        final CorePlugin plugin = CorePlugin.getDefault();
        URL installURL = plugin.getBundle().getEntry("/");//$NON-NLS-1$
        try {/*from   w  w  w .j  a va  2  s  .co m*/
            URL url = new URL(installURL, Ooaofooa.MODELS_DIRNAME + "/default." + Ooaofooa.MODELS_EXT); //$NON-NLS-1$
            final InputStream inStream = url.openStream();
            ImportStreamStatus iss = new ImportStreamStatus(id, inStream);
            if (container == null) {
                iss.run(new NullProgressMonitor());
            } else {
                dialog.run(true, false, iss);
            }
            message = iss.getMessage();
            try {
                inStream.close();
            } catch (IOException e2) {
                /* do nothing */ }
        } catch (IOException e1) {
            CorePlugin.logError("Internal error: failed to open default." + Ooaofooa.MODELS_EXT, e1);//$NON-NLS-1$
            return false;
        } catch (InterruptedException e) {
            CorePlugin.logError("Internal error: import was interrupted", e); //$NON-NLS-1$
            return false;
        } catch (InvocationTargetException e) {
            CorePlugin.logError("Internal error: plugin.doLoad not found", e); //$NON-NLS-1$
            return false;
        }
    } else {
        String templateFileName = m_templateFile;
        final IPath templatePath = new Path(templateFileName);
        // import the domain file into the model root with the id of the full path of the domain file
        if (templatePath.getFileExtension().equals(Ooaofooa.MODELS_EXT)) {
            final InputStream inStream;
            try {
                inStream = new FileInputStream(templatePath.toFile());
            } catch (FileNotFoundException e) {
                CorePlugin.logError("Internal error: failed to open " + templateFileName, e);
                return false;
            }
            try {
                ImportStreamStatus iss = new ImportStreamStatus(id, inStream);
                if (container == null) {
                    // for unit tests to prevent displaying progress dialogs
                    iss.run(new NullProgressMonitor());
                } else {
                    dialog.run(true, false, iss);
                }
                message = iss.getMessage();
                inStream.close();
            } catch (InterruptedException e) {
                CorePlugin.logError("Internal error: import was interrupted", e); //$NON-NLS-1$
                return false;
            } catch (InvocationTargetException e) {
                CorePlugin.logError("Internal error: plugin.doLoad not found", e); //$NON-NLS-1$
                return false;
            } catch (IOException e) {
                CorePlugin.logError("Unable to close stream to import file.", e); //$NON-NLS-1$
                /* do nothing */
            }
        } else {
            try {
                ImportFileStatus ifs = new ImportFileStatus(id, templatePath.toFile());
                if (container == null) {
                    // For unit tests.
                    ifs.run(new NullProgressMonitor());
                } else {
                    dialog.run(true, false, ifs);
                }
                message = ifs.getMessage();
            } catch (InterruptedException e) {
                CorePlugin.logError("Internal error: import was interrupted", e); //$NON-NLS-1$
                return false;
            } catch (InvocationTargetException e) {
                CorePlugin.logError("Internal error: plugin.doLoad not found", e); //$NON-NLS-1$
                return false;
            }
        }
        if (!message.equals("")) {
            CorePlugin.showImportErrorMessage(true, message);
            return true;
        }
    }
    // set the just loaded Domain instance name to the name specified by the user
    final Domain_c dom = Domain_c.DomainInstance(modelRoot, null, false);
    if (dom == null) {
        // There was a load error, already logged
        return false;
    }
    dom.setName(Ooaofooa.Getuniqueinitialname(modelRoot, m_domainName, dom.Converttoinstance()));
    IDConvertor.getInstance().recreateUUID(dom);

    // Create a PMC for the new domain
    try {
        if (dom.getPersistableComponent() == null) {
            PersistenceManager.getDefaultInstance().registerModel(dom, project);
        }
        IRunnableWithProgress persistenceRunnable = new IRunnableWithProgress() {

            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    monitor.beginTask("Persisting newly created model...", getComponentCount(dom));
                    persistSelfAndChildren(dom, monitor);
                    displayDuplicateDialog();
                    monitor.done();
                } catch (CoreException e) {
                    CorePlugin.logError("Unable to persist newly created model.", e);
                } finally {
                    duplicateNames.clear();
                }
            }

        };
        if (m_parseOnImport) {
            try {
                if (container == null) {
                    // For unit tests.
                    CorePlugin.parseAll(dom, new NullProgressMonitor());
                } else {
                    dialog.run(false, false, new IRunnableWithProgress() {

                        public void run(IProgressMonitor monitor)
                                throws InvocationTargetException, InterruptedException {
                            CorePlugin.parseAll(dom, monitor);
                        }

                    });
                }
            } catch (InvocationTargetException e) {
                CorePlugin.logError("Unable to parse model", e);
            } catch (InterruptedException e) {
                CorePlugin.logError("Unable to parse model", e);
            }
        }

        OALPersistenceUtil.persistOAL(modelRoot);

        if (container == null) {
            persistenceRunnable.run(new NullProgressMonitor());
        } else {
            dialog.run(false, false, persistenceRunnable);
        }
    } catch (CoreException e) {
        CorePlugin.logError("Unable to register model", e);
    } catch (InvocationTargetException e) {
        CorePlugin.logError("Unable to persist newly created model.", e);
    } catch (InterruptedException e) {
        CorePlugin.logError("Unable to persist newly created model.", e);
    }
    return true;
}

From source file:com.mentor.nucleus.bp.io.core.CoreExport.java

License:Open Source License

/**
 * Parse the specified element.  //w w  w.  ja  v a2  s. c  o  m
 * 
 * @arg The element to parse.  Currently this routine can only parse elements
 *      of type Domain_c or Component_c
 */
private void parseOneElement(final NonRootModelElement selectedElement, final IProgressMonitor monitor,
        Shell dialogShell) throws InvocationTargetException, InterruptedException {

    final String className = selectedElement.getClass().getName();
    final String instanceName = selectedElement.getName();

    errorLoggedDuringParse = false;

    // This does mean that if the element passed-in is not one we know
    // how to parse this routine returns success
    if ((selectedElement instanceof Domain_c) || (selectedElement instanceof Component_c)
            || (selectedElement instanceof Package_c) || (selectedElement instanceof Subsystem_c)
            || (selectedElement instanceof FunctionPackage_c)
            || (selectedElement instanceof ExternalEntityPackage_c)) {
        final NonRootModelElement nrme = selectedElement;
        IRunnableWithProgress rwp = new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                if (monitor != null) {
                    monitor.subTask("Parsing " + instanceName);
                }

                ParserAllActivityModifier aam = null;
                boolean workBenchIsRunning = PlatformUI.isWorkbenchRunning();
                if (nrme instanceof Domain_c) {
                    if (workBenchIsRunning) {
                        aam = new AllActivityModifier((Domain_c) nrme, monitor);
                    } else {
                        aam = new ParserAllActivityModifier((Domain_c) nrme, monitor);
                    }
                } else if (nrme instanceof Component_c) {
                    if (workBenchIsRunning) {
                        aam = new AllActivityModifier((Component_c) nrme, monitor);
                    } else {
                        aam = new ParserAllActivityModifier((Component_c) nrme, monitor);
                    }
                } else if (nrme instanceof Package_c) {
                    if (workBenchIsRunning) {
                        aam = new AllActivityModifier((Package_c) nrme, monitor);
                    } else {
                        aam = new ParserAllActivityModifier((Package_c) nrme, monitor);
                    }
                } else if (nrme instanceof Subsystem_c) {
                    if (workBenchIsRunning) {
                        aam = new AllActivityModifier((Subsystem_c) nrme, monitor);
                    } else {
                        aam = new ParserAllActivityModifier((Subsystem_c) nrme, monitor);
                    }
                } else if (nrme instanceof FunctionPackage_c) {
                    if (workBenchIsRunning) {
                        aam = new AllActivityModifier((FunctionPackage_c) nrme, monitor);
                    } else {
                        aam = new ParserAllActivityModifier((FunctionPackage_c) nrme, monitor);
                    }
                } else if (nrme instanceof ExternalEntityPackage_c) {
                    if (workBenchIsRunning) {
                        aam = new AllActivityModifier((ExternalEntityPackage_c) nrme, monitor);
                    } else {
                        aam = new ParserAllActivityModifier((ExternalEntityPackage_c) nrme, monitor);
                    }
                }

                if (aam != null) {
                    aam.processAllActivities(ParserAllActivityModifier.PARSE, false);
                }

                if (monitor != null) {
                    monitor.done();
                }
            }
        };

        // parse the element
        if (dialogShell == null) {
            if (monitor == null) {
                rwp.run(new NullProgressMonitor());
            } else {
                rwp.run(monitor);
            }
        } else {
            new ProgressMonitorDialog(dialogShell).run(true, false, rwp);
        }

    } else {
        // Log a warning that we received an element type that this
        // routine will not parse.  This really shouldn't happen.  If it
        // does it means something is being exported that may include OAL
        // that is not being persisted in the export.
        String message = "Warning: CoreExport.parseOneElement() received an element that will not be parsed.  ";
        message += "Class: " + className + "  Instance: " + instanceName;
        CorePlugin.logError(message, null);
    }

    if (!CoreUtil.IsRunningHeadless) {
        // Make sure that all events in the asynchronous event queue
        // are dispatched. This is here is help assure that parse errors
        // are detected by the ILogListener
        PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
            public void run() {
                // do nothing
            }
        });
    }

    if (errorLoggedDuringParse) {
        String message = "Warning: Parse errors encountered prior to model export.  ";
        message += "Class: " + className + "  Instance: " + instanceName;
        CorePlugin.logError(message, null);
    }
}

From source file:com.mentor.nucleus.bp.io.mdl.wizards.ModelExportWizard.java

License:Open Source License

/**
 * //from w ww.  j  a va  2  s  . c  o  m
 * @return true is the export was created with the prefernece to enable
 *              export of executable oal instance and false if not.
 *              
 * @throws FileNotFoundException
 * @throws InterruptedException
 * @throws InvocationTargetException
 */
private boolean createExportProcessor()
        throws FileNotFoundException, InterruptedException, InvocationTargetException {
    // we need to add the GD_GE instances for those elements
    // selected
    List<NonRootModelElement> elements = new ArrayList<NonRootModelElement>();
    final NonRootModelElement[] selectedElements = Selection.getInstance().getSelectedNonRootModelElements();

    IRunnableWithProgress runnableLoader = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) {
            // here we force load the selected elements to
            // prevent outputting null ids (which can happen
            // in certain circumstances) issue 3303 may
            // fix this at which point this code can be
            // removed
            for (int i = 0; i < selectedElements.length; i++) {
                PersistableModelComponent component = selectedElements[i].getPersistableComponent();
                component.loadComponentAndChildren(monitor);
            }
        }
    };

    if (getContainer() == null) {
        runnableLoader.run(new NullProgressMonitor());
    } else {
        new ProgressMonitorDialog(getContainer().getShell()).run(true, false, runnableLoader);
    }

    for (int i = 0; i < selectedElements.length; i++) {
        elements.add(selectedElements[i]);
    }
    addGraphicalElementsFor(selectedElements, elements);
    outStream = new ByteArrayOutputStream();
    exporter = com.mentor.nucleus.bp.core.CorePlugin.getStreamExportFactory().create(outStream,
            elements.toArray(new NonRootModelElement[elements.size()]), true, true);
    boolean exportOALInstances = false;
    if (exporter instanceof CoreExport) {

        ((CoreExport) exporter).setExportGraphics(CoreExport.USER_PREFERENCE);
        // Check the license.  This tests the license without checking it out.  If there is
        // no availble license this will return false.
        exportOALInstances = ((CoreExport) exporter).setExportOAL(CoreExport.USER_PREFERENCE);
    }
    return exportOALInstances;
}