Example usage for javax.swing JOptionPane YES_NO_OPTION

List of usage examples for javax.swing JOptionPane YES_NO_OPTION

Introduction

In this page you can find the example usage for javax.swing JOptionPane YES_NO_OPTION.

Prototype

int YES_NO_OPTION

To view the source code for javax.swing JOptionPane YES_NO_OPTION.

Click Source Link

Document

Type used for showConfirmDialog.

Usage

From source file:com.proyecto.vista.MantenimientoArea.java

private void btneliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btneliminarActionPerformed
    // TODO add your handling code here:
    accion = Controlador.ELIMINAR;/*  www . j a  va 2 s.  co  m*/
    if (tblarea.getSelectedRow() != -1) {

        Integer codigo = tblarea.getSelectedRow();

        Area area = areaControlador.buscarPorId(lista.get(codigo).getId());

        if (area != null) {
            if (JOptionPane.showConfirmDialog(null, "Desea Eliminar la Area?", "Mensaje del Sistema",
                    JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {

                int[] filas = tblarea.getSelectedRows();
                for (int i = 0; i < filas.length; i++) {
                    Area area2 = lista.get(filas[0]);
                    lista.remove(area2);
                    areaControlador.setSeleccionado(area2);
                    areaControlador.accion(accion);
                }
                if (areaControlador.accion(accion) == 3) {
                    JOptionPane.showMessageDialog(null, "Area eliminada correctamente", "Mensaje del Sistema",
                            JOptionPane.INFORMATION_MESSAGE);

                } else {
                    JOptionPane.showMessageDialog(null, "Area no eliminada", "Mensaje del Sistema",
                            JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Area no eliminada", "Mensaje del Sistema",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    } else {
        JOptionPane.showMessageDialog(null, "Debe seleccionar un Area", "Mensaje del Sistema",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:de.ailis.xadrian.components.ComplexEditor.java

/**
 * Prompts for a file name and saves the complex there.
 *//*w  w  w. j a v a2 s .  com*/
public void saveAs() {
    final SaveComplexDialog dialog = SaveComplexDialog.getInstance();
    dialog.setSelectedFile(getSuggestedFile());
    File file = dialog.open();
    if (file != null) {
        // Add file extension if none present
        if (FileUtils.getExtension(file) == null)
            file = new File(file.getPath() + ".x3c");

        // Save the file if it does not yet exists are user confirms
        // overwrite
        if (!file.exists() || JOptionPane.showConfirmDialog(null, I18N.getString("confirm.overwrite"),
                I18N.getString("confirm.title"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
            save(file);
        }
    }
}

From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java

/**
 * Ask the user for an image file for that a tiled map shall be created
 *///from  www . j ava2  s .c om
public void run() {
    JFileChooser fileChooser = new JFileChooser();

    // load current dir
    fileChooser.setCurrentDirectory(
            new File(pref.get(PREF_DIR, fileChooser.getCurrentDirectory().getAbsolutePath())));

    // open
    int returnVal = fileChooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        // save current dir
        pref.put(PREF_DIR, fileChooser.getCurrentDirectory().getAbsolutePath());

        // get file
        File imageFile = fileChooser.getSelectedFile();

        // get image dimension
        Dimension size = getSize(imageFile);
        log.info("Image size: " + size);

        // ask for min tile size
        int minTileSize = 0;
        while (minTileSize <= 0) {
            try {
                minTileSize = Integer.parseInt(
                        JOptionPane.showInputDialog("Minimal tile size", String.valueOf(DEF_MIN_TILE_SIZE)));
            } catch (Exception e) {
                minTileSize = 0;
            }
        }

        // determine min map width
        int width = size.width;

        while (width / 2 > minTileSize && width % 2 == 0) {
            width = width / 2;
        }
        int minMapWidth = width; // min map width

        log.info("Minimal map width: " + minMapWidth);

        // determine min map height
        int height = size.height;

        while (height / 2 > minTileSize && height % 2 == 0) {
            height = height / 2; // min map height
        }
        int minMapHeight = height;

        log.info("Minimal map height: " + minMapHeight);

        // ask for min map size
        int minMapSize = 0;
        while (minMapSize <= 0) {
            try {
                minMapSize = Integer.parseInt(
                        JOptionPane.showInputDialog("Minimal map size", String.valueOf(DEF_MIN_MAP_SIZE)));
            } catch (Exception e) {
                minMapSize = 0;
            }
        }

        // determine zoom levels
        int zoomLevels = 1;

        width = size.width;
        height = size.height;

        while (width % 2 == 0 && height % 2 == 0 && width / 2 >= Math.max(minMapWidth, minMapSize)
                && height / 2 >= Math.max(minMapHeight, minMapSize)) {
            zoomLevels++;
            width = width / 2;
            height = height / 2;
        }

        log.info("Number of zoom levels: " + zoomLevels);

        // determine tile width
        width = minMapWidth;
        int tileWidth = minMapWidth;
        for (int i = 3; i < Math.sqrt(minMapWidth) && width > minTileSize;) {
            tileWidth = width;
            if (width % i == 0) {
                width = width / i;
            } else
                i++;
        }

        // determine tile height
        height = minMapHeight;
        int tileHeight = minMapHeight;
        for (int i = 3; i < Math.sqrt(minMapHeight) && height > minTileSize;) {
            tileHeight = height;
            if (height % i == 0) {
                height = height / i;
            } else
                i++;
        }

        // create tiles for each zoom level
        if (JOptionPane.showConfirmDialog(null,
                "Create tiles (" + tileWidth + "x" + tileHeight + ") for " + zoomLevels + " zoom levels?",
                "Create tiles", JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            int currentWidth = size.width;
            int currentHeight = size.height;
            File currentImage = imageFile;

            Properties properties = new Properties();
            properties.setProperty(PROP_TILE_WIDTH, String.valueOf(tileWidth));
            properties.setProperty(PROP_TILE_HEIGHT, String.valueOf(tileHeight));
            properties.setProperty(PROP_ZOOM_LEVELS, String.valueOf(zoomLevels));

            List<File> files = new ArrayList<File>();

            for (int i = 0; i < zoomLevels; i++) {
                int mapWidth = currentWidth / tileWidth;
                int mapHeight = currentHeight / tileHeight;

                log.info("Creating tiles for zoom level " + i);
                log.info("Map width: " + currentWidth + " pixels, " + mapWidth + " tiles");
                log.info("Map height: " + currentHeight + " pixels, " + mapHeight + " tiles");

                // create tiles
                tile(currentImage, TILE_FILE_PREFIX + i + TILE_FILE_SEPARATOR + "%d", TILE_FILE_EXTENSION,
                        tileWidth, tileHeight);

                // add files to list
                for (int num = 0; num < mapWidth * mapHeight; num++) {
                    files.add(new File(imageFile.getParentFile().getAbsolutePath() + File.separator
                            + TILE_FILE_PREFIX + i + TILE_FILE_SEPARATOR + num + TILE_FILE_EXTENSION));
                }

                // store map width and height at current zoom
                properties.setProperty(PROP_MAP_WIDTH + i, String.valueOf(mapWidth));
                properties.setProperty(PROP_MAP_HEIGHT + i, String.valueOf(mapHeight));

                // create image for next zoom level
                currentWidth /= 2;
                currentHeight /= 2;
                // create temp image file name
                File nextImage = suffixFile(imageFile, i + 1);
                // resize image
                convert(currentImage, nextImage, currentWidth, currentHeight, 100);
                // delete previous temp file
                if (!currentImage.equals(imageFile)) {
                    if (!currentImage.delete()) {
                        log.warn("Error deleting " + imageFile.getAbsolutePath());
                    }
                }

                currentImage = nextImage;
            }

            // delete previous temp file
            if (!currentImage.equals(imageFile)) {
                if (!currentImage.delete()) {
                    log.warn("Error deleting " + imageFile.getAbsolutePath());
                }
            }

            // write properties file
            File propertiesFile = new File(
                    imageFile.getParentFile().getAbsolutePath() + File.separator + MAP_PROPERTIES_FILE);
            try {
                FileWriter propertiesWriter = new FileWriter(propertiesFile);
                try {
                    properties.store(propertiesWriter, "Map generated from " + imageFile.getName());
                    // add properties file to list
                    files.add(propertiesFile);
                } finally {
                    propertiesWriter.close();
                }
            } catch (IOException e) {
                log.error("Error writing map properties file", e);
            }

            // add a converter properties file
            String convProperties = askForPath(fileChooser, new ExactFileFilter(CONVERTER_PROPERTIES_FILE),
                    "Select a converter properties file");
            File convFile = null;
            if (convProperties != null) {
                convFile = new File(convProperties);
                files.add(convFile);
            }

            // create jar file
            log.info("Creating jar archive...");
            if (createJarArchive(replaceExtension(imageFile, MAP_ARCHIVE_EXTENSION), files)) {
                log.info("Archive successfully created, deleting tiles...");
                // don't delete converter properties
                if (convFile != null)
                    files.remove(files.size() - 1);
                // delete files
                for (File file : files) {
                    if (!file.delete()) {
                        log.warn("Error deleting " + file.getAbsolutePath());
                    }
                }
            }

            log.info("Fin.");
        }
    }
}

From source file:edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr.java

/**
 * Locks the semaphore./*ww w. ja va  2  s.c om*/
 * @param title The human (localized) title of the task 
 * @param name the unique name
 * @param context
 * @param scope the scope of the lock
 * @param allViewMode allows it to ask the user about 'View Only'
 * @return
 */
public static USER_ACTION lock(final String title, final String name, final String context, final SCOPE scope,
        final boolean allViewMode, final TaskSemaphoreMgrCallerIFace caller, final boolean checkUsage) {
    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();

        int count = 0;
        do {

            SpTaskSemaphore semaphore = null;
            try {
                semaphore = setLock(session, name, context, scope, true, false, checkUsage);

            } catch (StaleObjectException ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TaskSemaphoreMgr.class, ex);
                semaphore = null;
            }

            if (semaphore == null || previouslyLocked) {
                if (caller != null) {
                    return caller.resolveConflict(semaphore, previouslyLocked, prevLockedBy);
                }

                if (semaphore == null) {
                    String msg = UIRegistry.getLocalizedMessage("SpTaskSemaphore.IN_USE", title);//$NON-NLS-1$
                    Object[] options = { getResourceString("SpTaskSemaphore.TRYAGAIN"), //$NON-NLS-1$
                            getResourceString("CANCEL") //$NON-NLS-1$
                    };
                    int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(), msg,
                            getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (userChoice == JOptionPane.NO_OPTION) {
                        return USER_ACTION.Cancel;
                    }

                } else {
                    // Check to see if we have the same user on the same machine.
                    SpecifyUser user = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);
                    String currMachineName = InetAddress.getLocalHost().toString();
                    String dbMachineName = semaphore.getMachineName();

                    //System.err.println("["+dbMachineName+"]["+currMachineName+"]["+user.getId()+"]["+semaphore.getOwner().getId()+"]");
                    if (StringUtils.isNotEmpty(dbMachineName) && StringUtils.isNotEmpty(currMachineName)
                            && currMachineName.equals(dbMachineName) && semaphore.getOwner() != null
                            && user != null && user.getId().equals(semaphore.getOwner().getId())) {
                        if (allViewMode) {
                            int options = JOptionPane.YES_NO_OPTION;
                            Object[] optionLabels = new String[] {
                                    getResourceString("SpTaskSemaphore.VIEWMODE"), //$NON-NLS-1$
                                    getResourceString("CANCEL")//$NON-NLS-1$
                            };
                            int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                                    getLocalizedMessage("SpTaskSemaphore.IN_USE_BY_YOU", title),
                                    getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                                    options, JOptionPane.QUESTION_MESSAGE, null, optionLabels, 0);

                            return userChoice == JOptionPane.NO_OPTION ? USER_ACTION.Cancel
                                    : USER_ACTION.ViewMode; // CHECKED
                        }

                        int options = JOptionPane.OK_OPTION;
                        Object[] optionLabels = new String[] { getResourceString("OK")//$NON-NLS-1$
                        };
                        JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                                getLocalizedMessage("SpTaskSemaphore.IN_USE_BY_YOU", title),
                                getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                                options, JOptionPane.QUESTION_MESSAGE, null, optionLabels, 0);

                        return USER_ACTION.Cancel;
                    }

                    String userStr = prevLockedBy != null ? prevLockedBy
                            : semaphore.getOwner().getIdentityTitle();
                    String msgKey = allViewMode ? "SpTaskSemaphore.IN_USE_OV" : "SpTaskSemaphore.IN_USE";
                    String msg = UIRegistry.getLocalizedMessage(msgKey, title, userStr,
                            semaphore.getLockedTime() != null ? semaphore.getLockedTime().toString() : "");

                    int options;
                    int defBtn;
                    Object[] optionLabels;
                    if (allViewMode) {
                        defBtn = 2;
                        options = JOptionPane.YES_NO_CANCEL_OPTION;
                        optionLabels = new String[] { getResourceString("SpTaskSemaphore.VIEWMODE"), //$NON-NLS-1$
                                getResourceString("SpTaskSemaphore.TRYAGAIN"), //$NON-NLS-1$
                                getResourceString("CANCEL")//$NON-NLS-1$
                        };
                    } else {
                        defBtn = 0;
                        options = JOptionPane.YES_NO_OPTION;
                        optionLabels = new String[] { getResourceString("SpTaskSemaphore.TRYAGAIN"), //$NON-NLS-1$
                                getResourceString("CANCEL"), //$NON-NLS-1$
                        };
                    }

                    int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(), msg,
                            getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                            options, JOptionPane.QUESTION_MESSAGE, null, optionLabels, defBtn);
                    if (userChoice == JOptionPane.YES_OPTION) {
                        if (options == JOptionPane.YES_NO_CANCEL_OPTION) {
                            return USER_ACTION.ViewMode; // CHECKED
                        }
                        // this means try again

                    } else if (userChoice == JOptionPane.NO_OPTION) {
                        if (options == JOptionPane.YES_NO_OPTION) {
                            return USER_ACTION.Cancel;
                        }
                        // CHECKED

                    } else if (userChoice == JOptionPane.CANCEL_OPTION) {
                        return USER_ACTION.Cancel; // CHECKED
                    }
                }
            } else {
                return USER_ACTION.OK;
            }

            count++;

        } while (true);

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TaskSemaphoreMgr.class, ex);
        ex.printStackTrace();
        //log.error(ex);

    } finally {
        if (session != null) {
            session.close();
        }
    }
    return USER_ACTION.Error;
}

From source file:components.DialogDemo.java

/** Creates the panel shown by the second tab. */
private JPanel createFeatureDialogBox() {
    final int numButtons = 5;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();

    JButton showItButton = null;/*from  w  w  w  .j  av  a2s .c  o  m*/

    final String pickOneCommand = "pickone";
    final String textEnteredCommand = "textfield";
    final String nonAutoCommand = "nonautooption";
    final String customOptionCommand = "customoption";
    final String nonModalCommand = "nonmodal";

    radioButtons[0] = new JRadioButton("Pick one of several choices");
    radioButtons[0].setActionCommand(pickOneCommand);

    radioButtons[1] = new JRadioButton("Enter some text");
    radioButtons[1].setActionCommand(textEnteredCommand);

    radioButtons[2] = new JRadioButton("Non-auto-closing dialog");
    radioButtons[2].setActionCommand(nonAutoCommand);

    radioButtons[3] = new JRadioButton("Input-validating dialog " + "(with custom message area)");
    radioButtons[3].setActionCommand(customOptionCommand);

    radioButtons[4] = new JRadioButton("Non-modal dialog");
    radioButtons[4].setActionCommand(nonModalCommand);

    for (int i = 0; i < numButtons; i++) {
        group.add(radioButtons[i]);
    }
    radioButtons[0].setSelected(true);

    showItButton = new JButton("Show it!");
    showItButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String command = group.getSelection().getActionCommand();

            //pick one of many
            if (command == pickOneCommand) {
                Object[] possibilities = { "ham", "spam", "yam" };
                String s = (String) JOptionPane.showInputDialog(frame,
                        "Complete the sentence:\n" + "\"Green eggs and...\"", "Customized Dialog",
                        JOptionPane.PLAIN_MESSAGE, icon, possibilities, "ham");

                //If a string was returned, say so.
                if ((s != null) && (s.length() > 0)) {
                    setLabel("Green eggs and... " + s + "!");
                    return;
                }

                //If you're here, the return value was null/empty.
                setLabel("Come on, finish the sentence!");

                //text input
            } else if (command == textEnteredCommand) {
                String s = (String) JOptionPane.showInputDialog(frame,
                        "Complete the sentence:\n" + "\"Green eggs and...\"", "Customized Dialog",
                        JOptionPane.PLAIN_MESSAGE, icon, null, "ham");

                //If a string was returned, say so.
                if ((s != null) && (s.length() > 0)) {
                    setLabel("Green eggs and... " + s + "!");
                    return;
                }

                //If you're here, the return value was null/empty.
                setLabel("Come on, finish the sentence!");

                //non-auto-closing dialog
            } else if (command == nonAutoCommand) {
                final JOptionPane optionPane = new JOptionPane(
                        "The only way to close this dialog is by\n" + "pressing one of the following buttons.\n"
                                + "Do you understand?",
                        JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);

                //You can't use pane.createDialog() because that
                //method sets up the JDialog with a property change
                //listener that automatically closes the window
                //when a button is clicked.
                final JDialog dialog = new JDialog(frame, "Click a button", true);
                dialog.setContentPane(optionPane);
                dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                dialog.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent we) {
                        setLabel("Thwarted user attempt to close window.");
                    }
                });
                optionPane.addPropertyChangeListener(new PropertyChangeListener() {
                    public void propertyChange(PropertyChangeEvent e) {
                        String prop = e.getPropertyName();

                        if (dialog.isVisible() && (e.getSource() == optionPane)
                                && (JOptionPane.VALUE_PROPERTY.equals(prop))) {
                            //If you were going to check something
                            //before closing the window, you'd do
                            //it here.
                            dialog.setVisible(false);
                        }
                    }
                });
                dialog.pack();
                dialog.setLocationRelativeTo(frame);
                dialog.setVisible(true);

                int value = ((Integer) optionPane.getValue()).intValue();
                if (value == JOptionPane.YES_OPTION) {
                    setLabel("Good.");
                } else if (value == JOptionPane.NO_OPTION) {
                    setLabel("Try using the window decorations " + "to close the non-auto-closing dialog. "
                            + "You can't!");
                } else {
                    setLabel("Window unavoidably closed (ESC?).");
                }

                //non-auto-closing dialog with custom message area
                //NOTE: if you don't intend to check the input,
                //then just use showInputDialog instead.
            } else if (command == customOptionCommand) {
                customDialog.setLocationRelativeTo(frame);
                customDialog.setVisible(true);

                String s = customDialog.getValidatedText();
                if (s != null) {
                    //The text is valid.
                    setLabel("Congratulations!  " + "You entered \"" + s + "\".");
                }

                //non-modal dialog
            } else if (command == nonModalCommand) {
                //Create the dialog.
                final JDialog dialog = new JDialog(frame, "A Non-Modal Dialog");

                //Add contents to it. It must have a close button,
                //since some L&Fs (notably Java/Metal) don't provide one
                //in the window decorations for dialogs.
                JLabel label = new JLabel("<html><p align=center>" + "This is a non-modal dialog.<br>"
                        + "You can have one or more of these up<br>" + "and still use the main window.");
                label.setHorizontalAlignment(JLabel.CENTER);
                Font font = label.getFont();
                label.setFont(label.getFont().deriveFont(font.PLAIN, 14.0f));

                JButton closeButton = new JButton("Close");
                closeButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        dialog.setVisible(false);
                        dialog.dispose();
                    }
                });
                JPanel closePanel = new JPanel();
                closePanel.setLayout(new BoxLayout(closePanel, BoxLayout.LINE_AXIS));
                closePanel.add(Box.createHorizontalGlue());
                closePanel.add(closeButton);
                closePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 5));

                JPanel contentPane = new JPanel(new BorderLayout());
                contentPane.add(label, BorderLayout.CENTER);
                contentPane.add(closePanel, BorderLayout.PAGE_END);
                contentPane.setOpaque(true);
                dialog.setContentPane(contentPane);

                //Show it.
                dialog.setSize(new Dimension(300, 150));
                dialog.setLocationRelativeTo(frame);
                dialog.setVisible(true);
            }
        }
    });

    return createPane(moreDialogDesc + ":", radioButtons, showItButton);
}

