Example usage for javax.swing JOptionPane YES_NO_CANCEL_OPTION

List of usage examples for javax.swing JOptionPane YES_NO_CANCEL_OPTION

Introduction

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

Prototype

int YES_NO_CANCEL_OPTION

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

Click Source Link

Document

Type used for showConfirmDialog.

Usage

From source file:com.sshtools.shift.FileTransferDialog.java

/**
 *
 *
 * @param sftp// w w w .j a v a 2s. c  o  m
 * @param files
 * @param totalBytes
 */

public void getRemoteFiles(SftpClient sftp, java.util.List files, long totalBytes) {

    this.files = files;
    this.totalBytes = totalBytes;
    this.sftp = sftp;

    lblTargetAction.setText("Downloading to:");
    progressbar.setMaximum(100);

    if ((totalBytes / 1073741824) > 0) {
        // Were in the gigabytes
        formattedTotal = formatMb.format((double) totalBytes / 1073741824) + " GB";
    } else if ((totalBytes / 1048576) > 0) {
        // Were in the megabytes
        formattedTotal = formatMb.format((double) totalBytes / 1048576) + " MB";
    } else {
        // Were still in Kilobytes
        formattedTotal = formatKb.format((double) totalBytes / 1024) + " KB";
    }

    Thread thread = new Thread(new Runnable() {
        int i;

        public void run() {
            String pwd = FileTransferDialog.this.sftp.pwd();
            String lpwd = FileTransferDialog.this.sftp.lpwd();
            try {
                for (i = 0; i < FileTransferDialog.this.files.size(); i++) {
                    // Test whether the file exists before the download commences
                    File file = new File(lpwd + File.separator + FileTransferDialog.this.files.get(i));
                    if (file.exists()) {
                        int result = JOptionPane.showConfirmDialog(FileTransferDialog.this,
                                "This file already exists are you sure you wish to overwrite?\n\n"
                                        + file.getName(),
                                "Confirm File Overwrite", JOptionPane.YES_NO_CANCEL_OPTION);
                        if (result == JOptionPane.NO_OPTION) {
                            if (i == FileTransferDialog.this.files.size() - 1) {
                                // This was the last file for transfer
                                cancelOperation();
                                return;
                            } else {
                                String ff = pwd + "/" + FileTransferDialog.this.files.get(i);
                                FileAttributes attrs = FileTransferDialog.this.sftp.stat(ff);
                                started(attrs.getSize().longValue(), ff);
                                progressed(attrs.getSize().longValue());
                                completed();
                                // Was not the last file so goto next
                                continue;
                            }
                        }

                        if (result == JOptionPane.CANCEL_OPTION) {
                            // Cancel the upload operation
                            cancelOperation();
                            return;
                        }
                    }
                    setSource(pwd + "/" + FileTransferDialog.this.files.get(i));
                    setTarget(lpwd + File.separator + FileTransferDialog.this.files.get(i));

                    if (!cancelled) {
                        FileTransferDialog.this.sftp.get((String) FileTransferDialog.this.files.get(i),
                                FileTransferDialog.this);
                    }
                }
                // Notify any waiting threads that we've completed our operation
                completed = true;
                notifyWaiting();
            } catch (IOException ex) {
                if (!cancelled) {
                    SshToolsApplicationPanel.showErrorMessage(FileTransferDialog.this,
                            "The file operation failed!\n" + ex.getMessage(), "File Transfer", ex);
                    // Delete the partially completed file

                    File file = new File(lpwd + File.separator + FileTransferDialog.this.files.get(i));
                    if (file.exists()) {
                        file.delete();
                    }
                    setVisible(false);
                }
            }
        }
    });
    thread.start();
    try {
        setVisible(true);
    } catch (NullPointerException e) {
        setVisible(true);
    }
}

From source file:edu.ku.brc.af.prefs.PreferencesDlg.java

