Example usage for javax.swing JOptionPane showConfirmDialog

List of usage examples for javax.swing JOptionPane showConfirmDialog

Introduction

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

Prototype

public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType)
        throws HeadlessException 

Source Link

Document

Brings up a dialog where the number of choices is determined by the optionType parameter.

Usage

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

public void initialize(LandingPage l, String imgName, int mode) {
    lp = l;//www  . j  av  a2  s  . c o m
    blockDiagram = Toolkit.getDefaultToolkit()
            .getImage(getClass().getResource("/com/xilinx/kintex7/" + 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;
    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;
    // create a new jframe, and pack it
    frame = new JFrame("Kintex-7 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)
                    && ((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;
                    }

                    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 = 700;
    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/kintex7/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 = 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;

    t1_psize.setText(String.valueOf(maxpkt0));
    t2_psize.setText(String.valueOf(maxpkt1));

    t1_psize.setToolTipText(minpkt0 + "-" + maxpkt0);
    t2_psize.setToolTipText(minpkt1 + "-" + maxpkt1);

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

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

    startTimer();
}

From source file:com.opendoorlogistics.studio.scripts.list.ScriptsPanel.java

private List<MyAction> createActions(AppPermissions appPermissions) {
    ArrayList<MyAction> ret = new ArrayList<>();

    if (appPermissions.isScriptEditingAllowed()) {

        ret.add(new MyAction(SimpleActionConfig.addItem.setItemName("script"), false, false, false) {

            @Override/*w w w. ja  va  2s  .  com*/
            public void actionPerformed(ActionEvent e) {

                Script script = new SetupComponentWizard(SwingUtilities.getWindowAncestor(ScriptsPanel.this),
                        api, scriptUIManager.getAvailableFieldsQuery()).showModal();
                // Script script =new ScriptWizardActions(api,SwingUtilities.getWindowAncestor(ScriptsPanel.this)).promptUser();
                if (script != null) {
                    scriptUIManager.launchScriptEditor(script, null, isOkDirectory() ? directory : null);
                }
            }
        });

        ret.add(new MyAction(SimpleActionConfig.editItem.setItemName("script"), false, false, true) {

            @Override
            public void actionPerformed(ActionEvent e) {
                ScriptNode node = scriptsTree.getSelectedValue();
                if (node != null && node.isAvailable()) {
                    ScriptsPanel.this.scriptUIManager.launchScriptEditor(node.getFile(),
                            node.getLaunchEditorId());
                }
            }
        });

        ret.add(new MyAction(SimpleActionConfig.deleteItem.setItemName("script"), false, false, false) {

            @Override
            public void actionPerformed(ActionEvent e) {
                ScriptNode node = scriptsTree.getSelectedValue();
                if (node == null) {
                    return;
                }
                if (JOptionPane.showConfirmDialog(ScriptsPanel.this,
                        "Really delete script " + node.getFile().getName() + " from disk?", "Delete script",
                        JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION) {
                    if (!node.getFile().delete()) {
                        JOptionPane.showMessageDialog(ScriptsPanel.this, "Could not delete file");
                    } else {
                        onDirectoryChanged(directory);
                    }
                }
            }

            @Override
            public void updateEnabledState() {
                ScriptNode selected = scriptsTree.getSelectedValue();
                boolean enabled = true;
                if (selected == null) {
                    enabled = false;
                }
                if (enabled && selected.isScriptRoot() == false) {
                    // can only delete the root
                    enabled = false;
                }
                setEnabled(enabled);
            }
        });

        ret.add(new MyAction(SimpleActionConfig.testCompileScript, true, false, true) {
            @Override
            public void actionPerformed(ActionEvent e) {
                ScriptNode node = scriptsTree.getSelectedValue();
                if (node != null) {
                    scriptUIManager.testCompileScript(node.getFile(), node.getLaunchExecutorId());
                }
            }
        });

        ret.add(new MyAction(SimpleActionConfig.runScript, true, true, true) {
            @Override
            public void actionPerformed(ActionEvent e) {
                ScriptNode node = scriptsTree.getSelectedValue();
                if (node != null) {
                    scriptUIManager.executeScript(node.getFile(), node.getLaunchExecutorId());
                }
            }

            @Override
            public void updateEnabledState() {
                setEnabled(ScriptNode.isRunnable(scriptsTree.getSelectedValue(), scriptUIManager));
            }
        });

    }

    return ret;
}

From source file:be.agiv.security.demo.Main.java

private void secConvCancelToken() {
    GridBagLayout gridBagLayout = new GridBagLayout();
    GridBagConstraints gridBagConstraints = new GridBagConstraints();
    JPanel contentPanel = new JPanel(gridBagLayout);

    JLabel urlLabel = new JLabel("URL:");
    gridBagConstraints.gridx = 0;//from w w  w  .  j a  v a  2s .c om
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = GridBagConstraints.WEST;
    gridBagConstraints.ipadx = 5;
    gridBagLayout.setConstraints(urlLabel, gridBagConstraints);
    contentPanel.add(urlLabel);

    JTextField urlTextField = new JTextField(ClaimsAwareServiceFactory.SERVICE_SC_LOCATION, 60);
    gridBagConstraints.gridx++;
    gridBagLayout.setConstraints(urlTextField, gridBagConstraints);
    contentPanel.add(urlTextField);

    int result = JOptionPane.showConfirmDialog(this, contentPanel, "Secure Conversation Cancel Token",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.CANCEL_OPTION) {
        return;
    }

    String location = urlTextField.getText();

    SecureConversationClient secConvClient = new SecureConversationClient(location);
    try {
        secConvClient.cancelSecureConversationToken(this.secConvSecurityToken);
        this.secConvViewMenuItem.setEnabled(false);
        this.secConvCancelMenuItem.setEnabled(false);
        this.secConvSecurityToken = null;
        JOptionPane.showMessageDialog(this, "Secure conversation token cancelled.", "Secure Conversation",
                JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception e) {
        showException(e);
    }
}

From source file:com.emental.mindraider.ui.outline.OutlineArchiveJPanel.java

public void actionPerformed(ActionEvent e) {
    int result = JOptionPane.showConfirmDialog(MindRaider.mainJFrame,
            "Do you really want to delete all discarded Notes?", "Empty Archive", JOptionPane.YES_NO_OPTION);
    if (result == JOptionPane.YES_OPTION) {
        MindRaider.noteCustodian.deleteDiscardedConcepts(MindRaider.profile.getActiveOutlineUri().toString());
        OutlineJPanel.getInstance().refresh();
    }/* w w  w.ja v a  2  s  .com*/
}

From source file:ch.admin.hermes.etl.load.HermesETLApplication.java

/**
 * CommandLine parse und fehlende Argumente verlangen
 * @param args Args/*ww w  . ja v  a2 s .c o m*/
 * @throws ParseException
 */
private static void parseCommandLine(String[] args) throws Exception {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

    // HACK um UTF-8 CharSet fuer alle Dateien zu setzen (http://stackoverflow.com/questions/361975/setting-the-default-java-character-encoding)
    System.setProperty("file.encoding", "UTF-8");
    Field charset = Charset.class.getDeclaredField("defaultCharset");
    charset.setAccessible(true);
    charset.set(null, null);

    // commandline Options - FremdsystemSite, Username und Password
    Options options = new Options();
    options.addOption("s", true, "Zielsystem - URL");
    options.addOption("u", true, "Zielsystem - Username");
    options.addOption("p", true, "Zielsystem - Password");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    site = cmd.getOptionValue("s");
    user = cmd.getOptionValue("u");
    passwd = cmd.getOptionValue("p");

    // restliche Argumente pruefen - sonst usage ausgeben
    String[] others = cmd.getArgs();
    if (others.length >= 1 && (others[0].endsWith(".js") || others[0].endsWith(".ftl")))
        script = others[0];
    if (others.length >= 2 && others[1].endsWith(".xml"))
        model = others[1];

    // Dialog mit allen Werten zusammenstellen
    JComboBox<String> scenarios = new JComboBox<String>(crawler.getScenarios());

    JTextField tsite = new JTextField(45);
    tsite.setText(site);
    JTextField tuser = new JTextField(16);
    tuser.setText(user);
    JPasswordField tpasswd = new JPasswordField(16);
    tpasswd.setText(passwd);
    final JTextField tscript = new JTextField(45);
    tscript.setText(script);
    final JTextField tmodel = new JTextField(45);
    tmodel.setText(model);

    JPanel myPanel = new JPanel(new GridLayout(6, 2));
    myPanel.add(new JLabel("Szenario (von http://www.hermes.admin.ch):"));
    myPanel.add(scenarios);

    myPanel.add(new JLabel("XML Model:"));
    myPanel.add(tmodel);
    JPanel pmodel = new JPanel();
    pmodel.add(tmodel);
    JButton bmodel = new JButton("...");
    pmodel.add(bmodel);
    bmodel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            model = getFile("Szenario XML Model", new String[] { "XML Model" }, new String[] { ".xml" });
            if (model != null)
                tmodel.setText(model);
        }
    });
    myPanel.add(pmodel);

    scenarios.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            try {
                Object o = e.getItem();
                tmodel.setText(crawler.getModelURL(o.toString()));
                scenario = o.toString();
            } catch (Exception e1) {
            }
        }
    });

    // Script
    myPanel.add(new JLabel("Umwandlungs-Script:"));
    JPanel pscript = new JPanel();
    pscript.add(tscript);
    JButton bscript = new JButton("...");
    pscript.add(bscript);
    myPanel.add(pscript);
    bscript.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            script = getFile("JavaScript/Freemarker Umwandlungs-Script",
                    new String[] { "JavaScript", "Freemarker" }, new String[] { ".js", ".ftl" });
            if (script != null)
                tscript.setText(script);
        }
    });

    // Zielsystem Angaben
    myPanel.add(new JLabel("Zielsystem URL:"));
    myPanel.add(tsite);
    myPanel.add(new JLabel("Zielsystem Benutzer:"));
    myPanel.add(tuser);
    myPanel.add(new JLabel("Zielsystem Password:"));
    myPanel.add(tpasswd);

    // Trick um Feld scenario und model zu setzen.
    if (scenarios.getItemCount() >= 8)
        scenarios.setSelectedIndex(8);

    // Dialog
    int result = JOptionPane.showConfirmDialog(null, myPanel, "HERMES 5 XML Model nach Fremdsystem/Format",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        site = tsite.getText();
        user = tuser.getText();
        passwd = new String(tpasswd.getPassword());
        model = tmodel.getText();
        script = tscript.getText();
    } else
        System.exit(1);

    if (model == null || script == null || script.trim().length() == 0)
        usage();

    if (script.endsWith(".js"))
        if (site == null || user == null || passwd == null || user.trim().length() == 0
                || passwd.trim().length() == 0)
            usage();
}

