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:dbseer.gui.panel.DBSeerMiddlewarePanel.java

@Override
public void actionPerformed(ActionEvent actionEvent) {
    try {// w  w  w. ja v a 2  s. co m
        if (actionEvent.getSource() == startMonitoringButton) {
            id = idField.getText();
            password = String.valueOf(passwordField.getPassword());
            ip = ipField.getText();
            port = Integer.parseInt(portField.getText());
            //            liveDatasetPath = DBSeerGUI.userSettings.getDBSeerRootPath() + File.separator +
            //                  DBSeerConstants.LIVE_DATASET_PATH;
            String date = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            currentDatasetPath = DBSeerGUI.userSettings.getDBSeerRootPath() + File.separator
                    + DBSeerConstants.ROOT_DATASET_PATH + File.separator + date;

            final File newDatasetDirectory = new File(currentDatasetPath);

            // create new dataset directory
            FileUtils.forceMkdir(newDatasetDirectory);

            if (newDatasetDirectory == null || !newDatasetDirectory.isDirectory()) {
                JOptionPane.showMessageDialog(DBSeerGUI.mainFrame,
                        String.format("We could not create the dataset directory: %s", currentDatasetPath),
                        "Message", JOptionPane.PLAIN_MESSAGE);
                return;
            }

            if (runner != null) {
                runner.stop();
            }

            DBSeerGUI.liveMonitorPanel.reset();
            DBSeerGUI.liveMonitorInfo.reset();

            DBSeerGUI.middlewareStatus.setText("Middleware: Connecting...");
            startMonitoringButton.setEnabled(false);
            stopMonitoringButton.setEnabled(false);

            connectSuccess = true;
            runner = new MiddlewareClientRunner(id, password, ip, port, currentDatasetPath, this);
            runner.run();

            int sleepCount = 0;
            while (liveLogProcessor == null || !liveLogProcessor.isStarted()) {
                Thread.sleep(250);
                sleepCount += 250;
                if (!connectSuccess) {
                    return;
                }
                if (sleepCount > 10000) {
                    JOptionPane.showMessageDialog(DBSeerGUI.mainFrame,
                            String.format("Failed to receive live logs."), "Message",
                            JOptionPane.PLAIN_MESSAGE);
                    runner.stop();
                    liveLogProcessor = null;
                    return;
                }
            }

            DBSeerGUI.liveDatasets.clear();

            String[] servers = liveLogProcessor.getServers();
            for (String s : servers) {
                DBSeerDataSet newDataset = new DBSeerDataSet();
                newDataset.setName(date + "_" + s);
                OpenDirectoryAction openDir = new OpenDirectoryAction(newDataset);
                openDir.openWithoutDialog(new File(newDatasetDirectory + File.separator + s));
                DBSeerGUI.datasets.addElement(newDataset);
                newDataset.setCurrent(true);
                DBSeerGUI.liveDatasets.add(newDataset);
            }
            if (servers.length > 1) {
                DBSeerDataSet newDataset = new DBSeerDataSet();
                newDataset.setName(date + "_all");
                OpenDirectoryAction openDir = new OpenDirectoryAction(newDataset);
                openDir.openWithoutDialog(newDatasetDirectory);
                DBSeerGUI.datasets.addElement(newDataset);
                newDataset.setCurrent(true);
                DBSeerGUI.liveDatasets.add(newDataset);
            }

            // save last middleware connection
            DBSeerGUI.userSettings.setLastMiddlewareIP(ip);
            DBSeerGUI.userSettings.setLastMiddlewarePort(port);
            DBSeerGUI.userSettings.setLastMiddlewareID(id);

            XStreamHelper xmlHelper = new XStreamHelper();
            xmlHelper.toXML(DBSeerGUI.userSettings, DBSeerGUI.settingsPath);
        } else if (actionEvent.getSource() == stopMonitoringButton) {
            int stopMonitoring = JOptionPane.showConfirmDialog(DBSeerGUI.mainFrame,
                    "Do you really want to stop monitoring?", "Stop Monitoring", JOptionPane.YES_NO_OPTION);

            if (stopMonitoring == JOptionPane.YES_OPTION) {
                if (runner != null) {
                    runner.stop();
                }
                if (liveLogProcessor != null) {
                    liveLogProcessor.stop();
                }

                for (DBSeerDataSet dataset : DBSeerGUI.liveDatasets) {
                    dataset.setCurrent(false);
                }
                boolean isRemoved = false;
                if (DBSeerGUI.dbscan == null
                        || (DBSeerGUI.dbscan != null && !DBSeerGUI.dbscan.isInitialized())) {
                    JOptionPane.showMessageDialog(DBSeerGUI.mainFrame, String.format(
                            "Not enough transactions for clustering. You need at least %d transactions. Datasets are removed.",
                            DBSeerGUI.settings.dbscanInitPts), "Message", JOptionPane.PLAIN_MESSAGE);

                    for (DBSeerDataSet dataset : DBSeerGUI.liveDatasets) {
                        DBSeerGUI.datasets.removeElement(dataset);
                    }
                    isRemoved = true;
                }

                if (!isRemoved) {
                    if (liveLogProcessor != null && !liveLogProcessor.isTxWritingStarted()) {
                        JOptionPane.showMessageDialog(DBSeerGUI.mainFrame, String.format(
                                "Live monitoring has not written any transactions yet. Datasets are removed."),
                                "Message", JOptionPane.PLAIN_MESSAGE);

                        for (DBSeerDataSet dataset : DBSeerGUI.liveDatasets) {
                            DBSeerGUI.datasets.removeElement(dataset);
                        }
                    }
                }
                DBSeerGUI.liveDatasets.clear();

                if (liveLogProcessor != null) {
                    liveLogProcessor = null;
                }

                DBSeerGUI.liveMonitorPanel.reset();

                startMonitoringButton.setEnabled(true);
                stopMonitoringButton.setEnabled(false);
                DBSeerGUI.middlewareStatus.setText("Middleware: Not Connected");
            }
            //            if (DBSeerGUI.dbscan == null ||
            //                  (DBSeerGUI.dbscan != null && !DBSeerGUI.dbscan.isInitialized()))
            //            {
            //               JOptionPane.showMessageDialog(DBSeerGUI.mainFrame,
            //                     String.format("Not enough transactions for clustering. You need at least %d transactions. Dataset is not saved.", DBSeerGUI.settings.dbscanInitPts),
            //                     "Message", JOptionPane.PLAIN_MESSAGE);
            //
            //               DBSeerGUI.liveMonitorPanel.reset();
            //               DBSeerGUI.liveMonitorInfo.reset();
            //
            //               startMonitoringButton.setEnabled(true);
            //               stopMonitoringButton.setEnabled(false);
            //               DBSeerGUI.middlewareStatus.setText("Middleware: Not Connected");
            //
            //               return;
            //            }
            //            if (!liveLogProcessor.isTxWritingStarted())
            //            {
            //               JOptionPane.showMessageDialog(DBSeerGUI.mainFrame,
            //                     String.format("Live monitoring has not written any transactions yet. Dataset is not saved."),
            //                     "Message", JOptionPane.PLAIN_MESSAGE);
            //
            //               DBSeerGUI.liveMonitorPanel.reset();
            //               DBSeerGUI.liveMonitorInfo.reset();
            //
            //               startMonitoringButton.setEnabled(true);
            //               stopMonitoringButton.setEnabled(false);
            //               DBSeerGUI.middlewareStatus.setText("Middleware: Not Connected");
            //
            //               return;
            //            }
            //
            //            int saveResult = JOptionPane.showConfirmDialog(DBSeerGUI.mainFrame, "Do you want to save the monitored data?",
            //                  "Save monitored data as a dataset", JOptionPane.YES_NO_OPTION);
            //
            //            if (saveResult == JOptionPane.YES_OPTION)
            //            {
            //               String date = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            //               String newDatasetPath = DBSeerGUI.userSettings.getDBSeerRootPath() + File.separator +
            //                     DBSeerConstants.ROOT_DATASET_PATH + File.separator + date;
            //               File liveDatasetDirectory = new File(liveDatasetPath);
            //               final File newDatasetDirectory = new File(newDatasetPath);
            //
            //               // create new dataset directory
            //               FileUtils.forceMkdir(newDatasetDirectory);
            //
            //               // copy dataset
            //               FileUtils.copyDirectory(liveDatasetDirectory, newDatasetDirectory, false);
            //
            //               // show message dialog.
            //               JOptionPane.showMessageDialog(DBSeerGUI.mainFrame,
            //                     String.format("Dataset has been successfully saved under '%s'", newDatasetDirectory.getCanonicalPath()),
            //                     "Message", JOptionPane.PLAIN_MESSAGE);
            //
            //               String[] servers = liveLogProcessor.getServers();
            //               for (String s : servers)
            //               {
            //                  DBSeerDataSet newDataset = new DBSeerDataSet();
            //                  newDataset.setName(date + "_" + s);
            //                  OpenDirectoryAction openDir = new OpenDirectoryAction(newDataset);
            //                  openDir.openWithoutDialog(new File(newDatasetDirectory + File.separator + s));
            //                  DBSeerGUI.datasets.addElement(newDataset);
            //               }
            //               if (servers.length > 1)
            //               {
            //                  DBSeerDataSet newDataset = new DBSeerDataSet();
            //                  newDataset.setName(date + "_all");
            //                  OpenDirectoryAction openDir = new OpenDirectoryAction(newDataset);
            //                  openDir.openWithoutDialog(newDatasetDirectory);
            //                  DBSeerGUI.datasets.addElement(newDataset);
            //               }
            //               SaveSettingsAction saveSettings = new SaveSettingsAction();
            //               saveSettings.actionPerformed(new ActionEvent(this, 0, ""));
            //            }

        } else if (actionEvent.getSource() == applyRefreshRateButton) {
            int rate = Integer.parseInt(refreshRateField.getText());
            DBSeerGUI.liveMonitorRefreshRate = rate;
        }
    } catch (Exception e) {
        DBSeerExceptionHandler.handleException(e);
    }
    // old implementation
    /*
    final MiddlewareSocket socket = DBSeerGUI.middlewareSocket;
    if (actionEvent.getSource() == logInOutButton)
    {
       if (!isLoggedIn)
       {
            
    String ip = ipField.getText();
    int port = Integer.parseInt(portField.getText());
    String id = idField.getText();
    String password = String.valueOf(passwordField.getPassword());
            
    try
    {
       if (!socket.connect(ip, port))
       {
          return;
       }
       if (socket.login(id, password))
       {
          if (socket.isMonitoring(true))
          {
             DBSeerGUI.middlewareStatus.setText("Middleware Connected: " + socket.getIp() + ":" + socket.getPort() + " as " +
                   socket.getId() + " (Monitoring)");
             startMonitoringButton.setEnabled(false);
             stopMonitoringButton.setEnabled(true);
          }
          else
          {
             DBSeerGUI.middlewareStatus.setText("Middleware Connected: " + socket.getIp() + ":" + socket.getPort() + " as " +
                   socket.getId());
             startMonitoringButton.setEnabled(true);
             stopMonitoringButton.setEnabled(false);
          }
            
          // save last login credentials
          DBSeerGUI.userSettings.setLastMiddlewareIP(socket.getIp());
          DBSeerGUI.userSettings.setLastMiddlewarePort(socket.getPort());
          DBSeerGUI.userSettings.setLastMiddlewareID(socket.getId());
            
          XStreamHelper xmlHelper = new XStreamHelper();
          xmlHelper.toXML(DBSeerGUI.userSettings, DBSeerGUI.settingsPath);
            
          this.setLogin();
       }
       else
       {
          JOptionPane.showMessageDialog(null, socket.getErrorMessage(), "Middleware Login Error", JOptionPane.ERROR_MESSAGE);
       }
    }
    catch (Exception e)
    {
       DBSeerExceptionHandler.handleException(e, "Middleware Login Error");
    //            JOptionPane.showMessageDialog(null, e.getMessage(), "Middleware Login Error", JOptionPane.ERROR_MESSAGE);
    }
       }
       else // log out
       {
    try
    {
       socket.disconnect();
       startMonitoringButton.setEnabled(false);
       stopMonitoringButton.setEnabled(false);
    }
    catch (Exception e)
    {
       DBSeerExceptionHandler.handleException(e);
    }
       }
    }
    else if (actionEvent.getSource() == startMonitoringButton)
    {
       try
       {
    if (socket.startMonitoring())
    {
       DBSeerGUI.middlewareStatus.setText("Middleware Connected: " + socket.getIp() + ":" + socket.getPort() + " as " +
             socket.getId() + " (Monitoring)");
       startMonitoringButton.setEnabled(false);
       stopMonitoringButton.setEnabled(true);
    }
    else
    {
       JOptionPane.showMessageDialog(null, socket.getErrorMessage(), "Middleware Monitoring Error", JOptionPane.ERROR_MESSAGE);
    }
       }
       catch (IOException e)
       {
    JOptionPane.showMessageDialog(null, e.getMessage(), "Middleware Error", JOptionPane.ERROR_MESSAGE);
       }
    }
    else if (actionEvent.getSource() == stopMonitoringButton)
    {
       try
       {
    startMonitoringButton.setEnabled(true);
    stopMonitoringButton.setEnabled(false);
            
    if (!socket.isMonitoring(false))
    {
       return;
    }
            
    final String datasetRootPath = DBSeerGUI.userSettings.getDBSeerRootPath() + File.separator +
          DBSeerConstants.ROOT_DATASET_PATH;
    final String liveDatasetPath = DBSeerGUI.userSettings.getDBSeerRootPath() + File.separator +
          DBSeerConstants.LIVE_DATASET_PATH;
            
    final File rawDatasetDir = new File(datasetRootPath);
    if (!rawDatasetDir.exists())
    {
       rawDatasetDir.mkdirs();
    }
            
    String datasetName = (String)JOptionPane.showInputDialog(this, "Enter the name of new dataset", "New Dataset",
          JOptionPane.PLAIN_MESSAGE, null, null, "NewDataset");
            
    boolean getData = true;
    File newRawDatasetDir = null;
            
    if (datasetName == null)
    {
       getData = false;
    }
    else
    {
    //               newRawDatasetDir = new File(DBSeerConstants.RAW_DATASET_PATH + File.separator + datasetName);
       newRawDatasetDir = new File(datasetRootPath + File.separator + datasetName);
       while (newRawDatasetDir.exists())
       {
          datasetName = (String) JOptionPane.showInputDialog(this, datasetName + " already exists.\n" +
                      "Enter the name of new dataset", "New Dataset",
                JOptionPane.PLAIN_MESSAGE, null, null, "NewDataset");
          newRawDatasetDir = new File(datasetRootPath + File.separator + datasetName);
       }
       newRawDatasetDir.mkdirs();
    }
            
    final boolean downloadData = getData;
    final File datasetDir = newRawDatasetDir;
    final String datasetNameFinal = datasetName;
    final JPanel middlewarePanel = this;
    final JButton logButton = logInOutButton;
    final JButton startButton = startMonitoringButton;
            
    SwingWorker<Void, Void> datasetWorker = new SwingWorker<Void, Void>()
    {
       @Override
       protected Void doInBackground() throws Exception
       {
          if (downloadData)
          {
             DBSeerGUI.status.setText("Stopping monitoring...");
             middlewarePanel.setEnabled(false);
             logButton.setEnabled(false);
             startButton.setEnabled(false);
          }
          if (socket.stopMonitoring(downloadData))
          {
             DBSeerGUI.middlewareStatus.setText("Middleware Connected: " + socket.getIp() + ":" + socket.getPort() + " as " +
                   socket.getId());
             DBSeerGUI.liveMonitorPanel.reset();
            
             if (!downloadData)
             {
                return null;
             }
            
    //                     File logFile = socket.getLogFile();
    //                     byte[] buf = new byte[8192];
    //                     int length = 0;
    //
    //                     FileInputStream byteStream = new FileInputStream(logFile);
    //                     ZipInputStream zipInputStream = new ZipInputStream(byteStream);
    //                     ZipEntry entry = null;
    //
    //                     // unzip the monitor package.
    //                     while ((entry = zipInputStream.getNextEntry()) != null)
    //                     {
    //                        File entryFile = new File(liveDatasetPath + File.separator + entry.getName());
    //                        new File(entryFile.getParent()).mkdirs();
    //
    //                        FileOutputStream out = new FileOutputStream(liveDatasetPath + File.separator + entry.getName());
    //
    //                        try
    //                        {
    //                           while ((length = zipInputStream.read(buf, 0, 8192)) >= 0)
    //                           {
    //                              out.write(buf, 0, length);
    //                           }
    //                        }
    //                        catch (EOFException e)
    //                        {
    //                           // do nothing
    //                        }
    //
    //                        //zipInputStream.closeEntry();
    //                        out.flush();
    //                        out.close();
    //                     }
    //                     zipInputStream.close();
            
             // move dataset from 'temp' to user-specified directory
             File liveDir = new File(DBSeerGUI.userSettings.getDBSeerRootPath() + File.separator + DBSeerConstants.LIVE_DATASET_PATH);
             File[] files = liveDir.listFiles();
             for (File f : files)
             {
                FileUtils.moveFileToDirectory(f, datasetDir, false);
             }
            
             // We may not need to process the data after all?
    //                     int confirm = JOptionPane.showConfirmDialog(null,
    //                           "The monitoring data has been downloaded.\n" +
    //                                 "Do you want to proceed and process the downloaded dataset?",
    //                           "Warning",
    //                           JOptionPane.YES_NO_OPTION);
    //
    //                     if (confirm == JOptionPane.YES_OPTION)
    //                     {
    //                        // process the dataset
    //                        DBSeerGUI.status.setText("Processing the dataset...");
    //                        DataCenter dc = new DataCenter(DBSeerConstants.ROOT_DATASET_PATH, datasetNameFinal, true);
    //                        if (!dc.parseLogs())
    //                        {
    //                           JOptionPane.showMessageDialog(null, "Failed to parse received monitoring logs", "Error", JOptionPane.ERROR_MESSAGE);
    //                        }
    //
    //                        if (!dc.processDataset())
    //                        {
    //                           JOptionPane.showMessageDialog(null, "Failed to process received dataset", "Error", JOptionPane.ERROR_MESSAGE);
    //                        }
    //                     }
          }
          else
          {
             JOptionPane.showMessageDialog(null, socket.getErrorMessage(), "Middleware Monitoring Error", JOptionPane.ERROR_MESSAGE);
          }
          return null;
       }
            
       @Override
       protected void done()
       {
          DBSeerGUI.status.setText("");
          middlewarePanel.setEnabled(true);
          logButton.setEnabled(true);
          startButton.setEnabled(true);
       }
    };
    datasetWorker.execute();
       }
       catch (Exception e)
       {
    JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    DBSeerGUI.status.setText("");
       }
    }
    else if (actionEvent.getSource() == applyRefreshRateButton)
    {
       int rate = Integer.parseInt(refreshRateField.getText());
       DBSeerGUI.liveMonitorRefreshRate = rate;
    }
    */
}

