Example usage for org.eclipse.jface.dialogs MessageDialog QUESTION_WITH_CANCEL

List of usage examples for org.eclipse.jface.dialogs MessageDialog QUESTION_WITH_CANCEL

Introduction

In this page you can find the example usage for org.eclipse.jface.dialogs MessageDialog QUESTION_WITH_CANCEL.

Prototype

int QUESTION_WITH_CANCEL

To view the source code for org.eclipse.jface.dialogs MessageDialog QUESTION_WITH_CANCEL.

Click Source Link

Document

Constant for a simple dialog with the question image and Yes/No/Cancel buttons (value 6).

Usage

From source file:com.amazonaws.eclipse.elasticbeanstalk.jobs.TerminateEnvironmentJob.java

License:Open Source License

@Override
protected IStatus run(IProgressMonitor monitor) {
    AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId())
            .getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
    EnvironmentBehavior behavior = (EnvironmentBehavior) environment.getServer()
            .loadAdapter(EnvironmentBehavior.class, monitor);

    final DialogHolder dialogHolder = new DialogHolder();
    Display.getDefault().syncExec(new Runnable() {
        public void run() {
            MessageDialog dialog = new MessageDialog(Display.getDefault().getActiveShell(),
                    "Confirm environment termination",
                    AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON),
                    "Are you sure you want to terminate the environment " + environment.getEnvironmentName()
                            + "?  All EC2 instances in the environment will be terminated and you will be unable to use "
                            + "this environment again until you have recreated it.",
                    MessageDialog.QUESTION_WITH_CANCEL, new String[] { "OK", "Cancel" }, 1);
            dialogHolder.dialog = dialog;
            dialog.open();/*from w ww  .j a  v  a 2 s.c o  m*/
        }
    });

    if (dialogHolder.dialog.getReturnCode() != 0) {
        behavior.updateServerState(IServer.STATE_STOPPED);
        return Status.OK_STATUS;
    }

    try {
        if (doesEnvironmentExist()) {
            client.terminateEnvironment(
                    new TerminateEnvironmentRequest().withEnvironmentName(environment.getEnvironmentName()));
        }

        // It's more correct to set the state to stopping, rather than stopped immediately, 
        // but if we set it to stopping, WTP will block workspace actions waiting for the 
        // environment's state to get updated to stopped.  To prevent this, we stop immediately.
        behavior.updateServerState(IServer.STATE_STOPPED);
        return Status.OK_STATUS;
    } catch (AmazonClientException ace) {
        return new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Unable to terminate environment "
                + environment.getEnvironmentName() + " : " + ace.getMessage(), ace);
    }
}

From source file:com.appnativa.studio.Studio.java

License:Open Source License

public static Boolean yesNoCancel(String message) {
    int ret = MessageDialogEx.openEx(MessageDialog.QUESTION_WITH_CANCEL, Display.getDefault().getActiveShell(),
            getResourceAsString("Studio.title"), message, SWT.NONE);

    if (ret == 2) {
        return null;
    }//from ww w .j  ava  2 s . c  o  m

    return ret == 0;
}

From source file:com.arm.cmsis.pack.installer.CpPackInstaller.java

License:Open Source License

protected int timeoutQuestion(String pdscUrl) {
    Display.getDefault().syncExec(() -> {
        MessageDialog dialog = new MessageDialog(null, Messages.CpPackInstaller_Timout, null,
                NLS.bind(Messages.CpPackInstaller_TimeoutMessage, pdscUrl, TIME_OUT / 1000),
                MessageDialog.QUESTION_WITH_CANCEL, new String[] { IDialogConstants.YES_LABEL,
                        IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL },
                0);// w  w w.  jav a  2  s .  c  om
        wait = dialog.open();
    });
    return wait;
}

From source file:com.bdaum.zoom.ui.internal.dialogs.VoiceNoteDialog.java

License:Open Source License

