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

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

Introduction

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

Prototype

int QUESTION

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

Click Source Link

Document

Constant for the question image, or a simple dialog with the question image and Yes/No buttons (value 3).

Usage

From source file:net.tourbook.ui.views.tourDataEditor.TourDataEditorView.java

License:Open Source License

/**
 * @param isConfirmSave//from   ww w  .j  a v a  2 s. com
 * @return Returns <code>true</code> when the tour was saved, <code>false</code> when the tour
 *         is not saved but canceled
 */
private boolean saveTourConfirmation() {

    if (_isTourDirty == false) {
        return true;
    }

    // show the tour data editor
    try {
        getSite().getPage().showView(ID, null, IWorkbenchPage.VIEW_VISIBLE);
    } catch (final PartInitException e) {
        e.printStackTrace();
    }

    // confirm save/discard/cancel
    final int returnCode = new MessageDialog(Display.getCurrent().getActiveShell(),
            Messages.tour_editor_dlg_save_tour_title, null,
            NLS.bind(Messages.tour_editor_dlg_save_tour_message, TourManager.getTourDateFull(_tourData)),
            MessageDialog.QUESTION,
            new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL,
                    IDialogConstants.CANCEL_LABEL },
            0)//
                    .open();

    if (returnCode == 0) {

        // button YES: save tour

        saveTourIntoDB();

        return true;

    } else if (returnCode == 1) {

        // button NO: discard modifications

        discardModifications();

        return true;

    } else {

        // button CANCEL / dialog is canceled: tour is not saved and not discarded

        return false;
    }
}

From source file:nexcore.tool.uml.ui.core.registry.ResourceManager.java

License:Open Source License

/**
 * //  w  w w .ja  va2 s  . co  m
 * 
 *   void
 */
private void addUMLResourceChangeListener() {
    UMLResourceChangeManager rcm = UMLResourceChangeManager.getInstance();

    rcm.addResourceChangeListener(new UMLResourceChangeAdapter() {
        public void preProjectClose(IResourceChangeEvent event) {
            preProjectDelete(event);
        }

        public void preProjectDelete(final IResourceChangeEvent event) {
            // ?  
            Display.getDefault().syncExec(new Runnable() {
                public void run() {
                    try {
                        ProjectUtil.closeEditor((IProject) event.getResource());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    List<Resource> saveableList = hasModifiedResource(
                            new IResource[] { (IProject) event.getResource() });
                    boolean isSave = false;
                    int choice = IDialogConstants.NO_ID;
                    if (saveableList.size() > 0) {
                        final boolean canCancel = true;
                        String[] buttons;
                        buttons = new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL,
                                IDialogConstants.CANCEL_LABEL };

                        String message = String.format("'%s' has been modified. Save changes?",
                                saveableList.get(0).getURI());
                        ;
                        MessageDialog dialog = new MessageDialog(getShell(), "Save Resource", null, message,
                                MessageDialog.QUESTION, buttons, 0) {
                            protected int getShellStyle() {
                                return (canCancel ? SWT.CLOSE : SWT.NONE) | SWT.TITLE | SWT.BORDER
                                        | SWT.APPLICATION_MODAL | getDefaultOrientation();
                            }
                        };

                        choice = dialog.open();

                        switch (choice) {
                        case ISaveablePart2.YES:
                            isSave = true;
                            cleanResource(new NullProgressMonitor(),
                                    new IResource[] { (IProject) event.getResource() }, isSave);
                            break;
                        case ISaveablePart2.NO:
                            isSave = false;
                            cleanResource(new NullProgressMonitor(),
                                    new IResource[] { (IProject) event.getResource() }, isSave);
                            break;
                        case ISaveablePart2.CANCEL:
                            break;
                        default:
                            break;
                        }
                    } else {
                        cleanResource(new NullProgressMonitor(),
                                new IResource[] { (IProject) event.getResource() }, isSave);
                    }
                    ProjectUtil.refreshExplorer();
                    //                        IProject[] activeUMLProjects = ProjectUtil.getActiveUMLProjects();
                    //                        
                    //                        for(IProject project : activeUMLProjects) {
                    //                            try {
                    //                                project.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
                    //                            } catch (CoreException e) {
                    //                                e.printStackTrace();
                    //                            }
                    //                        }
                }
            });

        }

        public void projectOpened(IProject[] projects) {
            if (PROJECT_OPEN_IMPORT) { // import  ?  ? 
                for (IProject project : projects) {
                    openProject.add(project);
                }
                return;
            }

            for (IProject project : projects) {
                if (referencedProject.containsKey(project)) {
                    referencedProject.put(project, Boolean.TRUE);

                    IProject[] refProjects = referencedProject.keySet().toArray(new IProject[0]);
                    boolean isOpened = allOpened();
                    if (isOpened) {
                        initializeModelingData(refProjects, false);
                        referencedProject.clear();
                    }
                    return;
                }
            }
            initializeModelingData(projects, false);
        }

        public boolean allOpened() {
            for (Iterator<IProject> iterator = referencedProject.keySet().iterator(); iterator.hasNext();) {
                IProject project = (IProject) iterator.next();
                if (!referencedProject.get(project)) {
                    return false;
                }
            }

            return true;
        }

    });

    //        UMLResourceChangeAdapter listener = new UMLResourceChangeAdapter() {
    //            @Override
    //            public void projectOpened(IProject[] projects) {
    //                for (IProject project : projects) {
    ////                    referencedProject.remove(project);
    //                }
    //            }
    //        };
    //        rcm.addResourceChangeListener(listener);
}