From source file:eu.apenet.dpt.standalone.gui.dateconversion.DateConversionRulesDialog.java

private boolean showUnsavedChangesDialog() {
    int result = JOptionPane.showConfirmDialog(this, "You have unsaved changes. Cancel anyway?",
            "Unsaved changes", JOptionPane.YES_NO_OPTION);
    if (result == JOptionPane.YES_OPTION) {
        return true;
    }/*from w  w w . j  av  a 2 s . c  o  m*/
    return false;
}

From source file:net.sf.jabref.gui.exporter.SaveDatabaseAction.java

private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) throws SaveException {
    SaveSession session;//from ww  w  . j  av a 2  s.  co m
    frame.block();
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs)
                .withEncoding(encoding);
        BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter(FileSaveSession::new);
        if (selectedOnly) {
            session = databaseWriter.savePartOfDatabase(panel.getBibDatabaseContext(),
                    panel.getSelectedEntries(), prefs);
        } else {
            session = databaseWriter.saveDatabase(panel.getBibDatabaseContext(), prefs);

        }
        panel.registerUndoableChanges(session);

    } catch (UnsupportedCharsetException ex2) {
        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + Localization
                        .lang("Character encoding '%0' is not supported.", encoding.displayName()),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");
    } catch (SaveException ex) {
        if (ex == SaveException.FILE_LOCKED) {
            throw ex;
        }
        if (ex.specificEntry()) {
            // Error occured during processing of
            // be. Highlight it:
            int row = panel.getMainTable().findEntry(ex.getEntry());
            int topShow = Math.max(0, row - 3);
            panel.getMainTable().setRowSelectionInterval(row, row);
            panel.getMainTable().scrollTo(topShow);
            panel.showEntry(ex.getEntry());
        } else {
            LOGGER.error("Problem saving file", ex);
        }

        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + ".\n" + ex.getMessage(),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");

    } finally {
        frame.unblock();
    }

    boolean commit = true;
    if (!session.getWriter().couldEncodeAll()) {
        FormBuilder builder = FormBuilder.create()
                .layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref"));
        JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters());
        ta.setEditable(false);
        builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:",
                session.getEncoding().displayName())).xy(1, 1);
        builder.add(ta).xy(3, 1);
        builder.add(Localization.lang("What do you want to do?")).xy(1, 3);
        String tryDiff = Localization.lang("Try different encoding");
        int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), Localization.lang("Save database"),
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
                new String[] { Localization.lang("Save"), tryDiff, Localization.lang("Cancel") }, tryDiff);

        if (answer == JOptionPane.NO_OPTION) {
            // The user wants to use another encoding.
            Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"),
                    Localization.lang("Save database"), JOptionPane.QUESTION_MESSAGE, null,
                    Encodings.ENCODINGS_DISPLAYNAMES, encoding);
            if (choice == null) {
                commit = false;
            } else {
                Charset newEncoding = Charset.forName((String) choice);
                return saveDatabase(file, selectedOnly, newEncoding);
            }
        } else if (answer == JOptionPane.CANCEL_OPTION) {
            commit = false;
        }

    }

    try {
        if (commit) {
            session.commit(file.toPath());
            panel.getBibDatabaseContext().getMetaData().setEncoding(encoding); // Make sure to remember which encoding we used.
        } else {
            session.cancel();
        }
    } catch (SaveException e) {
        int ans = JOptionPane.showConfirmDialog(null,
                Localization.lang("Save failed during backup creation") + ". "
                        + Localization.lang("Save without backup?"),
                Localization.lang("Unable to create backup"), JOptionPane.YES_NO_OPTION);
        if (ans == JOptionPane.YES_OPTION) {
            session.setUseBackup(false);
            session.commit(file.toPath());
            panel.getBibDatabaseContext().getMetaData().setEncoding(encoding);
        } else {
            commit = false;
        }
    }

    return commit;
}

