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.igormaznitsa.zxpspritecorrector.files.TAPPlugin.java

@Override
public void writeTo(final File file, final ZXPolyData data, final SessionData session) throws IOException {
    final int saveAsSeparateFiles = JOptionPane.showConfirmDialog(this.mainFrame,
            "Save each block as a separated file?", "Separate files", JOptionPane.YES_NO_CANCEL_OPTION);
    if (saveAsSeparateFiles == JOptionPane.CANCEL_OPTION)
        return;/* w w  w . j a va  2  s.c o m*/

    final String baseName = file.getName();
    final String baseZXName = FilenameUtils.getBaseName(baseName);
    if (saveAsSeparateFiles == JOptionPane.YES_OPTION) {

        final FileNameDialog fileNameDialog = new FileNameDialog(this.mainFrame, "Saving as separated files",
                new String[] { addNumberToFileName(baseName, 0), addNumberToFileName(baseName, 1),
                        addNumberToFileName(baseName, 2), addNumberToFileName(baseName, 3) },
                new String[] { prepareNameForTAP(baseZXName, 0), prepareNameForTAP(baseZXName, 1),
                        prepareNameForTAP(baseZXName, 2), prepareNameForTAP(baseZXName, 3) },
                null);
        fileNameDialog.setVisible(true);
        if (fileNameDialog.approved()) {
            final String[] fileNames = fileNameDialog.getFileName();
            final String[] zxNames = fileNameDialog.getZxName();
            for (int i = 0; i < 4; i++) {
                final byte[] headerblock = makeHeaderBlock(zxNames[i], data.getInfo().getStartAddress(),
                        data.length());
                final byte[] datablock = makeDataBlock(data.getDataForCPU(i));
                final byte[] dataToSave = JBBPOut.BeginBin().Byte(wellTapBlock(headerblock))
                        .Byte(wellTapBlock(datablock)).End().toByteArray();

                final File fileToSave = new File(file.getParent(), fileNames[i]);
                if (!saveDataToFile(fileToSave, dataToSave))
                    return;
            }
        }
    } else {
        final FileNameDialog fileNameDialog = new FileNameDialog(this.mainFrame, "Save as " + baseName, null,
                new String[] { prepareNameForTAP(baseZXName, 0), prepareNameForTAP(baseZXName, 1),
                        prepareNameForTAP(baseZXName, 2), prepareNameForTAP(baseZXName, 3) },
                null);
        fileNameDialog.setVisible(true);
        if (fileNameDialog.approved()) {
            final String[] zxNames = fileNameDialog.getZxName();
            final JBBPOut out = JBBPOut.BeginBin();
            for (int i = 0; i < 4; i++) {
                final byte[] headerblock = makeHeaderBlock(zxNames[i], data.getInfo().getStartAddress(),
                        data.length());
                final byte[] datablock = makeDataBlock(data.getDataForCPU(i));
                out.Byte(wellTapBlock(headerblock)).Byte(wellTapBlock(datablock));
            }
            saveDataToFile(file, out.End().toByteArray());
        }
    }

}

From source file:eu.apenet.dpt.standalone.gui.batch.ConvertAndValidateActionListener.java

