Example usage for javax.swing JOptionPane OK_CANCEL_OPTION

List of usage examples for javax.swing JOptionPane OK_CANCEL_OPTION

Introduction

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

Prototype

int OK_CANCEL_OPTION

To view the source code for javax.swing JOptionPane OK_CANCEL_OPTION.

Click Source Link

Document

Type used for showConfirmDialog.

Usage

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

public void actionPerformed(ActionEvent event) {
    labels = dataPreparationToolGUI.getLabels();
    continueLoop = true;/*from w w  w .j a  va  2  s.co 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:imageviewer.system.ImageViewerClient.java

private void initialize(CommandLine args) {

    // First, process all the different command line arguments that we
    // need to override and/or send onwards for initialization.

    boolean fullScreen = (args.hasOption("fullscreen")) ? true : false;
    String dir = (args.hasOption("dir")) ? args.getOptionValue("dir") : null;
    String type = (args.hasOption("type")) ? args.getOptionValue("type") : "DICOM";
    String prefix = (args.hasOption("client")) ? args.getOptionValue("client") : null;

    LOG.info("Java home environment: " + System.getProperty("java.home"));

    // Logging system taken care of through properties file.  Check
    // for JAI.  Set up JAI accordingly with the size of the cache
    // tile and to recycle cached tiles as needed.

    verifyJAI();//from w  ww .j ava2 s.co  m
    TileCache tc = JAI.getDefaultInstance().getTileCache();
    tc.setMemoryCapacity(32 * 1024 * 1024);
    TileScheduler ts = JAI.createTileScheduler();
    ts.setPriority(Thread.MAX_PRIORITY);
    JAI.getDefaultInstance().setTileScheduler(ts);
    JAI.getDefaultInstance().setRenderingHint(JAI.KEY_CACHED_TILE_RECYCLING_ENABLED, Boolean.TRUE);

    // Set up the frame and everything else.  First, try and set the
    // UI manager to use our look and feel because it's groovy and
    // lets us control the GUI components much better.

    try {
        UIManager.setLookAndFeel(new ImageViewerLookAndFeel());
        LookAndFeelAddons.setAddon(ImageViewerLookAndFeelAddons.class);
    } catch (Exception exc) {
        LOG.error("Could not set imageViewer L&F.");
    }

    // Load up the ApplicationContext information...

    ApplicationContext ac = ApplicationContext.getContext();
    if (ac == null) {
        LOG.error("Could not load configuration, exiting.");
        System.exit(1);
    }

    // Override the client node information based on command line
    // arguments...Make sure that the files are there, otherwise just
    // default to a local configuration.

    String hostname = new String("localhost");
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (Exception exc) {
    }

    String[] gatewayConfigs = (prefix != null)
            ? (new String[] { "resources/server/" + prefix + "GatewayConfig.xml",
                    (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                    "resources/server/" + hostname + "GatewayConfig.xml",
                    "resources/server/localGatewayConfig.xml" })
            : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                    "resources/server/" + hostname + "GatewayConfig.xml",
                    "resources/server/localGatewayConfig.xml" });
    String[] nodeConfigs = (prefix != null)
            ? (new String[] { "resources/server/" + prefix + "NodeConfig.xml",
                    (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                    "resources/server/" + hostname + "NodeConfig.xml", "resources/server/localNodeConfig.xml" })
            : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                    "resources/server/" + hostname + "NodeConfig.xml",
                    "resources/server/localNodeConfig.xml" });

    for (int loop = 0; loop < gatewayConfigs.length; loop++) {
        String s = gatewayConfigs[loop];
        if ((s != null) && (s.length() != 0) && (!"null".equals(s))) {
            File f = new File(s);
            if (f.exists()) {
                ac.setProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG, s);
                break;
            }
        }
    }

    LOG.info("Using gateway config: " + ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG));

    for (int loop = 0; loop < nodeConfigs.length; loop++) {
        String s = nodeConfigs[loop];
        if ((s != null) && (s.length() != 0) && (!"null".equals(s))) {
            File f = new File(s);
            if (f.exists()) {
                ac.setProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE, s);
                break;
            }
        }
    }
    LOG.info("Using client config: " + ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE));

    // Load the layouts and set the default window/level manager...

    LayoutFactory.initialize();
    DefaultWindowLevelManager dwlm = new DefaultWindowLevelManager();

    // Create the main JFrame, set its behavior, and let the
    // ApplicationPanel know the glassPane and layeredPane.  Set the
    // menubar based on reading in the configuration menus.

    mainFrame = new JFrame("imageviewer");
    try {
        ArrayList<Image> iconList = new ArrayList<Image>();
        iconList.add(ImageIO.read(new File("resources/icons/mii.png")));
        iconList.add(ImageIO.read(new File("resources/icons/mii32.png")));
        mainFrame.setIconImages(iconList);
    } catch (Exception exc) {
    }

    mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    mainFrame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            int confirm = ApplicationPanel.getInstance().showDialog(
                    "Are you sure you want to quit imageViewer?", null, JOptionPane.QUESTION_MESSAGE,
                    JOptionPane.OK_CANCEL_OPTION, UIManager.getIcon("Dialog.shutdownIcon"));
            if (confirm == JOptionPane.OK_OPTION) {
                boolean hasUnsaved = SaveStack.getInstance().hasUnsavedItems();
                if (hasUnsaved) {
                    int saveResult = ApplicationPanel.getInstance().showDialog(
                            "There is still unsaved data.  Do you want to save this data in the local archive?",
                            null, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
                    if (saveResult == JOptionPane.CANCEL_OPTION)
                        return;
                    if (saveResult == JOptionPane.YES_OPTION)
                        SaveStack.getInstance().saveAll();
                }
                LOG.info("Shutting down imageServer local archive...");
                try {
                    ImageViewerClientNode.getInstance().shutdown();
                } catch (Exception exc) {
                    LOG.error("Problem shutting down imageServer local archive...");
                } finally {
                    System.exit(0);
                }
            }
        }
    });

    String menuFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_MENUS);
    String ribbonFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_RIBBON);
    if (menuFile != null) {
        JMenuBar mb = new JMenuBar();
        mb.setBackground(Color.black);
        MenuReader.parseFile(menuFile, mb);
        mainFrame.setJMenuBar(mb);
        ApplicationContext.getContext().setApplicationMenuBar(mb);
    } else if (ribbonFile != null) {
        RibbonReader rr = new RibbonReader();
        JRibbon jr = rr.parseFile(ribbonFile);
        mainFrame.getContentPane().add(jr, BorderLayout.NORTH);
        ApplicationContext.getContext().setApplicationRibbon(jr);
    }
    mainFrame.getContentPane().add(ApplicationPanel.getInstance(), BorderLayout.CENTER);
    ApplicationPanel.getInstance().setGlassPane((JPanel) (mainFrame.getGlassPane()));
    ApplicationPanel.getInstance().setLayeredPane(mainFrame.getLayeredPane());

    // Load specified plugins...has to occur after the menus are
    // created, btw.

    PluginLoader.initialize("config/plugins.xml");

    // Detect operating system...

    String osName = System.getProperty("os.name");
    ApplicationContext.getContext().setProperty(ApplicationContext.OS_NAME, osName);
    LOG.info("Detected operating system: " + osName);

    // Try and hack the searched library paths if it's windows so we
    // can add a local dll path...

    try {
        if (osName.contains("Windows")) {
            Field f = ClassLoader.class.getDeclaredField("usr_paths");
            f.setAccessible(true);
            String[] paths = (String[]) f.get(null);
            String[] tmp = new String[paths.length + 1];
            System.arraycopy(paths, 0, tmp, 0, paths.length);
            File currentPath = new File(".");
            tmp[paths.length] = currentPath.getCanonicalPath() + "/lib/dll/";
            f.set(null, tmp);
            f.setAccessible(false);
        }
    } catch (Exception exc) {
        LOG.error("Error attempting to dynamically set library paths.");
    }

    // Get screen resolution...

    GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration();
    Rectangle r = gc.getBounds();
    LOG.info("Detected screen resolution: " + (int) r.getWidth() + "x" + (int) r.getHeight());

    // Try and see if Java3D is installed, and if so, what version...

    try {
        VirtualUniverse vu = new VirtualUniverse();
        Map m = vu.getProperties();
        String s = (String) m.get("j3d.version");
        LOG.info("Detected Java3D version: " + s);
    } catch (Throwable t) {
        LOG.info("Unable to detect Java3D installation");
    }

    // Try and see if native JOGL is installed...

    try {
        System.loadLibrary("jogl");
        ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.TRUE);
        LOG.info("Detected native libraries for JOGL");
    } catch (Throwable t) {
        LOG.info("Unable to detect native JOGL installation");
        ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.FALSE);
    }

    // Start the local client node to connect to the network and the
    // local archive running on this machine...Thread the connection
    // process so it doesn't block the imageViewerClient creating this
    // instance.  We may not be connected to the given gateway, so the
    // socketServer may go blah...

    final boolean useNetwork = (args.hasOption("nonet")) ? false : true;
    ApplicationPanel.getInstance().addStatusMessage("ImageViewer is starting up, please wait...");
    if (useNetwork)
        LOG.info("Starting imageServer client to join network - please wait...");
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                ImageViewerClientNode.getInstance(
                        (String) ApplicationContext.getContext()
                                .getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                        (String) ApplicationContext.getContext()
                                .getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                        useNetwork);
                ApplicationPanel.getInstance().addStatusMessage("Ready");
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    });
    t.setPriority(9);
    t.start();

    this.fullScreen = fullScreen;
    mainFrame.setUndecorated(fullScreen);

    // Set the view to encompass the default screen.

    if (fullScreen) {
        Insets i = Toolkit.getDefaultToolkit().getScreenInsets(gc);
        mainFrame.setLocation(r.x + i.left, r.y + i.top);
        mainFrame.setSize(r.width - i.left - i.right, r.height - i.top - i.bottom);
    } else {
        mainFrame.setSize(1100, 800);
        mainFrame.setLocation(r.x + 200, r.y + 100);
    }

    if (dir != null)
        ApplicationPanel.getInstance().load(dir, type);

    timer = new Timer();
    timer.schedule(new GarbageCollectionTimer(), 5000, 2500);
    mainFrame.setVisible(true);
}

From source file:gate.corpora.CSVImporter.java

@Override
protected List<Action> buildActions(final NameBearerHandle handle) {
    List<Action> actions = new ArrayList<Action>();

    if (!(handle.getTarget() instanceof Corpus))
        return actions;

    actions.add(new AbstractAction("Populate from CSV File") {
        @Override//  www.  j a v  a  2s.  co  m
        public void actionPerformed(ActionEvent e) {

            // display the populater dialog and return if it is cancelled
            if (JOptionPane.showConfirmDialog(null, dialog, "Populate From CSV File",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION)
                return;

            // we want to run the population in a separate thread so we don't lock
            // up the GUI
            Thread thread = new Thread(Thread.currentThread().getThreadGroup(), "CSV Corpus Populater") {

                public void run() {
                    try {

                        // unescape the strings that define the format of the file and
                        // get the actual chars
                        char separator = StringEscapeUtils.unescapeJava(txtSeparator.getText()).charAt(0);
                        char quote = StringEscapeUtils.unescapeJava(txtQuoteChar.getText()).charAt(0);

                        // see if we can convert the URL to a File instance
                        File file = null;
                        try {
                            file = Files.fileFromURL(new URL(txtURL.getText()));
                        } catch (IllegalArgumentException iae) {
                            // this will happen if someone enters an actual URL, but we
                            // handle that later so we can just ignore the exception for
                            // now and keep going
                        }

                        if (file != null && file.isDirectory()) {
                            // if we have a File instance and that points at a directory
                            // then....

                            // get all the CSV files in the directory structure
                            File[] files = Files.listFilesRecursively(file, CSV_FILE_FILTER);

                            for (File f : files) {
                                // for each file...

                                // skip directories as we don't want to handle those
                                if (f.isDirectory())
                                    continue;

                                if (cboDocuments.isSelected()) {
                                    // if we are creating lots of documents from a single
                                    // file
                                    // then call the populate method passing through all the
                                    // options from the GUI
                                    populate((Corpus) handle.getTarget(), f.toURI().toURL(),
                                            txtEncoding.getText(), (Integer) textColModel.getValue(),
                                            cboFeatures.isSelected(), separator, quote);
                                } else {
                                    // if we are creating a single document from a single
                                    // file
                                    // then call the createDoc method passing through all
                                    // the
                                    // options from the GUI
                                    createDoc((Corpus) handle.getTarget(), f.toURI().toURL(),
                                            txtEncoding.getText(), (Integer) textColModel.getValue(),
                                            cboFeatures.isSelected(), separator, quote);
                                }
                            }
                        } else {
                            // we have a single URL to process so...

                            if (cboDocuments.isSelected()) {
                                // if we are creating lots of documents from a single file
                                // then call the populate method passing through all the
                                // options from the GUI
                                populate((Corpus) handle.getTarget(), new URL(txtURL.getText()),
                                        txtEncoding.getText(), (Integer) textColModel.getValue(),
                                        cboFeatures.isSelected(), separator, quote);
                            } else {
                                // if we are creating a single document from a single file
                                // then call the createDoc method passing through all the
                                // options from the GUI
                                createDoc((Corpus) handle.getTarget(), new URL(txtURL.getText()),
                                        txtEncoding.getText(), (Integer) textColModel.getValue(),
                                        cboFeatures.isSelected(), separator, quote);
                            }
                        }
                    } catch (Exception e) {
                        // TODO give a sensible error message
                        e.printStackTrace();
                    }
                }
            };

            // let's leave the GUI nice and responsive
            thread.setPriority(Thread.MIN_PRIORITY);

            // lets get to it and do some actual work!
            thread.start();

        }
    });

    return actions;
}

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  ww  w  .  jav  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: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);//from w  w w .  j  a va  2s  .  c  o 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:ConfigFiles.java

public ConfigFiles(Dimension screensize) {
    //         initializeFileBrowser();
    paths = new JPanel();
    paths.setBackground(Color.WHITE);
    //paths.setBorder(BorderFactory.createTitledBorder("Paths"));
    paths.setLayout(null);/*from www. j a v  a2  s .  c o m*/
    paths.setPreferredSize(new Dimension(930, 1144));
    paths.setSize(new Dimension(930, 1144));
    paths.setMinimumSize(new Dimension(930, 1144));
    paths.setMaximumSize(new Dimension(930, 1144));
    //paths.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
    setLayout(null);
    ttcpath = new JTextField();
    addPanel("TestCase Source Path",
            "Master directory with the test cases that can" + " be run by the framework", ttcpath,
            RunnerRepository.TESTSUITEPATH, 10, true, null);
    tMasterXML = new JTextField();
    tUsers = new JTextField();

    addPanel("Projects Path", "Location of projects XML files", tUsers, RunnerRepository.REMOTEUSERSDIRECTORY,
            83, true, null);

    tSuites = new JTextField();
    addPanel("Predefined Suites Path", "Location of predefined suites", tSuites,
            RunnerRepository.PREDEFINEDSUITES, 156, true, null);

    testconfigpath = new JTextField();
    addPanel("Test Configuration Path", "Test Configuration path", testconfigpath,
            RunnerRepository.TESTCONFIGPATH, 303, true, null);

    tepid = new JTextField();
    addPanel("EP name File", "Location of the file that contains" + " the Ep name list", tepid,
            RunnerRepository.REMOTEEPIDDIR, 595, true, null);
    tlog = new JTextField();
    addPanel("Logs Path", "Location of the directory that stores the most recent log files."
            + " The files are re-used each Run.", tlog, RunnerRepository.LOGSPATH, 667, true, null);
    tsecondarylog = new JTextField();

    JPanel p = addPanel("Secondary Logs Path",
            "Location of the directory that archives copies of the most recent log files, with"
                    + " original file names appended with <.epoch time>",
            tsecondarylog, RunnerRepository.SECONDARYLOGSPATH, 930, true, null);
    logsenabled.setSelected(Boolean.parseBoolean(RunnerRepository.PATHENABLED));
    logsenabled.setBackground(Color.WHITE);
    p.add(logsenabled);

    JPanel p7 = new JPanel();
    p7.setBackground(Color.WHITE);
    TitledBorder border7 = BorderFactory.createTitledBorder("Log Files");
    border7.setTitleFont(new Font("Arial", Font.PLAIN, 14));
    border7.setBorder(BorderFactory.createLineBorder(new Color(150, 150, 150), 1));
    p7.setBorder(border7);
    p7.setLayout(new BoxLayout(p7, BoxLayout.Y_AXIS));
    p7.setBounds(80, 740, 800, 190);
    paths.add(p7);
    JTextArea log2 = new JTextArea("All the log files that will be monitored");
    log2.setWrapStyleWord(true);
    log2.setLineWrap(true);
    log2.setEditable(false);
    log2.setCursor(null);
    log2.setOpaque(false);
    log2.setFocusable(false);
    log2.setBorder(null);
    log2.setFont(new Font("Arial", Font.PLAIN, 12));
    log2.setBackground(getBackground());
    log2.setMaximumSize(new Dimension(170, 25));
    log2.setPreferredSize(new Dimension(170, 25));
    JPanel p71 = new JPanel();
    p71.setBackground(Color.WHITE);
    p71.setLayout(new GridLayout());
    p71.setMaximumSize(new Dimension(700, 13));
    p71.setPreferredSize(new Dimension(700, 13));
    p71.add(log2);
    JPanel p72 = new JPanel();
    p72.setBackground(Color.WHITE);
    p72.setLayout(new BoxLayout(p72, BoxLayout.Y_AXIS));
    trunning = new JTextField();
    p72.add(addField(trunning, "Running: ", 0));
    tdebug = new JTextField();
    p72.add(addField(tdebug, "Debug: ", 1));
    tsummary = new JTextField();
    p72.add(addField(tsummary, "Summary: ", 2));
    tinfo = new JTextField();
    p72.add(addField(tinfo, "Info: ", 3));
    tcli = new JTextField();
    p72.add(addField(tcli, "Cli: ", 4));
    p7.add(p71);
    p7.add(p72);
    libpath = new JTextField();

    addPanel("Library path", "Secondary user library path", libpath, RunnerRepository.REMOTELIBRARY, 229, true,
            null);

    JPanel p8 = new JPanel();
    p8.setBackground(Color.WHITE);
    TitledBorder border8 = BorderFactory.createTitledBorder("File");
    border8.setTitleFont(new Font("Arial", Font.PLAIN, 14));
    border8.setBorder(BorderFactory.createLineBorder(new Color(150, 150, 150), 1));
    p8.setBorder(border8);
    p8.setLayout(null);
    p8.setBounds(80, 1076, 800, 50);
    if (PermissionValidator.canChangeFWM()) {
        paths.add(p8);
    }
    JButton save = new JButton("Save");
    save.setToolTipText("Save and automatically load config");
    save.setBounds(490, 20, 70, 20);
    save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            saveXML(false, "fwmconfig");
            loadConfig("fwmconfig.xml");
        }
    });
    p8.add(save);
    //         if(!PermissionValidator.canChangeFWM()){
    //             save.setEnabled(false);
    //         }
    JButton saveas = new JButton("Save as");
    saveas.setBounds(570, 20, 90, 20);
    saveas.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            String filename = CustomDialog.showInputDialog(JOptionPane.QUESTION_MESSAGE,
                    JOptionPane.OK_CANCEL_OPTION, ConfigFiles.this, "File Name", "Please enter file name");
            if (!filename.equals("NULL")) {
                saveXML(false, filename);
            }
        }
    });
    p8.add(saveas);

    final JButton loadXML = new JButton("Load Config");
    loadXML.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            try {
                String[] configs = RunnerRepository
                        .getRemoteFolderContent(RunnerRepository.USERHOME + "/twister/config/");
                JComboBox combo = new JComboBox(configs);
                int resp = (Integer) CustomDialog.showDialog(combo, JOptionPane.INFORMATION_MESSAGE,
                        JOptionPane.OK_CANCEL_OPTION, ConfigFiles.this, "Config", null);
                final String config;
                if (resp == JOptionPane.OK_OPTION)
                    config = combo.getSelectedItem().toString();
                else
                    config = null;
                if (config != null) {
                    new Thread() {
                        public void run() {
                            setEnabledTabs(false);
                            JFrame progress = new JFrame();
                            progress.setAlwaysOnTop(true);
                            progress.setLocation((int) loadXML.getLocationOnScreen().getX(),
                                    (int) loadXML.getLocationOnScreen().getY());
                            progress.setUndecorated(true);
                            JProgressBar bar = new JProgressBar();
                            bar.setIndeterminate(true);
                            progress.add(bar);
                            progress.pack();
                            progress.setVisible(true);
                            loadConfig(config);
                            progress.dispose();
                            setEnabledTabs(true);
                        }
                    }.start();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    loadXML.setBounds(670, 20, 120, 20);
    p8.add(loadXML);
    //         if(!PermissionValidator.canChangeFWM()){
    //             loadXML.setEnabled(false);
    //         }

    tdbfile = new JTextField();
    addPanel("Database XML path", "File location for database configuration", tdbfile,
            RunnerRepository.REMOTEDATABASECONFIGPATH + RunnerRepository.REMOTEDATABASECONFIGFILE, 375, true,
            null);
    temailfile = new JTextField();
    //         emailpanel = (JPanel)
    addPanel("Email XML path", "File location for email configuration", temailfile,
            RunnerRepository.REMOTEEMAILCONFIGPATH + RunnerRepository.REMOTEEMAILCONFIGFILE, 448, true, null)
                    .getParent();
    //paths.remove(emailpanel);

    //         emailpanel.setBounds(360,440,350,100);
    //         RunnerRepository.window.mainpanel.p4.getEmails().add(emailpanel);

    tglobalsfile = new JTextField();
    addPanel("Globals XML file", "File location for globals parameters", tglobalsfile,
            RunnerRepository.GLOBALSREMOTEFILE, 521, true, null);

    tceport = new JTextField();
    addPanel("Central Engine Port", "Central Engine port", tceport, RunnerRepository.getCentralEnginePort(),
            1003, false, null);
    //         traPort = new JTextField();
    //         addPanel("Resource Allocator Port","Resource Allocator Port",
    //                 traPort,RunnerRepository.getResourceAllocatorPort(),808,false,null);                
    //         thttpPort = new JTextField();
    //         addPanel("HTTP Server Port","HTTP Server Port",thttpPort,
    //                 RunnerRepository.getHTTPServerPort(),740,false,null);

    //paths.add(loadXML);

    if (!PermissionValidator.canChangeFWM()) {
        ttcpath.setEnabled(false);
        tMasterXML.setEnabled(false);
        tUsers.setEnabled(false);
        tepid.setEnabled(false);
        tSuites.setEnabled(false);
        tlog.setEnabled(false);
        trunning.setEnabled(false);
        tdebug.setEnabled(false);
        tsummary.setEnabled(false);
        tinfo.setEnabled(false);
        tcli.setEnabled(false);
        tdbfile.setEnabled(false);
        temailfile.setEnabled(false);
        tceport.setEnabled(false);
        libpath.setEnabled(false);
        tsecondarylog.setEnabled(false);
        testconfigpath.setEnabled(false);
        tglobalsfile.setEnabled(false);
        logsenabled.setEnabled(false);
    }

}

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

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

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

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

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

    String location = urlTextField.getText();

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

From source file:com.sshtools.tunnel.PortForwardingPane.java

protected void editPortForward() {

    ForwardingConfiguration config = model.getForwardingConfigurationAt(table.getSelectedRow());
    if (config.getName().equals("x11")) {
        JOptionPane.showMessageDialog(this, "You cannot edit X11 forwarding.", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;//from w  w  w.  j a  va 2  s  .c o m
    }
    PortForwardEditorPane editor = new PortForwardEditorPane(config);

    int option = JOptionPane.showConfirmDialog(this, editor, "Edit Tunnel", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE);

    if (option != JOptionPane.CANCEL_OPTION && option != JOptionPane.CLOSED_OPTION) {
        try {
            ForwardingClient forwardingClient = client;
            String id = editor.getForwardName();
            if (id.equals("x11")) {
                throw new Exception("The id of x11 is reserved.");
            }
            if (editor.getHost().equals("")) {
                throw new Exception("Please specify a destination host.");
            }
            int i = model.getRowCount();
            if (editor.isLocal()) {
                forwardingClient.removeLocalForwarding(config.getName());
                forwardingClient.addLocalForwarding(id, editor.getBindAddress(), editor.getLocalPort(),
                        editor.getHost(), editor.getRemotePort());
                forwardingClient.startLocalForwarding(id);
            } else {
                forwardingClient.removeRemoteForwarding(config.getName());
                forwardingClient.addRemoteForwarding(id, editor.getBindAddress(), editor.getLocalPort(),
                        editor.getHost(), editor.getRemotePort());
                forwardingClient.startRemoteForwarding(id);
            }

            if (i < model.getRowCount()) {
                table.getSelectionModel().addSelectionInterval(i, i);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        } finally {
            model.refresh();
            sessionPanel.setAvailableActions();
        }
    }
}

From source file:de.unibayreuth.bayeos.goat.panels.timeseries.JPanelChart.java

/**
 * Handles an action event./*from  ww w.ja v  a2 s.  c  o  m*/
 * 
 * @param evt
 *            the event.
 */
public void actionPerformed(ActionEvent evt) {
    try {
        String acmd = evt.getActionCommand();

        if (acmd.equals(ACTION_CHART_ZOOM_BOX)) {
            setPanMode(false);
        } else if (acmd.equals(ACTION_CHART_PAN)) {
            setPanMode(true);
        } else if (acmd.equals(ACTION_CHART_ZOOM_IN)) {
            ChartRenderingInfo info = this.chartPanel.getChartRenderingInfo();
            Rectangle2D rect = info.getPlotInfo().getDataArea();
            zoomBoth(rect.getCenterX(), rect.getCenterY(), ZOOM_FACTOR);
        } else if (acmd.equals(ACTION_CHART_ZOOM_OUT)) {
            ChartRenderingInfo info = this.chartPanel.getChartRenderingInfo();
            Rectangle2D rect = info.getPlotInfo().getDataArea();
            zoomBoth(rect.getCenterX(), rect.getCenterY(), 1 / ZOOM_FACTOR);
        } else if (acmd.equals(ACTION_CHART_ZOOM_TO_FIT)) {

            // X-axis (has no fixed borders)
            chartPanel.autoRangeHorizontal();
            Plot plot = chartPanel.getChart().getPlot();
            if (plot instanceof ValueAxisPlot) {
                XYPlot vvPlot = (XYPlot) plot;
                ValueAxis axis = vvPlot.getRangeAxis();
                if (axis != null) {
                    axis.setLowerBound(yMin);
                    axis.setUpperBound(yMax);
                }
            }
        } else if (acmd.equals(ACTION_CHART_EXPORT)) {
            try {
                chartPanel.doSaveAs();
            } catch (IOException i) {
                MsgBox.error(i.getMessage());
            }
        } else if (acmd.equals(ACTION_CHART_PRINT)) {
            chartPanel.createChartPrintJob();

        } else if (acmd.equals(ACTION_CHART_PROPERTIES)) {
            ChartPropertyEditPanel panel = new ChartPropertyEditPanel(jFreeChart);
            int result = JOptionPane.showConfirmDialog(this, panel,
                    localizationResources.getString("Chart_Properties"), JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.PLAIN_MESSAGE);
            if (result == JOptionPane.OK_OPTION) {
                panel.updateChartProperties(jFreeChart);
            }
        }

    } catch (Exception e) {
        MsgBox.error(e.getMessage());
    }
}

From source file:de.adv_online.aaa.profiltool.ProfilDialog.java

public void initialise(Converter c, Options o, ShapeChangeResult r, String xmi)
        throws ShapeChangeAbortException {

    try {//from   w  w w  .  j ava2  s.  co m
        String msg = "Akzeptieren Sie die in der mit diesem Tool ausgelieferten Datei 'Lizenzbedingungen zur Nutzung von Softwareskripten.doc' beschriebenen Lizenzbedingungen?"; // Meldung
        if (msg != null) {
            Object[] options = { "Ja", "Nein" };
            int val = JOptionPane.showOptionDialog(null, msg, "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
            if (val == 1)
                System.exit(0);
        }
    } catch (Exception e) {
        System.out.println("Fehler in Dialog: " + e.toString());
    }

    options = o;

    File eapFile = new File(xmi);
    try {
        eap = eapFile.getCanonicalFile().getAbsolutePath();
    } catch (IOException e) {
        eap = "ERROR.eap";
    }

    converter = new Converter(options, r);
    result = r;
    modelTransformed = false;
    transformationRunning = false;

    StatusBoard.getStatusBoard().registerStatusReader(this);

    // frame
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    // panel
    newContentPane = new JPanel(new BorderLayout());
    newContentPane.setOpaque(true);
    setContentPane(newContentPane);

    newContentPane.add(createMainTab(), BorderLayout.CENTER);

    statusBar = new StatusBar();

    Box fileBox = Box.createVerticalBox();
    fileBox.add(createStartPanel());
    fileBox.add(statusBar);

    newContentPane.add(fileBox, BorderLayout.SOUTH);

    int height = 610;
    int width = 560;

    pack();

    Insets fI = getInsets();
    setSize(width + fI.right + fI.left, height + fI.top + fI.bottom);
    Dimension sD = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation((sD.width - width) / 2, (sD.height - height) / 2);
    this.setMinimumSize(new Dimension(width, height));

    // frame closing
    WindowListener listener = new WindowAdapter() {
        public void windowClosing(WindowEvent w) {
            //JOptionPane.showMessageDialog(null, "Nein", "NO", JOptionPane.ERROR_MESSAGE);
            closeDialog();
        }
    };
    addWindowListener(listener);
}