private void importFile(IDialogSettings settings) {
    FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);
    switch (tabFolder.getSelectionIndex()) {
    case VOICE://from   w  ww  .ja va  2  s .c o m
        int l = Constants.SupportedSoundFileExtensions.length;
        String[] supportedsoundfileextensions = new String[l];
        for (int i = 0; i < l - 1; i++)
            supportedsoundfileextensions[i] = Constants.SupportedSoundFileExtensions[i] + ";" //$NON-NLS-1$
                    + supportedsoundfileextensions[i].toUpperCase();
        supportedsoundfileextensions[l - 1] = Constants.SupportedSoundFileExtensions[l - 1];
        dialog.setFilterExtensions(supportedsoundfileextensions);
        dialog.setFilterNames(Constants.SupportedSoundFileNames);
        String soundFile = settings.get(SOUNDFILE);
        if (soundFile != null)
            dialog.setFileName(soundFile);
        String file = dialog.open();
        if (file != null) {
            settings.put(SOUNDFILE, file);
            outputFile = new File(file);
            targetUri = sourceUri = outputFile.toURI().toString();
            dirty = true;
            updateButtons();
        }
        return;
    case TEXT:
        dialog.setFilterExtensions(new String[] { "*.txt;*.TXT" }); //$NON-NLS-1$
        dialog.setFilterNames(new String[] { Messages.VoiceNoteDialog_textfiles });
        String textFile = settings.get(TEXTFILE);
        if (textFile != null)
            dialog.setFileName(textFile);
        file = dialog.open();
        if (file != null) {
            settings.put(TEXTFILE, file);
            try {
                String s = readTextfile(file);
                int ret = 1;
                if (!note.getText().isEmpty()) {
                    AcousticMessageDialog mdialog = new AcousticMessageDialog(getShell(),
                            Messages.VoiceNoteDialog_overwrite_text, null, Messages.VoiceNoteDialog_text_exists,
                            MessageDialog.QUESTION_WITH_CANCEL, new String[] { Messages.VoiceNoteDialog_append,
                                    Messages.VoiceNoteDialog_overwrite, IDialogConstants.CANCEL_LABEL },
                            0);
                    ret = mdialog.open();
                    if (ret == 2)
                        return;
                }
                note.setText(ret == 1 ? s : note.getText() + '\n' + s);
                dirty = true;
                updateButtons();
            } catch (IOException e1) {
                note.setText(Messages.VoiceNoteDialog_io_error);
            }
        }
        return;
    case DRAWING:
        dialog.setFilterExtensions(new String[] { "*.zdrw" }); //$NON-NLS-1$
        dialog.setFilterNames(new String[] { NLS.bind(Messages.VoiceNoteDialog_zdrw, Constants.APPNAME) });
        textFile = settings.get(SVGFILE);
        if (textFile != null)
            dialog.setFileName(textFile);
        file = dialog.open();
        if (file != null) {
            settings.put(SVGFILE, file);
            try {
                String s = readTextfile(file);
                int ret = 1;
                if (paintExample.hasVectorFigure()) {
                    AcousticMessageDialog mdialog = new AcousticMessageDialog(getShell(),
                            Messages.VoiceNoteDialog_overwrite_drawing, null,
                            Messages.VoiceNoteDialog_drawing_exists, MessageDialog.QUESTION_WITH_CANCEL,
                            new String[] { Messages.VoiceNoteDialog_append, Messages.VoiceNoteDialog_overwrite,
                                    IDialogConstants.CANCEL_LABEL },
                            0);
                    ret = mdialog.open();
                    if (ret == 2)
                        return;
                }
                paintExample.importSvg(s, ret == 1);
                dirty = true;
                updateButtons();
            } catch (IOException e1) {
                AcousticMessageDialog.openError(getShell(), Messages.VoiceNoteDialog_error_reading_drawing,
                        NLS.bind(Messages.VoiceNoteDialog_io_error_reading_drawing, e1));
            } catch (ParserConfigurationException | SAXException e) {
                AcousticMessageDialog.openError(getShell(), Messages.VoiceNoteDialog_error_reading_drawing,
                        NLS.bind(Messages.VoiceNoteDialog_invalid_drawing, e));
            }
        }
    }
}