From source file:nexcore.tool.uml.ui.project.builder.CleanAction.java

License:Open Source License

/**
 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
 *//*  ww  w . j  av a 2 s  .  co m*/
@SuppressWarnings("unchecked")
public void run(final IAction action) {
    if ((null == selection) || (!(selection instanceof IStructuredSelection))) {
        return;
    }

    final List<IProject> projectList = new ArrayList<IProject>();

    for (Iterator iterator = ((IStructuredSelection) selection).iterator(); iterator.hasNext();) {
        Object obj = (Object) iterator.next();
        IProject project = ProjectUtil.findProject(obj);
        if (ProjectUtil.isActiveUMLProject(project) && !projectList.contains(project)) {
            projectList.add(project);
        }
    }

    Display.getDefault().syncExec(new Runnable() {
        public void run() {

            CommonViewer commonViewer = ViewerRegistry.getViewer();
            TreePath[] expanedTreePaths = TreeItemUtil.getExpandTreePaths(commonViewer.getTree()).clone();

            List<Resource> saveableList = ResourceManager
                    .hasModifiedResource(projectList.toArray(new IResource[] {}));
            boolean isSave = false;
            int choice = IDialogConstants.NO_ID;
            if (saveableList.size() > 0) {
                final boolean canCancel = true;
                String[] buttons;
                buttons = new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL,
                        IDialogConstants.CANCEL_LABEL };

                String message = NLS.bind(WorkbenchMessages.EditorManager_saveChangesQuestion,
                        saveableList.get(0).getURI());
                MessageDialog dialog = new MessageDialog(ViewerRegistry.getViewer().getTree().getShell(),
                        WorkbenchMessages.Save_Resource, null, message, MessageDialog.QUESTION, buttons, 0) {
                    protected int getShellStyle() {
                        return (canCancel ? SWT.CLOSE : SWT.NONE) | SWT.TITLE | SWT.BORDER
                                | SWT.APPLICATION_MODAL | getDefaultOrientation();
                    }
                };

                choice = dialog.open();

                switch (choice) {
                case ISaveablePart2.YES:
                    isSave = true;
                    break;
                case ISaveablePart2.NO:
                    isSave = false;
                    break;
                case ISaveablePart2.CANCEL:
                    // 
                    return;
                default:
                    break;
                }
            }

            ResourceManager.cleanResource(new NullProgressMonitor(), projectList.toArray(new IResource[] {}),
                    isSave);
            cleanTreeNode(projectList);

            TreeItemUtil.expandTreePath(expanedTreePaths, selection);
        }

        private void cleanTreeNode(final List<IProject> projectList) {
            Map<String, ITreeNode> treeNodes = ProjectRegistry.UMLTreeNodeRegistry.getTreeNodes();
            List<Object> removeTarget = new ArrayList<Object>();
            for (Iterator<String> iterator = treeNodes.keySet().iterator(); iterator.hasNext();) {
                String type = (String) iterator.next();
                for (IResource resource : projectList) {
                    URI uri = URI.createURI(resource.getFullPath().toString());
                    if (type.indexOf(uri.toString()) > -1) {
                        removeTarget.add(type);

                        treeNodes.get(type).refresh();
                    }
                }
            }

            // UMLTreeNodeRegistry.getTreeNodes() ? ?  
            for (Object o : removeTarget) {
                //                    ProjectRegistry.UMLTreeNodeRegistry.removeTreeNode(o);
            }

            for (IProject project : projectList) {
                ViewerRegistry.getViewer().refresh(project);
            }

            ResourceManager.getInstance().initializeModelingData(projectList.toArray(new IProject[] {}), true);
        }
    });

}

