Example usage for javax.swing JFileChooser FILES_AND_DIRECTORIES

List of usage examples for javax.swing JFileChooser FILES_AND_DIRECTORIES

Introduction

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

Prototype

int FILES_AND_DIRECTORIES

To view the source code for javax.swing JFileChooser FILES_AND_DIRECTORIES.

Click Source Link

Document

Instruction to display both files and directories.

Usage

From source file:Main.java

/**
 * opens a FileChooser to select a file or folder if a folder is selected a
 * default filename is appended/* w  w  w  .ja va 2s  .  co  m*/
 *
 * @param c        parent
 * @param fileName default file name (in case a folder is selected)
 * @return null if nothing got selected, otherwise the absolute path
 */
@SuppressWarnings("SameParameterValue")
public static String openFileOrDirectoryWithDefaultFileName(Component c, File currentDirectory,
        String fileName) {
    File file = openJFileChooser(c, currentDirectory, JFileChooser.FILES_AND_DIRECTORIES, null);
    if (file == null) {
        return null;
    }
    String path = file.getAbsolutePath();
    if (file.isDirectory()) {
        if (path.endsWith(File.separator)) {
            path = path + fileName;
        } else {
            path = path + File.separator + fileName;
        }
    }
    return path;
}

From source file:com.ecrimebureau.File.Hash.java

private void gethash() {

    File f = FileChooser.fileChoosers(JFileChooser.FILES_AND_DIRECTORIES);//new File(this.path);

    this.path = f.getAbsolutePath();

    if (f.isFile()) {

        try {/* ww w  .j  av  a  2 s . com*/
            jInternalFrame.setTitle("Hashing a Single File (1)");
            String hash = getChecksum(path, algorithim); //or "SHA-256", "SHA-384", "SHA-512,SHA1" 
            jTA.append(hash + " -> " + path + "\n");
            System.out.println(hash);

        } catch (Exception e) {
            System.out.println("An error occured. hashing -> " + path + "\n");
            jTA.append("An error occured. hashing -> " + path + "\n");
        }
    }

    else if (f.isDirectory()) {
        isDirectory = true;

        Collection files = FileUtils.listFiles(f, new RegexFileFilter("^(.*?)"), DirectoryFileFilter.DIRECTORY);

        int totalNumberofFiles = files.size();
        int startprogress = 1;

        jProgressBar.setMaximum(100);
        jInternalFrame.setTitle("Hashing " + totalNumberofFiles + " Files");

        for (Object i : files.toArray(new File[] {})) {
            try {
                String hash = getChecksum(i.toString(), algorithim); //or "SHA-256", "SHA-384", "SHA-512,SHA1"  
                System.out.println(hash + " -> " + i.toString() + "\n");
                jTA.append(hash + " -> " + i.toString() + "\n");

                //for the progress bar
                int percentageCompleted = (int) Math.round(startprogress * 100.0 / totalNumberofFiles);

                jProgressBar.setValue(percentageCompleted); //set the progress bar value

                jProgressBar.setString(String.valueOf(percentageCompleted) + "%");//the display string
                startprogress++; //increase the value
                //end progress bar

            } catch (Exception e) {
                System.out.println("An error occured. hashing -> " + i.toString() + "\n");
                jTA.append("An error occured. hashing -> " + i.toString() + "\n");
            }
        }
    }
}

From source file:licorice.gui.MainPanel.java

/**
 * Creates new form MainPanel//w ww .j av  a 2 s .  com
 */
public MainPanel() {
    try {
        String jarPath = MainPanel.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
        System.out.println(String.format("JAR Path '%s'", jarPath));
        File propFile = new File("licorice.properties");
        if (propFile.exists()) {
            prop.load(new FileInputStream("licorice.properties"));
            minQual = Integer.parseInt(prop.getProperty("minimum.quality"));
            maxNC = Double.parseDouble(prop.getProperty("maximum.nocall.rate"));
        } else {
            prop = new Properties();
            prop.setProperty("genome.path", "./genome/GCF_000004515.4_Glycine_max_v2.0_genomic.fna");
            prop.setProperty("input.default_dir", ".");
        }
        initComponents();
        doc = logPane.getStyledDocument();

        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

        File defaultDir = new File(prop.getProperty("input.default_dir"));
        if (!defaultDir.exists()) {
            defaultDir = new File(".");
        }

        fc.setCurrentDirectory(defaultDir);
    } catch (Exception ex) {
        log.error(ex.getMessage());
    }
}