From source file:com.centurylink.mdw.plugin.actions.WorkflowElementActionHandler.java

License:Apache License

public void run(Object element) {
    if (element instanceof WorkflowProcess) {
        WorkflowProcess processVersion = (WorkflowProcess) element;
        IEditorPart editorPart = findOpenEditor(processVersion);
        if (editorPart != null && editorPart.isDirty()) {
            if (MessageDialog.openQuestion(getShell(), "Process Launch",
                    "Save process '" + processVersion.getLabel() + "' before launching?"))
                editorPart.doSave(new NullProgressMonitor());
        }/*ww w .  j  av a  2 s  . com*/

        if (MdwPlugin.getDefault().getPreferenceStore()
                .getBoolean(PreferenceConstants.PREFS_WEB_BASED_PROCESS_LAUNCH)) {
            // web-based process launch
            try {
                IViewPart viewPart = getPage().showView("mdw.views.designer.process.launch");
                if (viewPart != null) {
                    ProcessLaunchView launchView = (ProcessLaunchView) viewPart;
                    launchView.setProcess(processVersion);
                }
            } catch (PartInitException ex) {
                PluginMessages.log(ex);
            }
        } else {
            if (editorPart == null) {
                // process must be open
                open((WorkflowElement) element);
            }
            ProcessLaunchShortcut launchShortcut = new ProcessLaunchShortcut();
            launchShortcut.launch(new StructuredSelection(processVersion), ILaunchManager.RUN_MODE);
        }
    } else if (element instanceof Activity) {
        Activity activity = (Activity) element;
        WorkflowProcess processVersion = activity.getProcess();

        IEditorPart editorPart = findOpenEditor(processVersion);
        if (editorPart != null && editorPart.isDirty()) {
            if (MessageDialog.openQuestion(getShell(), "Activity Launch",
                    "Save process '" + processVersion.getLabel() + "' before launching?"))
                editorPart.doSave(new NullProgressMonitor());
        }

        ActivityLaunchShortcut launchShortcut = new ActivityLaunchShortcut();
        launchShortcut.launch(new StructuredSelection(activity), ILaunchManager.RUN_MODE);
    } else if (element instanceof ExternalEvent) {
        ExternalEvent externalEvent = (ExternalEvent) element;
        ExternalEventLaunchShortcut launchShortcut = new ExternalEventLaunchShortcut();
        launchShortcut.launch(new StructuredSelection(externalEvent), ILaunchManager.RUN_MODE);
    } else if (element instanceof Template) {
        Template template = (Template) element;
        IEditorPart editorPart = template.getFileEditor();
        if (editorPart != null && editorPart.isDirty()) {
            if (MessageDialog.openQuestion(getShell(), "Run Template",
                    "Save template '" + template.getName() + "' before running?"))
                editorPart.doSave(new NullProgressMonitor());
        }

        template.openFile(new NullProgressMonitor());
        new TemplateRunDialog(getShell(), template).open();
    } else if (element instanceof Page) {
        Page page = (Page) element;
        IEditorPart editorPart = page.getFileEditor();
        if (editorPart != null) {
            if (editorPart.isDirty()) {
                if (MessageDialog.openQuestion(getShell(), "Run Page",
                        "Save page '" + page.getName() + "' before running?"))
                    editorPart.doSave(new NullProgressMonitor());
            }
        }
        page.run();
    } else if (element instanceof WorkflowProject || element instanceof ServerSettings) {
        ServerSettings serverSettings;
        if (element instanceof WorkflowProject) {
            WorkflowProject workflowProject = (WorkflowProject) element;
            if (workflowProject.isRemote())
                throw new IllegalArgumentException("Cannot run server for remote projects.");
            serverSettings = workflowProject.getServerSettings();
        } else {
            serverSettings = (ServerSettings) element;
        }

        if (ServerRunner.isServerRunning()) {
            String question = "A server may be running already.  Shut down the currently-running server?";
            MessageDialog dlg = new MessageDialog(getShell(), "Server Running", null, question,
                    MessageDialog.QUESTION_WITH_CANCEL, new String[] { "Shutdown", "Ignore", "Cancel" }, 0);
            int res = dlg.open();
            if (res == 0)
                new ServerRunner(serverSettings, getShell().getDisplay()).stop();
            else if (res == 2)
                return;
        }

        if (serverSettings.getHome() == null && element instanceof WorkflowProject) {
            final IProject project = serverSettings.getProject().isCloudProject()
                    ? serverSettings.getProject().getSourceProject()
                    : serverSettings.getProject().getEarProject();
            @SuppressWarnings("restriction")
            org.eclipse.ui.internal.dialogs.PropertyDialog dialog = org.eclipse.ui.internal.dialogs.PropertyDialog
                    .createDialogOn(getShell(), "mdw.workflow.mdwServerConnectionsPropertyPage", project);
            if (dialog != null)
                dialog.open();
        } else {
            IPreferenceStore prefStore = MdwPlugin.getDefault().getPreferenceStore();
            if (element instanceof WorkflowProject)
                prefStore.setValue(PreferenceConstants.PREFS_SERVER_WF_PROJECT,
                        ((WorkflowProject) element).getName());
            else
                prefStore.setValue(PreferenceConstants.PREFS_RUNNING_SERVER, serverSettings.getServerName());

            ServerRunner runner = new ServerRunner(serverSettings, getShell().getDisplay());
            if (serverSettings.getProject() != null)
                runner.setJavaProject(serverSettings.getProject().getJavaProject());
            runner.start();
        }
    }
}