From source file:com.xilinx.virtex7.MainScreen.java

public void initialize(LandingPage l, String imgName, int mode) {
    lp = l;/*from   w  ww  .  ja va  2 s . c o m*/
    blockDiagram = Toolkit.getDefaultToolkit()
            .getImage(getClass().getResource("/com/xilinx/virtex7/" + imgName));
    led1 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/com/xilinx/gui/green.png"));
    led2 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/com/xilinx/gui/ledoff.png"));
    led3 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/com/xilinx/gui/red.png"));
    this.mode = mode;
    setModeText(mode);
    dataMismatch0 = dataMismatch2 = errcnt0 = errcnt1 = false;
    dataMismatch4 = dataMismatch6 = errcnt2 = errcnt3 = false;
    di = null;
    di = new DriverInfo();
    di.init(mode);
    int ret = di.get_PCIstate();

    //ret = di.get_PowerStats();
    test1_option = DriverInfo.ENABLE_LOOPBACK;
    test2_option = DriverInfo.ENABLE_LOOPBACK;
    test3_option = DriverInfo.ENABLE_LOOPBACK;
    test4_option = DriverInfo.ENABLE_LOOPBACK;
    // create a new jframe, and pack it
    frame = new JFrame("Virtex-7 XT Connectivity TRD Control & Monitoring Interface");
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    final int m = mode;
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            // check if tests are running or not

            if ((testStarted || testStarted1 || testStarted2 || testStarted3)
                    && ((m != LandingPage.APPLICATION_MODE) || (m != LandingPage.APPLICATION_MODE_P2P))) {
                int confirmed = JOptionPane.showConfirmDialog(null,
                        "This will stop the tests and uninstall the drivers. Do you want to continue?", "Exit",
                        JOptionPane.YES_NO_OPTION);
                if (confirmed == JOptionPane.YES_OPTION) {
                    if (testStarted) {
                        di.stopTest(0, test1_option, Integer.parseInt(t1_psize.getText()));
                        testStarted = false;
                    }
                    if (testStarted1) {
                        di.stopTest(1, test2_option, Integer.parseInt(t2_psize.getText()));
                        testStarted1 = false;
                    }

                    if (testStarted2) {
                        di.stopTest(2, test3_option, Integer.parseInt(t3_psize.getText()));
                        testStarted2 = false;
                    }
                    if (testStarted3) {
                        di.stopTest(3, test4_option, Integer.parseInt(t4_psize.getText()));
                        testStarted3 = false;
                    }

                    timer.cancel();
                    textArea.removeAll();
                    di.flush();
                    di = null;
                    System.gc();
                    lp.uninstallDrivers();
                    showDialog("Removing Device Drivers...Please wait...");
                }
            } else {
                int confirmed = JOptionPane.showConfirmDialog(null,
                        "This will Uninstall the drivers. Do you want to continue?", "Exit",
                        JOptionPane.YES_NO_OPTION);
                if (confirmed == JOptionPane.YES_OPTION) {
                    timer.cancel();
                    textArea.removeAll();
                    di.flush();
                    di = null;
                    System.gc();
                    lp.uninstallDrivers();
                    showDialog("Removing Device Drivers...Please wait...");
                }
            }
        }
    });

    // make the frame half the height and width
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    height = screenSize.height;
    width = screenSize.width;

    minWidth = 1000;
    minHeight = 600;
    minFrameWidth = 1024;
    minFrameHeight = 745;

    reqHeight = 745;
    if (width < 1280)
        reqWidth = 1024;
    else if (width == 1280)
        reqWidth = 1280;
    else if (width < 1600) {
        reqWidth = width - (width * 4) / 100;
        reqHeight = height - (height * 3) / 100;
    } else {
        reqWidth = reqHeight = height = height - (height * 10) / 100;
    }

    frame.setSize(new Dimension(minFrameWidth, minFrameHeight));
    frame.setResizable(true);
    frame.addComponentListener(new ComponentListener() {

        @Override
        public void componentResized(ComponentEvent ce) {
            frame.setSize(new Dimension(Math.max(minFrameWidth, frame.getWidth()),
                    Math.max(minFrameHeight, frame.getHeight())));
        }

        @Override
        public void componentMoved(ComponentEvent ce) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void componentShown(ComponentEvent ce) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void componentHidden(ComponentEvent ce) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }
    });
    frame.setVisible(true);

    frame.setIconImage(
            Toolkit.getDefaultToolkit().getImage(getClass().getResource("/com/xilinx/virtex7/icon.png")));
    // center the jframe on screen
    frame.setLocationRelativeTo(null);

    frame.setContentPane(createContentPane());

    keyWord = new SimpleAttributeSet();
    StyleConstants.setForeground(keyWord, Color.RED);

    StyleConstants.setBold(keyWord, true);

    logStatus = new SimpleAttributeSet();
    StyleConstants.setForeground(logStatus, Color.BLACK);
    StyleConstants.setBold(logStatus, true);

    if ((mode == LandingPage.APPLICATION_MODE) || (mode == LandingPage.APPLICATION_MODE_P2P)) {
        testStarted = testStarted1 = testStarted2 = testStarted3 = true;
    }

    if (mode == LandingPage.PERFORMANCE_MODE_RAW) {
        t1_o1.setSelected(true);
        t1_o2.setEnabled(false);
        t1_o3.setEnabled(false);
        t2_o2.setEnabled(false);
        t2_o3.setEnabled(false);
    }
    if (mode == LandingPage.PERFORMANCE_MODE_RAW_DV) {
        t1_o2.setEnabled(false);
        t1_o3.setEnabled(false);
        t2_o2.setEnabled(false);
        t2_o3.setEnabled(false);
        t1_o1.setSelected(true);
    }

    // initialize max packet size
    ret = di.get_EngineState();
    EngState[] engData = di.getEngState();
    maxpkt0 = engData[0].MaxPktSize;
    minpkt0 = engData[0].MinPktSize;

    minpkt1 = engData[2].MinPktSize;
    maxpkt1 = engData[2].MaxPktSize;

    maxpkt2 = engData[4].MaxPktSize;
    minpkt2 = engData[4].MinPktSize;

    minpkt3 = engData[6].MinPktSize;
    maxpkt3 = engData[6].MaxPktSize;

    t1_psize.setText(String.valueOf(maxpkt0));
    t2_psize.setText(String.valueOf(maxpkt1));
    t3_psize.setText(String.valueOf(maxpkt2));
    t4_psize.setText(String.valueOf(maxpkt3));

    t1_psize.setToolTipText(minpkt0 + "-" + maxpkt0);
    t2_psize.setToolTipText(minpkt1 + "-" + maxpkt1);
    t3_psize.setToolTipText(minpkt2 + "-" + maxpkt2);
    t4_psize.setToolTipText(minpkt3 + "-" + maxpkt3);

    updateLog(di.getPCIInfo().getVersionInfo(), logStatus);
    updateLog("Configuration: " + modeText, logStatus);

    // LED status
    di.get_LedStats();
    lstats = di.getLedStats();
    setLedStats(lstats);

    //
    if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV) {
        t2_o1.setEnabled(true);
        t4_o1.setEnabled(true);
    } else {
        t2_o1.setEnabled(false);
        t4_o1.setEnabled(false);
    }
    t2_o2.setEnabled(false);
    t2_o3.setEnabled(false);
    t3_o2.setEnabled(false);
    t3_o3.setEnabled(false);
    t4_o2.setEnabled(false);
    t4_o3.setEnabled(false);
    startTimer();
}

