Example usage for javax.swing JFileChooser setFileSelectionMode

List of usage examples for javax.swing JFileChooser setFileSelectionMode

Introduction

In this page you can find the example usage for javax.swing JFileChooser setFileSelectionMode.

Prototype

@BeanProperty(preferred = true, enumerationValues = { "JFileChooser.FILES_ONLY",
        "JFileChooser.DIRECTORIES_ONLY",
        "JFileChooser.FILES_AND_DIRECTORIES" }, description = "Sets the types of files that the JFileChooser can choose.")
public void setFileSelectionMode(int mode) 

Source Link

Document

Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories.

Usage

From source file:org.surmon.pattern.importer.ImportAction.java

/**
 * Creates and shows import dialog. Also handles user interaction with the
 * dialog.//from   w  w w  .j  a v  a  2  s  .  co m
 */
public static void createAndShowDialog() {
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Import data");
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setAcceptAllFileFilterUsed(true);

    Collection<? extends PDataImporter> importers = Lookup.getDefault().lookupAll(PDataImporter.class);

    // find all importers and set the filters for open dialog
    for (PDataImporter importer : importers) {
        chooser.addChoosableFileFilter(importer.getExtensionFilter());
    }

    // open and wait for result
    int returnVal = chooser.showOpenDialog(null);

    // process the result from open dialog
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        final File file = chooser.getSelectedFile();

        if (file.exists()) {
            final String extension = FilenameUtils.getExtension(file.getName());
            final PDataImporter importer = selectImporter(importers, extension);
            if (importer != null) {
                executeImport(importer, file);
            } else {
                NotifyDescriptor nd = new NotifyDescriptor.Message(
                        "File " + extension + " doesn't contain image data or is not supported.");
                DialogDisplayer.getDefault().notify(nd);
            }
        }
    }
}

From source file:org.thelq.stackexchange.dbimport.gui.GUI.java