From source file:com.ecfeed.ui.wizards.NewEctFileCreationPage.java

License:Open Source License

public boolean performFinish() {
    IFile file = fPage.createNewFile();/*from ww  w.  j a va 2  s.  c  o m*/
    try {
        if (file.getContents().read() != -1) {
            MessageDialog dialog = new MessageDialog(getShell(), Messages.WIZARD_FILE_EXISTS_TITLE,
                    Display.getDefault().getSystemImage(SWT.ICON_QUESTION), Messages.WIZARD_FILE_EXISTS_MESSAGE,
                    MessageDialog.QUESTION_WITH_CANCEL,
                    new String[] { IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL },
                    IDialogConstants.OK_ID);
            if (dialog.open() != IDialogConstants.OK_ID) {
                return false;
            }
        }

        final IPath newFileFullPath = fPage.getContainerFullPath().append(fPage.getFileName());
        String modelName = newFileFullPath.removeFileExtension().lastSegment();
        RootNode model = new RootNode(modelName != null ? modelName : Constants.DEFAULT_NEW_ECT_MODEL_NAME,
                ModelVersionDistributor.getCurrentVersion());

        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        new EctSerializer(ostream, ModelVersionDistributor.getCurrentVersion()).serialize(model);
        ByteArrayInputStream istream = new ByteArrayInputStream(ostream.toByteArray());
        file.setContents(istream, true, true, null);

        //open new file in an ect editor
        IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

        page.openEditor(new FileEditorInput(file), Constants.ECT_EDITOR_ID);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return true;
}

From source file:com.heroku.eclipse.ui.git.HerokuCredentialsProvider.java

License:Open Source License

/**
 * Opens a dialog for a single non-user, non-password type item.
 * @param shell the shell to use//from   ww  w.  ja va 2 s.com
 * @param uri the uri of the get request
 * @param item the item to handle
 * @return <code>true</code> if the request was successful and values were supplied;
 *       <code>false</code> if the user canceled the request and did not supply all requested values.
 */
private boolean getSingleSpecial(Shell shell, URIish uri, CredentialItem item) {
    if (item instanceof CredentialItem.InformationalMessage) {
        MessageDialog.openInformation(shell, UIText.EGitCredentialsProvider_information, item.getPromptText());
        return true;
    } else if (item instanceof CredentialItem.YesNoType) {
        CredentialItem.YesNoType v = (CredentialItem.YesNoType) item;
        String[] labels = new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL,
                IDialogConstants.CANCEL_LABEL };
        int[] resultIDs = new int[] { IDialogConstants.YES_ID, IDialogConstants.NO_ID,
                IDialogConstants.CANCEL_ID };

        MessageDialog dialog = new MessageDialog(shell, UIText.EGitCredentialsProvider_question, null,
                item.getPromptText(), MessageDialog.QUESTION_WITH_CANCEL, labels, 0);
        dialog.setBlockOnOpen(true);
        int r = dialog.open();
        if (r < 0) {
            return false;
        }

        switch (resultIDs[r]) {
        case IDialogConstants.YES_ID: {
            v.setValue(true);
            return true;
        }
        case IDialogConstants.NO_ID: {
            v.setValue(false);
            return true;
        }
        default:
            // abort
            return false;
        }
    } else {
        // generically handles all other types of items
        return getMultiSpecial(shell, uri, item);
    }
}