@Override
public boolean closePrefs() {
    if (okBtn.isEnabled()) {
        Object[] options = { getResourceString("PrefsDlg.SAVE_PREFS"), //$NON-NLS-1$
                getResourceString("PrefsDlg.DONT_SAVE_PREFS"), //$NON-NLS-1$
                getResourceString("CANCEL") //$NON-NLS-1$
        };/*w  w  w  . j  av  a 2 s .co  m*/
        int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                getResourceString("PrefsDlg.MSG"), //$NON-NLS-1$
                getResourceString("PREFERENCES"), //$NON-NLS-1$
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (userChoice == JOptionPane.YES_OPTION) {
            okButtonPressed();

        } else if (userChoice == JOptionPane.NO_OPTION) {
            cancelButtonPressed();
        } else {
            return false;
        }
    } else {
        cancelButtonPressed();
    }
    return true;
}

From source file:es.emergya.ui.plugins.admin.aux1.RecursoDialog.java

public RecursoDialog(final Recurso rec, final AdminResources adminResources) {
    super();/* w ww.ja  v  a 2s. c o  m*/
    setAlwaysOnTop(true);
    setSize(600, 400);

    setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            super.windowClosing(e);
            if (cambios) {
                int res = JOptionPane.showConfirmDialog(RecursoDialog.this,
                        "Existen cambios sin guardar. Seguro que desea cerrar la ventana?",
                        "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION);
                if (res != JOptionPane.CANCEL_OPTION) {
                    e.getWindow().dispose();
                }
            } else {
                e.getWindow().dispose();
            }
        }
    });
    final Recurso r = (rec == null) ? null : RecursoConsultas.get(rec.getId());
    if (r != null) {
        setTitle(i18n.getString("Resources.summary.titleWindow") + " " + r.getIdentificador());
    } else {
        setTitle(i18n.getString("Resources.summary.titleWindow.new"));
    }
    setIconImage(getBasicWindow().getFrame().getIconImage());
    JPanel base = new JPanel();
    base.setBackground(Color.WHITE);
    base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS));

    // Icono del titulo
    JPanel title = new JPanel(new FlowLayout(FlowLayout.LEADING));
    title.setOpaque(false);
    JLabel labelTitulo = null;
    if (r != null) {
        labelTitulo = new JLabel(i18n.getString("Resources.summary"),
                LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT);

    } else {
        labelTitulo = new JLabel(i18n.getString("Resources.cabecera.nuevo"),
                LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT);

    }
    labelTitulo.setFont(LogicConstants.deriveBoldFont(12f));
    title.add(labelTitulo);
    base.add(title);

    // Nombre
    JPanel mid = new JPanel(new SpringLayout());
    mid.setOpaque(false);
    mid.add(new JLabel(i18n.getString("Resources.name"), JLabel.RIGHT));
    final JTextField name = new JTextField(25);
    if (r != null) {
        name.setText(r.getNombre());
    }

    name.getDocument().addDocumentListener(changeListener);
    name.setEditable(r == null);
    mid.add(name);

    // patrullas
    final JLabel labelSquads = new JLabel(i18n.getString("Resources.squad"), JLabel.RIGHT);
    mid.add(labelSquads);
    List<Patrulla> pl = PatrullaConsultas.getAll();
    pl.add(0, null);
    final JComboBox squads = new JComboBox(pl.toArray());
    squads.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXX");
    squads.addActionListener(changeSelectionListener);
    squads.setOpaque(false);
    labelSquads.setLabelFor(squads);
    if (r != null) {
        squads.setSelectedItem(r.getPatrullas());
    } else {
        squads.setSelectedItem(null);
    }
    squads.setEnabled((r != null && r.getHabilitado() != null) ? r.getHabilitado() : true);
    mid.add(squads);

    // // Identificador
    // mid.setOpaque(false);
    // mid.add(new JLabel(i18n.getString("Resources.identificador"),
    // JLabel.RIGHT));
    // final JTextField identificador = new JTextField("");
    // if (r != null) {
    // identificador.setText(r.getIdentificador());
    // }
    // identificador.getDocument().addDocumentListener(changeListener);
    // identificador.setEditable(r == null);
    // mid.add(identificador);
    // Espacio en blanco
    // mid.add(Box.createHorizontalGlue());
    // mid.add(Box.createHorizontalGlue());

    // Tipo
    final JLabel labelTipoRecursos = new JLabel(i18n.getString("Resources.type"), JLabel.RIGHT);
    mid.add(labelTipoRecursos);
    final JComboBox types = new JComboBox(RecursoConsultas.getTipos());
    labelTipoRecursos.setLabelFor(types);
    types.addActionListener(changeSelectionListener);
    if (r != null) {
        types.setSelectedItem(r.getTipo());
    } else {
        types.setSelectedItem(0);
    }
    // types.setEditable(true);
    types.setEnabled(true);
    mid.add(types);

    // Estado Eurocop
    mid.add(new JLabel(i18n.getString("Resources.status"), JLabel.RIGHT));
    final JTextField status = new JTextField();
    if (r != null && r.getEstadoEurocop() != null) {
        status.setText(r.getEstadoEurocop().getIdentificador());
    }
    status.setEditable(false);
    mid.add(status);

    // Subflota y patrulla
    mid.add(new JLabel(i18n.getString("Resources.subfleet"), JLabel.RIGHT));
    final JComboBox subfleets = new JComboBox(FlotaConsultas.getAllHabilitadas());
    subfleets.addActionListener(changeSelectionListener);
    if (r != null) {
        subfleets.setSelectedItem(r.getFlotas());
    } else {
        subfleets.setSelectedIndex(0);
    }
    subfleets.setEnabled(true);
    subfleets.setOpaque(false);
    mid.add(subfleets);

    // Referencia humana
    mid.add(new JLabel(i18n.getString("Resources.incidences"), JLabel.RIGHT));
    final JTextField rhumana = new JTextField();
    // if (r != null && r.getIncidencias() != null) {
    // rhumana.setText(r.getIncidencias().getReferenciaHumana());
    // }
    rhumana.setEditable(false);
    mid.add(rhumana);

    // dispositivo
    mid.add(new JLabel(i18n.getString("Resources.device"), JLabel.RIGHT));
    final PlainDocument plainDocument = new PlainDocument() {

        private static final long serialVersionUID = 4929271093724956016L;

        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if (this.getLength() + str.length() <= LogicConstants.LONGITUD_ISSI) {
                super.insertString(offs, str, a);
            }
        }
    };
    final JTextField issi = new JTextField(plainDocument, "", LogicConstants.LONGITUD_ISSI);
    plainDocument.addDocumentListener(changeListener);
    issi.setEditable(true);
    mid.add(issi);
    mid.add(new JLabel(i18n.getString("Resources.enabled"), JLabel.RIGHT));
    final JCheckBox enabled = new JCheckBox("", true);
    enabled.addActionListener(changeSelectionListener);
    enabled.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (enabled.isSelected()) {
                squads.setSelectedIndex(0);
            }
            squads.setEnabled(enabled.isSelected());
        }
    });
    enabled.setEnabled(true);
    enabled.setOpaque(false);
    if (r != null) {
        enabled.setSelected(r.getHabilitado());
    } else {
        enabled.setSelected(true);
    }
    if (r != null && r.getDispositivo() != null) {
        issi.setText(
                StringUtils.leftPad(String.valueOf(r.getDispositivo()), LogicConstants.LONGITUD_ISSI, '0'));
    }

    mid.add(enabled);

    // Fecha ultimo gps
    mid.add(new JLabel(i18n.getString("Resources.lastPosition"), JLabel.RIGHT));
    JTextField lastGPS = new JTextField();
    final Date lastGPSDateForRecurso = HistoricoGPSConsultas.lastGPSDateForRecurso(r);
    if (lastGPSDateForRecurso != null) {
        lastGPS.setText(SimpleDateFormat.getDateTimeInstance().format(lastGPSDateForRecurso));
    }
    lastGPS.setEditable(false);
    mid.add(lastGPS);

    // Espacio en blanco
    mid.add(Box.createHorizontalGlue());
    mid.add(Box.createHorizontalGlue());

    // informacion adicional
    JPanel infoPanel = new JPanel(new SpringLayout());
    final JTextField info = new JTextField(25);
    info.getDocument().addDocumentListener(changeListener);
    infoPanel.add(new JLabel(i18n.getString("Resources.info")));
    infoPanel.add(info);
    infoPanel.setOpaque(false);
    info.setOpaque(false);
    SpringUtilities.makeCompactGrid(infoPanel, 1, 2, 6, 6, 6, 18);

    if (r != null) {
        info.setText(r.getInfoAdicional());
    } else {
        info.setText("");
    }
    info.setEditable(true);

    // Espacio en blanco
    mid.add(Box.createHorizontalGlue());
    mid.add(Box.createHorizontalGlue());

    SpringUtilities.makeCompactGrid(mid, 5, 4, 6, 6, 6, 18);
    base.add(mid);
    base.add(infoPanel);

    JPanel buttons = new JPanel();
    buttons.setOpaque(false);
    JButton accept = null;
    if (r == null) {
        accept = new JButton("Crear", LogicConstants.getIcon("button_crear"));
    } else {
        accept = new JButton("Guardar", LogicConstants.getIcon("button_save"));
    }
    accept.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                if (cambios || r == null || r.getId() == null) {
                    boolean shithappens = true;
                    if ((r == null || r.getId() == null)) { // Estamos
                        // creando
                        // uno nuevo
                        if (RecursoConsultas.alreadyExists(name.getText())) {
                            shithappens = false;
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.nombreUnico"));
                        } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils
                                .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) {
                            JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT,
                                    "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI));
                            shithappens = false;
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && LogicConstants.isNumeric(issi.getText())
                                && RecursoConsultas.alreadyExists(new Integer(issi.getText()))) {
                            shithappens = false;
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.dispositivoUnico"));
                        }
                    }
                    if (shithappens) {
                        if (name.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.nombreNulo"));
                        } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils
                                .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) {
                            JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT,
                                    "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI));
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && LogicConstants.isNumeric(issi.getText()) && r != null && r.getId() != null
                                && RecursoConsultas.alreadyExists(new Integer(issi.getText()), r.getId())) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.issiUnico"));
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && !LogicConstants.isNumeric(issi.getText())) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noNumerico"));
                            // } else if (identificador.getText().isEmpty())
                            // {
                            // JOptionPane
                            // .showMessageDialog(
                            // RecursoDialog.this,
                            // i18n.getString("admin.recursos.popup.error.identificadorNulo"));
                        } else if (subfleets.getSelectedIndex() == -1) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noSubflota"));
                        } else if (types.getSelectedItem() == null
                                || types.getSelectedItem().toString().trim().isEmpty()) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noTipo"));
                        } else {
                            int i = JOptionPane.showConfirmDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.dialogo.guardar.titulo"),
                                    i18n.getString("admin.recursos.popup.dialogo.guardar.guardar"),
                                    JOptionPane.YES_NO_CANCEL_OPTION);

                            if (i == JOptionPane.YES_OPTION) {

                                Recurso recurso = r;

                                if (r == null) {
                                    recurso = new Recurso();
                                }

                                recurso.setInfoAdicional(info.getText());
                                if (issi.getText() != null && issi.getText().length() > 0) {
                                    recurso.setDispositivo(new Integer(issi.getText()));
                                } else {
                                    recurso.setDispositivo(null);
                                }
                                recurso.setFlotas(FlotaConsultas.find(subfleets.getSelectedItem().toString()));
                                if (squads.getSelectedItem() != null && enabled.isSelected()) {
                                    recurso.setPatrullas(
                                            PatrullaConsultas.find(squads.getSelectedItem().toString()));
                                } else {
                                    recurso.setPatrullas(null);
                                }
                                recurso.setNombre(name.getText());
                                recurso.setHabilitado(enabled.isSelected());
                                // recurso.setIdentificador(identificador
                                // .getText());
                                recurso.setTipo(types.getSelectedItem().toString());
                                dispose();

                                RecursoAdmin.saveOrUpdate(recurso);
                                adminResources.refresh(null);

                                PluginEventHandler.fireChange(adminResources);
                            } else if (i == JOptionPane.NO_OPTION) {
                                dispose();
                            }
                        }
                    }
                } else {
                    log.debug("No hay cambios");
                    dispose();
                }

            } catch (Throwable t) {
                log.error("Error guardando un recurso", t);
            }
        }
    });
    buttons.add(accept);

    JButton cancelar = new JButton("Cancelar", LogicConstants.getIcon("button_cancel"));

    cancelar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (cambios) {
                if (JOptionPane.showConfirmDialog(RecursoDialog.this,
                        "Existen cambios sin guardar. Seguro que desea cerrar la ventana?",
                        "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.CANCEL_OPTION) {
                    dispose();
                }
            } else {
                dispose();
            }
        }
    });

    buttons.add(cancelar);

    base.add(buttons);

    getContentPane().add(base);
    setLocationRelativeTo(null);
    cambios = false;
    if (r == null) {
        cambios = true;
    }

    pack();

    int x;
    int y;

    Container myParent = getBasicWindow().getPluginContainer().getDetachedTab(0);
    Point topLeft = myParent.getLocationOnScreen();
    Dimension parentSize = myParent.getSize();

    Dimension mySize = getSize();

    if (parentSize.width > mySize.width) {
        x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
    } else {
        x = topLeft.x;
    }

    if (parentSize.height > mySize.height) {
        y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
    } else {
        y = topLeft.y;
    }

    setLocation(x, y);
    cambios = false;
}