public GUI(Controller passedController) {
    //Initialize logger
    logAppender = new GUILogAppender(this);

    //Set our Look&Feel
    try {/* w  ww  . jav a 2s  .c o  m*/
        if (SystemUtils.IS_OS_WINDOWS)
            UIManager.setLookAndFeel(new WindowsLookAndFeel());
        else
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.warn("Defaulting to Swing L&F due to exception", e);
    }

    this.controller = passedController;
    frame = new JFrame();
    frame.setTitle("Unified StackExchange Data Dump Importer v" + Controller.VERSION);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    //Setup menu
    JMenuBar menuBar = new JMenuBar();
    menuAdd = new JMenuItem("Add Folders/Archives");
    menuAdd.setMnemonic(KeyEvent.VK_F);
    menuBar.add(menuAdd);
    frame.setJMenuBar(menuBar);

    //Primary panel
    FormLayout primaryLayout = new FormLayout("5dlu, pref:grow, 5dlu, 5dlu, pref",
            "pref, top:pref, pref, fill:140dlu:grow, pref, fill:80dlu");
    PanelBuilder primaryBuilder = new PanelBuilder(primaryLayout)
            .border(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    //DB Config panel
    primaryBuilder.addSeparator("Database Configuration", CC.xyw(1, 1, 2));
    FormLayout configLayout = new FormLayout("pref, 3dlu, pref:grow, 6dlu, pref",
            "pref, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow");
    configLayout.setHonorsVisibility(true);
    final PanelBuilder configBuilder = new PanelBuilder(configLayout);
    configBuilder.addLabel("Server", CC.xy(1, 2), dbType = new JComboBox<DatabaseOption>(), CC.xy(3, 2));
    configBuilder.add(dbAdvanced = new JCheckBox("Show advanced options"), CC.xy(5, 2));
    configBuilder.addLabel("JDBC Connection", CC.xy(1, 4), jdbcString = new JTextField(15), CC.xyw(3, 4, 3));
    configBuilder.addLabel("Username", CC.xy(1, 6), username = new JTextField(10), CC.xy(3, 6));
    configBuilder.addLabel("Password", CC.xy(1, 8), password = new JPasswordField(10), CC.xy(3, 8));
    configBuilder.add(importButton = new JButton("Import"), CC.xywh(5, 6, 1, 3));
    //Add hidden
    JLabel dialectLabel = new JLabel("Dialect");
    dialectLabel.setVisible(false);
    configBuilder.add(dialectLabel, CC.xy(1, 10), dialect = new JTextField(10), CC.xyw(3, 10, 3));
    dialect.setVisible(false);
    JLabel driverLabel = new JLabel("Driver");
    driverLabel.setVisible(false);
    configBuilder.add(driverLabel, CC.xy(1, 12), driver = new JTextField(10) {
        @Override
        public void setText(String text) {
            if (StringUtils.isBlank(text))
                log.debug("Text is blank", new RuntimeException("Text " + text + " is blank"));
            super.setText(text);
        }
    }, CC.xyw(3, 12, 3));
    driver.setVisible(false);
    primaryBuilder.add(configBuilder.getPanel(), CC.xy(2, 2));

    //Options
    primaryBuilder.addSeparator("Options", CC.xyw(4, 1, 2));
    FormLayout optionsLayout = new FormLayout("pref, 3dlu, pref:grow", "");
    DefaultFormBuilder optionsBuilder = new DefaultFormBuilder(optionsLayout);
    optionsBuilder.append(disableCreateTables = new JCheckBox("Disable Creating Tables"), 3);
    optionsBuilder.append("Global Table Prefix", globalTablePrefix = new JTextField(7));
    optionsBuilder.append("Threads", threads = new JSpinner());
    //Save a core for the database
    int numThreads = Runtime.getRuntime().availableProcessors();
    numThreads = (numThreads != 1) ? numThreads - 1 : numThreads;
    threads.setModel(new SpinnerNumberModel(numThreads, 1, 100, 1));
    optionsBuilder.append("Batch Size", batchSize = new JSpinner());
    batchSize.setModel(new SpinnerNumberModel(500, 1, 500000, 1));
    primaryBuilder.add(optionsBuilder.getPanel(), CC.xy(5, 2));

    //Locations
    primaryBuilder.addSeparator("Dump Locations", CC.xyw(1, 3, 5));
    FormLayout locationsLayout = new FormLayout("pref, 15dlu, pref, 5dlu, pref, 5dlu, pref:grow, 2dlu, pref",
            "");
    locationsBuilder = new DefaultFormBuilder(locationsLayout, new ScrollablePanel()).background(Color.WHITE)
            .lineGapSize(Sizes.ZERO);
    locationsPane = new JScrollPane(locationsBuilder.getPanel());
    locationsPane.getViewport().setBackground(Color.white);
    locationsPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    locationsPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    primaryBuilder.add(locationsPane, CC.xyw(2, 4, 4));

    //Logger
    primaryBuilder.addSeparator("Log", CC.xyw(1, 5, 5));
    loggerText = new JTextPane();
    loggerText.setEditable(false);
    JPanel loggerTextPanel = new JPanel(new BorderLayout());
    loggerTextPanel.add(loggerText);
    JScrollPane loggerPane = new JScrollPane(loggerTextPanel);
    loggerPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    loggerPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    JPanel loggerPanePanel = new JPanel(new BorderLayout());
    loggerPanePanel.add(loggerPane);
    primaryBuilder.add(loggerPanePanel, CC.xyw(2, 6, 4));

    menuAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //TODO: Allow 7z files but handle corner cases
            final JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            fc.setMultiSelectionEnabled(true);
            fc.setDialogTitle("Select Folders/Archives");
            fc.addChoosableFileFilter(new FileNameExtensionFilter("Archives", "7z", "zip"));
            fc.addChoosableFileFilter(new FileFilter() {
                @Getter
                protected String description = "Folders";

                @Override
                public boolean accept(File file) {
                    return file.isDirectory();
                }
            });

            if (fc.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION)
                return;

            //Add files and folders in a seperate thread while updating gui in EDT
            importButton.setEnabled(false);
            for (File curFile : fc.getSelectedFiles()) {
                DumpContainer dumpContainer = null;
                try {
                    if (curFile.isDirectory())
                        dumpContainer = new FolderDumpContainer(curFile);
                    else
                        dumpContainer = new ArchiveDumpContainer(controller, curFile);
                    controller.addDumpContainer(dumpContainer);
                } catch (Exception ex) {
                    String type = (dumpContainer != null) ? dumpContainer.getType() : "";
                    LoggerFactory.getLogger(getClass()).error("Cannot open " + type, ex);
                    String location = (dumpContainer != null) ? Utils.getLongLocation(dumpContainer) : "";
                    showErrorDialog(ex, "Cannot open " + location, curFile.getAbsolutePath());
                    continue;
                }
            }
            updateLocations();
            importButton.setEnabled(true);
        }
    });

    //Add options (Could be in a map, but this is cleaner)
    dbType.addItem(new DatabaseOption().name("MySQL 5.5.3+")
            .jdbcString("jdbc:mysql://127.0.0.1:3306/stackexchange?rewriteBatchedStatements=true")
            .dialect("org.hibernate.dialect.MySQL5Dialect").driver("com.mysql.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("PostgreSQL 8.1")
            .jdbcString("jdbc:postgresql://127.0.0.1:5432/stackexchange")
            .dialect("org.hibernate.dialect.PostgreSQL81Dialect").driver("org.postgresql.Driver"));
    dbType.addItem(new DatabaseOption().name("PostgreSQL 8.2+")
            .jdbcString("jdbc:postgresql://127.0.0.1:5432/stackexchange")
            .dialect("org.hibernate.dialect.PostgreSQL82Dialect").driver("org.postgresql.Driver"));
    dbType.addItem(new DatabaseOption().name("SQL Server")
            .jdbcString("jbdc:jtds:mssql://127.0.0.1:1433/stackexchange")
            .dialect("org.hibernate.dialect.SQLServerDialect").driver("net.sourceforge.jtds.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("SQL Server 2005+")
            .jdbcString("jbdc:jtds:mssql://127.0.0.1:1433/stackexchange")
            .dialect("org.hibernate.dialect.SQLServer2005Dialect").driver("net.sourceforge.jtds.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("SQL Server 2008+")
            .jdbcString("jbdc:jtds:mssql://127.0.0.1:1433/stackexchange")
            .dialect("org.hibernate.dialect.SQLServer2008Dialect").driver("net.sourceforge.jtds.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("H2").jdbcString("jdbc:h2:stackexchange")
            .dialect("org.hibernate.dialect.H2Dialect").driver("org.h2.Driver"));
    dbType.setSelectedItem(null);
    dbType.addItemListener(new ItemListener() {
        boolean shownMysqlWarning = false;

        public void itemStateChanged(ItemEvent e) {
            //Don't run this twice for a single select
            if (e.getStateChange() == ItemEvent.DESELECTED)
                return;

            DatabaseOption selectedOption = (DatabaseOption) dbType.getSelectedItem();
            if (selectedOption.name().startsWith("MySQL") && !shownMysqlWarning) {
                //Hide popup so you don't have to click twice on the dialog 
                dbType.setPopupVisible(false);
                JOptionPane.showMessageDialog(frame,
                        "Warning: Your server must be configured with character_set_server=utf8mb4"
                                + "\nOtherwise, data dumps that contain 4 byte UTF-8 characters will fail",
                        "MySQL Warning", JOptionPane.WARNING_MESSAGE);
                shownMysqlWarning = true;
            }

            setDbOption(selectedOption);
        }
    });

    //Show and hide advanced options with checkbox
    dbAdvanced.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            boolean selected = ((JCheckBox) e.getSource()).isSelected();
            driver.setVisible(selected);
            ((JLabel) driver.getClientProperty("labeledBy")).setVisible(selected);
            dialect.setVisible(selected);
            ((JLabel) dialect.getClientProperty("labeledBy")).setVisible(selected);
        }
    });

    importButton.addActionListener(new ActionListener() {
        protected void showImportError(String error) {
            JOptionPane.showMessageDialog(frame, error, "Configuration Error", JOptionPane.ERROR_MESSAGE);
        }

        protected void showInputErrorDatabase(String error) {
            if (dbType.getSelectedItem() == null)
                showImportError("No dbType specified, " + StringUtils.uncapitalize(error));
            else
                showImportError(error);
        }

        public void actionPerformed(ActionEvent e) {
            boolean validationPassed = false;
            if (controller.getDumpContainers().isEmpty())
                showImportError("Please add dump folders/archives");
            else if (StringUtils.isBlank(jdbcString.getText()))
                showInputErrorDatabase("Must specify JDBC String");
            else if (StringUtils.isBlank(driver.getText()))
                showInputErrorDatabase("Must specify driver");
            else if (StringUtils.isBlank(dialect.getText()))
                showInputErrorDatabase("Must specify hibernate dialect");
            else
                validationPassed = true;

            if (!validationPassed)
                return;

            //Disable all GUI components so they can't change anything during processing
            setGuiEnabled(false);

            //Run in new thread
            controller.getGeneralThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        start();
                    } catch (final Exception e) {
                        //Show an error message box
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                LoggerFactory.getLogger(getClass()).error("Cannot import", e);
                                showErrorDialog(e, "Cannot import", null);
                            }
                        });
                    }
                    //Renable GUI
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            setGuiEnabled(true);
                        }
                    });
                }
            });
        }
    });

    //Done, init logger
    logAppender.init();
    log.info("Finished creating GUI");

    //Display
    frame.setContentPane(primaryBuilder.getPanel());
    frame.pack();
    frame.setMinimumSize(frame.getSize());

    frame.setVisible(true);
}