From source file:com.holycityaudio.SpinCAD.SpinCADFile.java

public void fileSaveAsm(SpinCADPatch patch) {
    // Create a file chooser
    String savedPath = prefs.get("MRUSpnFolder", "");

    final JFileChooser fc = new JFileChooser(savedPath);
    // In response to a button click:
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Spin ASM Files", "spn");
    fc.setFileFilter(filter);/*from w  w  w  .jav a 2s . c  o  m*/
    // XXX DEBUG
    fc.showSaveDialog(new JFrame());
    File fileToBeSaved = fc.getSelectedFile();

    if (!fc.getSelectedFile().getAbsolutePath().endsWith(".spn")) {
        fileToBeSaved = new File(fc.getSelectedFile() + ".spn");
    }
    int n = JOptionPane.YES_OPTION;
    if (fileToBeSaved.exists()) {
        JFrame frame1 = new JFrame();
        n = JOptionPane.showConfirmDialog(frame1, "Would you like to overwrite it?", "File already exists!",
                JOptionPane.YES_NO_OPTION);
    }
    if (n == JOptionPane.YES_OPTION) {
        String filePath = fileToBeSaved.getPath();
        fileToBeSaved.delete();

        try {
            fileSaveAsm(patch, filePath);
        } catch (IOException e) {
            JOptionPane.showOptionDialog(null, "File save error!", "Error", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, null, null);
            e.printStackTrace();
        }
        saveMRUSpnFolder(filePath);
    }
}