From source file:strobe.spectroscopy.StrobeSpectroscopy.java

private void menuFileSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuFileSaveActionPerformed
    int result = fileChooser.showSaveDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        if (selectedFile.exists()) {
            int resultOverride = JOptionPane.showConfirmDialog(this, "File is already exists.", "Rewrite file?",
                    JOptionPane.YES_NO_CANCEL_OPTION);

            switch (resultOverride) {
            case JOptionPane.NO_OPTION:
                menuFileSaveActionPerformed(evt);
                return;
            case JOptionPane.CANCEL_OPTION:
                fileChooser.cancelSelection();
                return;
            }/*from w ww  .ja  va2 s .c o m*/

            fileChooser.approveSelection();
        }
        String name = selectedFile.getName();

        String fileNameForSave = (name.contains(".txt") ? selectedFile.getPath()
                : selectedFile.getPath() + ".txt");

        if (!dataGraphList.isEmpty()) {
            DataUtils.writeData(dataGraphList, fileNameForSave);
        } else {
            JOptionPane.showMessageDialog(this, "No data to write!");
            fileChooser.cancelSelection();
        }
    }
    dataGraphList.clear();
}

From source file:edu.ku.brc.af.ui.forms.formatters.UIFormatterEditorDlg.java

/**
 * //  w w w .  ja v  a  2 s. co  m
 */