From source file:org.tinymediamanager.ui.TmmUIHelper.java

private static Path openJFileChooser(int mode, String dialogTitle, boolean open, String filename,
        FileNameExtensionFilter filter) {
    JFileChooser fileChooser;
    // are we forced to open the legacy file chooser?
    if ("true".equals(System.getProperty("tmm.legacy.filechooser"))) {
        fileChooser = new JFileChooser();
    } else {/*from  www . j av a2  s .c o  m*/
        fileChooser = new NativeFileChooser();
    }

    fileChooser.setFileSelectionMode(mode);
    if (lastDir != null) {
        fileChooser.setCurrentDirectory(lastDir.toFile());
    }
    fileChooser.setDialogTitle(dialogTitle);

    int result = -1;
    if (open) {
        result = fileChooser.showOpenDialog(MainWindow.getFrame());
    } else {
        if (StringUtils.isNotBlank(filename)) {
            fileChooser.setSelectedFile(new File(filename));
            fileChooser.setFileFilter(filter);
        }
        result = fileChooser.showSaveDialog(MainWindow.getFrame());
    }

    if (result == JFileChooser.APPROVE_OPTION) {
        if (mode == JFileChooser.DIRECTORIES_ONLY) {
            lastDir = fileChooser.getSelectedFile().toPath();
        } else {
            lastDir = fileChooser.getSelectedFile().getParentFile().toPath();
        }
        return fileChooser.getSelectedFile().toPath();
    }

    return null;
}