From source file:no.javatime.inplace.bundlemanager.BundleEventManager.java

License:Open Source License

/**
 * Bundle has been uninstalled from an external source in an activated workspace. Either restore (activate
 * or install) the bundle or deactivate the workspace depending on default actions or user option/choice.
 * // www. ja v a 2 s. c  o m
 * @param project the project to restore or deactivate
 * @param bundle the bundle to restore or deactivate
 */
private void externalUninstall(final Bundle bundle, final IProject project) {

    final String symbolicName = bundle.getSymbolicName();
    final String location = bundle.getLocation();
    // After the fact
    InPlace.getDisplay().asyncExec(new Runnable() {
        @Override
        public void run() {
            BundleCommandImpl bundleManager = BundleCommandImpl.INSTANCE;
            int autoDependencyAction = 1; // Default auto dependency action
            new OpenProjectHandler().saveModifiedFiles();
            Boolean dependencies = false;
            Collection<IProject> reqProjects = Collections.emptySet();
            if (bundleRegion.isActivated(bundle)) {
                ProjectSorter bs = new ProjectSorter();
                reqProjects = bs.sortRequiringProjects(Collections.singletonList(project), Boolean.TRUE);
                // Remove initial project from result set
                reqProjects.remove(project);
                dependencies = reqProjects.size() > 0;
                if (dependencies) {
                    String msg = WarnMessage.getInstance().formatString("has_requiring_bundles",
                            bundleRegion.formatBundleList(bundleRegion.getBundles(reqProjects), true),
                            bundleRegion.getSymbolicKey(bundle, null));
                    StatusManager.getManager().handle(
                            new BundleStatus(StatusCode.WARNING, InPlace.PLUGIN_ID, msg), StatusManager.LOG);
                }
            }
            // User choice to deactivate workspace or restore uninstalled bundle
            try {
                if (!InPlace.getDefault().getOptionsService().isAutoHandleExternalCommands()) {
                    String question = null;
                    int index = 0;
                    if (dependencies) {
                        question = Message.getInstance().formatString("deactivate_question_requirements",
                                symbolicName, location,
                                bundleRegion.formatBundleList(bundleRegion.getBundles(reqProjects), true));
                        index = 1;
                    } else {
                        question = Message.getInstance().formatString("deactivate_question", symbolicName,
                                location);
                    }
                    MessageDialog dialog = new MessageDialog(null, "InPlace Activator", null, question,
                            MessageDialog.QUESTION, new String[] { "Yes", "No" }, index);
                    autoDependencyAction = dialog.open();
                }
            } catch (InPlaceException e) {
                StatusManager.getManager().handle(
                        new BundleStatus(StatusCode.EXCEPTION, InPlace.PLUGIN_ID, e.getMessage(), e),
                        StatusManager.LOG);
            }
            bundleManager.unregisterBundle(bundle);
            if (autoDependencyAction == 0) {
                if (ProjectProperties.isProjectActivated(project)) {
                    // Restore activated bundle and dependent bundles
                    ActivateBundleJob activateBundleJob = new ActivateBundleJob(
                            ActivateBundleJob.activateJobName, project);
                    if (dependencies) {
                        // Bring workspace back to a consistent state before restoring
                        UninstallJob uninstallJob = new UninstallJob(UninstallJob.uninstallJobName,
                                reqProjects);
                        BundleManager.addBundleJob(uninstallJob, 0);
                        activateBundleJob.addPendingProjects(reqProjects);
                    }
                    BundleManager.addBundleJob(activateBundleJob, 0);
                } else {
                    // Workspace is activated but bundle is not. Install the bundle
                    InstallJob installJob = new InstallJob(InstallJob.installJobName, project);
                    BundleManager.addBundleJob(installJob, 0);
                }
            } else if (autoDependencyAction == 1) {
                // Deactivate workspace to obtain a consistent state between all workspace bundles
                DeactivateJob deactivateJob = new DeactivateJob(DeactivateJob.deactivateWorkspaceJobName);
                deactivateJob.addPendingProjects(ProjectProperties.getActivatedProjects());
                BundleManager.addBundleJob(deactivateJob, 0);
            }
        }
    });
}