From source file:com.mirth.connect.manager.ManagerController.java

/**
 * Alerts the user with a yes/no option with the passed in 'message'
 *///from   w  ww  . jav a2  s .co m
public boolean alertOptionDialog(Component parent, String message) {
    int option = JOptionPane.showConfirmDialog(parent, message, "Select an Option", JOptionPane.YES_NO_OPTION);
    if (option == JOptionPane.YES_OPTION) {
        return true;
    } else {
        return false;
    }
}

From source file:org.datacleaner.bootstrap.Bootstrap.java

private FileObject[] downloadFiles(String[] urls, FileObject targetDirectory, String[] targetFilenames,
        WindowContext windowContext, MonitorHttpClient httpClient, MonitorConnection monitorConnection) {
    final DownloadFilesActionListener downloadAction = new DownloadFilesActionListener(urls, targetDirectory,
            targetFilenames, null, windowContext, httpClient);
    try {/*from   w ww .  j a v  a2s.  c om*/
        downloadAction.actionPerformed(null);
        FileObject[] files = downloadAction.getFiles();
        if (logger.isInfoEnabled()) {
            logger.info("Succesfully downloaded urls: {}", Arrays.toString(urls));
        }
        return files;
    } catch (SSLPeerUnverifiedException e) {
        downloadAction.cancelDownload(true);
        if (monitorConnection == null || monitorConnection.isAcceptUnverifiedSslPeers()) {
            throw new IllegalStateException("Failed to verify SSL peer", e);
        }
        if (logger.isInfoEnabled()) {
            logger.info("SSL peer not verified. Asking user for confirmation to accept urls: {}",
                    Arrays.toString(urls));
        }
        int confirmation = JOptionPane.showConfirmDialog(null,
                "Unverified SSL peer.\n\n"
                        + "The certificate presented by the server could not be verified.\n\n"
                        + "Do you want to continue, accepting the unverified certificate?",
                "Unverified SSL peer", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
        if (confirmation != JOptionPane.YES_OPTION) {
            throw new IllegalStateException(e);
        }
        monitorConnection.setAcceptUnverifiedSslPeers(true);
        httpClient = monitorConnection.getHttpClient();

        return downloadFiles(urls, targetDirectory, targetFilenames, windowContext, httpClient,
                monitorConnection);
    }
}

From source file:condorclient.MainFXMLController.java

@FXML
void reScheduleFired(ActionEvent event) {
    //cluster?//from  w ww .  j  a  v  a  2s.c  o  m
    int oldId = 0;//??
    int delNo = 0;
    int reScheduleId = 0;

    URL url = null;

    // String scheddURLStr="http://localhost:9628";
    XMLHandler handler = new XMLHandler();
    String scheddStr = handler.getURL("schedd");
    try {
        url = new URL(scheddStr);
    } catch (MalformedURLException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
    }
    Schedd schedd = null;

    int n = JOptionPane.showConfirmDialog(null, "?????", "",
            JOptionPane.YES_NO_OPTION);
    if (n == JOptionPane.YES_OPTION) {

        //checkboxclusterId
        System.out.print(Thread.currentThread().getName() + "\n");

        try {
            schedd = new Schedd(url);
        } catch (ServiceException ex) {
            Logger.getLogger(CondorClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        //ClassAdStructAttr[]

        ClassAd ad = null;//birdbath.ClassAd;
        ClassAdStructAttr[][] classAdArray = null;
        ClassAdStructAttr[][] classAdArray2 = null;
        String taskStatus = "";

        final List<?> selectedNodeList = new ArrayList<>(table.getSelectionModel().getSelectedItems());
        for (Object o : selectedNodeList) {
            if (o instanceof ObservableDisplayedClassAd) {
                oldId = Integer.parseInt(((ObservableDisplayedClassAd) o).getClusterId());
                taskStatus = ((ObservableDisplayedClassAd) o).getJobStatus();
                if (taskStatus.equals("") || taskStatus.equals("?") || taskStatus.equals("")) {
                    JOptionPane.showMessageDialog(null, "??????");
                    return;
                }

            }
        }
        //e
        int job = 0;
        Transaction xact = schedd.createTransaction();
        try {
            xact.begin(30);

        } catch (RemoteException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println("oldId:" + oldId);

        String findreq = "owner==\"" + condoruser + "\"&&ClusterId==" + oldId;
        try {
            classAdArray = schedd.getJobAds(findreq);
            classAdArray2 = schedd.getJobAds(findreq);
        } catch (RemoteException ex) {
            Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
        }
        //?jobclassAd?
        int newClusterId = 0;
        try {
            newClusterId = xact.createCluster();

        } catch (RemoteException e) {
        }
        int newJobId = 0;
        //            XMLHandler handler = new XMLHandler();
        String oldname = handler.getJobName("" + oldId);
        String transferInput = "";
        String jobdir = null;
        //?job??job
        int jobcount = 0;
        String timestamp = (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
        System.out.println("oldname" + oldname);
        jobdir = handler.getTaskDir("" + oldId);
        String expfilename = handler.getExpFile("" + oldId);
        String infofilename = handler.getInfoFile("" + oldId);
        for (ClassAdStructAttr[] x : classAdArray) {

            ad = new ClassAd(x);
            job = Integer.parseInt(ad.get("ProcId"));
            ClassAdStructAttr[] attributes = null;// {new ClassAdStructAttr()};

            System.out.println("jobdir:===" + jobdir);

            //??
            // 
            File[] files = { new File(expfilename), new File(infofilename) };// new File[2];

            System.out.println(expfilename + "===" + infofilename);

            //
            String oldiwd = jobdir.substring(0, jobdir.length() - 14);//D:\tmp\test\dirtest\20140902200811;
            String resultdirstr = oldiwd + timestamp + "\\" + job;//job
            // new String(handler.getTaskDir(oldname).getBytes(),"UTF-8");
            //
            //attributes[0] = new ClassAdStructAttr("Iwd", ClassAdAttrType.value3, resultdirstr);
            File newjobdir = new File(resultdirstr);
            try {
                System.out.println("resultdirstr:" + resultdirstr);
                FileUtils.forceMkdir(newjobdir);
            } catch (IOException ex) {
                Logger.getLogger(CreateJobDialogController.class.getName()).log(Level.SEVERE, null, ex);
            }
            //?
            /* for (int j = 0; j < inputfilecount; j++) {
              System.out.println("j:" + j);
              try {
              FileUtils.copyFileToDirectory(files[j], newjobdir);
              } catch (IOException ex) {
              Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
              }
              }*/

            try {
                newJobId = xact.createJob(newClusterId);
            } catch (RemoteException ex) {
                Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {

                xact.submit(newClusterId, newJobId, condoruser, UniverseType.VANILLA, ad.get("Cmd"),
                        ad.get("Arguments"), ad.get("Requirements"), attributes, files);
                xact.closeSpool(oldId, job);
            } catch (RemoteException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        //s
        try {
            xact.removeCluster(oldId, "");
        } catch (RemoteException ex) {
            Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            xact.commit();
        } catch (RemoteException e) {

            e.printStackTrace();
        }
        try {
            schedd.requestReschedule();
        } catch (RemoteException ex) {
            Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("comit:" + oldname);

        String olddir = handler.getTaskDir("" + oldId);

        System.out.println("olddir:" + olddir);
        // olddir.substring(0, olddir.length() - 14);//??14?
        String newdir = olddir.substring(0, olddir.length() - 14) + timestamp;
        System.out.println("newdir:" + newdir);
        //  System.out.println(olddir+"\nmm"+newdir);
        handler.removeJob("" + oldId);
        handler.addJob(oldname, "" + newClusterId, newdir, expfilename, infofilename);

        // reConfigureButtons();
    } else if (n == JOptionPane.NO_OPTION) {
        System.out.println("qu xiao");

    }

    System.out.print("recreateTransaction succeed\n");

}

From source file:net.sf.nmedit.nomad.core.Nomad.java

public void fileSave(boolean saveAs) {
    Document d = pageContainer.getSelection();
    if (d == null)
        return;//from  w  w w .  j av  a  2s. c  o m

    if (!saveAs) {
        Iterator<FileService> iter = ServiceRegistry.getServices(FileService.class);
        FileService useService = null;
        while (iter.hasNext()) {
            FileService fs = iter.next();
            if (fs.isDirectSaveOperationSupported(d)) {
                useService = fs;
                break;
            }
        }

        if (useService != null) {
            useService.save(d, useService.getAssociatedFile(d));
            return;
        }
    }

    JFileChooser chooser = new JFileChooser();
    chooser.setSelectedFile(lastSaveInFolderLocation);
    chooser.setMultiSelectionEnabled(false);

    Iterator<FileService> iter = ServiceRegistry.getServices(FileService.class);
    while (iter.hasNext()) {
        FileService fs = iter.next();

        boolean add = (saveAs && fs.isSaveOperationSupported(d))
                || ((!saveAs) && fs.isDirectSaveOperationSupported(d));

        if (add)
            chooser.addChoosableFileFilter(fs.getFileFilter());
    }

    File sfile = d.getFile();
    if (sfile == null && d.getTitle() != null)
        sfile = new File(d.getTitle());
    if (sfile != null)
        chooser.setSelectedFile(sfile);

    if (!(chooser.showSaveDialog(mainWindow) == JFileChooser.APPROVE_OPTION))
        return;

    FileService service = FileServiceTool.lookupFileService(chooser);

    if (service != null) {
        File newFile = chooser.getSelectedFile();
        if (newFile == null)
            return;

        if (newFile.exists() && JOptionPane.showConfirmDialog(mainWindow,
                "Overwrite existing file '" + newFile.getAbsolutePath() + "' ?", "File already exists.",
                JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
            return;

        service.save(d, newFile);

        lastSaveInFolderLocation = newFile.getParentFile();
    } else {
        JOptionPane.showMessageDialog(mainWindow, "Could not find service to save file.");
    }
}