From source file:gdt.jgui.entity.bonddetail.JBondDetailPanel.java

/**
 * Get the context menu.//  w w w.  j  a va  2s. co  m
 * @return the context menu.
 */
@Override
public JMenu getContextMenu() {

    menu1 = new JMenu("Context");
    menu1.addMenuListener(new MenuListener() {
        @Override
        public void menuSelected(MenuEvent e) {
            //   System.out.println("JBondDetailPanel:getConextMenu:BEGIN");
            menu1.removeAll();
            JMenuItem selectItem = new JMenuItem("Select all");
            selectItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JItemPanel[] ipa = getItems();
                    if (ipa != null) {
                        for (JItemPanel ip : ipa)
                            ip.setChecked(true);
                    }
                }
            });
            menu1.add(selectItem);
            JMenuItem unselectItem = new JMenuItem("Unselect all");
            unselectItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JItemPanel[] ipa = getItems();
                    if (ipa != null) {
                        for (JItemPanel ip : ipa)
                            ip.setChecked(false);
                    }
                }
            });
            menu1.addSeparator();
            JMenuItem doneItem = new JMenuItem("Done");
            doneItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (requesterResponseLocator$ != null) {
                        try {
                            byte[] ba = Base64.decodeBase64(requesterResponseLocator$);
                            String responseLocator$ = new String(ba, "UTF-8");
                            JConsoleHandler.execute(console, responseLocator$);
                        } catch (Exception ee) {
                            LOGGER.severe(ee.toString());
                        }
                    } else
                        console.back();

                }

            });
            menu1.add(doneItem);
            menu1.addSeparator();
            addItem = new JMenuItem("Add");
            addItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        Entigrator entigrator = console.getEntigrator(entihome$);

                        JContext adp = (JContext) ExtensionHandler.loadHandlerInstance(entigrator,
                                BondDetailHandler.EXTENSION_KEY, "gdt.jgui.entity.bonddetail.JAddDetailPanel");
                        String adpLocator$ = adp.getLocator();
                        adpLocator$ = Locator.append(adpLocator$, Entigrator.ENTIHOME, entihome$);
                        adpLocator$ = Locator.append(adpLocator$, EntityHandler.ENTITY_KEY, entityKey$);
                        JConsoleHandler.execute(console, adpLocator$);

                    } catch (Exception ee) {
                        LOGGER.severe(ee.toString());
                    }
                }
            });
            menu1.add(addItem);
            if (hasToPaste()) {
                JMenuItem pasteItem = new JMenuItem("Paste");
                pasteItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        paste();

                    }
                });
                menu1.add(pasteItem);
            }
            if (hasSelectedItems()) {
                JMenuItem deleteItem = new JMenuItem("Delete");
                deleteItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int response = JOptionPane.showConfirmDialog(console.getContentPanel(), "Delete ?",
                                "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        if (response == JOptionPane.YES_OPTION) {

                            delete();
                            JBondDetailPanel bdp = new JBondDetailPanel();
                            String bdpLocator$ = bdp.getLocator();
                            bdpLocator$ = Locator.append(bdpLocator$, Entigrator.ENTIHOME, entihome$);
                            bdpLocator$ = Locator.append(bdpLocator$, EntityHandler.ENTITY_KEY, entityKey$);
                            bdpLocator$ = Locator.append(bdpLocator$, JBondsPanel.BOND_KEY, bondKey$);
                            JConsoleHandler.execute(console, bdpLocator$);
                        }
                    }
                });
                menu1.add(deleteItem);
            }

        }

        @Override
        public void menuDeselected(MenuEvent e) {
        }

        @Override
        public void menuCanceled(MenuEvent e) {
        }
    });
    return menu1;
}