From source file:org.tmpotter.ui.ActionHandler.java

/**
 * Save project as specified filename.//  www.j av  a2 s  .  c om
 */
private void saveProjectAs() {
    File outFile = new File(modelMediator.getProjectName().concat(".tmpx"));
    try {
        boolean save = false;
        boolean cancel = false;
        while (!save && !cancel) {
            final JFileChooser fc = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("TMX File", "tmpx");
            fc.setFileFilter(filter);
            boolean nameOfUser = false;
            while (!nameOfUser) {
                fc.setLocation(230, 300);
                fc.setCurrentDirectory(RuntimePreferences.getUserHome());
                fc.setDialogTitle(getString("DLG.SAVEAS"));
                fc.setMultiSelectionEnabled(false);
                fc.setSelectedFile(outFile);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                RuntimePreferences.setUserHome(fc.getCurrentDirectory());
                int returnVal;
                returnVal = fc.showSaveDialog(parent);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    outFile = fc.getSelectedFile();
                    if (!outFile.getName().endsWith(".tmpx")) {
                        outFile = new File(outFile.getName().concat(".tmpx"));
                    }
                    nameOfUser = true;
                } else {
                    nameOfUser = true;
                    cancel = true;
                }
            }
            int selected;
            if (nameOfUser && !cancel) {
                if (outFile.exists()) {
                    final Object[] options = { getString("BTN.SAVE"), getString("BTN.CANCEL") };
                    selected = JOptionPane.showOptionDialog(parent, getString("MSG.FILE_EXISTS"),
                            getString("MSG.WARNING"), JOptionPane.OK_CANCEL_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (selected == 0) {
                        save = true;
                    }
                } else {
                    save = true;
                }
            }
        }
        if (save) {
            cleanTmData();
            ProjectProperties prop = modelMediator.getProjectProperties();
            prop.setFilePathProject(outFile);
            TmxpWriter.writeTmxp(prop, tmData.getDocumentOriginal(), tmData.getDocumentTranslation());
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(parent, JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.wso2.carbon.cluster.ui.ClusterWizard.java

private void btnFolderPathSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFolderPathSelectActionPerformed
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int returnVal = chooser.showOpenDialog(getParent());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        clusterAbsFolderPath = chooser.getSelectedFile().getAbsolutePath();
        txtFolderPath.setText(clusterAbsFolderPath);
    }/* www  .j  a  v  a2  s .  co m*/
}

From source file:org.zaproxy.zap.extension.beanshell.BeanShellConsoleFrame.java

private JButton getBtnLoad() {
    if (btnLoad == null) {
        btnLoad = new JButton();
        btnLoad.setText(Constant.messages.getString("beanshell.button.load"));

        btnLoad.addActionListener(new ActionListener() {
            @Override//from   w  w w.ja v a 2  s.c  om
            public void actionPerformed(ActionEvent e) {
                if (getBeanShellPanel().isSaved() == false) {
                    int confirm = view
                            .showConfirmDialog(Constant.messages.getString("beanshell.dialog.unsaved"));
                    if (confirm == JOptionPane.CANCEL_OPTION)
                        return;
                }
                JFileChooser fc = new JFileChooser(scriptsDir);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                int result = fc.showOpenDialog(getBeanShellPanel());

                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        String temp = loadScript(fc.getSelectedFile());
                        getBeanShellPanel().getTxtEditor().setText(temp);
                        getBeanShellPanel().getTxtEditor().discardAllEdits();
                        getBeanShellPanel().setSaved(true);
                        currentScriptFile = fc.getSelectedFile();
                    } catch (IOException ex) {
                        log.error(ex.getMessage(), ex);
                        View.getSingleton().showWarningDialog(
                                Constant.messages.getString("beanshell.error.message.loading.script"));
                    }
                }
            }
        });
    }
    return btnLoad;
}