From source file:org.apache.directory.studio.apacheds.configuration.editor.ServerConfigurationEditorUtils.java

License:Apache License

/**
 * Performs the "Save as..." action.// ww  w  .  ja v  a 2  s . c o m
 *
 * @param monitor the monitor
 * @param shell the shell
 * @param input the editor input
 * @param configWriter the configuration writer
 * @param newInput a flag to indicate if a new input is required
 * @return the new input for the editor
 * @throws Exception
 */
public static IEditorInput saveAs(IProgressMonitor monitor, Shell shell, IEditorInput input,
        ConfigWriter configWriter, Configuration configuration, boolean newInput) throws Exception {
    // detect IDE or RCP:
    // check if perspective org.eclipse.ui.resourcePerspective is available
    boolean isIDE = CommonUIUtils.isIDEEnvironment();

    if (isIDE) {
        // Asking the user for the location where to 'save as' the file
        SaveAsDialog dialog = new SaveAsDialog(shell);

        String inputClassName = input.getClass().getName();

        if (input instanceof FileEditorInput) {
            // FileEditorInput class is used when the file is opened
            // from a project in the workspace.
            dialog.setOriginalFile(((FileEditorInput) input).getFile());
        } else if (input instanceof IPathEditorInput) {
            dialog.setOriginalFile(
                    ResourcesPlugin.getWorkspace().getRoot().getFile(((IPathEditorInput) input).getPath()));
        } else if (inputClassName.equals("org.eclipse.ui.internal.editors.text.JavaFileEditorInput") //$NON-NLS-1$
                || inputClassName.equals("org.eclipse.ui.ide.FileStoreEditorInput")) //$NON-NLS-1$
        {
            // The class 'org.eclipse.ui.internal.editors.text.JavaFileEditorInput'
            // is used when opening a file from the menu File > Open... in Eclipse 3.2.x
            // The class 'org.eclipse.ui.ide.FileStoreEditorInput' is used when
            // opening a file from the menu File > Open... in Eclipse 3.3.x
            dialog.setOriginalFile(
                    ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(input.getToolTipText())));
        } else {
            dialog.setOriginalName(ApacheDS2ConfigurationPluginConstants.CONFIG_LDIF);
        }

        // Open the dialog
        if (openDialogInUIThread(dialog) != Dialog.OK) {
            return null;
        }

        // Getting if the resulting file
        IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(dialog.getResult());

        // Creating the file if it does not exist
        if (!file.exists()) {
            file.create(new ByteArrayInputStream("".getBytes()), true, null); //$NON-NLS-1$
        }

        // Creating the new input for the editor
        FileEditorInput fei = new FileEditorInput(file);

        // Saving the file to disk
        File configFile = fei.getPath().toFile();
        saveConfiguration(configFile, configWriter, configuration);

        return fei;
    } else {
        boolean canOverwrite = false;
        String path = null;

        while (!canOverwrite) {
            // Open FileDialog
            path = openFileDialogInUIThread(shell);

            if (path == null) {
                return null;
            }

            // Check whether file exists and if so, confirm overwrite
            final File externalFile = new File(path);

            if (externalFile.exists()) {
                String question = NLS.bind(
                        Messages.getString("ServerConfigurationEditorUtils.TheFileAlreadyExistsWantToReplace"), //$NON-NLS-1$
                        path);
                MessageDialog overwriteDialog = new MessageDialog(shell,
                        Messages.getString("ServerConfigurationEditorUtils.Question"), null, question, //$NON-NLS-1$
                        MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL,
                                IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL },
                        0);
                int overwrite = openDialogInUIThread(overwriteDialog);

                switch (overwrite) {
                case 0: // Yes
                    canOverwrite = true;
                    break;

                case 1: // No
                    break;

                case 2: // Cancel
                default:
                    return null;
                }
            } else {
                canOverwrite = true;
            }
        }

        // Saving the file to disk
        saveConfiguration(new File(path), configWriter, configuration);

        // Checking if a new input is required
        if (newInput) {
            // Creating the new input for the editor
            return new PathEditorInput(new Path(path));
        } else {
            return null;
        }
    }
}

From source file:org.apache.directory.studio.connection.ui.preferences.PasswordsKeystorePreferencePage.java

License:Apache License