From source file:com.dragoniade.deviantart.deviation.SearchRss.java

private int retrieveTotal(ProgressDialog progress, Collection collection) {
    int offset = collection == null ? 6000 : 480;
    int greaterThan = 0;
    int lessThan = Integer.MAX_VALUE;
    int iteration = 0;
    String searchQuery = search.getSearch().replace("%username%", user);

    while (total < 0) {
        if (progress.isCancelled()) {
            return -1;
        }/*from ww w.  j a v  a  2  s .co  m*/

        progress.setText("Fetching total (" + ++iteration + ")");
        String queryString = "http://backend.deviantart.com/rss.xml?q=" + searchQuery
                + (collection == null ? "" : "/" + collection.getId()) + "&type=deviation&offset=" + offset;
        GetMethod method = new GetMethod(queryString);
        try {
            int sc = -1;
            do {
                sc = client.executeMethod(method);
                if (sc != 200) {
                    LoggableException ex = new LoggableException(method.getResponseBodyAsString());
                    Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ex);

                    int res = DialogHelper.showConfirmDialog(owner,
                            "An error has occured when contacting deviantART : error " + sc + ". Try again?",
                            "Continue?", JOptionPane.YES_NO_OPTION);
                    if (res == JOptionPane.NO_OPTION) {
                        return -1;
                    }
                }
            } while (sc != 200);

            XmlToolkit toolkit = XmlToolkit.getInstance();

            Element responses = toolkit.parseDocument(method.getResponseBodyAsStream());
            method.releaseConnection();

            List<?> deviations = toolkit.getMultipleNodes(responses, "channel/item");

            HashMap<String, String> prefixes = new HashMap<String, String>();
            prefixes.put("atom", responses.getOwnerDocument().lookupNamespaceURI("atom"));
            Node next = toolkit.getSingleNode(responses, "channel/atom:link[@rel='next']",
                    toolkit.getNamespaceContext(prefixes));
            int size = deviations.size();

            if (debug) {
                System.out.println();
                System.out.println();
                System.out.println("Lesser  Than: " + lessThan);
                System.out.println("Greater Than: " + greaterThan);
                System.out.println("Offset: " + offset);
                System.out.println("Size: " + size);
            }

            if (size != OFFSET && size > 0) {
                if (next != null) {
                    greaterThan = offset + OFFSET;
                } else {
                    if (debug)
                        System.out.println("Total (offset + size) : " + (offset + size));
                    return offset + size;
                }
            }

            // Page is full, there is more deviations
            if (size == OFFSET) {
                greaterThan = offset + OFFSET;
            }

            if (size == 0) {
                lessThan = offset;
            }

            if (greaterThan == lessThan) {
                if (debug)
                    System.out.println("Total (greaterThan) : " + greaterThan);
                return greaterThan;
            }

            if (lessThan == Integer.MAX_VALUE) {
                offset = offset * 2;
            } else {
                offset = (greaterThan + lessThan) / 2;
                if (offset % 60 != 0) {
                    offset = (offset / 60) * 60;
                }
            }

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }
        } catch (IOException e) {
            int res = DialogHelper.showConfirmDialog(owner,
                    "An error has occured when contacting deviantART : error " + e + ". Try again?",
                    "Continue?", JOptionPane.YES_NO_OPTION);
            if (res == JOptionPane.NO_OPTION) {
                return -1;
            }
        }
    }

    return total;

}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private boolean verifyCertificate(X509Certificate cert) {
    try {/*from w w w.ja va2s  .c  om*/
        String keypass = "";
        String keystorename = System.getProperty("deployment.user.security.trusted.certs");
        if (keystorename == null) {
            throw new IOException("No trusted certs keystore");
        }

        KeyStore keystore = KeyStore.getInstance("JKS", "SUN");
        File file = new File(keystorename);
        if (!file.exists()) {
            keystore.load(null, keypass.toCharArray());
        } else {
            keystore.load(new FileInputStream(keystorename), keypass.toCharArray());
        }
        boolean isInStore = false;
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements() && !isInStore) {
            String alias = aliases.nextElement();
            Certificate certificate = keystore.getCertificate(alias);
            if (certificate != null) {
                if (certificate.equals(cert)) {
                    isInStore = true;
                }
            }
        }
        if (!isInStore) {
            int result = JOptionPane.showConfirmDialog(null,
                    "Do you want to trust the bridge implementation " + "signed by\n"
                            + cert.getSubjectX500Principal().getName(),
                    "Trust source?", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                keystore.setEntry("deploymentusercert-" + System.currentTimeMillis(),
                        new KeyStore.TrustedCertificateEntry(cert), null);
                FileOutputStream output = new FileOutputStream(keystorename);
                keystore.store(output, keypass.toCharArray());
                output.close();
                return true;
            }
            return false;
        }
        return true;
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return false;
}

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