public void actionPerformed(ActionEvent event) {
    labels = dataPreparationToolGUI.getLabels();
    continueLoop = true;/*from  www.j a  v a 2  s .c o m*/
    dataPreparationToolGUI.disableAllBtnAndItems();
    dataPreparationToolGUI.disableEditionTab();
    dataPreparationToolGUI.disableRadioButtons();
    dataPreparationToolGUI.disableAllBatchBtns();
    dataPreparationToolGUI.getAPEPanel().setFilename("");
    final Object[] objects = dataPreparationToolGUI.getXmlEadList().getSelectedValues();
    final ApexActionListener apexActionListener = this;
    new Thread(new Runnable() {
        public void run() {
            FileInstance uniqueFileInstance = null;
            String uniqueXslMessage = "";
            int numberOfFiles = objects.length;
            int currentFileNumberBatch = 0;
            ProgressFrame progressFrame = new ProgressFrame(labels, parent, true, false, apexActionListener);
            JProgressBar batchProgressBar = progressFrame.getProgressBarBatch();

            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableConversionBtn();
            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableValidationBtn();
            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableConvertAndValidateBtn();
            dataPreparationToolGUI.getXmlEadList().setEnabled(false);

            for (Object oneFile : objects) {
                if (!continueLoop) {
                    break;
                }

                File file = (File) oneFile;
                FileInstance fileInstance = dataPreparationToolGUI.getFileInstances().get(file.getName());
                if (numberOfFiles == 1) {
                    uniqueFileInstance = fileInstance;
                }

                if (!fileInstance.isXml()) {
                    fileInstance.setXml(XmlChecker.isXmlParseable(file) == null);
                    if (!fileInstance.isXml()) {
                        if (type == CONVERT || type == CONVERT_AND_VALIDATE) {
                            fileInstance.setConversionErrors(labels.getString("conversion.error.fileNotXml"));
                        } else if (type == VALIDATE || type == CONVERT_AND_VALIDATE) {
                            fileInstance.setValidationErrors(labels.getString("validation.error.fileNotXml"));
                        }
                        dataPreparationToolGUI.enableSaveBtn();
                        dataPreparationToolGUI.enableRadioButtons();
                        dataPreparationToolGUI.enableEditionTab();
                    }
                }

                SummaryWorking summaryWorking = new SummaryWorking(dataPreparationToolGUI.getResultArea(),
                        batchProgressBar);
                summaryWorking.setTotalNumberFiles(numberOfFiles);
                summaryWorking.setCurrentFileNumberBatch(currentFileNumberBatch);
                Thread threadRunner = new Thread(summaryWorking);
                threadRunner.setName(SummaryWorking.class.toString());
                threadRunner.start();

                JProgressBar progressBar = null;

                Thread threadProgress = null;
                CounterThread counterThread = null;
                CounterCLevelCall counterCLevelCall = null;

                if (fileInstance.isXml()) {
                    currentFileNumberBatch = currentFileNumberBatch + 1;
                    if (type == CONVERT || type == CONVERT_AND_VALIDATE) {

                        dataPreparationToolGUI.setResultAreaText(labels.getString("converting") + " "
                                + file.getName() + " (" + (currentFileNumberBatch) + "/" + numberOfFiles + ")");

                        String eadid = "";
                        boolean doTransformation = true;
                        if (fileInstance.getValidationSchema()
                                .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath()))
                                || fileInstance.getValidationSchema().equals(
                                        Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath()))) {
                            StaxTransformationTool staxTransformationTool = new StaxTransformationTool(file);
                            staxTransformationTool.run();
                            LOG.debug("file has eadid? " + staxTransformationTool.isFileWithEadid());
                            if (!staxTransformationTool.isFileWithEadid()) {
                                EadidQueryComponent eadidQueryComponent;
                                if (staxTransformationTool.getUnitid() != null
                                        && !staxTransformationTool.getUnitid().equals("")) {
                                    eadidQueryComponent = new EadidQueryComponent(
                                            staxTransformationTool.getUnitid());
                                } else {
                                    eadidQueryComponent = new EadidQueryComponent(labels);
                                }
                                int result = JOptionPane.showConfirmDialog(parent,
                                        eadidQueryComponent.getMainPanel(), labels.getString("enterEADID"),
                                        JOptionPane.OK_CANCEL_OPTION);
                                while (StringUtils.isEmpty(eadidQueryComponent.getEntryEadid())
                                        && result != JOptionPane.CANCEL_OPTION) {
                                    result = JOptionPane.showConfirmDialog(parent,
                                            eadidQueryComponent.getMainPanel(), labels.getString("enterEADID"),
                                            JOptionPane.OK_CANCEL_OPTION);
                                }
                                if (result == JOptionPane.OK_OPTION) {
                                    eadid = eadidQueryComponent.getEntryEadid();
                                } else if (result == JOptionPane.CANCEL_OPTION) {
                                    doTransformation = false;
                                }
                            }
                        }
                        if (doTransformation) {
                            int counterMax = 0;
                            if (fileInstance.getConversionScriptName()
                                    .equals(Utilities.XSL_DEFAULT_APEEAD_NAME)) {
                                progressBar = progressFrame.getProgressBarSingle();
                                progressBar.setVisible(true);
                                progressFrame
                                        .setTitle(labels.getString("progressTrans") + " - " + file.getName());
                                CountCLevels countCLevels = new CountCLevels();
                                counterMax = countCLevels.countOneFile(file);
                                if (counterMax > 0) {
                                    counterCLevelCall = new CounterCLevelCall();
                                    counterCLevelCall.initializeCounter(counterMax);
                                    counterThread = new CounterThread(counterCLevelCall, progressBar,
                                            counterMax);
                                    threadProgress = new Thread(counterThread);
                                    threadProgress.setName(CounterThread.class.toString());
                                    threadProgress.start();
                                }
                            }
                            try {
                                try {
                                    File xslFile = new File(fileInstance.getConversionScriptPath());

                                    File outputFile = new File(Utilities.TEMP_DIR + "temp_" + file.getName());
                                    outputFile.deleteOnExit();
                                    StringWriter xslMessages;
                                    HashMap<String, String> parameters = dataPreparationToolGUI.getParams();
                                    parameters.put("eadidmissing", eadid);
                                    CheckIsEadFile checkIsEadFile = new CheckIsEadFile(file);
                                    checkIsEadFile.run();
                                    if (checkIsEadFile.isEadRoot()) {
                                        File outputFile_temp = new File(
                                                Utilities.TEMP_DIR + ".temp_" + file.getName());
                                        TransformationTool.createTransformation(FileUtils.openInputStream(file),
                                                outputFile_temp, Utilities.BEFORE_XSL_FILE, null, true, true,
                                                null, true, null);
                                        xslMessages = TransformationTool.createTransformation(
                                                FileUtils.openInputStream(outputFile_temp), outputFile, xslFile,
                                                parameters, true, true, null, true, counterCLevelCall);
                                        outputFile_temp.delete();
                                    } else {
                                        xslMessages = TransformationTool.createTransformation(
                                                FileUtils.openInputStream(file), outputFile, xslFile,
                                                parameters, true, true, null, true, null);
                                    }
                                    fileInstance.setConversionErrors(xslMessages.toString());
                                    fileInstance
                                            .setCurrentLocation(Utilities.TEMP_DIR + "temp_" + file.getName());
                                    fileInstance.setConverted();
                                    fileInstance.setLastOperation(FileInstance.Operation.CONVERT);
                                    uniqueXslMessage = xslMessages.toString();
                                    if (xslMessages.toString().equals("")) {
                                        if (fileInstance.getConversionScriptName()
                                                .equals(Utilities.XSL_DEFAULT_APEEAD_NAME)) {
                                            fileInstance.setConversionErrors(
                                                    labels.getString("conversion.noExcludedElements"));
                                        } else {
                                            fileInstance.setConversionErrors(
                                                    labels.getString("conversion.finished"));
                                        }
                                    }

                                    if (!continueLoop) {
                                        break;
                                    }

                                } catch (Exception e) {
                                    fileInstance.setConversionErrors(labels.getString("conversionException")
                                            + "\r\n\r\n-------------\r\n" + e.getMessage());
                                    throw new Exception("Error when converting " + file.getName(), e);
                                }

                                if (threadProgress != null) {
                                    counterThread.stop();
                                    threadProgress.interrupt();
                                }
                                if (progressBar != null) {
                                    if (counterMax > 0) {
                                        progressBar.setValue(counterMax);
                                    }
                                    progressBar.setIndeterminate(true);
                                }

                            } catch (Exception e) {
                                LOG.error("Error when converting and validating", e);
                            } finally {
                                summaryWorking.stop();
                                threadRunner.interrupt();
                                dataPreparationToolGUI.getXmlEadListLabel().repaint();
                                dataPreparationToolGUI.getXmlEadList().repaint();
                                if (progressBar != null) {
                                    progressBar.setVisible(false);
                                }
                            }
                        }
                        if (numberOfFiles == 1) {
                            uniqueFileInstance = fileInstance;
                        }
                    }

                    if (type == VALIDATE || type == CONVERT_AND_VALIDATE) {

                        try {
                            try {
                                File fileToValidate = new File(fileInstance.getCurrentLocation());
                                InputStream is = FileUtils.openInputStream(fileToValidate);
                                dataPreparationToolGUI
                                        .setResultAreaText(labels.getString("validating") + " " + file.getName()
                                                + " (" + currentFileNumberBatch + "/" + numberOfFiles + ")");
                                XsdObject xsdObject = fileInstance.getValidationSchema();

                                List<SAXParseException> exceptions;
                                if (xsdObject.getName().equals(Xsd_enum.DTD_EAD_2002.getReadableName())) {
                                    exceptions = DocumentValidation.xmlValidationAgainstDtd(
                                            fileToValidate.getAbsolutePath(),
                                            Utilities.getUrlPathXsd(xsdObject));
                                } else {
                                    exceptions = DocumentValidation.xmlValidation(is,
                                            Utilities.getUrlPathXsd(xsdObject), xsdObject.isXsd11());
                                }
                                if (exceptions == null || exceptions.isEmpty()) {
                                    fileInstance.setValid(true);
                                    fileInstance.setValidationErrors(labels.getString("validationSuccess"));
                                    if (xsdObject.getFileType().equals(FileInstance.FileType.EAD)
                                            && xsdObject.getName().equals("apeEAD")) {
                                        XmlQualityCheckerCall xmlQualityCheckerCall = new XmlQualityCheckerCall();
                                        InputStream is2 = FileUtils
                                                .openInputStream(new File(fileInstance.getCurrentLocation()));
                                        TransformationTool.createTransformation(is2, null,
                                                Utilities.XML_QUALITY_FILE, null, true, true, null, false,
                                                xmlQualityCheckerCall);
                                        String xmlQualityStr = createXmlQualityString(xmlQualityCheckerCall);
                                        fileInstance.setValidationErrors(
                                                fileInstance.getValidationErrors() + xmlQualityStr);
                                        fileInstance.setXmlQualityErrors(
                                                createXmlQualityErrors(xmlQualityCheckerCall));
                                    }
                                } else {
                                    String errors = Utilities.stringFromList(exceptions);
                                    fileInstance.setValidationErrors(errors);
                                    fileInstance.setValid(false);
                                }
                                fileInstance.setLastOperation(FileInstance.Operation.VALIDATE);
                            } catch (Exception ex) {
                                fileInstance.setValid(false);
                                fileInstance.setValidationErrors(labels.getString("validationException")
                                        + "\r\n\r\n-------------\r\n" + ex.getMessage());
                                throw new Exception("Error when validating", ex);
                            }
                        } catch (Exception e) {
                            LOG.error("Error when validating", e);
                        } finally {
                            summaryWorking.stop();
                            threadRunner.interrupt();
                            dataPreparationToolGUI.getXmlEadListLabel().repaint();
                            dataPreparationToolGUI.getXmlEadList().repaint();
                            if (progressBar != null) {
                                progressBar.setVisible(false);
                            }
                        }
                        if (numberOfFiles == 1) {
                            uniqueFileInstance = fileInstance;
                        }
                    }
                }
            }
            Toolkit.getDefaultToolkit().beep();
            if (progressFrame != null) {
                try {
                    progressFrame.stop();
                } catch (Exception e) {
                    LOG.error("Error when stopping the progress bar", e);
                }
            }
            dataPreparationToolGUI.getFinalAct().run();
            if (numberOfFiles > 1) {
                dataPreparationToolGUI.getXmlEadList().clearSelection();
            } else if (uniqueFileInstance != null) {
                if (type != VALIDATE) {
                    dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                            .setConversionErrorText(replaceGtAndLt(uniqueFileInstance.getConversionErrors()));
                    if (uniqueXslMessage.equals("")) {
                        dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                                .checkFlashingTab(APETabbedPane.TAB_CONVERSION, Utilities.FLASHING_GREEN_COLOR);
                    } else {
                        dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                                .checkFlashingTab(APETabbedPane.TAB_CONVERSION, Utilities.FLASHING_RED_COLOR);
                    }
                }
                if (type != CONVERT) {
                    dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                            .setValidationErrorText(uniqueFileInstance.getValidationErrors());
                    if (uniqueFileInstance.isValid()) {
                        dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                                .checkFlashingTab(APETabbedPane.TAB_VALIDATION, Utilities.FLASHING_GREEN_COLOR);
                        if (uniqueFileInstance.getValidationSchema()
                                .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath()))) {
                            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableConversionEdmBtn();
                            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableValidationReportBtn();
                        } else if (uniqueFileInstance.getValidationSchema()
                                .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath()))
                                || uniqueFileInstance.getValidationSchema()
                                        .equals(Utilities.getXsdObjectFromPath(Xsd_enum.DTD_EAD_2002.getPath()))
                                || uniqueFileInstance.getValidationSchema().equals(
                                        Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAC_SCHEMA.getPath()))) {
                            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableConversionBtn();
                            // dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableValidationReportBtn();
                        }
                    } else {
                        dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                                .checkFlashingTab(APETabbedPane.TAB_VALIDATION, Utilities.FLASHING_RED_COLOR);
                        if (uniqueFileInstance.getValidationSchema()
                                .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath()))
                                || uniqueFileInstance.getValidationSchema().equals(
                                        Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath()))
                                || uniqueFileInstance.getValidationSchema()
                                        .equals(Utilities.getXsdObjectFromPath(Xsd_enum.DTD_EAD_2002.getPath()))
                                || uniqueFileInstance.getValidationSchema().equals(
                                        Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_EAC_SCHEMA.getPath()))
                                || uniqueFileInstance.getValidationSchema().equals(
                                        Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAC_SCHEMA.getPath()))) {
                            dataPreparationToolGUI.enableConversionBtns();
                            dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                                    .enableConvertAndValidateBtn();
                        }
                    }
                }
                dataPreparationToolGUI.enableMessageReportBtns();
            }
            if (continueLoop) {
                dataPreparationToolGUI.setResultAreaText(labels.getString("finished"));
            } else {
                dataPreparationToolGUI.setResultAreaText(labels.getString("aborted"));
            }
            dataPreparationToolGUI.enableSaveBtn();
            if (type == CONVERT) {
                dataPreparationToolGUI.enableValidationBtns();
            }
            dataPreparationToolGUI.enableRadioButtons();
            dataPreparationToolGUI.enableEditionTab();
        }
    }).start();
}

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)));
        }//from   w  w w .  j av  a 2  s.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:net.sf.profiler4j.console.Console.java