/**
 * Disables the passwords keystore./*from  w w w.j a v a2  s . co m*/
 *
 * @return <code>true</code> if the passwords keystore was successfully disabled,
 *         <code>false</code> if not.
 */
private boolean disablePasswordsKeystore() {
    // Asking the user if he wants to keep its connections passwords
    MessageDialog keepConnectionsPasswordsDialog = new MessageDialog(enableKeystoreCheckbox.getShell(),
            Messages.getString("PasswordsKeystorePreferencePage.KeepConnectionsPasswords"), //$NON-NLS-1$
            null, Messages.getString("PasswordsKeystorePreferencePage.DoYouWantToKeepYourConnectionsPasswords"), //$NON-NLS-1$
            MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL,
                    IDialogConstants.CANCEL_LABEL },
            0);
    int keepConnectionsPasswordsValue = keepConnectionsPasswordsDialog.open();

    if (keepConnectionsPasswordsValue == 1) {
        // The user chose NOT to keep the connections passwords
        connectionsPasswordsBackup.clear();
        passwordsKeyStoreManager.deleteKeystoreFile();
        return true;
    } else if (keepConnectionsPasswordsValue == 0) {
        // The user chose to keep the connections passwords
        connectionsPasswordsBackup.clear();

        while (true) {
            // We ask the user for the keystore password
            PasswordDialog passwordDialog = new PasswordDialog(enableKeystoreCheckbox.getShell(),
                    Messages.getString("PasswordsKeystorePreferencePage.VerifyMasterPassword"), //$NON-NLS-1$
                    Messages.getString("PasswordsKeystorePreferencePage.PleaseEnterYourMasterPassword"), //$NON-NLS-1$
                    null);

            if (passwordDialog.open() == PasswordDialog.CANCEL) {
                // The user cancelled the action
                return false;
            }

            // Getting the password
            String password = passwordDialog.getPassword();

            // Checking the password
            Exception checkPasswordException = null;
            try {
                if (passwordsKeyStoreManager.checkMasterPassword(password)) {
                    break;
                }
            } catch (KeyStoreException e) {
                checkPasswordException = e;
            }

            // Creating the message
            String message = null;

            if (checkPasswordException == null) {
                message = Messages
                        .getString("PasswordsKeystorePreferencePage.MasterPasswordVerificationFailed"); //$NON-NLS-1$
            } else {
                message = Messages.getString(
                        "PasswordsKeystorePreferencePage.MasterPasswordVerificationFailedWithException") //$NON-NLS-1$
                        + checkPasswordException.getMessage();
            }

            // We ask the user if he wants to retry to unlock the passwords keystore
            MessageDialog errorDialog = new MessageDialog(enableKeystoreCheckbox.getShell(),
                    Messages.getString("PasswordsKeystorePreferencePage.VerifyMasterPasswordFailed"), null, //$NON-NLS-1$
                    message, MessageDialog.ERROR, new String[] { IDialogConstants.RETRY_LABEL, IDialogConstants.CANCEL_LABEL }, 0);

            if (errorDialog.open() == MessageDialog.CANCEL) {
                // The user cancelled the action
                return false;
            }
        }

        // Getting the connection IDs having their passwords saved in the keystore
        String[] connectionIds = passwordsKeyStoreManager.getConnectionIds();

        if (connectionIds != null) {
            // Adding the passwords to the backup map
            for (String connectionId : connectionIds) {
                String password = passwordsKeyStoreManager.getConnectionPassword(connectionId);

                if (password != null) {
                    connectionsPasswordsBackup.put(connectionId, password);
                }
            }
        }

        passwordsKeyStoreManager.deleteKeystoreFile();

        return true;
    } else {
        // The user cancelled the action
        return false;
    }
}

From source file:org.apache.directory.studio.entryeditors.EntryEditorManager.java

License:Apache License

private void askUpdateSharedWorkingCopy(IWorkbenchPartReference partRef, IEntry originalEntry,
        IEntry oscSharedWorkingCopy, Object source) {
    MessageDialog dialog = new MessageDialog(partRef.getPart(false).getSite().getShell(),
            Messages.getString("EntryEditorManager.EntryChanged"), null, Messages //$NON-NLS-1$
                    .getString("EntryEditorManager.EntryChangedDescription"), //$NON-NLS-1$
            MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 0);
    int result = dialog.open();

    if (result == 0) {
        // update reference copy and working copy
        updateOscSharedReferenceCopy(originalEntry);
        updateOscSharedWorkingCopy(originalEntry);

        // inform all OSC editors
        List<IEntryEditor> oscEditors = getOscEditors(oscSharedWorkingCopy);

        for (IEntryEditor oscEditor : oscEditors) {
            oscEditor.workingCopyModified(source);
        }/*from  www .  j  a  v  a 2 s . co m*/
    }
}