From source file:SwingUtil.java

/**
 * Open a JFileChooser dialog for selecting a directory and return the
 * selected directory./*  ww  w .j  a  va2  s  .c o  m*/
 *
 *
 * @param owner
 * The frame or dialog that controls the invokation of this dialog.
 * @param defaultDir
 * The directory to show when the dialog opens.
 * @param title
 * Tile for the dialog.
 *
 * @return
 * The selected directory as a File. Null if user cancels dialog without
 * a selection.
 *
 */
public static File getDirectoryChoice(Component owner, File defaultDir, String title) {
    //
    // There is apparently a bug in the native Windows FileSystem class that
    // occurs when you use a file chooser and there is a security manager
    // active. An error dialog is displayed indicating there is no disk in
    // Drive A:. To avoid this, the security manager is temporarily set to
    // null and then reset after the file chooser is closed.
    //
    SecurityManager sm = null;
    JFileChooser chooser = null;
    File choice = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);
    chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    if ((defaultDir != null) && defaultDir.exists() && defaultDir.isDirectory()) {
        chooser.setCurrentDirectory(defaultDir);
        chooser.setSelectedFile(defaultDir);
    }
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            if (chooser.getSelectedFile().exists()) {
                choice = chooser.getSelectedFile();
            } else {
                File parentFile = new File(chooser.getSelectedFile().getParent());

                choice = parentFile;
            }
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}

From source file:com.digitalgeneralists.assurance.ui.components.FilePickerTextField.java

protected void initializeComponent() {
    if (!this.initialized) {
        this.filePicker.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        GridBagLayout gridbag = new GridBagLayout();
        this.setLayout(gridbag);

        final JPanel filePathPanel = new JPanel();
        filePathPanel.setLayout(new GridBagLayout());

        GridBagConstraints filePathPanelConstraints = new GridBagConstraints();
        filePathPanelConstraints.anchor = GridBagConstraints.NORTH;
        filePathPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
        filePathPanelConstraints.gridx = 0;
        filePathPanelConstraints.gridy = 0;
        filePathPanelConstraints.weightx = 1.0;
        filePathPanelConstraints.weighty = 1.0;
        filePathPanelConstraints.gridheight = 1;
        filePathPanelConstraints.gridwidth = 2;
        filePathPanelConstraints.insets = new Insets(0, 0, 0, 0);

        GridBagConstraints pathTextFieldConstraints = new GridBagConstraints();
        pathTextFieldConstraints.anchor = GridBagConstraints.NORTH;
        pathTextFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
        pathTextFieldConstraints.gridx = 0;
        pathTextFieldConstraints.gridy = 0;
        pathTextFieldConstraints.weightx = 0.9;
        pathTextFieldConstraints.weighty = 1.0;
        pathTextFieldConstraints.gridheight = 1;
        pathTextFieldConstraints.gridwidth = 1;
        pathTextFieldConstraints.insets = new Insets(0, 0, 0, 0);

        GridBagConstraints pathFileChooserButtonConstraints = new GridBagConstraints();
        pathFileChooserButtonConstraints.anchor = GridBagConstraints.NORTH;
        pathFileChooserButtonConstraints.fill = GridBagConstraints.HORIZONTAL;
        pathFileChooserButtonConstraints.gridx = 1;
        pathFileChooserButtonConstraints.gridy = 0;
        pathFileChooserButtonConstraints.weightx = 0.1;
        pathFileChooserButtonConstraints.weighty = 1.0;
        pathFileChooserButtonConstraints.gridheight = 1;
        pathFileChooserButtonConstraints.gridwidth = 1;
        pathFileChooserButtonConstraints.insets = new Insets(0, 0, 0, 0);

        filePathPanel.add(this.pathTextField, pathTextFieldConstraints);
        filePathPanel.add(this.pathFileChooserButton, pathFileChooserButtonConstraints);
        this.add(filePathPanel, filePathPanelConstraints);
        this.pathFileChooserButton.setActionCommand(AssuranceActions.chooseFilePathAction);
        this.pathTextField.getDocument().addDocumentListener(this.textPropertyValidationListener);
        this.pathFileChooserButton.addActionListener(this);

        this.initialized = true;
    }//from   w ww .j  ava2s. c o  m
}