public void openProject() {

    if (client.isConnected()) {
        int ret = JOptionPane.showConfirmDialog(mainFrame, "Proceed and disconnect?", "Open Profiling Project",
                JOptionPane.YES_NO_OPTION);
        if (ret == JOptionPane.NO_OPTION) {
            return;
        }/*from  w w w . ja v  a2 s . c  o m*/
    }

    if (checkUnsavedChanges()) {
        return;
    }

    if (client.isConnected()) {
        disconnect();
        if (client.isConnected()) {
            return;
        }
    }
    JFileChooser fc = new JFileChooser(lastDir);
    fc.addChoosableFileFilter(projectFilter);
    if (fc.showOpenDialog(mainFrame) == JFileChooser.APPROVE_OPTION) {
        File selFile = fc.getSelectedFile();
        SAXBuilder builder = new SAXBuilder();
        Document doc = null;
        try {
            doc = builder.build(selFile);
        } catch (JDOMException e) {
            error("XML Error", e);
        } catch (IOException e) {
            error("I/O Error", e);
        }
        if (doc != null) {
            Project p = new Project();
            Element el = doc.getRootElement();
            p.setHostname(el.getChildText("Host"));
            p.setPort(Integer.parseInt(el.getChildText("Port")));
            Element rulesEl = el.getChild("Rules");

            p.setAccess(Rule.AccessOption.valueOf(rulesEl.getAttributeValue("access")));
            p.setBeanprops(Boolean.parseBoolean(rulesEl.getAttributeValue("beanProps")));

            p.getRules().clear();
            for (Iterator i = rulesEl.getChildren("Rule").iterator(); i.hasNext();) {
                Element r = (Element) i.next();
                Rule rule = new Rule(r.getText(), Rule.Action.valueOf(r.getAttributeValue("action")));
                p.getRules().add(rule);
            }

            // Backwards compatible way to read the export pattern
            // If it is not there, we leave the defaults as they are,
            // otherwise we set the saved setting.
            Element export = el.getChild(PROJECT_XML_ELEMENT__EXPORT_PATTERN);
            if (null != export) {
                String enabled = export.getAttributeValue(PROJECT_XML_ATTRIBUTE__ENABLED);
                p.setExportAutomaticallyEnabled(Boolean.valueOf(enabled));
                p.setExportPattern(export.getAttributeValue(PROJECT_XML_ATTRIBUTE__PATTERN));
            }

            p.setFile(selFile);
            p.clearChanged();
            this.project = p;
            lastDir = selFile.getParentFile();
        }
    }

}