From source file:org.apache.directory.studio.entryeditors.EntryEditorUtils.java

License:Apache License

/**
 * Asks the user if he wants to save the modifications made to the entry before 
 * opening the new input./*from  w w w.j a va2  s .  c  o m*/
 * <p>
 * If the user answers 'Yes', then the entry's modifications are saved.
 * <p>
 * This method returns whether or not the whole operation completed.
 * <p>Based on this return value, <code>true</code> or <code>false</code>, the editor
 * then updates its input or not.
 *
 * @param editor
 *      the editor
 * @return
 *      <code>true</code> if the whole operation completed correctly,
 *      <code>false</code> if not.
 */
public static boolean askSaveSharedWorkingCopyBeforeInputChange(IEntryEditor editor) {
    // Asking for saving the modifications
    MessageDialog dialog = new MessageDialog(Display.getCurrent().getActiveShell(),
            Messages.getString("EntryEditorUtils.SaveChanges"), null, Messages //$NON-NLS-1$
                    .getString("EntryEditorUtils.SaveChangesDescription"), //$NON-NLS-1$
            MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 0);
    int result = dialog.open();
    if (result == 0) {
        // Saving the modifications
        EntryEditorInput eei = editor.getEntryEditorInput();
        IStatus status = eei.saveSharedWorkingCopy(true, editor);

        if ((status == null) || !status.isOK()) {
            // If save failed, let's keep the modifications in the editor and return false
            return false;
        }
    }

    return true;
}

From source file:org.apache.directory.studio.ldapbrowser.ui.wizards.BatchOperationWizard.java

License:Apache License

/**
 * {@inheritDoc}//  ww  w.ja v  a 2s  .c  om
 */