From source file:cool.pandora.modeller.ui.handlers.base.AddDataHandler.java

/**
 * addData./*from  w w w.  jav a  2s .  c  o  m*/
 */
void addData() {
    final File selectFile = new File(File.separator + ".");
    final JFrame frame = new JFrame();
    final JFileChooser fc = new JFileChooser(selectFile);
    fc.setDialogType(JFileChooser.OPEN_DIALOG);
    fc.setMultiSelectionEnabled(true);
    fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    fc.setDialogTitle("Add File or Directory");
    final int option = fc.showOpenDialog(frame);

    if (option == JFileChooser.APPROVE_OPTION) {
        final File[] files = fc.getSelectedFiles();
        final String message = ApplicationContextUtil.getMessage("bag.message.filesadded");
        if (files != null && files.length > 0) {
            addBagData(files);
            ApplicationContextUtil.addConsoleMessage(message + " " + getFileNames(files));
        } else {
            final File file = fc.getSelectedFile();
            addBagData(file);
            ApplicationContextUtil.addConsoleMessage(message + " " + file.getAbsolutePath());
        }
        bagView.bagPayloadTreePanel.refresh(bagView.bagPayloadTree);
        bagView.updateAddData();
    }
}

From source file:de.peterspan.csv2db.ui.FileSelectionPanel.java

private JFileChooser getFileChooser() {
    JFileChooser fc = new JFileChooser();
    fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    fc.setAcceptAllFileFilterUsed(false);

    fc.addChoosableFileFilter(new FileFilter() {

        @Override//  w  w  w  .  j a  v  a2s  . c  o m
        public String getDescription() {
            return "CSV Files";
        }

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

            return FilenameUtils.isExtension(file.getName().toLowerCase(), "csv");
        }
    });

    return fc;
}

From source file:edu.scripps.fl.pubchem.xmltool.gui.GUIComponent.java

public void openPDF(boolean isInternalR, File pdf, Component comp) throws FileNotFoundException {
    if (isInternalR) {
        try {//  w  ww. j a v  a2 s .c  o  m
            Desktop.getDesktop().open(pdf);
        } catch (Exception ex) {
            log.info(ex.getMessage());
            String msg = "Unable to open PDF format through java. Would you like to save "
                    + pdf.getAbsoluteFile() + " in a new location?";
            JOptionPane pane = new JOptionPane(msg, JOptionPane.QUESTION_MESSAGE,
                    JOptionPane.YES_NO_CANCEL_OPTION, null, null, JOptionPane.YES_OPTION);
            JDialog dialog = pane.createDialog(comp, "Report PDF");
            dialog.setVisible(true);
            Object choice = pane.getValue();
            if (choice.equals(JOptionPane.YES_OPTION)) {
                jfcFiles = new JFileChooser();
                jfcFiles.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                int state = jfcFiles.showSaveDialog(comp);

                if (state == JFileChooser.APPROVE_OPTION) {
                    File file = checkFileExtension(".pdf");
                    log.info("Opening: " + file.getName() + ".");
                    if (file != null)
                        pdf.renameTo(file);
                } else {
                    log.info("Open command cancelled by user.");
                }
            }
        }
    }
}

From source file:edu.harvard.mcz.imagecapture.loader.JobVerbatimFieldLoad.java