From source file:com.netxforge.netxstudio.screens.editing.CDOScreenFormService.java

License:Open Source License

/**
 * Warns if the current screen is dirty, if not saving, flush the command
 * stack. If saving, save depending on the screen type.
 * /*w w  w.  ja va  2s .  c o  m*/
 * @return false if cancelled
 */
public boolean dirtyWarning() {
    // Warn for unsaved changes.
    if (getCDOEditingService().isDirty()) {

        CDOView view = getCDOEditingService().getView();
        if (view instanceof CDOTransaction) {
            StudioUtils.cdoDumpDirtyObject((CDOTransaction) view);

            int result = DirtyStateMessageDialog.openAndReturn(MessageDialog.QUESTION_WITH_CANCEL,
                    Display.getCurrent().getActiveShell(), "Save needed",
                    "You have unsaved changes, which will be discarded when not saved, save?",
                    (CDOTransaction) view);

            switch (result) {

            case DirtyStateMessageDialog.OK: {
                if (getActiveScreen() instanceof IDataScreenInjection) {
                    ((IDataScreenInjection) getActiveScreen()).addData();
                } else {
                    getCDOEditingService().doSave(new NullProgressMonitor());
                }
            }
                break;
            case 1: // NO
                undoAndFlush();
                break;
            case 2: // CANCEL;
                return true;
            }
        }

    } else {
        // Flush the stack anyway.
        getCDOEditingService().getEditingDomain().getCommandStack().flush();
    }
    return false;
}

From source file:com.netxforge.netxstudio.screens.f2.details.NewEditNode.java

License:Open Source License