public boolean performFinish() {
    if (this.applyOnPage != null) {
        this.applyOnPage.saveDialogSettings();
        this.finishPage.saveDialogSettings();

        // get LDIF
        String ldifFragment = ""; //$NON-NLS-1$
        if (typePage.getOperationType() == BatchOperationTypeWizardPage.OPERATION_TYPE_CREATE_LDIF) {
            ldifFragment = this.ldifPage.getLdifFragment();
        } else if (typePage.getOperationType() == BatchOperationTypeWizardPage.OPERATION_TYPE_MODIFY) {
            ldifFragment = this.modifyPage.getLdifFragment();
        }
        if (typePage.getOperationType() == BatchOperationTypeWizardPage.OPERATION_TYPE_DELETE) {
            ldifFragment = "changetype: delete" + BrowserCoreConstants.LINE_SEPARATOR; //$NON-NLS-1$
        }

        // get DNs
        Dn[] dns = applyOnPage.getApplyOnDns();
        if (dns == null) {
            if (applyOnPage.getApplyOnSearch() != null) {
                ISearch search = applyOnPage.getApplyOnSearch();
                if (search.getBrowserConnection() != null) {
                    search.setSearchResults(null);
                    SearchRunnable runnable = new SearchRunnable(new ISearch[] { search });
                    IStatus status = RunnableContextRunner.execute(runnable, getContainer(), true);
                    if (status.isOK()) {
                        ISearchResult[] srs = search.getSearchResults();
                        dns = new Dn[srs.length];
                        for (int i = 0; i < srs.length; i++) {
                            dns[i] = srs[i].getDn();
                        }
                    }
                }
            }
        }

        if (dns != null) {
            StringBuffer ldif = new StringBuffer();
            for (int i = 0; i < dns.length; i++) {
                ldif.append("dn: "); //$NON-NLS-1$
                ldif.append(dns[i].getName());
                ldif.append(BrowserCoreConstants.LINE_SEPARATOR);
                ldif.append(ldifFragment);
                ldif.append(BrowserCoreConstants.LINE_SEPARATOR);
            }

            if (finishPage
                    .getExecutionMethod() == BatchOperationFinishWizardPage.EXECUTION_METHOD_LDIF_EDITOR) {
                // Opening an LDIF Editor with the LDIF content
                try {
                    IEditorInput input = new NonExistingLdifEditorInput();
                    IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
                            .openEditor(input, LdifEditor.getId());
                    IDocumentProvider documentProvider = ((LdifEditor) editor).getDocumentProvider();
                    if (documentProvider != null) {
                        IDocument document = documentProvider.getDocument(input);
                        if (document != null) {
                            document.set(ldif.toString());
                        }
                    }
                } catch (PartInitException e) {
                    return false;
                }

                return true;
            } else if (finishPage
                    .getExecutionMethod() == BatchOperationFinishWizardPage.EXECUTION_METHOD_LDIF_FILE) // TODO
            {
                // Saving the LDIF to a file

                // Getting the shell
                Shell shell = Display.getDefault().getActiveShell();

                // detect IDE or RCP:
                // check if perspective org.eclipse.ui.resourcePerspective is available
                boolean isIDE = CommonUIUtils.isIDEEnvironment();

                if (isIDE) {
                    // Asking the user for the location where to 'save as' the file
                    SaveAsDialog dialog = new SaveAsDialog(shell);

                    if (dialog.open() != Dialog.OK) {
                        return false;
                    }

                    // Getting if the resulting file
                    IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(dialog.getResult());

                    try {
                        // Creating the file if it does not exist
                        if (!file.exists()) {
                            file.create(new ByteArrayInputStream("".getBytes()), true, null); //$NON-NLS-1$
                        }

                        // Saving the LDIF to the file in the workspace
                        file.setContents(new ByteArrayInputStream(ldif.toString().getBytes()), true, true,
                                new NullProgressMonitor());
                    } catch (Exception e) {
                        return false;
                    }
                } else {
                    boolean canOverwrite = false;
                    String path = null;

                    while (!canOverwrite) {
                        // Open FileDialog
                        FileDialog dialog = new FileDialog(shell, SWT.SAVE);
                        path = dialog.open();
                        if (path == null) {
                            return false;
                        }

                        // Check whether file exists and if so, confirm overwrite
                        final File externalFile = new File(path);
                        if (externalFile.exists()) {
                            String question = NLS.bind(
                                    Messages.getString("BatchOperationWizard.TheFileAlreadyExistsReplace"), //$NON-NLS-1$
                                    path);
                            MessageDialog overwriteDialog = new MessageDialog(shell,
                                    Messages.getString("BatchOperationWizard.Question"), null, question, //$NON-NLS-1$
                                    MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL,
                                            IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL },
                                    0);
                            int overwrite = overwriteDialog.open();
                            switch (overwrite) {
                            case 0: // Yes
                                canOverwrite = true;
                                break;
                            case 1: // No
                                break;
                            case 2: // Cancel
                            default:
                                return false;
                            }
                        } else {
                            canOverwrite = true;
                        }
                    }

                    // Saving the LDIF to the file on disk
                    try {
                        BufferedWriter outFile = new BufferedWriter(new FileWriter(path));
                        outFile.write(ldif.toString());
                        outFile.close();
                    } catch (Exception e) {
                        return false;
                    }
                }

                return true;
            } else if (finishPage
                    .getExecutionMethod() == BatchOperationFinishWizardPage.EXECUTION_METHOD_LDIF_CLIPBOARD) {
                // Copying the LDIF to the clipboard
                CopyAction.copyToClipboard(new Object[] { ldif.toString() },
                        new Transfer[] { TextTransfer.getInstance() });

                return true;
            } else if (finishPage
                    .getExecutionMethod() == BatchOperationFinishWizardPage.EXECUTION_METHOD_ON_CONNECTION) {
                // Executing the LDIF on the connection
                ExecuteLdifRunnable runnable = new ExecuteLdifRunnable(getConnection(), ldif.toString(), true,
                        finishPage.getContinueOnError());
                StudioBrowserJob job = new StudioBrowserJob(runnable);
                job.execute();

                return true;
            }
        }

        return false;
    }

    return true;
}

From source file:org.apache.directory.studio.schemaeditor.view.ViewUtils.java

License:Apache License

/**
 * Displays a Information Question message dialog with the given title and message.
 * //from   ww  w .j av  a2 s.c  om
 * @param title the title of the window
 * @param message the message to display
 * @return <code>true</code> if the user presses the OK or Yes button,
 *         <code>false</code> otherwise
 */
public static boolean displayQuestionMessageDialog(String title, String message) {
    return displayMessageDialog(MessageDialog.QUESTION, title, message);
}