From source file:net.sf.jabref.importer.OpenDatabaseAction.java

/**
 * @param file the file, may be null or not existing
 *///from w  ww  . j a  v a  2 s.  com
private void openTheFile(File file, boolean raisePanel) {
    if ((file != null) && file.exists()) {
        File fileToLoad = file;
        frame.output(Localization.lang("Opening") + ": '" + file.getPath() + "'");
        boolean tryingAutosave = false;
        boolean autoSaveFound = AutoSaveManager.newerAutoSaveExists(file);
        if (autoSaveFound && !Globals.prefs.getBoolean(JabRefPreferences.PROMPT_BEFORE_USING_AUTOSAVE)) {
            // We have found a newer autosave, and the preferences say we should load
            // it without prompting, so we replace the fileToLoad:
            fileToLoad = AutoSaveManager.getAutoSaveFile(file);
            tryingAutosave = true;
        } else if (autoSaveFound) {
            // We have found a newer autosave, but we are not allowed to use it without
            // prompting.
            int answer = JOptionPane.showConfirmDialog(null, "<html>"
                    + Localization.lang("An autosave file was found for this database. This could indicate "
                            + "that JabRef didn't shut down cleanly last time the file was used.")
                    + "<br>" + Localization.lang("Do you want to recover the database from the autosave file?")
                    + "</html>", Localization.lang("Recover from autosave"), JOptionPane.YES_NO_OPTION);
            if (answer == JOptionPane.YES_OPTION) {
                fileToLoad = AutoSaveManager.getAutoSaveFile(file);
                tryingAutosave = true;
            }
        }

        boolean done = false;
        while (!done) {
            String fileName = file.getPath();
            Globals.prefs.put(JabRefPreferences.WORKING_DIRECTORY, file.getPath());
            // Should this be done _after_ we know it was successfully opened?

            if (FileBasedLock.hasLockFile(file.toPath())) {
                Optional<FileTime> modificationTime = FileBasedLock.getLockFileTimeStamp(file.toPath());
                if ((modificationTime.isPresent()) && ((System.currentTimeMillis()
                        - modificationTime.get().toMillis()) > FileBasedLock.LOCKFILE_CRITICAL_AGE)) {
                    // The lock file is fairly old, so we can offer to "steal" the file:
                    int answer = JOptionPane.showConfirmDialog(null,
                            "<html>" + Localization.lang("Error opening file") + " '" + fileName + "'. "
                                    + Localization.lang("File is locked by another JabRef instance.") + "<p>"
                                    + Localization.lang("Do you want to override the file lock?"),
                            Localization.lang("File locked"), JOptionPane.YES_NO_OPTION);
                    if (answer == JOptionPane.YES_OPTION) {
                        FileBasedLock.deleteLockFile(file.toPath());
                    } else {
                        return;
                    }
                } else if (!FileBasedLock.waitForFileLock(file.toPath(), 10)) {
                    JOptionPane.showMessageDialog(null,
                            Localization.lang("Error opening file") + " '" + fileName + "'. "
                                    + Localization.lang("File is locked by another JabRef instance."),
                            Localization.lang("Error"), JOptionPane.ERROR_MESSAGE);
                    return;
                }

            }

            Charset encoding = Globals.prefs.getDefaultEncoding();
            ParserResult result;
            String errorMessage = null;
            try {
                result = OpenDatabaseAction.loadDatabase(fileToLoad, encoding);
            } catch (IOException ex) {
                LOGGER.error("Error loading database " + fileToLoad, ex);
                result = ParserResult.getNullResult();
            }
            if (result.isNullResult()) {
                JOptionPane.showMessageDialog(null,
                        Localization.lang("Error opening file") + " '" + fileName + "'",
                        Localization.lang("Error"), JOptionPane.ERROR_MESSAGE);

                String message = "<html>" + errorMessage + "<p>"
                        + (tryingAutosave ? Localization.lang(
                                "Error opening autosave of '%0'. Trying to load '%0' instead.", file.getName())
                                : ""/*Globals.lang("Error opening file '%0'.", file.getName())*/)
                        + "</html>";
                JOptionPane.showMessageDialog(null, message, Localization.lang("Error opening file"),
                        JOptionPane.ERROR_MESSAGE);

                if (tryingAutosave) {
                    tryingAutosave = false;
                    fileToLoad = file;
                } else {
                    done = true;
                }
                continue;
            } else {
                done = true;
            }

            final BasePanel panel = addNewDatabase(result, file, raisePanel);
            if (tryingAutosave) {
                panel.markNonUndoableBaseChanged();
            }

            // After adding the database, go through our list and see if
            // any post open actions need to be done. For instance, checking
            // if we found new entry types that can be imported, or checking
            // if the database contents should be modified due to new features
            // in this version of JabRef:
            final ParserResult finalReferenceToResult = result;
            SwingUtilities.invokeLater(
                    () -> OpenDatabaseAction.performPostOpenActions(panel, finalReferenceToResult, true));
        }

    }
}