/**
 * @param title/*from   w  ww .  jav a  2s. c  om*/
 * @param name
 * @param scope
 * @return
 */
public static boolean askUserToUnlock(final String title, final String name, final SCOPE scope) {
    SpecifyUser user = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);
    Discipline discipline = scope == SCOPE.Discipline
            ? AppContextMgr.getInstance().getClassObject(Discipline.class)
            : null;
    Collection collection = scope == SCOPE.Collection
            ? AppContextMgr.getInstance().getClassObject(Collection.class)
            : null;

    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();

        SpTaskSemaphore semaphore = null;
        try {
            semaphore = getSemaphore(session, name, scope, discipline, collection);

        } 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) {
            // can't be unlocked at this time.
            // or it isn't locked

        } else {
            if (!semaphore.getIsLocked()
                    && !(semaphore.getUsageCount() != null && semaphore.getUsageCount() > 0)) {
                return false;
            }

            // Check to see if we have the same user on the same machine.
            String currMachineName = InetAddress.getLocalHost().toString();
            String dbMachineName = semaphore.getMachineName();

            if (StringUtils.isNotEmpty(dbMachineName) && StringUtils.isNotEmpty(currMachineName)
                    && currMachineName.equals(dbMachineName) && semaphore.getOwner() != null && user != null
                    && user.getId().equals(semaphore.getOwner().getId())) {
                // In use by this user

                int options = JOptionPane.YES_NO_OPTION;
                Object[] optionLabels = new String[] { getResourceString("SpTaskSemaphore.OVERRIDE"), //$NON-NLS-1$
                        getResourceString("CANCEL")//$NON-NLS-1$
                };
                int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                        getLocalizedMessage("SpTaskSemaphore.IN_USE_BY_YOU_UNLK", title, title),
                        getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                        options, JOptionPane.QUESTION_MESSAGE, null, optionLabels, 1);

                return userChoice == JOptionPane.YES_OPTION;
            }

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

            int options;
            Object[] optionLabels;
            options = JOptionPane.YES_NO_OPTION;
            optionLabels = new String[] { getResourceString("SpTaskSemaphore.OVERRIDE"), //$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, 1);
            return userChoice == JOptionPane.YES_OPTION;
        }

    } 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 false;
}