From source file:com.clough.android.adbv.view.UpdateTableDialog.java

private void applyChangesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyChangesButtonActionPerformed
    // TODO add your handling code here:
    List<Row> rowsToInsert = rowController.getRowsToInsert();
    List<Row> rowsToUpdate = rowController.getRowsToUpdate();
    List<Row> rowsToDelete = rowController.getRowsToDelete();
    int insertCount = rowsToInsert.size();
    int updateCount = rowsToUpdate.size();
    int deleteCount = rowsToDelete.size();
    if (insertCount > 0 || updateCount > 0 || deleteCount > 0) {
        String message = "Inserting row count " + insertCount + "\n" + "Updating row count " + updateCount
                + "\n" + "Deleting row count " + deleteCount + "\n"
                + "Are you sure you want apply this changes?";
        if (JOptionPane.showConfirmDialog(null, message, "Applying changes",
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
            mainFrame.setTableChangeList(rowsToChange, rowsToInsert, rowsToUpdate, rowsToDelete);
            dispose();//from  w  w  w  .  jav a 2 s .c o  m
        }
    } else {
        JOptionPane.showMessageDialog(null, "No changes to apply", "Applying changes",
                JOptionPane.INFORMATION_MESSAGE);
        dispose();
    }
}

From source file:com.diversityarrays.kdxplore.exportdata.CurationDataExporter.java