From source file:electroStaticUI.UserInput.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void getChargeData() {
    numberOfCharges = Integer.parseInt(getNumberOfCharges.getText());
    DefaultValues.allocatePointChargeArray(numberOfCharges);
    chargesToCalc = new PointCharge[numberOfCharges];
    mapper = new CustomMapper(DefaultValues.getCircOrRect());
    chargeDataFrame = new JFrame();
    chargeDataFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    JPanel chargeDataPanel = new JPanel();
    chargeDataFrame.setTitle("Data For Charge #: " + (1 + okButtonPushes));
    JLabel chargeLabel = new JLabel("Charge");
    JLabel chargeUnitLabel = new JLabel("C");
    charge = new JTextField(10);
    charge.setEditable(true);/*  w ww. ja  v a  2 s.co  m*/
    chargeModComboBox = new JComboBox(chargeModList);
    chargeModComboBox.setSelectedIndex(5);
    chargeModComboBox.setVisible(true);
    JLabel xPositionLabel = new JLabel("X Value");
    xPosition = new JTextField(10);
    xPosition.setEditable(true);
    JLabel yPositionLabel = new JLabel("Y Value");
    yPosition = new JTextField(10);
    yPosition.setEditable(true);
    //JLabel zPositionLabel = new JLabel("Z Value");
    //JTextField zPosition = new JTextField(5);
    //zPosition.setEditable(true);
    JButton okButton = new JButton("OK");
    chargeDataPanel.add(chargeLabel);
    chargeDataPanel.add(charge);
    chargeDataPanel.add(chargeModComboBox);
    chargeDataPanel.add(chargeUnitLabel);
    chargeDataPanel.add(xPositionLabel);
    chargeDataPanel.add(xPosition);
    chargeDataPanel.add(yPositionLabel);
    chargeDataPanel.add(yPosition);
    chargeDataPanel.add(okButton);
    chargeDataPanel.setMinimumSize(new Dimension(600, 100));
    chargeDataPanel.setVisible(true);
    chargeDataFrame.add(chargeDataPanel);
    chargeDataFrame.setVisible(true);
    chargeDataFrame.setMinimumSize(new Dimension(600, 100));
    xPosition.setText("0");
    yPosition.setText("0");
    charge.setText("0");
    /*
     * okButton anonymous action listener takes the data entered into the JTextfields and creates point charges from it.
     */
    okButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //do {
            //chargesToCalc[okButtonPushes] = new PointCharge(Double.parseDouble(charge.getText()), Double.parseDouble(xPosition.getText()), Double.parseDouble(yPosition.getText()));
            int chargeModIndex = chargeModComboBox.getSelectedIndex();
            DefaultValues.setChargeModIndex(chargeModIndex);
            chargeValue = Double.parseDouble(charge.getText());
            xValue = Double.parseDouble(xPosition.getText());
            yValue = Double.parseDouble(yPosition.getText());
            chargesToCalc[okButtonPushes] = new PointCharge(chargeValue, xValue, yValue);
            charge.setText("0");
            xPosition.setText("0");
            yPosition.setText("0");
            okButtonPushes++;
            chargeDataFrame.setTitle("Data For Charge #: " + (1 + okButtonPushes));
            if (okButtonPushes == numberOfCharges) {
                confirm = JOptionPane.showConfirmDialog(null,
                        "You have entered " + okButtonPushes
                                + " charges. Press OK to confirm. \nPress Cancel to re-enter the charges",
                        null, JOptionPane.OK_CANCEL_OPTION);
                if (confirm == JOptionPane.OK_OPTION) {
                    DefaultValues.setCurrentPointCharges(chargesToCalc);
                    ElectroStaticUIContainer.removeGraphFromdisplayPanel();
                    theCalculator = new CalculatorPanel();
                    calcVec = new VectorCalculator(mapper);
                    volts = new VoltageAtPoint(mapper.getFieldPoints());
                    manGraph = new ManualPolygons(mapper);
                    chart = manGraph.delaunayBuild();
                    drawVecs = new DrawElectricFieldLines(mapper);
                    ElectroStaticUIContainer.add3DGraphToDisplayPanel(chart);
                    ElectroStaticUIContainer.addVectorGraphToDisplayPanel(drawVecs.getChart());
                    setVectorChartToSave();
                    setChart3dToSave();
                    rotateIt = new ChartMouseController(chart);
                    okButtonPushes = 0;
                    chargeDataFrame.removeAll();
                    chargeDataFrame.dispose();
                } else if (confirm == JOptionPane.CANCEL_OPTION)
                    okButtonPushes = 0;
            }

        }
        //while(okButtonPushes < numberOfCharges);

        //}
    });
}