From source file:org.zaproxy.zap.extension.beanshell.BeanShellConsoleFrame.java

private JButton getBtnSave() {
    if (btnSave == null) {
        btnSave = new JButton();
        btnSave.setText(Constant.messages.getString("beanshell.button.save"));

        btnSave.addActionListener(new ActionListener() {
            @Override//from   ww  w .  ja va  2 s . co  m
            public void actionPerformed(ActionEvent e) {
                if (currentScriptFile != null) {
                    try {
                        saveScript(getBeanShellPanel().getTxtEditor().getText(), currentScriptFile);
                        getBeanShellPanel().setSaved(true);
                    } catch (IOException ex) {
                        log.error(ex.getMessage(), ex);
                        View.getSingleton().showWarningDialog(
                                Constant.messages.getString("beanshell.error.message.saving.script"));
                    }

                } else {
                    JFileChooser fc = new JFileChooser(scriptsDir);
                    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    int result = fc.showSaveDialog(getBeanShellPanel());

                    if (result == JFileChooser.APPROVE_OPTION) {
                        try {
                            saveScript(getBeanShellPanel().getTxtEditor().getText(), fc.getSelectedFile());
                            getBeanShellPanel().setSaved(true);
                            currentScriptFile = fc.getSelectedFile();
                        } catch (IOException ex) {
                            log.error(ex.getMessage(), ex);
                            View.getSingleton().showWarningDialog(
                                    Constant.messages.getString("beanshell.error.message.saving.script"));
                        }
                    }
                }
            }
        });
    }
    return btnSave;
}