private void buildInfoSection() {
    Section scnInfo = toolkit.createSection(this, Section.EXPANDED | Section.TITLE_BAR);
    toolkit.paintBordersFor(scnInfo);/*from  w ww  .j  av  a  2  s  .com*/
    scnInfo.setText("Info");

    Composite composite = toolkit.createComposite(scnInfo, SWT.NONE);
    toolkit.paintBordersFor(composite);
    scnInfo.setClient(composite);
    composite.setLayout(new GridLayout(4, false));

    Label lblName = toolkit.createLabel(composite, "NE ID:", SWT.NONE);
    lblName.setAlignment(SWT.RIGHT);
    GridData gd_lblName = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
    gd_lblName.widthHint = 80;
    lblName.setLayoutData(gd_lblName);

    txtName = toolkit.createText(composite, "New Text", SWT.NONE | widgetStyle);
    txtName.setText("");
    GridData gd_txtName = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
    gd_txtName.widthHint = 150;
    txtName.setLayoutData(gd_txtName);
    new Label(composite, SWT.NONE);
    new Label(composite, SWT.NONE);

    Label lblType = toolkit.createLabel(composite, "Type:", SWT.NONE);
    lblType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));

    txtNodeType = toolkit.createText(composite, "New Text", SWT.NONE | SWT.READ_ONLY);
    txtNodeType.setText("");
    txtNodeType.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));

    if (!readonly) {
        nodeTypeRemoveHyperlink = toolkit.createImageHyperlink(composite, SWT.NONE);
        nodeTypeRemoveHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
            public void linkActivated(HyperlinkEvent e) {

                final CompoundCommand cp = new CompoundCommand();
                final NodeType nt = node.getNodeType();
                if (nt != null) {
                    final Command dc = WarningDeleteCommand.create(editingService.getEditingDomain(), nt);
                    cp.append(dc);
                }
                if (node.eIsSet(OperatorsPackage.Literals.NODE__ORIGINAL_NODE_TYPE_REF)) {
                    final SetCommand sc = new SetCommand(editingService.getEditingDomain(), node,
                            OperatorsPackage.Literals.NODE__ORIGINAL_NODE_TYPE_REF, null);
                    cp.append(sc);
                }

                // We can't really do this, as our object will be
                // dangling.
                // Command c = new
                // SetCommand(editingService.getEditingDomain(),
                // node, OperatorsPackage.Literals.NODE__NODE_TYPE,
                // null);
                editingService.getEditingDomain().getCommandStack().execute(cp);
            }
        });
        GridData gd_imageHyperlink_1 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
        gd_imageHyperlink_1.widthHint = 18;
        nodeTypeRemoveHyperlink.setLayoutData(gd_imageHyperlink_1);
        nodeTypeRemoveHyperlink
                .setImage(ResourceManager.getPluginImage("org.eclipse.ui", "/icons/full/etool16/delete.gif"));
        toolkit.paintBordersFor(nodeTypeRemoveHyperlink);
        nodeTypeRemoveHyperlink.setText("");

        Button btnSelectNodeType = toolkit.createButton(composite, "Select...", SWT.NONE);
        btnSelectNodeType.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                Resource nodeTypeResource = editingService.getData(LibraryPackage.Literals.NODE_TYPE);
                NodeTypeFilterDialog dialog = new NodeTypeFilterDialog(NewEditNode.this.getShell(),
                        nodeTypeResource);

                int result = dialog.open();
                if (result == IDialogConstants.OK_ID) {
                    NodeType nt = (NodeType) dialog.getFirstResult();
                    // Ask the user if the node should be replaced,
                    // or simply set as the original node type.
                    int strategy = MessageDialogWithResult.openWithResult(MessageDialog.QUESTION_WITH_CANCEL,
                            NewEditNode.this.getShell(), "Network Element Type Option",
                            " Choose to select parts from the original Network Element Type: " + nt.getName()
                                    + "?\n" + " When selecting \'No\' the structure of \'" + node.getNodeID()
                                    + "\' will be replaced by the original network "
                                    + "Element Type structure\n (WARNING: Choosing \'No\' will replace the current structure, all editing will be lost)",
                            SWT.NONE);
                    switch (strategy) {
                    case MessageDialogWithResult.OK: {
                        handleSetOriginalNodeType(nt);
                        break;
                    }
                    case 1: { // NO
                        handleNodeTypeCopy(nt);
                        break;
                    }
                    case 2: {// CANCEL
                    }
                    }
                }
            }

            private void handleSetOriginalNodeType(NodeType nt) {

                CompoundCommand cc = new CompoundCommand();

                // Create a node type, if we don't have any. This case happens when selecting 'Yes' when asked if the structured should be copied, 
                // but no original type has been set earlier. (Or has been cleared before). 
                if (!node.eIsSet(OperatorsPackage.Literals.NODE__NODE_TYPE)) {

                    NodeType createNodeType = LibraryFactory.eINSTANCE.createNodeType();
                    createNodeType.setName(nt.getName());

                    Command setNodeTypeCommand = new SetCommand(editingService.getEditingDomain(), node,
                            OperatorsPackage.Literals.NODE__NODE_TYPE, createNodeType);
                    cc.append(setNodeTypeCommand);
                }

                Command setOriginalNodeTypeRef = new SetCommand(editingService.getEditingDomain(), node,
                        OperatorsPackage.Literals.NODE__ORIGINAL_NODE_TYPE_REF, nt);

                cc.append(setOriginalNodeTypeRef);

                editingService.getEditingDomain().getCommandStack().execute(cc);
            }

            private void handleNodeTypeCopy(NodeType nt) {

                @SuppressWarnings("serial")
                EcoreUtil.Copier nodeTypeCopier = new EcoreUtil.Copier() {

                    @Override
                    protected EObject createCopy(EObject eObject) {
                        EObject createCopy = super.createCopy(eObject);
                        if (createCopy instanceof Component) {

                            Lifecycle newLC = GenericsFactory.eINSTANCE.createLifecycle();
                            newLC.setProposed(NonModelUtils.toXMLDate(NonModelUtils.todayAndNow()));
                            ((Component) createCopy).setLifecycle(newLC);

                        }
                        return createCopy;
                    }

                    /**
                     * Our version of copy reference has a special treatment
                     * for NetXResource object.
                     */
                    @Override
                    protected void copyReference(EReference eReference, EObject eObject, EObject copyEObject) {

                        if (eReference == LibraryPackage.Literals.COMPONENT__RESOURCE_REFS) {
                            copyResourceReference(eReference, eObject, copyEObject);
                        } else {
                            super.copyReference(eReference, eObject, copyEObject);
                        }
                    }

                    protected void copyResourceReference(EReference eReference, EObject eObject,
                            EObject copyEObject) {
                        if (eObject.eIsSet(eReference) && eReference.isMany()) {
                            @SuppressWarnings("unchecked")
                            InternalEList<EObject> source = (InternalEList<EObject>) eObject.eGet(eReference);
                            @SuppressWarnings("unchecked")
                            InternalEList<EObject> target = (InternalEList<EObject>) copyEObject
                                    .eGet(getTarget(eReference));
                            if (source.isEmpty()) {
                                target.clear();
                            } else {
                                boolean isBidirectional = eReference.getEOpposite() != null;
                                int index = 0;
                                for (Iterator<EObject> k = resolveProxies ? source.iterator()
                                        : source.basicIterator(); k.hasNext();) {
                                    EObject referencedEObject = k.next();
                                    EObject copyReferencedEObject = get(referencedEObject);
                                    if (copyReferencedEObject == null) {
                                        if (useOriginalReferences) {
                                            // NetXResource is a bidi link,
                                            // so
                                            // make an actual copy (A copier
                                            // within a copier... auch).
                                            if (isBidirectional) {
                                                EcoreUtil.Copier defaultCopier = new EcoreUtil.Copier();
                                                EObject newEObject = defaultCopier.copy(referencedEObject);

                                                if (copyEObject instanceof Component) {

                                                    // String
                                                    // cdoResourcePath =
                                                    // null;
                                                    // try {
                                                    // cdoResourcePath =
                                                    // modelUtils
                                                    // .cdoCalculateResourceName(node);
                                                    // } catch
                                                    // (IllegalAccessException
                                                    // e) {
                                                    // if
                                                    // (ScreensActivator.DEBUG)
                                                    // {
                                                    // ScreensActivator.TRACE
                                                    // .trace(ScreensActivator.TRACE_SCREENS_OPTION,
                                                    // "Error creating CDO Resource name for node: "
                                                    // + node.getNodeID(),
                                                    // e);
                                                    // }
                                                    // }
                                                    //
                                                    // if (cdoResourcePath
                                                    // == null) {
                                                    // if
                                                    // (ScreensActivator.DEBUG)
                                                    // {
                                                    // ScreensActivator.TRACE
                                                    // .trace(ScreensActivator.TRACE_SCREENS_OPTION,
                                                    // "Error, CDO resource can't be determoned, should not occur!");
                                                    // }
                                                    // return; // Can't
                                                    // // calculate
                                                    // // path for
                                                    // // empty
                                                    // // names.
                                                    // } else {
                                                    // if
                                                    // (ScreensActivator.DEBUG)
                                                    // {
                                                    // ScreensActivator.TRACE
                                                    // .trace(ScreensActivator.TRACE_SCREENS_OPTION,
                                                    // "Creating CDO Resource "
                                                    // + cdoResourcePath);
                                                    // }
                                                    // }
                                                    // final Resource
                                                    // resourcesResource =
                                                    // editingService
                                                    // .getDataService()
                                                    // .getProvider()
                                                    // .getResource(
                                                    // editingService
                                                    // .getEditingDomain()
                                                    // .getResourceSet(),
                                                    // cdoResourcePath);

                                                    final Resource cdoResourceForNetXResource = StudioUtils
                                                            .cdoResourceGetOrCreate(node,
                                                                    (CDOTransaction) node.cdoView());
                                                    cdoResourceForNetXResource.getContents().add(newEObject);
                                                }

                                                target.addUnique(index, newEObject);
                                                index++;
                                            } else {
                                                target.addUnique(index, referencedEObject);
                                                ++index;
                                            }
                                        }
                                    } else {

                                        // This would actually do what?
                                        if (isBidirectional) {
                                            int position = target.indexOf(copyReferencedEObject);
                                            if (position == -1) {
                                                target.addUnique(index, copyReferencedEObject);
                                            } else if (index != position) {
                                                target.move(index, copyReferencedEObject);
                                            }
                                        } else {
                                            target.addUnique(index, copyReferencedEObject);
                                        }
                                        ++index;
                                    }
                                }
                            }
                        }
                    }
                };

                NodeType copyOf = (NodeType) nodeTypeCopier.copy(nt);
                nodeTypeCopier.copyReferences();

                CompoundCommand cc = new CompoundCommand();
                Command setOriginalNodeTypeRef = new SetCommand(editingService.getEditingDomain(), node,
                        OperatorsPackage.Literals.NODE__ORIGINAL_NODE_TYPE_REF, nt);
                Command setNodeTypeCommand = new SetCommand(editingService.getEditingDomain(), node,
                        OperatorsPackage.Literals.NODE__NODE_TYPE, copyOf);

                cc.append(setOriginalNodeTypeRef);
                cc.append(setNodeTypeCommand);
                editingService.getEditingDomain().getCommandStack().execute(cc);
            }

        });
    }
}