public void exportCurationData(ExportOptions options) {
    RowDataEmitter rowDataEmitter = null;

    boolean success = false;
    File tmpfile = null;/*ww  w  .j a v  a2 s.c o  m*/

    File outputFile = options.file;

    List<PlotAttribute> plotAttributes = helper.getPlotAttributes(options.allPlotAttributes);
    List<TraitInstance> traitInstances = helper.getTraitInstances(options.whichTraitInstances);

    try {
        String loname = outputFile.getName().toLowerCase();

        tmpfile = File.createTempFile(TEMPDIR_KDX, SUFFIX_TMP, outputFile.getParentFile());

        if (loname.endsWith(SUFFIX_XLS)) {
            rowDataEmitter = new OldExcelRowDataEmitter(options, tmpfile, trial);
        } else if (loname.endsWith(SUFFIX_XLSX)) {
            // NOTE: BMS not supported for XLSX
            rowDataEmitter = new NewExcelRowDataEmitter(options, tmpfile, trial);
        } else {
            rowDataEmitter = new CsvRowDataEmitter(options, tmpfile);
            if (!loname.endsWith(SUFFIX_CSV)) {
                outputFile = new File(outputFile.getParentFile(), outputFile.getName() + SUFFIX_CSV);
            }
        }

        rowDataEmitter.emitTrialDetails(trialAttributes, plotAttributes, traitInstances);

        rowDataEmitter.emitSampleData(plotAttributes, traitInstances);

        success = true;
    } catch (IOException e) {
        JOptionPane.showMessageDialog(messageComponent, e.getMessage(), "I/O Error", JOptionPane.ERROR_MESSAGE);
    } finally {
        if (rowDataEmitter != null) {
            try {
                rowDataEmitter.close();
            } catch (IOException ignore) {
            }
        }
        if (success) {
            if (outputFile.exists()) {
                outputFile.delete();
            }
            if (tmpfile.renameTo(outputFile)) {
                messagePrinter.println("Exported data to " + outputFile.getPath());
                if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(messageComponent,
                        "Saved " + outputFile.getName(), "Open the saved file?", JOptionPane.YES_NO_OPTION)) {
                    try {
                        Util.openFile(outputFile);
                    } catch (IOException e) {
                        messagePrinter.println("Failed to open " + outputFile.getPath());
                        messagePrinter.println(e.getMessage());
                    }
                }
            } else {

            }
        } else {
            if (tmpfile != null) {
                tmpfile.delete();
            }
        }
    }
}