From source file:org.zaproxy.zap.extension.beanshell.BeanShellConsoleFrame.java

private JButton getBtnSaveAs() {
    if (btnSaveAs == null) {
        btnSaveAs = new JButton();
        btnSaveAs.setText(Constant.messages.getString("beanshell.button.saveas"));

        btnSaveAs.addActionListener(new ActionListener() {
            @Override/*from   ww  w .  ja v a  2  s  .  c om*/
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser(scriptsDir);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                int result = fc.showSaveDialog(getBeanShellPanel());
                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        saveScript(getBeanShellPanel().getTxtEditor().getText(), fc.getSelectedFile());
                        getBeanShellPanel().setSaved(true);
                        currentScriptFile = fc.getSelectedFile();
                    } catch (IOException ex) {
                        log.error(ex.getMessage(), ex);
                        View.getSingleton().showWarningDialog(
                                Constant.messages.getString("beanshell.error.message.saving.script"));
                    }
                }
            }
        });
    }
    return btnSaveAs;
}

From source file:org.zaproxy.zap.extension.dynssl.DynamicSSLPanel.java

/**
 * Import Root CA certificate from other ZAP configuration files.
 *//* w  w w . j av  a 2 s.c  o  m*/
private void doImport() {
    if (checkExistingCertificate()) {
        // prevent overwriting
        return;
    }
    final JFileChooser fc = new JFileChooser(System.getProperty("user.home"));
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setMultiSelectionEnabled(false);
    fc.setSelectedFile(new File(CONFIGURATION_FILENAME));
    fc.setFileFilter(new FileFilter() {
        @Override
        public String getDescription() {
            // config.xml or *.pem files
            return Constant.messages.getString("dynssl.filter.file");
        }

        @Override
        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(CONFIGURATION_FILENAME)
                    || f.getName().toLowerCase().endsWith("pem") || f.isDirectory();
        }
    });
    final int result = fc.showOpenDialog(this);
    final File f = fc.getSelectedFile();
    if (result == JFileChooser.APPROVE_OPTION && f.exists()) {
        if (logger.isInfoEnabled()) {
            logger.info("Loading Root CA certificate from " + f);
        }
        KeyStore ks = null;
        if (f.getName().toLowerCase().endsWith("pem")) {
            ks = convertPemFileToKeyStore(f.toPath());
        } else {
            try {
                final ZapXmlConfiguration conf = new ZapXmlConfiguration(f);
                final String rootcastr = conf.getString(DynSSLParam.PARAM_ROOT_CA);
                ks = SslCertificateUtils.string2Keystore(rootcastr);
            } catch (final Exception e) {
                logger.error("Error importing Root CA cert from config file:", e);
                JOptionPane.showMessageDialog(this,
                        Constant.messages.getString("dynssl.message1.filecouldntloaded"),
                        Constant.messages.getString("dynssl.message1.title"), JOptionPane.ERROR_MESSAGE);
            }
        }
        if (ks != null) {
            setRootca(ks);
        }

    }
}

From source file:org.zaproxy.zap.extension.dynssl.DynamicSSLPanel.java

/**
 * Saving Root CA certificate to disk./*w ww.j a v  a  2  s .c  om*/
 */
private void doSave() {
    if (txt_PubCert.getDocument().getLength() < MIN_CERT_LENGTH) {
        logger.error("Illegal state! There seems to be no certificate available.");
        bt_save.setEnabled(false);
    }
    final JFileChooser fc = new JFileChooser(System.getProperty("user.home"));
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setMultiSelectionEnabled(false);
    fc.setSelectedFile(new File(OWASP_ZAP_ROOT_CA_FILENAME));
    if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        final File f = fc.getSelectedFile();
        if (logger.isInfoEnabled()) {
            logger.info("Saving Root CA certificate to " + f);
        }
        try {
            writePubCertificateToFile(f);
        } catch (final Exception e) {
            logger.error("Error while writing certificate data to file " + f, e);
        }
    }
}