protected void checkForChanges() {
    if (fieldHasChanged) {
        Object[] options = { getResourceString("SAVE"), //$NON-NLS-1$ 
                getResourceString("DISCARD") }; //$NON-NLS-1$
        int retVal = JOptionPane.showOptionDialog(null, getResourceString("FFE_SAVE_CHG"), //$NON-NLS-1$
                getResourceString("SaveChangesTitle"), JOptionPane.YES_NO_CANCEL_OPTION, //$NON-NLS-1$
                JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (retVal == JOptionPane.YES_OPTION) {
            fieldsPanel.getEditBtn().doClick();
        }
    }
}

From source file:com.jvms.i18neditor.editor.Editor.java

public boolean closeCurrentProject() {
    boolean result = true;
    if (dirty) {//from ww w .ja v a  2s. c  om
        int confirm = JOptionPane.showConfirmDialog(this, MessageBundle.get("dialogs.save.text"),
                MessageBundle.get("dialogs.save.title"), JOptionPane.YES_NO_CANCEL_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            result = saveProject();
        } else {
            result = confirm != JOptionPane.CANCEL_OPTION;
        }
    }
    if (result && project != null) {
        storeProjectState();
    }
    if (result && dirty) {
        setDirty(false);
    }
    return result;
}

From source file:de.ailis.xadrian.frames.MainFrame.java

/**
 * Closes the current tab. Prompts for saving unsaved changes before
 * closing. Returns true if the tab was closed or false if it was not
 * closed./*  ww w  .j  av  a  2 s  .com*/
 *
 * @return True if tab was closed, false if not
 */
public boolean closeCurrentTab() {
    final Component current = getCurrentTab();
    if (current != null) {
        final ComplexEditor editor = (ComplexEditor) current;
        if (editor.isChanged()) {
            final int answer = JOptionPane.showConfirmDialog(null,
                    I18N.getString("confirm.saveChanges", editor.getComplex().getName()),
                    I18N.getTitle("confirm.saveChanges"), JOptionPane.YES_NO_CANCEL_OPTION);
            if (answer == JOptionPane.CLOSED_OPTION)
                return false;
            if (answer == JOptionPane.CANCEL_OPTION)
                return false;
            if (answer == JOptionPane.YES_OPTION) {
                editor.save();
                if (editor.isChanged())
                    return false;
            }
        }

        this.tabs.remove(current);

        // Replace the tab control with the welcome panel if no tabs present
        if (this.tabs.getTabCount() == 0) {
            remove(this.tabs);
            add(this.welcomePanel, BorderLayout.CENTER);
            repaint();
        }

        fireChange();
        return true;
    }
    return false;
}

From source file:com.dragoniade.deviantart.favorites.FavoritesDownloader.java

private String getDocumentUrl(Deviation da, AtomicBoolean download) {
    String downloadUrl = da.getDocumentDownloadUrl();
    GetMethod method = new GetMethod(downloadUrl);

    try {//from   w ww .  j  av  a2s.  c o m
        int sc = -1;
        do {
            method.setFollowRedirects(false);
            sc = client.executeMethod(method);
            requestCount++;

            if (sc >= 300 && sc <= 399) {
                String location = method.getResponseHeader("Location").getValue();
                method.releaseConnection();
                return location;
            } else {
                LoggableException ex = new LoggableException(method.getResponseBodyAsString());
                Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ex);

                int res = showConfirmDialog(owner,
                        "An error has occured when contacting deviantART : error " + sc + ". Try again?",
                        "Continue?", JOptionPane.YES_NO_CANCEL_OPTION);
                if (res == JOptionPane.NO_OPTION) {
                    String text = "<br/><a style=\"color:red;\" href=\"" + da.getUrl() + "\">" + downloadUrl
                            + " has an error" + "</a>";
                    setPaneText(text);
                    method.releaseConnection();
                    progress.incremTotal();
                    download.set(false);
                    return null;
                }
                if (res == JOptionPane.CANCEL_OPTION) {
                    return null;
                }
            }
        } while (true);
    } catch (HttpException e) {
        showMessageDialog(owner, "Error contacting deviantART: " + e.getMessage(), "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    } catch (IOException e) {
        showMessageDialog(owner, "Error contacting deviantART: " + e.getMessage(), "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    }
}

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

/**
 * Locks the semaphore.//from  www .j a v a2s  .  co m
 * @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:ru.apertum.qsystem.client.forms.FAdmin.java

/**
     * Creates new form FAdmin//from   www  .j a v  a  2  s. com
     */
    public FAdmin() {
        addWindowListener(new WindowListener() {

            @Override
            public void windowOpened(WindowEvent e) {
            }

            @Override
            public void windowClosing(WindowEvent e) {
                timer.stop();
            }

            @Override
            public void windowClosed(WindowEvent e) {
            }

            @Override
            public void windowIconified(WindowEvent e) {
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
            }

            @Override
            public void windowActivated(WindowEvent e) {
                Uses.closeSplash();
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
            }
        });
        initComponents();

        setTitle(getTitle() + " " + Uses.getLocaleMessage("project.name" + FAbout.getCMRC_SUFF()));

        try {
            setIconImage(
                    ImageIO.read(FAdmin.class.getResource("/ru/apertum/qsystem/client/forms/resources/admin.png")));
        } catch (IOException ex) {
            System.err.println(ex);
        }

        // 
        final Toolkit kit = Toolkit.getDefaultToolkit();
        setLocation((Math.round(kit.getScreenSize().width - getWidth()) / 2),
                (Math.round(kit.getScreenSize().height - getHeight()) / 2));
        // ? ?
        final JFrame fr = this;
        tray = QTray.getInstance(fr, "/ru/apertum/qsystem/client/forms/resources/admin.png",
                getLocaleMessage("tray.caption"));
        tray.addItem(getLocaleMessage("tray.caption"), (ActionEvent e) -> {
            setVisible(true);
            setState(JFrame.NORMAL);
        });
        tray.addItem("-", (ActionEvent e) -> {
        });
        tray.addItem(getLocaleMessage("tray.exit"), (ActionEvent e) -> {
            dispose();
            System.exit(0);
        });

        int ii = 1;
        final ButtonGroup bg = new ButtonGroup();
        final String currLng = Locales.getInstance().getLangCurrName();
        for (String lng : Locales.getInstance().getAvailableLocales()) {
            final JRadioButtonMenuItem item = new JRadioButtonMenuItem(
                    org.jdesktop.application.Application.getInstance(ru.apertum.qsystem.QSystem.class).getContext()
                            .getActionMap(FAdmin.class, fr).get("setCurrentLang"));
            bg.add(item);
            item.setSelected(lng.equals(currLng));
            item.setText(lng); // NOI18N
            item.setName("QRadioButtonMenuItem" + (ii++)); // NOI18N
            menuLangs.add(item);
        }

        //  ??    ??.
        listUsers.addListSelectionListener((ListSelectionEvent e) -> {
            userListChange();
        });
        //  ??    ??.
        listResponse.addListSelectionListener((ListSelectionEvent e) -> {
            responseListChange();
        });
        listSchedule.addListSelectionListener((ListSelectionEvent e) -> {
            scheduleListChange();
        });
        listCalendar.addListSelectionListener(new ListSelectionListener() {

            private int oldSelectedValue = 0;
            private int tmp = 0;

            public int getOldSelectedValue() {
                return oldSelectedValue;
            }

            public void setOldSelectedValue(int oldSelectedValue) {
                this.oldSelectedValue = tmp;
                this.tmp = oldSelectedValue;
            }

            private boolean canceled = false;

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (canceled) {
                    canceled = false;
                } else {
                    if (tableCalendar.getModel() instanceof CalendarTableModel) {
                        final CalendarTableModel model = (CalendarTableModel) tableCalendar.getModel();
                        if (!model.isSaved()) {
                            final int res = JOptionPane.showConfirmDialog(null,
                                    getLocaleMessage("calendar.change.title"),
                                    getLocaleMessage("calendar.change.caption"), JOptionPane.YES_NO_CANCEL_OPTION,
                                    JOptionPane.QUESTION_MESSAGE);
                            switch (res) {
                            case 0: // ?  ??
                                model.save();
                                calendarListChange();
                                setOldSelectedValue(listCalendar.getSelectedIndex());
                                break;
                            case 1: // ??  ??

                                calendarListChange();
                                setOldSelectedValue(listCalendar.getSelectedIndex());

                                break;
                            case 2: //  ??  ???   
                                canceled = true;
                                listCalendar.setSelectedIndex(getOldSelectedValue());
                                break;
                            }
                        } else {
                            calendarListChange();
                            setOldSelectedValue(listCalendar.getSelectedIndex());
                        }
                    } else {
                        calendarListChange();
                        setOldSelectedValue(listCalendar.getSelectedIndex());
                    }
                }
            }
        });
        //  ??  ?  ??.
        treeServices.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        treeInfo.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        /*
         treeServices.setCellRenderer(new DefaultTreeCellRenderer() {
            
         @Override
         public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
         super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
         setText(((Element) value).attributeValue(Uses.TAG_NAME));
         return this;
         }
         });*/
        treeServices.addTreeSelectionListener((TreeSelectionEvent e) -> {
            serviceListChange();
        });
        treeInfo.addTreeSelectionListener((TreeSelectionEvent e) -> {
            infoListChange();
        });

        textFieldStartTime.setInputVerifier(DateVerifier);
        textFieldFinishTime.setInputVerifier(DateVerifier);

        // ?
        loadSettings();
        //   ? ?.
        startTimer();
        //  
        loadConfig();

        spinnerPropServerPort.getModel().addChangeListener(new ChangeNet());
        spinnerPropClientPort.getModel().addChangeListener(new ChangeNet());
        spinnerWebServerPort.getModel().addChangeListener(new ChangeNet());

        spinnerServerPort.getModel().addChangeListener(new ChangeSettings());
        spinnerClientPort.getModel().addChangeListener(new ChangeSettings());
        spinnerUserRS.getModel().addChangeListener(new ChangeUser());

        //?   .
        final Helper helper = Helper.getHelp("ru/apertum/qsystem/client/help/admin.hs");
        helper.setHelpListener(menuItemHelp);
        helper.enableHelpKey(jPanel1, "introduction");
        helper.enableHelpKey(jPanel3, "monitoring");
        helper.enableHelpKey(jPanel4, "configuring");
        helper.enableHelpKey(jPanel8, "net");

        helper.enableHelpKey(jPanel17, "schedulers");
        helper.enableHelpKey(jPanel19, "calendars");
        helper.enableHelpKey(jPanel2, "infoSystem");
        helper.enableHelpKey(jPanel13, "responses");
        helper.enableHelpKey(jPanel18, "results");

        treeServices.setTransferHandler(new TransferHandler() {

            @Override
            public boolean canImport(TransferHandler.TransferSupport info) {
                final JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation();
                if (dl.getChildIndex() == -1) {
                    return false;
                }
                // Get the string that is being dropped.
                final Transferable t = info.getTransferable();
                final QService data;
                try {
                    data = (QService) t.getTransferData(DataFlavor.stringFlavor);
                    return (data.getParent().getId()
                            .equals(((QService) dl.getPath().getLastPathComponent()).getId()));
                } catch (UnsupportedFlavorException | IOException e) {
                    return false;
                }
            }

            @Override
            public boolean importData(TransferHandler.TransferSupport info) {
                if (!info.isDrop()) {
                    return false;
                }
                final QService data;
                try {
                    data = (QService) info.getTransferable().getTransferData(DataFlavor.stringFlavor);
                } catch (UnsupportedFlavorException | IOException e) {
                    System.err.println(e);
                    return false;
                }
                final JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation();
                final TreePath tp = dl.getPath();
                final QService parent = (QService) tp.getLastPathComponent();
                ((QServiceTree) treeServices.getModel()).moveNode(data, parent, dl.getChildIndex());
                return true;
            }

            @Override
            public int getSourceActions(JComponent c) {
                return MOVE;
            }

            @Override
            protected Transferable createTransferable(JComponent c) {
                return (QService) ((JTree) c).getLastSelectedPathComponent();
            }
        });
        treeServices.setDropMode(DropMode.INSERT);

        //   ?
        final AnnotationSessionFactoryBean as = (AnnotationSessionFactoryBean) Spring.getInstance().getFactory()
                .getBean("conf");
        if (as.getServers().size() > 1) {
            final JMenu menu = new JMenu(getLocaleMessage("admin.servers"));
            as.getServers().stream().map((ser) -> {
                final JMenuItem mi1 = new JMenuItem(as);
                mi1.setText(ser.isCurrent() ? "<html><u><i>" + ser.getName() + "</i></u>" : ser.getName());
                return mi1;
            }).forEach((mi1) -> {
                menu.add(mi1);
            });
            jMenuBar1.add(menu, 4);
            jMenuBar1.add(new JLabel(
                    "<html><span style='font-size:13.0pt;color:red'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  ["
                            + as.getName() + "]"));
        }
        comboBoxVoices.setVisible(false);
    }