From source file:com.eviware.soapui.DefaultSoapUICore.java

protected Settings initSettings(String fileName) {
    // TODO Why try to load settings from current directory before using root?
    // This caused a bug in Eclipse:
    // https://sourceforge.net/tracker/?func=detail&atid=737763&aid=2620284&group_id=136013
    File settingsFile = new File(fileName).exists() ? new File(fileName) : null;

    try {//  w w w  .j a  v a 2  s.  c o m
        if (settingsFile == null) {
            settingsFile = new File(new File(getRoot()), DEFAULT_SETTINGS_FILE);
            if (!settingsFile.exists()) {
                settingsFile = new File(new File(System.getProperty("user.home", ".")), DEFAULT_SETTINGS_FILE);
                lastSettingsLoad = 0;
            }
        } else {
            settingsFile = new File(fileName);
            if (!settingsFile.getAbsolutePath().equals(this.settingsFile))
                lastSettingsLoad = 0;
        }

        if (!settingsFile.exists()) {
            if (settingsDocument == null) {
                log.info("Creating new settings at [" + settingsFile.getAbsolutePath() + "]");
                settingsDocument = SoapuiSettingsDocumentConfig.Factory.newInstance();
                setInitialImport(true);
            }

            lastSettingsLoad = System.currentTimeMillis();
        } else if (settingsFile.lastModified() > lastSettingsLoad) {
            settingsDocument = SoapuiSettingsDocumentConfig.Factory.parse(settingsFile);

            byte[] encryptedContent = settingsDocument.getSoapuiSettings().getEncryptedContent();
            if (encryptedContent != null) {
                char[] password = null;
                if (this.password == null) {
                    // swing element -!! uh!
                    JPasswordField passwordField = new JPasswordField();
                    JLabel qLabel = new JLabel("Password");
                    JOptionPane.showConfirmDialog(null, new Object[] { qLabel, passwordField },
                            "Global Settings", JOptionPane.OK_CANCEL_OPTION);
                    password = passwordField.getPassword();
                } else {
                    password = this.password.toCharArray();
                }

                byte[] data = OpenSSL.decrypt("des3", password, encryptedContent);
                try {
                    settingsDocument = SoapuiSettingsDocumentConfig.Factory.parse(new String(data, "UTF-8"));
                } catch (Exception e) {
                    log.warn("Wrong password.");
                    JOptionPane.showMessageDialog(null,
                            "Wrong password, creating backup settings file [ " + settingsFile.getAbsolutePath()
                                    + ".bak.xml. ]\nSwitch to default settings.",
                            "Error - Wrong Password", JOptionPane.ERROR_MESSAGE);
                    settingsDocument.save(new File(settingsFile.getAbsolutePath() + ".bak.xml"));
                    throw e;
                }
            }

            log.info("initialized soapui-settings from [" + settingsFile.getAbsolutePath() + "]");
            lastSettingsLoad = settingsFile.lastModified();

            if (settingsWatcher == null) {
                settingsWatcher = new SettingsWatcher();
                SoapUI.getSoapUITimer().scheduleAtFixedRate(settingsWatcher, 10000, 10000);
            }
        }
    } catch (Exception e) {
        log.warn("Failed to load settings from [" + e.getMessage() + "], creating new");
        settingsDocument = SoapuiSettingsDocumentConfig.Factory.newInstance();
        lastSettingsLoad = 0;
    }

    if (settingsDocument.getSoapuiSettings() == null) {
        settingsDocument.addNewSoapuiSettings();
        settings = new XmlBeansSettingsImpl(null, null, settingsDocument.getSoapuiSettings());

        initDefaultSettings(settings);
    } else {
        settings = new XmlBeansSettingsImpl(null, null, settingsDocument.getSoapuiSettings());
    }

    this.settingsFile = settingsFile.getAbsolutePath();

    if (!settings.isSet(WsdlSettings.EXCLUDED_TYPES)) {
        StringList list = new StringList();
        list.add("schema@http://www.w3.org/2001/XMLSchema");
        settings.setString(WsdlSettings.EXCLUDED_TYPES, list.toXml());
    }

    if (!settings.isSet(WebRecordingSettings.EXCLUDED_HEADERS)) {
        StringList list = new StringList();
        list.add("Cookie");
        list.add("Set-Cookie");
        list.add("Referer");
        list.add("Keep-Alive");
        list.add("Connection");
        list.add("Proxy-Connection");
        list.add("Pragma");
        list.add("Cache-Control");
        list.add("Transfer-Encoding");
        list.add("Date");
        settings.setString(WebRecordingSettings.EXCLUDED_HEADERS, list.toXml());
    }

    if (settings.getString(HttpSettings.HTTP_VERSION, HttpSettings.HTTP_VERSION_1_1)
            .equals(HttpSettings.HTTP_VERSION_0_9)) {
        settings.setString(HttpSettings.HTTP_VERSION, HttpSettings.HTTP_VERSION_1_1);
    }

    setIfNotSet(WsdlSettings.NAME_WITH_BINDING, true);
    setIfNotSet(WsdlSettings.NAME_WITH_BINDING, 500);
    setIfNotSet(HttpSettings.HTTP_VERSION, HttpSettings.HTTP_VERSION_1_1);
    setIfNotSet(HttpSettings.MAX_TOTAL_CONNECTIONS, 2000);
    setIfNotSet(HttpSettings.RESPONSE_COMPRESSION, true);
    setIfNotSet(HttpSettings.LEAVE_MOCKENGINE, true);
    setIfNotSet(UISettings.AUTO_SAVE_PROJECTS_ON_EXIT, true);
    setIfNotSet(UISettings.SHOW_DESCRIPTIONS, true);
    setIfNotSet(WsdlSettings.XML_GENERATION_ALWAYS_INCLUDE_OPTIONAL_ELEMENTS, true);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATES_TO, true);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATIONSHIP_TYPE, true);
    setIfNotSet(UISettings.SHOW_STARTUP_PAGE, true);
    setIfNotSet(UISettings.GC_INTERVAL, "60");
    setIfNotSet(WsdlSettings.CACHE_WSDLS, true);
    setIfNotSet(WsdlSettings.PRETTY_PRINT_RESPONSE_MESSAGES, true);
    setIfNotSet(HttpSettings.RESPONSE_COMPRESSION, true);
    setIfNotSet(HttpSettings.INCLUDE_REQUEST_IN_TIME_TAKEN, true);
    setIfNotSet(HttpSettings.INCLUDE_RESPONSE_IN_TIME_TAKEN, true);
    setIfNotSet(HttpSettings.LEAVE_MOCKENGINE, true);
    setIfNotSet(UISettings.AUTO_SAVE_INTERVAL, "0");
    setIfNotSet(UISettings.GC_INTERVAL, "60");
    setIfNotSet(UISettings.SHOW_STARTUP_PAGE, true);
    setIfNotSet(WsaSettings.SOAP_ACTION_OVERRIDES_WSA_ACTION, false);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATIONSHIP_TYPE, true);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATES_TO, true);
    setIfNotSet(WsaSettings.OVERRIDE_EXISTING_HEADERS, false);
    setIfNotSet(WsaSettings.ENABLE_FOR_OPTIONAL, false);
    setIfNotSet(VersionUpdateSettings.AUTO_CHECK_VERSION_UPDATE, true);

    boolean setWsiDir = false;
    String wsiLocationString = settings.getString(WSISettings.WSI_LOCATION, null);
    if (StringUtils.isNullOrEmpty(wsiLocationString)) {
        setWsiDir = true;
    } else {
        File wsiFile = new File(wsiLocationString);
        if (!wsiFile.exists()) {
            setWsiDir = true;
        }
    }
    if (setWsiDir) {
        String wsiDir = System.getProperty("wsi.dir", new File(".").getAbsolutePath());
        settings.setString(WSISettings.WSI_LOCATION, wsiDir);
    }
    HttpClientSupport.addSSLListener(settings);

    return settings;
}