From source file:ca.uviccscu.lp.persistence.ChooseFolderDialog.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    String path = jTextField3.getText();
    File f = new File(path);
    l.trace("WFolder path entered: [" + path + "]");
    int verification = SettingsManager.verifyWorkingFolder(path);
    l.trace("Initial WFolder verification: " + verification);
    if (verification != 0) {
        switch (verification) {
        case (1): {
            if (path == null || path.equals("")) {
                verification = 8;//from  w  w  w . ja v  a 2  s . c  om
                l.trace("WFolder  verification ch: " + verification);
                JOptionPane.showMessageDialog(this, "Path field empty!", "WFolder creation error",
                        JOptionPane.ERROR_MESSAGE);
            }
            if (verification == 1) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    java.util.logging.Logger.getLogger(ChooseFolderDialog.class.getName()).log(Level.SEVERE,
                            null, ex);
                }
                int resp = JOptionPane.showConfirmDialog(this, "Directory doesn't exist! Create?",
                        "WFolder creation warning", JOptionPane.YES_NO_OPTION);
                if (resp == JOptionPane.YES_OPTION) {
                    verification = 0;
                    l.trace("WFolder verification ch: " + verification);
                } else if (resp == JOptionPane.NO_OPTION) {
                    verification = 7;
                    l.trace("WFolder verification ch: " + verification);
                }
            }
            break;
        }
        case (2): {
            if (path == null || path.equals("")) {
                verification = 8;
                l.trace("WFolder verification ch: " + verification);
                JOptionPane.showMessageDialog(this, "Path field empty!", "WFolder creation error",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Path not absolute!", "WFolder creation error",
                        JOptionPane.ERROR_MESSAGE);
            }
            break;
        }
        case (3): {
            JOptionPane.showMessageDialog(this, "Can't read!", "WFolder creation error",
                    JOptionPane.ERROR_MESSAGE);
            break;
        }
        case (4): {
            JOptionPane.showMessageDialog(this, "Can't write!", "WFolder creation error",
                    JOptionPane.ERROR_MESSAGE);
            break;
        }
        case (5): {
            JOptionPane.showMessageDialog(this, "File error!", "WFolder creation error",
                    JOptionPane.ERROR_MESSAGE);
            break;
        }
        case (6): {
            //JOptionPane.showMessageDialog(this, "File error!", "WFolder creation error", JOptionPane.ERROR_MESSAGE);
            l.error("Directory not empty");
            l.trace("WFolder verification ch: " + verification);
            //JDialog jd = new JDialog((JFrame) null, true);
            int resp = JOptionPane.showConfirmDialog(null,
                    "Directory nonempty: " + f.getAbsolutePath() + ". Wipe and proceed?", "Confirm deletion",
                    JOptionPane.YES_NO_OPTION);
            if (resp == JOptionPane.YES_OPTION) {
                try {
                    FileUtils.deleteDirectory(f);
                    verification = 0;
                } catch (IOException ex) {
                    l.fatal("Can't wipe directory", ex);
                    System.exit(1);
                }
            }
            break;
        }
        }
    }
    l.trace("Final WFolder verification: " + verification);
    if (verification == 0) {
        Shared.lastFolder_path = path;
        Shared.lastFolder_verification = verification;
        Shared.lastFolder_wasCancelled = false;
        this.setVisible(false);
    }
}