From source file:com.compomics.colims.client.controller.AnalyticalRunsSearchSettingsController.java

/**
 * Delete the database entity (project, experiment, analytical runs) from
 * the database. Shows a confirmation dialog first. When confirmed, a
 * DeleteDbTask message is sent to the DB task queue. A message dialog is
 * shown in case the queue cannot be reached or in case of an IOException
 * thrown by the sendDbTask method.//from  ww w .jav a 2 s .  c om
 *
 * @param entity the entity to delete
 * @param dbEntityClass the database entity class
 * @return true if the delete task is confirmed.
 */
private boolean deleteEntity(final DatabaseEntity entity, final Class dbEntityClass) {
    boolean deleteConfirmation = false;

    //check delete permissions
    if (userBean.getDefaultPermissions().get(DefaultPermission.DELETE)) {
        int option = JOptionPane.showConfirmDialog(mainController.getMainFrame(),
                "Are you sure? This will remove all underlying database relations (spectra, psm's, ...) as well."
                        + System.lineSeparator() + "A delete task will be sent to the database task queue.",
                "Delete " + dbEntityClass.getSimpleName() + " confirmation.", JOptionPane.YES_NO_OPTION);
        if (option == JOptionPane.YES_OPTION) {
            //check connection
            if (queueManager.isReachable()) {
                DeleteDbTask deleteDbTask = new DeleteDbTask(dbEntityClass, entity.getId(),
                        userBean.getCurrentUser().getId());
                try {
                    dbTaskProducer.sendDbTask(deleteDbTask);
                    deleteConfirmation = true;
                } catch (IOException e) {
                    LOGGER.error(e, e.getCause());
                    eventBus.post(new UnexpectedErrorMessageEvent(e.getMessage()));
                }
            } else {
                eventBus.post(new StorageQueuesConnectionErrorMessageEvent(queueManager.getBrokerName(),
                        queueManager.getBrokerUrl(), queueManager.getBrokerJmxUrl()));
            }
        }
    } else {
        mainController.showPermissionErrorDialog(
                "Your user doesn't have rights to delete this " + entity.getClass().getSimpleName());
    }

    return deleteConfirmation;
}

From source file:com.konifar.material_icon_generator.MaterialDesignIconGenerateDialog.java

@Override
protected void doOKAction() {
    if (model == null)
        return;/*from   w w w.  j ava2 s.c om*/

    if (!isConfirmed())
        return;

    if (alreadyFileExists()) {
        final int option = JOptionPane.showConfirmDialog(panelMain, "File already exists, overwrite this ?",
                "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
                new ImageIcon(getClass().getResource(ICON_WARNING)));

        if (option == JOptionPane.YES_OPTION) {
            create();
        }
    } else {
        create();
    }

}