From source file:com.onpositive.mapper.actions.MergeAllLayersAction.java

License:Open Source License

protected void doPerformAction() {
    Map map = editor.getMap();//  www .  j  a va2 s  .  c o m

    boolean result = MessageDialog.open(MessageDialog.QUESTION_WITH_CANCEL, editor.getEditorSite().getShell(),
            "Merge Tiles?", "Do you wish to merge tile images, and create a new tile set?", SWT.NONE);
    //        int ret = JOptionPane.showConfirmDialog(null,
    //                "Do you wish to merge tile images, and create a new tile set?",
    //                "Merge Tiles?", JOptionPane.YES_NO_CANCEL_OPTION);

    if (result) {
        TileMergeHelper tmh = new TileMergeHelper(map);
        int len = map.getTotalLayers();
        //TODO: Add a dialog option: "Yes, visible only"
        TileLayer newLayer = tmh.merge(0, len, true);
        map.removeAllLayers();
        map.addLayer(newLayer);
        newLayer.setName("Merged Layer");
        map.addTileset(tmh.getSet());
        editor.setCurrentLayer(0);
    } else /*if (ret == JOptionPane.NO_OPTION)*/ {
        while (map.getTotalLayers() > 1) {
            map.mergeLayerDown(editor.getCurrentLayerIndex());
        }
        editor.setCurrentLayer(0);
    }

}