From source file:be.fedict.eid.tsl.tool.TslTool.java

@Override
public void actionPerformed(ActionEvent event) {
    String command = event.getActionCommand();
    if (EXIT_ACTION_COMMAND.equals(command)) {
        System.exit(0);// w w w. j a  v  a2s .  c  o  m
    } else if (OPEN_ACTION_COMMAND.equals(command)) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Open TSL");
        int returnValue = fileChooser.showOpenDialog(this);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            displayTsl(fileChooser.getSelectedFile());
        }
    } else if (ABOUT_ACTION_COMMAND.equals(command)) {
        JOptionPane.showMessageDialog(this,
                "eID TSL Tool\n" + "Copyright (C) 2009-2013 FedICT\n" + "http://code.google.com/p/eid-tsl/",
                "About", JOptionPane.INFORMATION_MESSAGE);
    } else if (CLOSE_ACTION_COMMAND.equals(command)) {
        if (this.activeTslInternalFrame.getTrustServiceList().hasChanged()) {
            int result = JOptionPane.showConfirmDialog(this, "TSL has been changed.\n" + "Save the TSL?",
                    "Save", JOptionPane.YES_NO_CANCEL_OPTION);
            if (JOptionPane.CANCEL_OPTION == result) {
                return;
            }
            if (JOptionPane.YES_OPTION == result) {
                try {
                    this.activeTslInternalFrame.save();
                } catch (IOException e) {
                    LOG.error("IO error: " + e.getMessage(), e);
                }
            }
        }
        try {
            this.activeTslInternalFrame.setClosed(true);
        } catch (PropertyVetoException e) {
            LOG.warn("property veto error: " + e.getMessage(), e);
        }
    } else if (SIGN_ACTION_COMMAND.equals(command)) {
        LOG.debug("sign");
        TrustServiceList trustServiceList = this.activeTslInternalFrame.getTrustServiceList();
        if (trustServiceList.hasSignature()) {
            int confirmResult = JOptionPane.showConfirmDialog(this,
                    "TSL is already signed.\n" + "Resign the TSL?", "Resign", JOptionPane.OK_CANCEL_OPTION);
            if (JOptionPane.CANCEL_OPTION == confirmResult) {
                return;
            }
        }
        SignSelectPkcs11FinishablePanel pkcs11Panel = new SignSelectPkcs11FinishablePanel();
        WizardDescriptor wizardDescriptor = new WizardDescriptor(
                new WizardDescriptor.Panel[] { new SignInitFinishablePanel(), pkcs11Panel,
                        new SignSelectCertificatePanel(pkcs11Panel, trustServiceList),
                        new SignFinishFinishablePanel() });
        wizardDescriptor.setTitle("Sign TSL");
        wizardDescriptor.putProperty("WizardPanel_autoWizardStyle", Boolean.TRUE);
        DialogDisplayer dialogDisplayer = DialogDisplayer.getDefault();
        Dialog wizardDialog = dialogDisplayer.createDialog(wizardDescriptor);
        wizardDialog.setVisible(true);
    } else if (SAVE_ACTION_COMMAND.equals(command)) {
        LOG.debug("save");
        try {
            this.activeTslInternalFrame.save();
            this.saveMenuItem.setEnabled(false);
        } catch (IOException e) {
            LOG.debug("IO error: " + e.getMessage(), e);
        }
    } else if (SAVE_AS_ACTION_COMMAND.equals(command)) {
        LOG.debug("save as");
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Save As");
        int result = fileChooser.showSaveDialog(this);
        if (JFileChooser.APPROVE_OPTION == result) {
            File tslFile = fileChooser.getSelectedFile();
            if (tslFile.exists()) {
                int confirmResult = JOptionPane.showConfirmDialog(this,
                        "File already exists.\n" + tslFile.getAbsolutePath() + "\n" + "Overwrite file?",
                        "Overwrite", JOptionPane.OK_CANCEL_OPTION);
                if (JOptionPane.CANCEL_OPTION == confirmResult) {
                    return;
                }
            }
            try {
                this.activeTslInternalFrame.saveAs(tslFile);
            } catch (IOException e) {
                LOG.debug("IO error: " + e.getMessage(), e);
            }
            this.saveMenuItem.setEnabled(false);
        }
    } else if (EXPORT_ACTION_COMMAND.equals(command)) {
        LOG.debug("export");
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Export to PDF");
        int result = fileChooser.showSaveDialog(this);
        if (JFileChooser.APPROVE_OPTION == result) {
            File pdfFile = fileChooser.getSelectedFile();
            if (pdfFile.exists()) {
                int confirmResult = JOptionPane.showConfirmDialog(this,
                        "File already exists.\n" + pdfFile.getAbsolutePath() + "\n" + "Overwrite file?",
                        "Overwrite", JOptionPane.OK_CANCEL_OPTION);
                if (JOptionPane.CANCEL_OPTION == confirmResult) {
                    return;
                }
            }
            try {
                this.activeTslInternalFrame.export(pdfFile);
            } catch (IOException e) {
                LOG.debug("IO error: " + e.getMessage(), e);
            }
        }
    } else if ("TSL-BE-2010-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2010, Trimester.FIRST);
        displayTsl("*TSL-BE-2010-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2010-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2010, Trimester.SECOND);
        displayTsl("*TSL-BE-2010-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2010-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2010, Trimester.THIRD);
        displayTsl("*TSL-BE-2010-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2011-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2011, Trimester.FIRST);
        displayTsl("*TSL-BE-2011-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2011-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2011, Trimester.SECOND);
        displayTsl("*TSL-BE-2011-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2011-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2011, Trimester.THIRD);
        displayTsl("*TSL-BE-2011-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2012-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2012, Trimester.FIRST);
        displayTsl("*TSL-BE-2012-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2012-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2012, Trimester.SECOND);
        displayTsl("*TSL-BE-2012-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2012-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2012, Trimester.THIRD);
        displayTsl("*TSL-BE-2012-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2013-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2013, Trimester.FIRST);
        displayTsl("*TSL-BE-2013-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2013-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2013, Trimester.SECOND);
        displayTsl("*TSL-BE-2013-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2013-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2013, Trimester.THIRD);
        displayTsl("*TSL-BE-2013-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2014-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2014, Trimester.FIRST);
        displayTsl("*TSL-BE-2014-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2014-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2014, Trimester.SECOND);
        displayTsl("*TSL-BE-2014-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2014-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2014, Trimester.THIRD);
        displayTsl("*TSL-BE-2014-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2015-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2015, Trimester.FIRST);
        displayTsl("*TSL-BE-2015-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2015-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2015, Trimester.SECOND);
        displayTsl("*TSL-BE-2015-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2015-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2015, Trimester.THIRD);
        displayTsl("*TSL-BE-2015-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    }
}

From source file:com.alvermont.terraj.planet.ui.TerrainFrame.java

private void saveImageItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveImageItemActionPerformed
{//GEN-HEADEREND:event_saveImageItemActionPerformed

    int choice = pngChooser.showSaveDialog(this);

    if (choice == JFileChooser.APPROVE_OPTION) {
        try {/* w w  w  .java2s. c o  m*/
            if (!pngChooser.getFileContents().canRead() || (JOptionPane.showConfirmDialog(this,
                    "This file already exists. Do you want to\n" + "overwrite it?", "Replace File?",
                    JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)) {
                final OutputStream target = pngChooser.getFileContents().getOutputStream(true);

                // More JNLP silliness. How am I supposed to know what size
                // an image file will compress to and there is no guidance
                // in the documentation as to what value can be reasonably
                // requested here. I've just picked something and gone with
                // it, which seems to be in line with the philosophy of
                // the people who designed Java WebStart
                pngChooser.getFileContents().setMaxLength(500000);

                ImageIO.write(image,
                        PNGFileFilter.getFormatName(new File(pngChooser.getFileContents().getName())), target);

                target.close();
            }
        } catch (IOException ioe) {
            log.error("Error writing image file", ioe);

            JOptionPane.showMessageDialog(this,
                    "Error: " + ioe.getMessage() + "\nCheck log file for full details", "Error Saving",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:com.simplexrepaginator.RepaginateFrame.java

protected JButton createInputButton() {
    JButton b = new JButton("Click or drag to set input files", PDF_1342);

    b.setHorizontalTextPosition(SwingConstants.RIGHT);
    b.setIconTextGap(25);/*  w w w .j a v  a  2 s  . c  o  m*/

    b.setTransferHandler(new InputButtonTransferHandler());

    b.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(true);
            chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            if (chooser.showOpenDialog(RepaginateFrame.this) != JFileChooser.APPROVE_OPTION)
                return;
            setInput(Arrays.asList(chooser.getSelectedFiles()));
            if (JOptionPane.showConfirmDialog(RepaginateFrame.this, "Use input paths as output paths?",
                    "Use Input As Output?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                setOutput(new ArrayList<File>(repaginator.getInputFiles()));
            }
        }
    });

    return b;
}