@Override
public void start() {
    startDateTime = new Date();
    Singleton.getSingletonInstance().getJobList().addJob((RunnableJob) this);
    runStatus = RunStatus.STATUS_RUNNING;

    String selectedFilename = "";

    if (file == null) {
        final JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        if (Singleton.getSingletonInstance().getProperties().getProperties()
                .getProperty(ImageCaptureProperties.KEY_LASTLOADPATH) != null) {
            fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                    .getProperties().getProperty(ImageCaptureProperties.KEY_LASTLOADPATH)));
        }//w w  w .j a  v a2s .c  o  m

        int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            file = fileChooser.getSelectedFile();
        }
    }

    if (file != null) {
        log.debug("Selected file to load: " + file.getName() + ".");

        if (file.exists() && file.isFile() && file.canRead()) {
            // Save location
            Singleton.getSingletonInstance().getProperties().getProperties()
                    .setProperty(ImageCaptureProperties.KEY_LASTLOADPATH, file.getPath());
            selectedFilename = file.getName();

            String[] headers = new String[] {};

            CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headers);
            int rows = 0;
            try {
                rows = readRows(file, csvFormat);
            } catch (FileNotFoundException e) {
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                        "Unable to load data, file not found: " + e.getMessage(), "Error: File Not Found",
                        JOptionPane.OK_OPTION);
                errors.append("File not found ").append(e.getMessage()).append("\n");
                log.error(e.getMessage(), e);
            } catch (IOException e) {
                errors.append("Error loading csv format, trying tab delimited: ").append(e.getMessage())
                        .append("\n");
                log.debug(e.getMessage());
                try {
                    // try reading as tab delimited format, if successful, use that format.
                    CSVFormat tabFormat = CSVFormat.newFormat('\t').withIgnoreSurroundingSpaces(true)
                            .withHeader(headers).withQuote('"');
                    rows = readRows(file, tabFormat);
                    csvFormat = tabFormat;
                } catch (IOException e1) {
                    errors.append("Error Loading data: ").append(e1.getMessage()).append("\n");
                    log.error(e.getMessage(), e1);
                }
            }

            try {
                Reader reader = new FileReader(file);

                CSVParser csvParser = new CSVParser(reader, csvFormat);

                Map<String, Integer> csvHeader = csvParser.getHeaderMap();
                headers = new String[csvHeader.size()];
                int i = 0;
                for (String header : csvHeader.keySet()) {
                    headers[i++] = header;
                    log.debug(header);
                }

                boolean okToRun = true;
                //TODO: Work picking/checking responsibility into a FieldLoaderWizard
                List<String> headerList = Arrays.asList(headers);
                if (!headerList.contains("barcode")) {
                    log.error("Input file " + file.getName()
                            + " header does not contain required field 'barcode'.");
                    // no barcode field, we can't match the input to specimen records.
                    errors.append("Field \"barcode\" not found in csv file headers.  Unable to load data.")
                            .append("\n");
                    okToRun = false;
                }

                if (okToRun) {

                    Iterator<CSVRecord> iterator = csvParser.iterator();

                    FieldLoader fl = new FieldLoader();

                    if (headerList.size() == 3 && headerList.contains("verbatimUnclassifiedText")
                            && headerList.contains("questions") && headerList.contains("barcode")) {
                        log.debug("Input file matches case 1: Unclassified text only.");
                        // Allowed case 1a: unclassified text only

                        int confirm = JOptionPane.showConfirmDialog(
                                Singleton.getSingletonInstance().getMainFrame(),
                                "Confirm load from file " + selectedFilename + " (" + rows
                                        + " rows) with just barcode and verbatimUnclassifiedText",
                                "Verbatim unclassified Field found for load", JOptionPane.OK_CANCEL_OPTION);
                        if (confirm == JOptionPane.OK_OPTION) {
                            String barcode = "";
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                counter.incrementSpecimens();
                                CSVRecord record = iterator.next();
                                try {
                                    String verbatimUnclassifiedText = record.get("verbatimUnclassifiedText");
                                    barcode = record.get("barcode");
                                    String questions = record.get("questions");

                                    fl.load(barcode, verbatimUnclassifiedText, questions, true);
                                    counter.incrementSpecimensUpdated();
                                } catch (IllegalArgumentException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                } catch (LoadException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            errors.append("Load canceled by user.").append("\n");
                        }
                    } else if (headerList.size() == 4 && headerList.contains("verbatimUnclassifiedText")
                            && headerList.contains("questions") && headerList.contains("barcode")
                            && headerList.contains("verbatimClusterIdentifier")) {
                        log.debug(
                                "Input file matches case 1: Unclassified text only (with cluster identifier).");
                        // Allowed case 1b: unclassified text only (including cluster identifier)

                        int confirm = JOptionPane.showConfirmDialog(
                                Singleton.getSingletonInstance().getMainFrame(),
                                "Confirm load from file " + selectedFilename + " (" + rows
                                        + " rows) with just barcode and verbatimUnclassifiedText",
                                "Verbatim unclassified Field found for load", JOptionPane.OK_CANCEL_OPTION);
                        if (confirm == JOptionPane.OK_OPTION) {
                            String barcode = "";
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                counter.incrementSpecimens();
                                CSVRecord record = iterator.next();
                                try {
                                    String verbatimUnclassifiedText = record.get("verbatimUnclassifiedText");
                                    String verbatimClusterIdentifier = record.get("verbatimClusterIdentifier");
                                    barcode = record.get("barcode");
                                    String questions = record.get("questions");

                                    fl.load(barcode, verbatimUnclassifiedText, verbatimClusterIdentifier,
                                            questions, true);
                                    counter.incrementSpecimensUpdated();
                                } catch (IllegalArgumentException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                } catch (LoadException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            errors.append("Load canceled by user.").append("\n");
                        }

                    } else if (headerList.size() == 8 && headerList.contains("verbatimUnclassifiedText")
                            && headerList.contains("questions") && headerList.contains("barcode")
                            && headerList.contains("verbatimLocality") && headerList.contains("verbatimDate")
                            && headerList.contains("verbatimNumbers")
                            && headerList.contains("verbatimCollector")
                            && headerList.contains("verbatimCollection")) {
                        // Allowed case two, transcription into verbatim fields, must be exact list of all
                        // verbatim fields, not including cluster identifier or other metadata.
                        log.debug("Input file matches case 2: Full list of verbatim fields.");

                        int confirm = JOptionPane.showConfirmDialog(
                                Singleton.getSingletonInstance().getMainFrame(),
                                "Confirm load from file " + selectedFilename + " (" + rows
                                        + " rows) with just barcode and verbatim fields.",
                                "Verbatim Fields found for load", JOptionPane.OK_CANCEL_OPTION);
                        if (confirm == JOptionPane.OK_OPTION) {

                            String barcode = "";
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                counter.incrementSpecimens();
                                CSVRecord record = iterator.next();
                                try {
                                    String verbatimLocality = record.get("verbatimLocality");
                                    String verbatimDate = record.get("verbatimDate");
                                    String verbatimCollector = record.get("verbatimCollector");
                                    String verbatimCollection = record.get("verbatimCollection");
                                    String verbatimNumbers = record.get("verbatimNumbers");
                                    String verbatimUnclasifiedText = record.get("verbatimUnclassifiedText");
                                    barcode = record.get("barcode");
                                    String questions = record.get("questions");

                                    fl.load(barcode, verbatimLocality, verbatimDate, verbatimCollector,
                                            verbatimCollection, verbatimNumbers, verbatimUnclasifiedText,
                                            questions);
                                    counter.incrementSpecimensUpdated();
                                } catch (IllegalArgumentException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                } catch (LoadException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            errors.append("Load canceled by user.").append("\n");
                        }

                    } else {
                        // allowed case three, transcription into arbitrary sets verbatim or other fields
                        log.debug("Input file case 3: Arbitrary set of fields.");

                        // Check column headers before starting run.
                        boolean headersOK = false;

                        try {
                            HeaderCheckResult headerCheck = fl.checkHeaderList(headerList);
                            if (headerCheck.isResult()) {
                                int confirm = JOptionPane.showConfirmDialog(
                                        Singleton.getSingletonInstance().getMainFrame(),
                                        "Confirm load from file " + selectedFilename + " (" + rows
                                                + " rows) with headers: \n"
                                                + headerCheck.getMessage().replaceAll(":", ":\n"),
                                        "Fields found for load", JOptionPane.OK_CANCEL_OPTION);
                                if (confirm == JOptionPane.OK_OPTION) {
                                    headersOK = true;
                                } else {
                                    errors.append("Load canceled by user.").append("\n");
                                }
                            } else {
                                int confirm = JOptionPane.showConfirmDialog(
                                        Singleton.getSingletonInstance().getMainFrame(),
                                        "Problem found with headers in file, try to load anyway?\nHeaders: \n"
                                                + headerCheck.getMessage().replaceAll(":", ":\n"),
                                        "Problem in fields for load", JOptionPane.OK_CANCEL_OPTION);
                                if (confirm == JOptionPane.OK_OPTION) {
                                    headersOK = true;
                                } else {
                                    errors.append("Load canceled by user.").append("\n");
                                }
                            }
                        } catch (LoadException e) {
                            errors.append("Error loading data: \n").append(e.getMessage()).append("\n");
                            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                    e.getMessage().replaceAll(":", ":\n"), "Error Loading Data: Problem Fields",
                                    JOptionPane.ERROR_MESSAGE);

                            log.error(e.getMessage(), e);
                        }

                        if (headersOK) {
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                Map<String, String> data = new HashMap<String, String>();
                                CSVRecord record = iterator.next();
                                String barcode = record.get("barcode");
                                Iterator<String> hi = headerList.iterator();
                                boolean containsNonVerbatim = false;
                                while (hi.hasNext()) {
                                    String header = hi.next();
                                    // Skip any fields prefixed by the underscore character _
                                    if (!header.equals("barcode") && !header.startsWith("_")) {
                                        data.put(header, record.get(header));
                                        if (!header.equals("questions")
                                                && MetadataRetriever.isFieldExternallyUpdatable(Specimen.class,
                                                        header)
                                                && MetadataRetriever.isFieldVerbatim(Specimen.class, header)) {
                                            containsNonVerbatim = true;
                                        }
                                    }
                                }
                                if (data.size() > 0) {
                                    try {
                                        boolean updated = false;
                                        if (containsNonVerbatim) {
                                            updated = fl.loadFromMap(barcode, data,
                                                    WorkFlowStatus.STAGE_CLASSIFIED, true);
                                        } else {
                                            updated = fl.loadFromMap(barcode, data,
                                                    WorkFlowStatus.STAGE_VERBATIM, true);
                                        }
                                        counter.incrementSpecimens();
                                        if (updated) {
                                            counter.incrementSpecimensUpdated();
                                        }
                                    } catch (HibernateException e1) {
                                        // Catch (should just be development) problems with the underlying query 
                                        StringBuilder message = new StringBuilder();
                                        message.append("Query Error loading row (").append(lineNumber)
                                                .append(")[").append(barcode).append("]")
                                                .append(e1.getMessage());
                                        RunnableJobError err = new RunnableJobError(selectedFilename, barcode,
                                                Integer.toString(lineNumber), e1.getMessage(), e1,
                                                RunnableJobError.TYPE_LOAD_FAILED);
                                        counter.appendError(err);
                                        log.error(e1.getMessage(), e1);

                                    } catch (LoadException e) {
                                        StringBuilder message = new StringBuilder();
                                        message.append("Error loading row (").append(lineNumber).append(")[")
                                                .append(barcode).append("]").append(e.getMessage());

                                        RunnableJobError err = new RunnableJobError(selectedFilename, barcode,
                                                Integer.toString(lineNumber), e.getMessage(), e,
                                                RunnableJobError.TYPE_LOAD_FAILED);

                                        counter.appendError(err);
                                        // errors.append(message.append("\n").toString());
                                        log.error(e.getMessage(), e);
                                    }
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            String message = "Can't load data, problem with headers.";
                            errors.append(message).append("\n");
                            log.error(message);
                        }
                    }
                }
                csvParser.close();
                reader.close();
            } catch (FileNotFoundException e) {
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                        "Unable to load data, file not found: " + e.getMessage(), "Error: File Not Found",
                        JOptionPane.OK_OPTION);
                errors.append("File not found ").append(e.getMessage()).append("\n");
                log.error(e.getMessage(), e);
            } catch (IOException e) {
                errors.append("Error Loading data: ").append(e.getMessage()).append("\n");
                log.error(e.getMessage(), e);
            }
        }

    } else {
        //TODO: handle error condition
        log.error("File selection cancelled by user.");
    }

    report(selectedFilename);
    done();
}

From source file:com.mirth.connect.client.ui.MessageImportDialog.java

private void browseSelected() {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    if (userPreferences != null) {
        File currentDir = new File(userPreferences.get("currentDirectory", ""));

        if (currentDir.exists()) {
            chooser.setCurrentDirectory(currentDir);
        }//from  w w  w .  j a v  a  2 s  .c  o m
    }

    if (chooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
        if (userPreferences != null) {
            userPreferences.put("currentDirectory", chooser.getCurrentDirectory().getPath());
        }

        fileTextField.setText(chooser.getSelectedFile().getAbsolutePath());
    }
}