From source file:com.entertailion.java.fling.FlingFrame.java

public FlingFrame(String appId) {
    super();// w  w  w  .  java  2s .c  om
    this.appId = appId;
    rampClient = new RampClient(this);

    addWindowListener(this);

    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    Locale locale = Locale.getDefault();
    resourceBundle = ResourceBundle.getBundle("com/entertailion/java/fling/resources/resources", locale);
    setTitle(MessageFormat.format(resourceBundle.getString("fling.title"), Fling.VERSION));

    JPanel listPane = new JPanel();
    // show list of ChromeCast devices detected on the local network
    listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
    JPanel devicePane = new JPanel();
    devicePane.setLayout(new BoxLayout(devicePane, BoxLayout.LINE_AXIS));
    deviceList = new JComboBox();
    deviceList.addActionListener(this);
    devicePane.add(deviceList);
    URL url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/refresh.png");
    ImageIcon icon = new ImageIcon(url, resourceBundle.getString("button.refresh"));
    refreshButton = new JButton(icon);
    refreshButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            // refresh the list of devices
            if (deviceList.getItemCount() > 0) {
                deviceList.setSelectedIndex(0);
            }
            discoverDevices();
        }
    });
    refreshButton.setToolTipText(resourceBundle.getString("button.refresh"));
    devicePane.add(refreshButton);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/settings.png");
    icon = new ImageIcon(url, resourceBundle.getString("settings.title"));
    settingsButton = new JButton(icon);
    settingsButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JTextField transcodingExtensions = new JTextField(50);
            transcodingExtensions.setText(transcodingExtensionValues);
            JTextField transcodingParameters = new JTextField(50);
            transcodingParameters.setText(transcodingParameterValues);

            JPanel myPanel = new JPanel(new BorderLayout());
            JPanel labelPanel = new JPanel(new GridLayout(3, 1));
            JPanel fieldPanel = new JPanel(new GridLayout(3, 1));
            myPanel.add(labelPanel, BorderLayout.WEST);
            myPanel.add(fieldPanel, BorderLayout.CENTER);
            labelPanel.add(new JLabel(resourceBundle.getString("transcoding.extensions"), JLabel.RIGHT));
            fieldPanel.add(transcodingExtensions);
            labelPanel.add(new JLabel(resourceBundle.getString("transcoding.parameters"), JLabel.RIGHT));
            fieldPanel.add(transcodingParameters);
            labelPanel.add(new JLabel(resourceBundle.getString("device.manual"), JLabel.RIGHT));
            JPanel devicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            final JComboBox manualDeviceList = new JComboBox();
            if (manualServers.size() == 0) {
                manualDeviceList.setVisible(false);
            } else {
                for (DialServer dialServer : manualServers) {
                    manualDeviceList.addItem(dialServer);
                }
            }
            devicePanel.add(manualDeviceList);
            JButton addButton = new JButton(resourceBundle.getString("device.manual.add"));
            addButton.setToolTipText(resourceBundle.getString("device.manual.add.tooltip"));
            addButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    JTextField name = new JTextField();
                    JTextField ipAddress = new JTextField();
                    Object[] message = { resourceBundle.getString("device.manual.name") + ":", name,
                            resourceBundle.getString("device.manual.ipaddress") + ":", ipAddress };

                    int option = JOptionPane.showConfirmDialog(null, message,
                            resourceBundle.getString("device.manual"), JOptionPane.OK_CANCEL_OPTION);
                    if (option == JOptionPane.OK_OPTION) {
                        try {
                            manualServers.add(
                                    new DialServer(name.getText(), InetAddress.getByName(ipAddress.getText())));

                            Object selected = deviceList.getSelectedItem();
                            int selectedIndex = deviceList.getSelectedIndex();
                            deviceList.removeAllItems();
                            deviceList.addItem(resourceBundle.getString("devices.select"));
                            for (DialServer dialServer : servers) {
                                deviceList.addItem(dialServer);
                            }
                            for (DialServer dialServer : manualServers) {
                                deviceList.addItem(dialServer);
                            }
                            deviceList.invalidate();
                            if (selectedIndex > 0) {
                                deviceList.setSelectedItem(selected);
                            } else {
                                if (deviceList.getItemCount() == 2) {
                                    // Automatically select single device
                                    deviceList.setSelectedIndex(1);
                                }
                            }

                            manualDeviceList.removeAllItems();
                            for (DialServer dialServer : manualServers) {
                                manualDeviceList.addItem(dialServer);
                            }
                            manualDeviceList.setVisible(true);
                            storeProperties();
                        } catch (UnknownHostException e1) {
                            Log.e(LOG_TAG, "manual IP address", e1);

                            JOptionPane.showMessageDialog(FlingFrame.this,
                                    resourceBundle.getString("device.manual.invalidip"));
                        }
                    }
                }
            });
            devicePanel.add(addButton);
            JButton removeButton = new JButton(resourceBundle.getString("device.manual.remove"));
            removeButton.setToolTipText(resourceBundle.getString("device.manual.remove.tooltip"));
            removeButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    Object selected = manualDeviceList.getSelectedItem();
                    manualDeviceList.removeItem(selected);
                    if (manualDeviceList.getItemCount() == 0) {
                        manualDeviceList.setVisible(false);
                    }
                    deviceList.removeItem(selected);
                    deviceList.invalidate();
                    manualServers.remove(selected);
                    storeProperties();
                }
            });
            devicePanel.add(removeButton);
            fieldPanel.add(devicePanel);
            int result = JOptionPane.showConfirmDialog(FlingFrame.this, myPanel,
                    resourceBundle.getString("settings.title"), JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.OK_OPTION) {
                transcodingParameterValues = transcodingParameters.getText();
                transcodingExtensionValues = transcodingExtensions.getText();
                storeProperties();
            }
        }
    });
    settingsButton.setToolTipText(resourceBundle.getString("settings.title"));
    devicePane.add(settingsButton);
    listPane.add(devicePane);

    // TODO
    volume = new JSlider(JSlider.VERTICAL, 0, 100, 0);
    volume.setUI(new MySliderUI(volume));
    volume.setMajorTickSpacing(25);
    // volume.setMinorTickSpacing(5);
    volume.setPaintTicks(true);
    volume.setEnabled(true);
    volume.setValue(100);
    volume.setToolTipText(resourceBundle.getString("volume.title"));
    volume.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider) e.getSource();
            if (!source.getValueIsAdjusting()) {
                int position = (int) source.getValue();
                rampClient.volume(position / 100.0f);
            }
        }

    });
    JPanel centerPanel = new JPanel(new BorderLayout());
    // centerPanel.add(volume, BorderLayout.WEST);

    centerPanel.add(DragHereIcon.makeUI(this), BorderLayout.CENTER);
    listPane.add(centerPanel);

    scrubber = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
    scrubber.addChangeListener(this);
    scrubber.setMajorTickSpacing(25);
    scrubber.setMinorTickSpacing(5);
    scrubber.setPaintTicks(true);
    scrubber.setEnabled(false);
    listPane.add(scrubber);

    // panel of playback buttons
    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
    label = new JLabel("00:00:00");
    buttonPane.add(label);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/play.png");
    icon = new ImageIcon(url, resourceBundle.getString("button.play"));
    playButton = new JButton(icon);
    playButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            rampClient.play();
        }
    });
    buttonPane.add(playButton);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/pause.png");
    icon = new ImageIcon(url, resourceBundle.getString("button.pause"));
    pauseButton = new JButton(icon);
    pauseButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            rampClient.pause();
        }
    });
    buttonPane.add(pauseButton);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/stop.png");
    icon = new ImageIcon(url, resourceBundle.getString("button.stop"));
    stopButton = new JButton(icon);
    stopButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            rampClient.stop();
            setDuration(0);
            scrubber.setValue(0);
            scrubber.setEnabled(false);
        }
    });
    buttonPane.add(stopButton);
    listPane.add(buttonPane);
    getContentPane().add(listPane);

    createProgressDialog();
    startWebserver();
    discoverDevices();
}

From source file:edu.ku.brc.services.biogeomancer.GeoCoordBGMProvider.java

public void processGeoRefData(final List<GeoCoordDataIFace> items,
        final GeoCoordProviderListenerIFace listenerArg, final String helpContextArg) {
    this.listener = listenerArg;
    this.helpContext = helpContextArg;

    UsageTracker.incrUsageCount("Tools.BioGeomancerData"); //$NON-NLS-1$

    log.info("Performing BioGeomancer lookup of selected records"); //$NON-NLS-1$

    // create a progress bar dialog to show the network progress
    final ProgressDialog progressDialog = new ProgressDialog(
            UIRegistry.getResourceString("GeoCoordBGMProvider.BIOGEOMANCER_PROGRESS"), false, true); // I18N //$NON-NLS-1$
    progressDialog.getCloseBtn().setText(getResourceString("CANCEL")); //$NON-NLS-1$
    progressDialog.setModal(true);/*w  w w.  j  a  va2  s . c  om*/
    progressDialog.setProcess(0, items.size());

    // XXX Java 6
    //progressDialog.setIconImage( IconManager.getImage("AppIcon").getImage());

    // use a SwingWorker thread to do all of the work, and update the GUI when done
    final SwingWorker bgTask = new SwingWorker() {
        final JStatusBar statusBar = UIRegistry.getStatusBar();
        protected boolean cancelled = false;

        @Override
        public void interrupt() {
            super.interrupt();
            cancelled = true;
        }

        @SuppressWarnings("synthetic-access") //$NON-NLS-1$
        @Override
        public Object construct() {
            // perform the BG web service call ON all rows, storing results in the rows

            int progress = 0;

            for (GeoCoordDataIFace item : items) {
                if (cancelled) {
                    break;
                }

                // get the locality data
                String localityNameStr = item.getLocalityString();

                // get the geography data
                String country = item.getCountry();
                String state = item.getState();
                String county = item.getCounty();

                log.info("Making call to BioGeomancer service: " + localityNameStr); //$NON-NLS-1$
                String bgResults;
                BioGeomancerQuerySummaryStruct bgQuerySummary;
                try {
                    bgResults = BioGeomancer.getBioGeomancerResponse(item.getGeoCoordId().toString(), country,
                            state, county, localityNameStr);
                    bgQuerySummary = BioGeomancer.parseBioGeomancerResponse(bgResults);
                } catch (IOException ex1) {
                    String warning = getResourceString("GeoCoordBGMProvider.WB_BIOGEOMANCER_UNAVAILABLE"); //$NON-NLS-1$
                    statusBar.setWarningMessage(warning, ex1);
                    log.error("A network error occurred while contacting the BioGeomancer service", ex1); //$NON-NLS-1$

                    // update the progress bar UI and move on
                    progressDialog.setProcess(++progress);
                    continue;
                } catch (Exception ex2) {
                    UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(GeoCoordBGMProvider.class,
                            ex2);
                    // right now we'll simply blame this on BG
                    // in the future we might get more specific about this error
                    String warning = getResourceString("GeoCoordBGMProvider.WB_BIOGEOMANCER_UNAVAILABLE"); //$NON-NLS-1$
                    statusBar.setWarningMessage(warning, ex2);
                    log.warn("Failed to get result count from BioGeomancer respsonse", ex2); //$NON-NLS-1$

                    // update the progress bar UI and move on
                    progressDialog.setProcess(++progress);
                    continue;
                }

                // if there was at least one result, pre-cache a map for that result
                int resCount = bgQuerySummary.results.length;
                if (resCount > 0) {
                    final int rowNumber = item.getGeoCoordId();
                    final BioGeomancerQuerySummaryStruct summaryStruct = bgQuerySummary;
                    // create a thread to go grab the map so it will be cached for later use
                    Thread t = new Thread(new Runnable() {
                        public void run() {
                            try {
                                log.info("Requesting map of BioGeomancer results for workbench row " //$NON-NLS-1$
                                        + rowNumber);
                                BioGeomancer.getMapOfQuerySummary(summaryStruct, null);
                            } catch (Exception e) {
                                UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance()
                                        .capture(GeoCoordBGMProvider.class, e);
                                log.warn("Failed to pre-cache BioGeomancer results map", e); //$NON-NLS-1$
                            }
                        }
                    });
                    t.setName("Map Pre-Caching Thread: row " + item.getGeoCoordId()); // I18N //$NON-NLS-1$
                    log.debug("Starting map pre-caching thread"); //$NON-NLS-1$
                    t.start();
                }

                // if we got at least one result...
                if (resCount > 0) {
                    item.setXML(bgResults);
                }

                // update the progress bar UI and move on
                progressDialog.setProcess(++progress);
            }

            return null;
        }

        @Override
        public void finished() {
            statusBar.setText(getResourceString("GeoCoordBGMProvider.BIOGEOMANCER_COMPLETED")); //$NON-NLS-1$

            if (!cancelled) {
                // hide the progress dialog
                progressDialog.setVisible(false);

                // find out how many records actually had results
                List<GeoCoordDataIFace> rowsWithResults = new Vector<GeoCoordDataIFace>();
                for (GeoCoordDataIFace row : items) {
                    if (row.getXML() != null) {
                        rowsWithResults.add(row);
                    }
                }

                // if no records had possible results...
                int numRecordsWithResults = rowsWithResults.size();
                if (numRecordsWithResults == 0) {
                    statusBar.setText(getResourceString("GeoCoordBGMProvider.NO_BG_RESULTS")); //$NON-NLS-1$
                    JOptionPane.showMessageDialog(UIRegistry.getTopWindow(),
                            getResourceString("GeoCoordBGMProvider.NO_BG_RESULTS"),
                            getResourceString("NO_RESULTS"), JOptionPane.INFORMATION_MESSAGE);
                    return;
                }

                if (listener != null) {
                    listener.aboutToDisplayResults();
                }

                // ask the user if they want to review the results
                String message = String.format(
                        getResourceString("GeoCoordBGMProvider.BGM_VIEW_RESULTS_CONFIRM"), //$NON-NLS-1$
                        String.valueOf(numRecordsWithResults));
                int userChoice = JOptionPane.showConfirmDialog(UIRegistry.getTopWindow(), message,
                        getResourceString("GeoCoordBGMProvider.CONTINUE"), JOptionPane.YES_NO_OPTION);//$NON-NLS-1$

                if (userChoice != JOptionPane.YES_OPTION) {
                    statusBar.setText(getResourceString("GeoCoordBGMProvider.BIOGEOMANCER_TERMINATED")); //$NON-NLS-1$
                    return;
                }

                displayBioGeomancerResults(rowsWithResults);
            }
        }
    };

    // if the user hits close, stop the worker thread
    progressDialog.getCloseBtn().addActionListener(new ActionListener() {
        @SuppressWarnings("synthetic-access") //$NON-NLS-1$
        public void actionPerformed(ActionEvent ae) {
            log.debug("Stopping the BioGeomancer service worker thread"); //$NON-NLS-1$
            bgTask.interrupt();
        }
    });

    log.debug("Starting the BioGeomancer service worker thread"); //$NON-NLS-1$
    bgTask.start();
    UIHelper.centerAndShow(progressDialog);
}