Example usage for javax.swing JTextArea setText

List of usage examples for javax.swing JTextArea setText

Introduction

In this page you can find the example usage for javax.swing JTextArea setText.

Prototype

@BeanProperty(bound = false, description = "the text of this component")
public void setText(String t) 

Source Link

Document

Sets the text of this TextComponent to the specified text.

Usage

From source file:search2go.UIFrame.java

public UIFrame() throws IOException, ParseException {
    topLevels = new TopLevelGTermSet[] { CCs, MFs, BPs };

    this.addWindowListener(new WindowAdapter() {
        @Override/*w  ww .j  a v  a2  s. c  o  m*/
        public void windowClosing(WindowEvent et) {
            try {
                if (os.isWindows()) {
                    Runtime.getRuntime().exec("cmd /C TaskKill -IM blastx.exe -F");
                    Runtime.getRuntime().exec("cmd /C TaskKill -IM blastn.exe -F");
                    Runtime.getRuntime().exec("cmd /C TaskKill -IM blastp.exe -F");
                    Runtime.getRuntime().exec("cmd /C TaskKill -IM python.exe -F");
                } else {
                    Runtime.getRuntime().exec("killAll -KILL blastx");
                    Runtime.getRuntime().exec("killAll -KILL blastn");
                    Runtime.getRuntime().exec("killAll -KILL blastp");
                    Runtime.getRuntime().exec("killAll -KILL python");
                }
            } catch (IOException ex) {
                System.out.println("Error closing child processes");
            }
        }
    });

    initComponents();

    txtBlastOutput.getDocument().addDocumentListener(new BufferEnforcer(txtBlastOutput));
    txtFullOutput.getDocument().addDocumentListener(new BufferEnforcer(txtFullOutput));
    txtMapOutput.getDocument().addDocumentListener(new BufferEnforcer(txtMapOutput));

    ((DefaultCaret) txtBlastOutput.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    ((DefaultCaret) txtMapOutput.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    ((DefaultCaret) txtFullOutput.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

    webSaveMenu = new JPopupMenu();
    JMenuItem saveWeb = new JMenuItem();
    saveWeb.setText("Save");
    saveWeb.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            webSaveDialogue.showSaveDialog(pnlChartHolder);
            File saveFile = webSaveDialogue.getSelectedFile();
            if (!saveFile.getPath().contains(".png"))
                saveFile = new File(saveFile.getPath() + ".png");
            try {
                BufferedImage webChartImage = new BufferedImage(pnlChartHolder.getWidth(),
                        pnlChartHolder.getHeight(), BufferedImage.TYPE_INT_RGB);
                pnlChartHolder.print(webChartImage.getGraphics());
                ImageIO.write(webChartImage, "png", saveFile);
            } catch (Exception ex) {
                javax.swing.JOptionPane.showMessageDialog(pnlChartHolder,
                        "Error saving chart. Please try again.");
            }
        }

    });
    webSaveMenu.add(saveWeb);
    pnlChartHolder.add(webSaveMenu);
    pnlChartHolder.setLayout(new java.awt.BorderLayout());

    try {
        currentProj = Workspace.open(new Path("Search2GO_Data"));
        chkDoCCs.setState(currentProj.willDoCC());
        chkDoBPs.setState(currentProj.willDoBP());
        chkDoMFs.setState(currentProj.willDoMF());
        txtQuery.setText(currentProj.getQueryPath());
        txtQueryFP.setText(currentProj.getQueryPath());
        txtDatabase.setText(currentProj.getPathToDB());
        txtDatabaseFP.setText(currentProj.getPathToDB());
        txtThreads.setValue(currentProj.getThreadNo());
        txtThreadsFP.setValue(currentProj.getThreadNo());
        cbxNXP.setSelectedIndex(currentProj.getBlastTypeIndex());
        cbxNXPFP.setSelectedIndex(currentProj.getBlastTypeIndex());
        cbxDBID.setSelectedIndex(currentProj.getSelectedDBIndex());
        cbxDBIDFP.setSelectedIndex(currentProj.getSelectedDBIndex());
        txtBitScore.setValue(currentProj.getBitScoreThreshold());
        txtBitScoreFP.setValue(currentProj.getBitScoreThreshold());
        txtBlastE.setValue(currentProj.getEThreshold());
        txtMapE.setValue(currentProj.getEThreshold());
        txtEFP.setValue(currentProj.getEThreshold());
    } catch (FileNotFoundException e) {
        currentProj = Workspace.create(new Path("Search2GO_Data"));
        chkDoCCs.setState(currentProj.willDoCC());
        chkDoBPs.setState(currentProj.willDoBP());
        chkDoMFs.setState(currentProj.willDoMF());
    }
    this.setTitle("Search2GO " + currentProj.getPath().toString());

    GTermTableModel = new DefaultTableModel();
    GTermTableModel.setColumnCount(2);
    GTermTableModel.setColumnIdentifiers(new String[] { "GO ID", "Frequency" });

    ListSelectionModel GTermSelector = tblGOFreq.getSelectionModel();
    GTermSelector.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                if (tblGOFreq.getSelectedRow() > -1) {
                    DefaultListModel emptyModel = new DefaultListModel();
                    lstQueries.setModel(emptyModel);
                    txtTermInfo.setText("");
                    String selectedID = (String) tblGOFreq.getValueAt(tblGOFreq.getSelectedRow(), 0);
                    JTextArea tempHolderInfo = new JTextArea();
                    JTextArea tempHolderQueries = new JTextArea();

                    if (tblGOFreq.getSelectedRow() != -1) {
                        ResetGTermInfoGetter(tempHolderInfo, tempHolderQueries);
                        gTermInfoGetter.getProcess(0).addParameter("id",
                                selectedID.substring(0, selectedID.indexOf("[")));
                        gTermInfoGetter.getProcess(1).addParameter("id",
                                selectedID.substring(0, selectedID.indexOf("[")));
                        GTerm currentGTerm = gTerms.getGTerm(selectedID.substring(0, selectedID.indexOf("[")));
                        gTermInfoGetter.getProcess(1).addParameter("db", currentGTerm.getTopLevel().getCode());
                        gTermInfoGetter.setTail(new ProcessSequenceEnd() {
                            @Override
                            public void run() {
                                tempHolderInfo.setText("id: " + selectedID + "\n" + tempHolderInfo.getText());
                                txtTermInfo.setText(tempHolderInfo.getText());

                                DefaultListModel queryList = new DefaultListModel();
                                for (String str : tempHolderQueries.getText().split(";")) {
                                    queryList.addElement(str.replaceAll("Query: ", ""));
                                }

                                lstQueries.setModel(queryList);
                                prgIdentification.setIndeterminate(false);
                            }
                        });
                        try {
                            gTermInfoGetter.start();
                            prgIdentification.setIndeterminate(true);
                        } catch (IOException ex) {
                            Logger.getLogger(UIFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        }
    });

    lstQueries.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting() && !e.toString().contains("invalid")
                    && lstQueries.getSelectedValue() != null) {
                JTextArea tempHolder = new JTextArea();

                ProcessSequence fetchLocusSequence = new ProcessSequence(new ProcessSequenceEnd() {
                    @Override
                    public void run() {
                        if (txtTermInfo.getText().contains("Score")) {
                            txtTermInfo.setText(
                                    txtTermInfo.getText().substring(0, txtTermInfo.getText().indexOf("Score")));
                        }
                        txtTermInfo.append(tempHolder.getText());
                        prgIdentification.setIndeterminate(false);
                    }
                });
                Path fetchLocusPath = new Path("Processes");
                fetchLocusPath.append("fetchLocus.py");
                Process fetchLocus = new Process(tempHolder);
                fetchLocus.setScriptCommand(fetchLocusPath.toEscString());
                fetchLocus.addParameter("dir", currentProj.getPath().toEscString());
                fetchLocus.addParameter("q",
                        new ParameterString(lstQueries.getSelectedValue().replace("\n", "")).toString());

                String selectedID = (String) tblGOFreq.getValueAt(tblGOFreq.getSelectedRow(), 0);
                GTerm currentGTerm = gTerms.getGTerm(selectedID.substring(0, selectedID.indexOf("[")));
                fetchLocus.addParameter("db", currentGTerm.getTopLevel().getCode());
                fetchLocus.addParameter("id", currentGTerm.getID());
                fetchLocusSequence.addProcess(fetchLocus);

                try {
                    fetchLocusSequence.start();
                    prgIdentification.setIndeterminate(true);
                } catch (IOException ex) {
                    Logger.getLogger(UIFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    });

    DocumentListener filterListener = new DocumentListener() {
        private void anyUpdate() {
            gTerms.getFilter().setFilterString(txtSearchTerms.getText());
            if (!txtMinFreqFilter.getText().equals(""))
                gTerms.getFilter().setMinFreq(Integer.parseInt(txtMinFreqFilter.getText()));
            else
                gTerms.getFilter().setMinFreq(0);
            if (!txtMaxFreqFilter.getText().equals(""))
                gTerms.getFilter().setMaxFreq(Integer.parseInt(txtMaxFreqFilter.getText()));
            else
                gTerms.getFilter().setMaxFreq(-1);
            fillIdentTable(gTerms.stringFilter(), false);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            anyUpdate();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            anyUpdate();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            anyUpdate();
        }
    };
    txtSearchTerms.getDocument().addDocumentListener(filterListener);
    txtMinFreqFilter.getDocument().addDocumentListener(filterListener);
    txtMaxFreqFilter.getDocument().addDocumentListener(filterListener);

    NumberFormat numberMask = NumberFormat.getIntegerInstance();
    numberMask.setGroupingUsed(false);
    NumberFormatter numberMasker = new NumberFormatter(numberMask);
    NumberFormatter numberMaskerAndBlank = new NumberFormatter(numberMask) {
        @Override
        public Object stringToValue(String s) throws ParseException {
            if (s == null || s.length() == 0)
                return null;
            return super.stringToValue(s);
        }
    };
    DefaultFormatterFactory numberMaskFactory = new DefaultFormatterFactory(numberMasker);
    DefaultFormatterFactory numberMaskAndBlankFactory = new DefaultFormatterFactory(numberMaskerAndBlank);

    txtThreads.setFormatterFactory(numberMaskFactory);
    txtThreadsFP.setFormatterFactory(numberMaskFactory);
    txtBitScore.setFormatterFactory(numberMaskAndBlankFactory);
    txtBitScoreFP.setFormatterFactory(numberMaskAndBlankFactory);
    txtMinFreqFilter.setFormatterFactory(numberMaskFactory);
    txtMaxFreqFilter.setFormatterFactory(numberMaskFactory);
    txtBlastE.setFormatterFactory(numberMaskAndBlankFactory);
    txtMapE.setFormatterFactory(numberMaskAndBlankFactory);
    txtEFP.setFormatterFactory(numberMaskAndBlankFactory);

    blastButton = new StopButton(btnBlast);
    mapButton = new StopButton(btnMapIDs);
    identButton = new StopButton(btnGTermIdent);
    fullButton = new StopButton(btnProcessFP);

    if (currentProj.getStage() >= 2)
        identify(false);
}

From source file:com.adobe.aem.demo.gui.AemDemo.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void initialize() {

    // Initialize properties
    setDefaultProperties(AemDemoUtils// w  ww  .j  a v a  2  s  .  co m
            .loadProperties(buildFile.getParentFile().getAbsolutePath() + File.separator + "build.properties"));
    setPersonalProperties(AemDemoUtils.loadProperties(buildFile.getParentFile().getAbsolutePath()
            + File.separator + "conf" + File.separator + "build-personal.properties"));

    // Constructing the main frame
    frameMain = new JFrame();
    frameMain.setBounds(100, 100, 700, 530);
    frameMain.getContentPane().setLayout(null);

    // Main menu bar for the Frame
    JMenuBar menuBar = new JMenuBar();

    JMenu mnAbout = new JMenu("AEM Demo Machine");
    mnAbout.setMnemonic(KeyEvent.VK_A);
    menuBar.add(mnAbout);

    JMenuItem mntmDoc = new JMenuItem("Help and Documentation");
    mntmDoc.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_H, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmDoc.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.openWebpage(AemDemoUtils.getActualPropertyValue(defaultProperties, personalProperties,
                    AemDemoConstants.OPTIONS_DOCUMENTATION));
        }
    });
    mnAbout.add(mntmDoc);

    JMenuItem mntmQuit = new JMenuItem("Quit");
    mntmQuit.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_Q, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmQuit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(-1);
        }
    });
    mnAbout.add(mntmQuit);

    JMenu mnNew = new JMenu("New");
    mnNew.setMnemonic(KeyEvent.VK_N);
    menuBar.add(mnNew);

    // New Demo Machine
    JMenuItem mntmNewDemo = new JMenuItem("Demo Environment");
    mntmNewDemo.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_N, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmNewDemo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            if (AemDemo.this.getBuildInProgress()) {

                JOptionPane.showMessageDialog(null,
                        "A Demo Environment is currently being built. Please wait until it is finished.");

            } else {

                final AemDemoNew dialogNew = new AemDemoNew(AemDemo.this);
                dialogNew.setModal(true);
                dialogNew.setVisible(true);
                dialogNew.getDemoBuildName().requestFocus();
                ;

            }
        }
    });
    mnNew.add(mntmNewDemo);

    JMenuItem mntmNewOptions = new JMenuItem("Demo Properties");
    mntmNewOptions.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_P, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmNewOptions.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            final AemDemoOptions dialogOptions = new AemDemoOptions(AemDemo.this);
            dialogOptions.setModal(true);
            dialogOptions.setVisible(true);

        }
    });
    mnNew.add(mntmNewOptions);

    JMenu mnUpdate = new JMenu("Add-ons");
    menuBar.add(mnUpdate);

    // Sites Add-on
    JMenu mnSites = new JMenu("Sites");
    mnUpdate.add(mnSites);

    JMenuItem mntmSitesDownloadAddOn = new JMenuItem("Download Add-On");
    mntmSitesDownloadAddOn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_sites");
        }
    });
    mnSites.add(mntmSitesDownloadAddOn);

    JMenuItem mntmSitesDownloadFP = new JMenuItem("Download Feature Pack (VPN)");
    mntmSitesDownloadFP.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_sites_fp");
        }
    });
    mnSites.add(mntmSitesDownloadFP);

    mnSites.addSeparator();

    JMenuItem mntmSitesInstallAddOn = new JMenuItem("Install Add-on");
    mntmSitesInstallAddOn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "sites");
        }
    });
    mnSites.add(mntmSitesInstallAddOn);

    // Assets Add-on
    JMenu mnAssets = new JMenu("Assets");
    mnUpdate.add(mnAssets);

    JMenuItem mntmAssetsDownloadAddOn = new JMenuItem("Download Add-on");
    mntmAssetsDownloadAddOn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_assets");
        }
    });
    mnAssets.add(mntmAssetsDownloadAddOn);
    mnAssets.addSeparator();

    JMenuItem mntmAssetsInstallAddOn = new JMenuItem("Install Add-on");
    mntmAssetsInstallAddOn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "assets");
        }
    });
    mnAssets.add(mntmAssetsInstallAddOn);

    // Communities Add-on
    JMenu mnCommunities = new JMenu("Communities");
    mnUpdate.add(mnCommunities);

    JMenuItem mntmAemCommunitiesUber = new JMenuItem("Download Latest Bundles (VPN)");
    mntmAemCommunitiesUber.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_U, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmAemCommunitiesUber.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_communities_bundles");
        }
    });
    mnCommunities.add(mntmAemCommunitiesUber);

    JMenuItem mntmAemCommunitiesFeaturePacks = new JMenuItem("Download Latest Feature Packs (PackageShare)");
    mntmAemCommunitiesFeaturePacks.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_communities_fp");
        }
    });
    mnCommunities.add(mntmAemCommunitiesFeaturePacks);

    JMenuItem mntmAemCommunitiesEnablement = new JMenuItem("Download Enablement Demo Site Add-on (4.5GB)");
    mntmAemCommunitiesEnablement.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_enablement");
        }
    });
    mnCommunities.add(mntmAemCommunitiesEnablement);
    mnCommunities.addSeparator();

    JMenuItem mntmAemCommunitiesAddOn = new JMenuItem("Install Add-on");
    mntmAemCommunitiesAddOn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "communities");
        }
    });
    mnCommunities.add(mntmAemCommunitiesAddOn);

    // Forms Add-on
    JMenu mnForms = new JMenu("Forms");
    mnUpdate.add(mnForms);

    JMenuItem mntmAemFormsFP = new JMenuItem("Download Demo Add-on (PackageShare)");
    mntmAemFormsFP.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_forms_fp");
        }
    });
    mnForms.add(mntmAemFormsFP);

    mnForms.addSeparator();

    JMenuItem mntmAemFormsAddOn = new JMenuItem("Install Add-on");
    mntmAemFormsAddOn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "forms");
        }
    });
    mnForms.add(mntmAemFormsAddOn);

    // Apps Add-on
    JMenu mnApps = new JMenu("Apps");
    mnUpdate.add(mnApps);

    JMenuItem mntmAemApps = new JMenuItem("Download Add-on");
    mntmAemApps.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_apps");
        }
    });
    mnApps.add(mntmAemApps);

    mnApps.addSeparator();

    JMenuItem mntmAemAppsAddOn = new JMenuItem("Install Add-on");
    mntmAemAppsAddOn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "apps");
        }
    });
    mnApps.add(mntmAemAppsAddOn);

    // Commerce Add-on
    JMenu mnCommerce = new JMenu("Commerce");
    mnUpdate.add(mnCommerce);

    JMenu mnCommerceDownload = new JMenu("Download Add-on");
    mnCommerce.add(mnCommerceDownload);

    // Commerce EP
    JMenuItem mnCommerceDownloadEP = new JMenuItem("ElasticPath");
    mnCommerceDownloadEP.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_commerce_ep");
        }
    });
    mnCommerceDownload.add(mnCommerceDownloadEP);

    // Commerce WebSphere
    JMenuItem mnCommerceDownloadWAS = new JMenuItem("WebSphere");
    mnCommerceDownloadWAS.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_commerce_websphere");
        }
    });
    mnCommerceDownload.add(mnCommerceDownloadWAS);

    mnCommerce.addSeparator();

    JMenuItem mntmAemCommerceAddOn = new JMenuItem("Install Add-on");
    mntmAemCommerceAddOn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "commerce");
        }
    });
    mnCommerce.add(mntmAemCommerceAddOn);

    mnUpdate.addSeparator();

    JMenuItem mntmAemDownloadAll = new JMenuItem("Download All Add-ons");
    mntmAemDownloadAll.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_all");
        }
    });
    mnUpdate.add(mntmAemDownloadAll);

    JMenuItem mntmAemDownloadFromDrive = new JMenuItem("Download Web Page");
    mntmAemDownloadFromDrive.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            AemDemoUtils.openWebpage(AemDemoUtils.getActualPropertyValue(defaultProperties, personalProperties,
                    AemDemoConstants.OPTIONS_WEBDOWNLOAD));

        }
    });
    mnUpdate.add(mntmAemDownloadFromDrive);

    JMenu mnInfrastructure = new JMenu("Infrastructure");
    menuBar.add(mnInfrastructure);

    JMenu mnMongo = new JMenu("MongoDB");

    JMenuItem mntmInfraMongoDB = new JMenuItem("Download");
    mntmInfraMongoDB.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_mongo");
        }
    });
    mnMongo.add(mntmInfraMongoDB);

    JMenuItem mntmInfraMongoDBInstall = new JMenuItem("Install");
    mntmInfraMongoDBInstall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "install_mongo");
        }
    });
    mnMongo.add(mntmInfraMongoDBInstall);
    mnMongo.addSeparator();

    JMenuItem mntmInfraMongoDBStart = new JMenuItem("Start");
    mntmInfraMongoDBStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "mongo_start");
        }
    });
    mnMongo.add(mntmInfraMongoDBStart);

    JMenuItem mntmInfraMongoDBStop = new JMenuItem("Stop");
    mntmInfraMongoDBStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "mongo_stop");
        }
    });
    mnMongo.add(mntmInfraMongoDBStop);
    mnInfrastructure.add(mnMongo);

    // SOLR options
    JMenu mnSOLR = new JMenu("SOLR");

    JMenuItem mntmInfraSOLR = new JMenuItem("Download");
    mntmInfraSOLR.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_solr");
        }
    });
    mnSOLR.add(mntmInfraSOLR);

    JMenuItem mntmInfraSOLRInstall = new JMenuItem("Install");
    mntmInfraSOLRInstall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "install_solr");
        }
    });
    mnSOLR.add(mntmInfraSOLRInstall);
    mnSOLR.addSeparator();

    JMenuItem mntmInfraSOLRStart = new JMenuItem("Start");
    mntmInfraSOLRStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "solr_start");
        }
    });
    mnSOLR.add(mntmInfraSOLRStart);

    JMenuItem mntmInfraSOLRStop = new JMenuItem("Stop");
    mntmInfraSOLRStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "solr_stop");
        }
    });
    mnSOLR.add(mntmInfraSOLRStop);

    mnInfrastructure.add(mnSOLR);

    // MySQL options
    JMenu mnMySQL = new JMenu("MySQL");

    JMenuItem mntmInfraMysql = new JMenuItem("Download");
    mntmInfraMysql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_mysql");
        }
    });
    mnMySQL.add(mntmInfraMysql);

    JMenuItem mntmInfraMysqlInstall = new JMenuItem("Install");
    mntmInfraMysqlInstall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "install_mysql");
        }
    });
    mnMySQL.add(mntmInfraMysqlInstall);

    mnMySQL.addSeparator();

    JMenuItem mntmInfraMysqlStart = new JMenuItem("Start");
    mntmInfraMysqlStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "mysql_start");
        }
    });
    mnMySQL.add(mntmInfraMysqlStart);

    JMenuItem mntmInfraMysqlStop = new JMenuItem("Stop");
    mntmInfraMysqlStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "mysql_stop");
        }
    });
    mnMySQL.add(mntmInfraMysqlStop);

    mnInfrastructure.add(mnMySQL);

    // FFMPEPG options
    JMenu mnFFMPEG = new JMenu("FFMPEG");

    JMenuItem mntmInfraFFMPEG = new JMenuItem("Download");
    mntmInfraFFMPEG.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_ffmpeg");
        }
    });
    mnFFMPEG.add(mntmInfraFFMPEG);

    JMenuItem mntmInfraFFMPEGInstall = new JMenuItem("Install");
    mntmInfraFFMPEGInstall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "install_ffmpeg");
        }
    });
    mnFFMPEG.add(mntmInfraFFMPEGInstall);

    mnInfrastructure.add(mnFFMPEG);

    // Apache James options
    JMenu mnJames = new JMenu("James SMTP");

    JMenuItem mnJamesStart = new JMenuItem("Start");
    mnJamesStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "james_start");
        }
    });
    mnJames.add(mnJamesStart);

    JMenuItem mnJamesStop = new JMenuItem("Stop");
    mnJamesStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "james_stop");
        }
    });
    mnJames.add(mnJamesStop);

    mnInfrastructure.add(mnJames);

    mnInfrastructure.addSeparator();

    JMenuItem mntmInfraInstall = new JMenuItem("All in One Setup");
    mntmInfraInstall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "infrastructure");
        }
    });
    mnInfrastructure.add(mntmInfraInstall);

    JMenu mnOther = new JMenu("Other");
    menuBar.add(mnOther);

    JMenu mntmAemDownload = new JMenu("AEM & License files (VPN)");

    JMenuItem mntmAemDownloadAEM61 = new JMenuItem("Download AEM 6.1");
    mntmAemDownloadAEM61.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_aem61");
        }
    });
    mntmAemDownload.add(mntmAemDownloadAEM61);

    JMenuItem mntmAemDownloadAEM60 = new JMenuItem("Download AEM 6.0");
    mntmAemDownloadAEM60.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_aem60");
        }
    });
    mntmAemDownload.add(mntmAemDownloadAEM60);

    JMenuItem mntmAemDownloadCQ561 = new JMenuItem("Download CQ 5.6.1");
    mntmAemDownloadCQ561.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_cq561");
        }
    });
    mntmAemDownload.add(mntmAemDownloadCQ561);

    JMenuItem mntmAemDownloadCQ56 = new JMenuItem("Download CQ 5.6");
    mntmAemDownloadCQ56.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_cq56");
        }
    });
    mntmAemDownload.add(mntmAemDownloadCQ56);

    JMenuItem mntmAemDownloadOthers = new JMenuItem("Other Releases & License files");
    mntmAemDownloadOthers.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.openWebpage(AemDemoUtils.getActualPropertyValue(defaultProperties, personalProperties,
                    AemDemoConstants.OPTIONS_DOWNLOAD));
        }
    });
    mntmAemDownload.add(mntmAemDownloadOthers);

    mnOther.add(mntmAemDownload);

    JMenuItem mntmAemSnapshot = new JMenuItem("Download Latest AEM Snapshot (VPN)");
    mntmAemSnapshot.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_T, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmAemSnapshot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_snapshot");
        }
    });
    mnOther.add(mntmAemSnapshot);

    JMenuItem mntmAemDemoMachine = new JMenuItem("Download Latest AEM Demo Machine");
    mntmAemDemoMachine.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmAemDemoMachine.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.openWebpage(AemDemoUtils.getActualPropertyValue(defaultProperties, personalProperties,
                    AemDemoConstants.OPTIONS_DEMODOWNLOAD));
        }
    });
    mnOther.add(mntmAemDemoMachine);

    // Adding the menu bar
    frameMain.setJMenuBar(menuBar);

    // Adding other form elements
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(24, 184, 650, 230);
    frameMain.getContentPane().add(scrollPane);

    final JTextArea textArea = new JTextArea("");
    textArea.setEditable(false);
    scrollPane.setViewportView(textArea);

    // List of demo machines available
    JScrollPane scrollDemoList = new JScrollPane();
    scrollDemoList.setBounds(24, 55, 208, 100);
    frameMain.getContentPane().add(scrollDemoList);
    listModelDemoMachines = AemDemoUtils.listDemoMachines(buildFile.getParentFile().getAbsolutePath());
    listDemoMachines = new JList(listModelDemoMachines);
    scrollDemoList.setViewportView(listDemoMachines);

    // Capturing the output stream of ANT commands
    AemDemoOutputStream out = new AemDemoOutputStream(textArea);
    System.setOut(new PrintStream(out));

    JButton btnStart = new JButton("Start");
    btnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            AemDemoUtils.antTarget(AemDemo.this, "start");

        }
    });
    btnStart.setBounds(250, 50, 117, 29);
    frameMain.getContentPane().add(btnStart);

    // Set Start as the default button
    JRootPane rootPane = SwingUtilities.getRootPane(btnStart);
    rootPane.setDefaultButton(btnStart);

    JButton btnInfo = new JButton("Details");
    btnInfo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            AemDemoUtils.antTarget(AemDemo.this, "version");
            AemDemoUtils.antTarget(AemDemo.this, "configuration");

        }
    });
    btnInfo.setBounds(250, 80, 117, 29);
    frameMain.getContentPane().add(btnInfo);

    JButton btnStop = new JButton("Stop");
    btnStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            AemDemoUtils.antTarget(AemDemo.this, "stop");

        }
    });
    btnStop.setBounds(500, 50, 117, 29);
    frameMain.getContentPane().add(btnStop);

    JButton btnExit = new JButton("Exit");
    btnExit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(-1);
        }
    });
    btnExit.setBounds(550, 429, 117, 29);
    frameMain.getContentPane().add(btnExit);

    JButton btnClear = new JButton("Clear");
    btnClear.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            textArea.setText("");
        }
    });
    btnClear.setBounds(40, 429, 117, 29);
    frameMain.getContentPane().add(btnClear);

    JButton btnBackup = new JButton("Backup");
    btnBackup.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "backup");
        }
    });
    btnBackup.setBounds(500, 80, 117, 29);
    frameMain.getContentPane().add(btnBackup);

    JButton btnRestore = new JButton("Restore");
    btnRestore.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "restore");
        }
    });
    btnRestore.setBounds(500, 110, 117, 29);
    frameMain.getContentPane().add(btnRestore);

    JButton btnDelete = new JButton("Delete");
    btnDelete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "uninstall");
        }
    });
    btnDelete.setBounds(500, 140, 117, 29);
    frameMain.getContentPane().add(btnDelete);

    JLabel lblSelectYourDemo = new JLabel("Select your Demo Environment");
    lblSelectYourDemo.setBounds(24, 31, 219, 16);
    frameMain.getContentPane().add(lblSelectYourDemo);

    JLabel lblCommandOutput = new JLabel("Command Output");
    lblCommandOutput.setBounds(24, 164, 160, 16);
    frameMain.getContentPane().add(lblCommandOutput);

    // Launching the download tracker task
    AemDemoDownload aemDownload = new AemDemoDownload(AemDemo.this);
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    executor.scheduleAtFixedRate(aemDownload, 0, 5, TimeUnit.SECONDS);

}

From source file:search2go.UIFrame.java

private void blast(JTextField queries, JFormattedTextField eValue, JTextField db, JTextField threads,
        JComboBox type, JTextArea output, boolean fullProcess) throws IOException {
    Path queriesPath = new Path(queries.getText());
    Path dbPath = new Path(db.getText());
    String threadNo = threads.getText();
    String blastType = type.getSelectedItem().toString().replace("BLAST", "");

    currentProj.setQueries(queriesPath.toEscString());
    currentProj.setPathToDB(dbPath.toEscString());
    currentProj.setThreadNo(Integer.parseInt(threadNo));
    currentProj.setBlastTypeIndex(type.getSelectedIndex());
    currentProj.setEthreshold(Integer.parseInt(txtBlastE.getText()));

    blastSequence = new ProcessSequence(currentProj, new ProcessSequenceEnd() {
        @Override//from  w w  w.  j  a  v  a 2 s . com
        public void run() {
            output.append("BLAST Done! Please proceed to Mapping\n");
            prgBlast.setIndeterminate(false);
            currentProj.setAvailable(true);
            currentProj.setStage(1);
            if (fullProcess) {
                map(txtBitScoreFP, eValue, cbxDBIDFP, txtFullOutput, true);
            }
            blastButton.restore();
        }
    });

    Path outLoc = new Path(currentProj.getPath());
    outLoc.append("BLAST_Results.xml");
    Process blastProcess = new Process(output, outLoc);

    blastProcess.setBaseCommand("");
    blastProcess.setScriptCommand(type.getSelectedItem().toString().toLowerCase());
    blastProcess.addParameter("query", queriesPath.toEscString());
    blastProcess.addParameter("db", dbPath.toEscString());
    blastProcess.addParameter("num_threads", threadNo);
    if (!eValue.getText().equals(""))
        blastProcess.addParameter("evalue", eValue.getText());
    blastProcess.addParameter("outfmt", Integer.toString(5));

    blastSequence.addProcess(blastProcess);

    try {
        blastSequence.start();
        blastButton.setStopTargets(blastSequence);
        if (!fullProcess)
            blastButton.activate();
        currentProj.setStage(0);
        output.setText("Searching...\n");
        prgBlast.setIndeterminate(true);
    } catch (IOException ex) {
        javax.swing.JOptionPane.showMessageDialog(this, "Error running BLAST search.");
    }
}

From source file:search2go.UIFrame.java

private void map(JFormattedTextField bitScore, JFormattedTextField eValue, JComboBox originDB, JTextArea output,
        boolean fullProcess) {
    currentProj.setSelectedDBIndex(originDB.getSelectedIndex());
    currentProj.setBitScoreThreshold(Integer.parseInt(bitScore.getText()));
    currentProj.setEthreshold(Integer.parseInt(txtMapE.getText()));
    mapSequence = new ProcessSequence(currentProj, new ProcessSequenceEnd() {
        @Override/*from  w ww. j av a 2s  . c o m*/
        public void run() {
            if (!output.getText().contains(
                    "No valid hits found. Please retry with lower bit score or higher e-value thresholds.")) {
                if (currentProj.willDoCC())
                    currentProj.setStage(0, 2);
                if (currentProj.willDoBP())
                    currentProj.setStage(1, 2);
                if (currentProj.willDoBP())
                    currentProj.setStage(2, 2);
                output.append("Mapping done! Please proceed to Identification.\n");
                if (fullProcess) {
                    output.append("Identifying...\n");
                    identify(true);
                }
            }
            currentProj.setAvailable(true);
            prgMapping.setIndeterminate(false);
            mapButton.restore();
        }
    });

    Process mapProcess = new Process(output);

    Path mapScriptPath = new Path("Processes");
    mapScriptPath.append("MapFromBlast.py");
    mapProcess.setScriptCommand(mapScriptPath.toEscString());

    mapSequence.addProcess(mapProcess);
    mapProcess.addParameter("dir", currentProj.getPath().toEscString());
    if (!bitScore.getText().equals(""))
        mapProcess.addParameter("bs", bitScore.getText());
    if (!eValue.getText().equals(""))
        mapProcess.addParameter("e", eValue.getText());
    mapProcess.addParameter("id", originDB.getSelectedItem().toString().replaceAll(" ", ""));
    Path blastLoc = new Path(currentProj.getPath());
    blastLoc.append("BLAST_Results.xml");
    mapProcess.addParameter("o", blastLoc.toString());
    mapProcess.addParameter("gdb", currentProj.getTargetDBString());

    try {
        mapSequence.start();
        mapButton.setStopTargets(mapSequence);
        if (!fullProcess)
            mapButton.activate();
        if (currentProj.willDoCC())
            currentProj.setStage(0, 1);
        if (currentProj.willDoBP())
            currentProj.setStage(1, 1);
        if (currentProj.willDoBP())
            currentProj.setStage(2, 1);
        System.out.println(currentProj.getStage());
        output.setText("Mapping...\n");
        prgMapping.setIndeterminate(true);
    } catch (IOException ex) {
        javax.swing.JOptionPane.showMessageDialog(this, "Error running mapping program.");
    }
}

From source file:edu.ku.brc.specify.dbsupport.SpecifySchemaUpdateService.java

/**
 * Fixes the Schema for Database Version 1.2
 * @param conn//from w  w w  .j  av a2s  .c  om
 * @throws Exception
 */
private boolean doFixesForDBSchemaVersions(final Connection conn, final String databaseName) throws Exception {
    /////////////////////////////
    // PaleoContext
    /////////////////////////////
    getTableNameAndTitleForFrame(PaleoContext.getClassTableId());
    Integer len = getFieldLength(conn, databaseName, "paleocontext", "Text1");
    alterFieldLength(conn, databaseName, "paleocontext", "Text1", 32, 64);
    alterFieldLength(conn, databaseName, "paleocontext", "Text2", 32, 64);

    len = getFieldLength(conn, databaseName, "paleocontext", "Remarks");
    if (len == null) {
        int count = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM paleocontext");
        int rv = update(conn, "ALTER TABLE paleocontext ADD Remarks VARCHAR(60)");
        if (rv != count) {
            errMsgList.add("Error updating PaleoContext.Remarks");
            return false;
        }
    }
    frame.incOverall();

    DBConnection dbc = DBConnection.getInstance();

    /////////////////////////////
    // FieldNotebookPage
    /////////////////////////////
    getTableNameAndTitleForFrame(FieldNotebookPage.getClassTableId());
    len = getFieldLength(conn, databaseName, "fieldnotebookpage", "PageNumber");
    if (len != null && len == 16) {
        alterFieldLength(conn, databaseName, "fieldnotebookpage", "PageNumber", 16, 32);
        update(conn, "ALTER TABLE fieldnotebookpage ALTER COLUMN ScanDate DROP DEFAULT");
    }
    frame.incOverall();

    /////////////////////////////
    // Project Table
    /////////////////////////////
    alterFieldLength(conn, databaseName, "project", "projectname", 50, 128);
    frame.incOverall();

    /////////////////////////////
    // AttachmentImageAttribute Table
    /////////////////////////////
    if (doesTableExist(databaseName, "attachmentimageattribute")) {
        alterFieldLength(conn, databaseName, "attachmentimageattribute", "CreativeCommons", 128, 500);
        frame.incOverall();
    }

    /////////////////////////////
    // LocalityDetail
    /////////////////////////////

    String tblName = getTableNameAndTitleForFrame(LocalityDetail.getClassTableId());

    boolean statusOK = true;
    String sql = String.format(
            "SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = 'localitydetail' AND COLUMN_NAME = 'UtmScale' AND DATA_TYPE = 'varchar'",
            dbc.getDatabaseName());
    int count = BasicSQLUtils.getCountAsInt(sql);
    if (count > 0) {
        Vector<Object[]> values = query("SELECT ld.LocalityDetailID, ld.UtmScale, l.LocalityName "
                + "FROM localitydetail ld INNER JOIN locality l ON ld.LocalityID = l.LocalityID WHERE ld.UtmScale IS NOT NULL");

        update(conn, "ALTER TABLE localitydetail DROP COLUMN UtmScale");
        addColumn(conn, databaseName, tblName, "UtmScale", "FLOAT", "UtmOrigLongitude");
        addColumn(conn, databaseName, tblName, "MgrsZone", "VARCHAR(4)", "UtmScale");

        HashMap<String, String> badLocalitiesHash = new HashMap<String, String>();

        try {
            PreparedStatement pStmt = conn
                    .prepareStatement("UPDATE localitydetail SET UtmScale=? WHERE LocalityDetailID=?");

            for (Object[] row : values) {
                Integer locDetailId = (Integer) row[0];
                String scale = (String) row[1];
                String locName = (String) row[2];

                scale = StringUtils.contains(scale, ',') ? StringUtils.replace(scale, ",", "") : scale;
                if (!StringUtils.isNumeric(scale)) {
                    badLocalitiesHash.put(locName, scale);
                    continue;
                }

                float scaleFloat = 0.0f;
                try {
                    scaleFloat = Float.parseFloat(scale);

                } catch (NumberFormatException ex) {
                    badLocalitiesHash.put(locName, scale);
                    continue;
                }

                pStmt.setFloat(1, scaleFloat);
                pStmt.setInt(2, locDetailId);
                pStmt.execute();
            }
            pStmt.close();

        } catch (SQLException ex) {
            statusOK = false;
        }

        if (badLocalitiesHash.size() > 0) {
            try {
                File file = new File(
                        UIRegistry.getUserHomeDir() + File.separator + "localitydetailerrors.html");
                TableWriter tblWriter = new TableWriter(file.getAbsolutePath(), "Locality Detail Errors");
                tblWriter.startTable();
                tblWriter.logHdr(new String[] { "Locality Name", "Scale" });

                for (String key : badLocalitiesHash.keySet()) {
                    tblWriter.log(key, badLocalitiesHash.get(key));
                }
                tblWriter.endTable();
                tblWriter.flush();
                tblWriter.close();

                UIRegistry.showLocalizedError("LOC_DETAIL_ERRORS", badLocalitiesHash.size(),
                        file.getAbsoluteFile());

                badLocalitiesHash.clear();

                if (file.exists()) {
                    try {
                        AttachmentUtils.openURI(file.toURI());

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    } else {
        addColumn(conn, databaseName, tblName, "UtmScale", "FLOAT", "UtmOrigLongitude");
    }
    frame.incOverall();

    //////////////////////////////////////////////
    // collectingeventattribute Schema 1.3
    //////////////////////////////////////////////
    DBMSUserMgr dbmsMgr = DBMSUserMgr.getInstance();
    if (dbmsMgr.connectToDBMS(itUserNamePassword.first, itUserNamePassword.second, dbc.getServerName())) {
        boolean status = true;

        Connection connection = dbmsMgr.getConnection();
        try {
            // Add New Fields to Determination
            tblName = getTableNameAndTitleForFrame(Determination.getClassTableId());
            addColumn(conn, databaseName, tblName, "VarQualifier",
                    "ALTER TABLE %s ADD COLUMN %s VARCHAR(16) AFTER Qualifier");
            addColumn(conn, databaseName, tblName, "SubSpQualifier",
                    "ALTER TABLE %s ADD COLUMN %s VARCHAR(16) AFTER VarQualifier");
            frame.incOverall();

            // CollectingEventAttributes
            sql = String.format(
                    "SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = 'collectingeventattribute' AND COLUMN_NAME = 'CollectionMemberID'",
                    dbc.getDatabaseName());
            count = BasicSQLUtils.getCountAsInt(sql);

            connection.setCatalog(dbc.getDatabaseName());

            //int numCEAttrs = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM collectingeventattribute");
            if (count > 0) {
                HashMap<Integer, Integer> collIdToDispIdHash = new HashMap<Integer, Integer>();
                sql = "SELECT UserGroupScopeId, DisciplineID FROM collection";
                for (Object[] cols : query(sql)) {
                    Integer colId = (Integer) cols[0];
                    Integer dspId = (Integer) cols[1];
                    collIdToDispIdHash.put(colId, dspId);
                }

                count = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM collectingeventattribute");

                IdMapperMgr.getInstance().setDBs(connection, connection);
                IdTableMapper mapper = new IdTableMapper("ceattrmapper", "id",
                        "SELECT CollectingEventAttributeID, CollectionMemberID FROM collectingeventattribute",
                        true, false);
                mapper.setFrame(frame);
                mapper.mapAllIdsNoIncrement(count > 0 ? count : null);

                Statement stmt = null;
                try {
                    getTableNameAndTitleForFrame(CollectingEventAttribute.getClassTableId());

                    stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                            ResultSet.CONCUR_READ_ONLY);
                    update(conn, "DROP INDEX COLEVATSColMemIDX on collectingeventattribute");
                    update(conn, "ALTER TABLE collectingeventattribute DROP COLUMN CollectionMemberID");
                    update(conn, "ALTER TABLE collectingeventattribute ADD COLUMN DisciplineID int(11)");
                    update(conn, "CREATE INDEX COLEVATSDispIDX ON collectingeventattribute(DisciplineID)");

                    double inc = count > 0 ? (100.0 / (double) count) : 0;
                    double cnt = 0;
                    int percent = 0;
                    frame.setProcess(0, 100);
                    frame.setProcessPercent(true);

                    PreparedStatement pStmt = conn.prepareStatement(
                            "UPDATE collectingeventattribute SET DisciplineID=? WHERE CollectingEventAttributeID=?");
                    ResultSet rs = stmt
                            .executeQuery("SELECT CollectingEventAttributeID FROM collectingeventattribute");
                    while (rs.next()) {
                        Integer ceAttrId = rs.getInt(1);
                        Integer oldColId = mapper.get(ceAttrId);
                        if (oldColId != null) {
                            Integer dispId = collIdToDispIdHash.get(oldColId);
                            if (dispId != null) {
                                pStmt.setInt(1, dispId);
                                pStmt.setInt(2, ceAttrId);
                                pStmt.execute();

                            } else {
                                log.debug("Error getting hashed DisciplineID from Old Collection ID[" + oldColId
                                        + "]  ceAttrId[" + ceAttrId + "]");
                            }
                        } else {
                            log.debug("Error getting mapped  Collection ID[" + oldColId + "]  ceAttrId["
                                    + ceAttrId + "]");
                        }

                        cnt += inc;
                        if (((int) cnt) > percent) {
                            percent = (int) cnt;
                            frame.setProcess(percent);
                        }
                    }
                    rs.close();
                    pStmt.close();

                    frame.setProcess(100);

                } catch (SQLException ex) {
                    ex.printStackTrace();

                } finally {
                    if (stmt != null)
                        stmt.close();
                }
                mapper.cleanup();
            }
            frame.incOverall();

            //-----------------------------
            // Collectors
            //-----------------------------
            sql = String.format(
                    "SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = 'collector' AND COLUMN_NAME = 'CollectionMemberID'",
                    dbc.getDatabaseName());
            count = BasicSQLUtils.getCountAsInt(sql);
            if (count > 0) {
                HashMap<Integer, Integer> collIdToDivIdHash = new HashMap<Integer, Integer>();
                sql = "SELECT c.UserGroupScopeId, d.DivisionID FROM collection c INNER JOIN discipline d ON c.DisciplineID = d.UserGroupScopeId";
                for (Object[] cols : query(sql)) {
                    Integer colId = (Integer) cols[0];
                    Integer divId = (Integer) cols[1];
                    collIdToDivIdHash.put(colId, divId);
                }

                count = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM collector");

                IdMapperMgr.getInstance().setDBs(connection, connection);
                IdTableMapper mapper = new IdTableMapper("collectormap", "id",
                        "SELECT CollectorID, CollectionMemberID FROM collector", true, false);
                mapper.setFrame(frame);
                mapper.mapAllIdsNoIncrement(count > 0 ? count : null);

                getTableNameAndTitleForFrame(Collector.getClassTableId());
                Statement stmt = null;
                try {
                    stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                            ResultSet.CONCUR_READ_ONLY);
                    update(conn, "DROP INDEX COLTRColMemIDX on collector");
                    update(conn, "ALTER TABLE collector DROP COLUMN CollectionMemberID");
                    update(conn, "ALTER TABLE collector ADD COLUMN DivisionID INT(11)");
                    update(conn, "CREATE INDEX COLTRDivIDX ON collector(DivisionID)");

                    double inc = count > 0 ? (100.0 / (double) count) : 0;
                    double cnt = 0;
                    int percent = 0;
                    frame.setProcess(0, 100);
                    frame.setProcessPercent(true);

                    PreparedStatement pStmt = conn
                            .prepareStatement("UPDATE collector SET DivisionID=? WHERE CollectorID=?");
                    ResultSet rs = stmt.executeQuery("SELECT CollectorID FROM collector");
                    while (rs.next()) {
                        Integer coltrId = rs.getInt(1);
                        Integer oldColId = mapper.get(coltrId);
                        if (oldColId != null) {
                            Integer divId = collIdToDivIdHash.get(oldColId);
                            if (divId != null) {
                                pStmt.setInt(1, divId);
                                pStmt.setInt(2, coltrId);
                                pStmt.execute();

                            } else {
                                log.debug("Error getting hashed DisciplineID from Old Collection ID[" + oldColId
                                        + "]");
                            }
                        } else {
                            log.debug("Error getting mapped Collector ID[" + oldColId + "]");
                        }

                        cnt += inc;
                        if (((int) cnt) > percent) {
                            percent = (int) cnt;
                            frame.setProcess(percent);
                        }
                    }
                    rs.close();
                    pStmt.close();

                    frame.setProcess(100);

                } catch (SQLException ex) {
                    ex.printStackTrace();

                } finally {
                    if (stmt != null)
                        stmt.close();
                }
                mapper.cleanup();

                frame.incOverall();
            }

        } catch (Exception ex) {
            ex.printStackTrace();

        } finally {
            frame.getProcessProgress().setIndeterminate(true);
            frame.setDesc("Loading updated schema...");

            if (!status) {
                //UIRegistry.showLocalizedError("SCHEMA_UPDATE_ERROR", errMsgStr);
                JTextArea ta = UIHelper.createTextArea();
                ta.setText(errMsgStr);
                CellConstraints cc = new CellConstraints();
                PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g"));
                pb.add(new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), cc.xy(1, 1));
                pb.setDefaultDialogBorder();

                CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getTopWindow(),
                        getResourceString("SCHEMA_UPDATE_ERROR"), true, pb.getPanel());
                UIHelper.centerAndShow(dlg);
            }

            dbmsMgr.close();
        }
    }

    return statusOK;
}

From source file:com.adobe.aem.demomachine.gui.AemDemo.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void initialize() {

    // Initialize properties
    setDefaultProperties(AemDemoUtils/* w ww  .  j  av a 2 s  .c  o m*/
            .loadProperties(buildFile.getParentFile().getAbsolutePath() + File.separator + "build.properties"));
    setPersonalProperties(AemDemoUtils.loadProperties(buildFile.getParentFile().getAbsolutePath()
            + File.separator + "conf" + File.separator + "build-personal.properties"));

    // Constructing the main frame
    frameMain = new JFrame();
    frameMain.setBounds(100, 100, 700, 530);
    frameMain.getContentPane().setLayout(null);

    // Main menu bar for the Frame
    JMenuBar menuBar = new JMenuBar();

    JMenu mnAbout = new JMenu("AEM Demo Machine");
    mnAbout.setMnemonic(KeyEvent.VK_A);
    menuBar.add(mnAbout);

    JMenuItem mntmUpdates = new JMenuItem("Check for Updates");
    mntmUpdates.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmUpdates.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "demo_update");
        }
    });
    mnAbout.add(mntmUpdates);

    JMenuItem mntmDoc = new JMenuItem("Help and Documentation");
    mntmDoc.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_H, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmDoc.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.openWebpage(AemDemoUtils.getActualPropertyValue(defaultProperties, personalProperties,
                    AemDemoConstants.OPTIONS_DOCUMENTATION));
        }
    });
    mnAbout.add(mntmDoc);

    JMenuItem mntmScripts = new JMenuItem("Demo Scripts (VPN)");
    mntmScripts.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.openWebpage(AemDemoUtils.getActualPropertyValue(defaultProperties, personalProperties,
                    AemDemoConstants.OPTIONS_SCRIPTS));
        }
    });
    mnAbout.add(mntmScripts);

    JMenuItem mntmDiagnostics = new JMenuItem("Diagnostics");
    mntmDiagnostics.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Map<String, String> env = System.getenv();
            System.out.println("====== System Environment Variables ======");
            for (String envName : env.keySet()) {
                System.out.format("%s=%s%n", envName, env.get(envName));
            }
            System.out.println("====== JVM Properties ======");
            RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
            List<String> jvmArgs = runtimeMXBean.getInputArguments();
            for (String arg : jvmArgs) {
                System.out.println(arg);
            }
            System.out.println("====== Runtime Properties ======");
            Properties props = System.getProperties();
            props.list(System.out);
        }
    });
    mnAbout.add(mntmDiagnostics);

    JMenuItem mntmQuit = new JMenuItem("Quit");
    mntmQuit.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_Q, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmQuit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(-1);
        }
    });
    mnAbout.add(mntmQuit);

    JMenu mnNew = new JMenu("New");
    menuBar.add(mnNew);

    // New Demo Machine
    JMenuItem mntmNewDemo = new JMenuItem("Demo Environment");
    mntmNewDemo.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_N, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmNewDemo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            if (AemDemo.this.getBuildInProgress()) {

                JOptionPane.showMessageDialog(null,
                        "A Demo Environment is currently being built. Please wait until it is finished.");

            } else {

                final AemDemoNew dialogNew = new AemDemoNew(AemDemo.this);
                dialogNew.setModal(true);
                dialogNew.setVisible(true);
                dialogNew.getDemoBuildName().requestFocus();
                ;

            }
        }
    });
    mnNew.add(mntmNewDemo);

    JMenuItem mntmNewOptions = new JMenuItem("Demo Properties");
    mntmNewOptions.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_P, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmNewOptions.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            final AemDemoOptions dialogOptions = new AemDemoOptions(AemDemo.this);
            dialogOptions.setModal(true);
            dialogOptions.setVisible(true);

        }
    });
    mnNew.add(mntmNewOptions);

    JMenu mnUpdate = new JMenu("Add-ons");
    menuBar.add(mnUpdate);

    // Sites Add-on
    JMenu mnSites = new JMenu("Sites");
    mnUpdate.add(mnSites);

    JMenuItem mntmSitesDownloadAddOn = new JMenuItem("Download Demo Add-on");
    mntmSitesDownloadAddOn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_sites");
        }
    });
    mnSites.add(mntmSitesDownloadAddOn);

    JMenuItem mntmSitesDownloadFP = new JMenuItem("Download Packages (PackageShare)");
    mntmSitesDownloadFP.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_sites_packages");
        }
    });
    mnSites.add(mntmSitesDownloadFP);

    // Assets Add-on
    JMenu mnAssets = new JMenu("Assets");
    mnUpdate.add(mnAssets);

    JMenuItem mntmAssetsDownloadAddOn = new JMenuItem("Download Demo Add-on");
    mntmAssetsDownloadAddOn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_assets");
        }
    });
    mnAssets.add(mntmAssetsDownloadAddOn);

    JMenuItem mntmAssetsDownloadFP = new JMenuItem("Download Packages (PackageShare)");
    mntmAssetsDownloadFP.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_assets_packages");
        }
    });
    mnAssets.add(mntmAssetsDownloadFP);

    // Communities Add-on
    JMenu mnCommunities = new JMenu("Communities/Livefyre");
    mnUpdate.add(mnCommunities);

    JMenuItem mntmAemCommunitiesFeaturePacks = new JMenuItem("Download Packages (PackageShare)");
    mntmAemCommunitiesFeaturePacks.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_communities_packages");
        }
    });
    mnCommunities.add(mntmAemCommunitiesFeaturePacks);

    // Forms Add-on
    JMenu mnForms = new JMenu("Forms");
    mnUpdate.add(mnForms);

    JMenuItem mntmAemFormsAddon = new JMenuItem("Download Demo Add-on");
    mntmAemFormsAddon.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_forms");
        }
    });
    mnForms.add(mntmAemFormsAddon);

    JMenuItem mntmAemFormsFP = new JMenuItem("Download Packages (PackageShare)");
    mntmAemFormsFP.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_forms_packages");
        }
    });
    mnForms.add(mntmAemFormsFP);

    // Mobile Add-on
    JMenu mnApps = new JMenu("Mobile");
    mnUpdate.add(mnApps);

    JMenuItem mntmAemAppsAddon = new JMenuItem("Download Demo Add-on");
    mntmAemAppsAddon.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_apps");
        }
    });
    mnApps.add(mntmAemAppsAddon);

    JMenuItem mntmAemApps = new JMenuItem("Download Packages (PackageShare)");
    mntmAemApps.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_apps_packages");
        }
    });
    mnApps.add(mntmAemApps);

    // Commerce Add-on
    JMenu mnCommerce = new JMenu("Commerce");
    mnUpdate.add(mnCommerce);

    JMenu mnCommerceDownload = new JMenu("Download Packages");
    mnCommerce.add(mnCommerceDownload);

    // Commerce EP
    JMenuItem mnCommerceDownloadEP = new JMenuItem("ElasticPath (PackageShare)");
    mnCommerceDownloadEP.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_commerce_ep");
        }
    });
    mnCommerceDownload.add(mnCommerceDownloadEP);

    // Commerce WebSphere
    JMenuItem mnCommerceDownloadWAS = new JMenuItem("WebSphere (PackageShare)");
    mnCommerceDownloadWAS.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_commerce_websphere");
        }
    });
    mnCommerceDownload.add(mnCommerceDownloadWAS);

    // WeRetail Add-on
    JMenu mnWeRetail = new JMenu("We-Retail");
    mnUpdate.add(mnWeRetail);

    JMenuItem mnWeRetailAddon = new JMenuItem("Download Demo Add-on");
    mnWeRetailAddon.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_weretail");
        }
    });
    mnWeRetail.add(mnWeRetailAddon);

    // Download all section
    mnUpdate.addSeparator();

    JMenuItem mntmAemDownloadAll = new JMenuItem("Download All Add-ons");
    mntmAemDownloadAll.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_all");
        }
    });
    mnUpdate.add(mntmAemDownloadAll);

    JMenu mnInfrastructure = new JMenu("Infrastructure");
    menuBar.add(mnInfrastructure);

    JMenu mnMongo = new JMenu("MongoDB");

    JMenuItem mntmInfraMongoDB = new JMenuItem("Download");
    mntmInfraMongoDB.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_mongo");
        }
    });
    mnMongo.add(mntmInfraMongoDB);

    JMenuItem mntmInfraMongoDBInstall = new JMenuItem("Install");
    mntmInfraMongoDBInstall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "install_mongo");
        }
    });
    mnMongo.add(mntmInfraMongoDBInstall);
    mnMongo.addSeparator();

    JMenuItem mntmInfraMongoDBStart = new JMenuItem("Start");
    mntmInfraMongoDBStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "mongo_start");
        }
    });
    mnMongo.add(mntmInfraMongoDBStart);

    JMenuItem mntmInfraMongoDBStop = new JMenuItem("Stop");
    mntmInfraMongoDBStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "mongo_stop");
        }
    });
    mnMongo.add(mntmInfraMongoDBStop);
    mnInfrastructure.add(mnMongo);

    // SOLR options
    JMenu mnSOLR = new JMenu("SOLR");

    JMenuItem mntmInfraSOLR = new JMenuItem("Download");
    mntmInfraSOLR.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_solr");
        }
    });
    mnSOLR.add(mntmInfraSOLR);

    JMenuItem mntmInfraSOLRInstall = new JMenuItem("Install");
    mntmInfraSOLRInstall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "install_solr");
        }
    });
    mnSOLR.add(mntmInfraSOLRInstall);
    mnSOLR.addSeparator();

    JMenuItem mntmInfraSOLRStart = new JMenuItem("Start");
    mntmInfraSOLRStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "solr_start");
        }
    });
    mnSOLR.add(mntmInfraSOLRStart);

    JMenuItem mntmInfraSOLRStop = new JMenuItem("Stop");
    mntmInfraSOLRStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "solr_stop");
        }
    });
    mnSOLR.add(mntmInfraSOLRStop);

    mnInfrastructure.add(mnSOLR);

    // MySQL options
    JMenu mnMySQL = new JMenu("MySQL");

    JMenuItem mntmInfraMysql = new JMenuItem("Download");
    mntmInfraMysql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_mysql");
        }
    });
    mnMySQL.add(mntmInfraMysql);

    JMenuItem mntmInfraMysqlInstall = new JMenuItem("Install");
    mntmInfraMysqlInstall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "install_mysql");
        }
    });
    mnMySQL.add(mntmInfraMysqlInstall);

    mnMySQL.addSeparator();

    JMenuItem mntmInfraMysqlStart = new JMenuItem("Start");
    mntmInfraMysqlStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "mysql_start");
        }
    });
    mnMySQL.add(mntmInfraMysqlStart);

    JMenuItem mntmInfraMysqlStop = new JMenuItem("Stop");
    mntmInfraMysqlStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "mysql_stop");
        }
    });
    mnMySQL.add(mntmInfraMysqlStop);

    mnInfrastructure.add(mnMySQL);

    // James options
    JMenu mnJames = new JMenu("James SMTP/POP");

    JMenuItem mntmInfraJames = new JMenuItem("Download");
    mntmInfraJames.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_james");
        }
    });
    mnJames.add(mntmInfraJames);

    JMenuItem mntmInfraJamesInstall = new JMenuItem("Install");
    mntmInfraJamesInstall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "install_james");
        }
    });
    mnJames.add(mntmInfraJamesInstall);
    mnJames.addSeparator();

    JMenuItem mntmInfraJamesStart = new JMenuItem("Start");
    mntmInfraJamesStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "james_start");
        }
    });
    mnJames.add(mntmInfraJamesStart);

    JMenuItem mntmInfraJamesStop = new JMenuItem("Stop");
    mntmInfraJamesStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "james_stop");
        }
    });
    mnJames.add(mntmInfraJamesStop);

    mnInfrastructure.add(mnJames);

    // FFMPEPG options
    JMenu mnFFMPEG = new JMenu("FFMPEG");

    JMenuItem mntmInfraFFMPEG = new JMenuItem("Download");
    mntmInfraFFMPEG.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_ffmpeg");
        }
    });
    mnFFMPEG.add(mntmInfraFFMPEG);

    JMenuItem mntmInfraFFMPEGInstall = new JMenuItem("Install");
    mntmInfraFFMPEGInstall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "install_ffmpeg");
        }
    });
    mnFFMPEG.add(mntmInfraFFMPEGInstall);

    mnInfrastructure.add(mnFFMPEG);

    mnInfrastructure.addSeparator();

    // InDesignServer options
    JMenu mnInDesignServer = new JMenu("InDesign Server");

    JMenuItem mntmInfraInDesignServerDownload = new JMenuItem("Download");
    mntmInfraInDesignServerDownload.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_indesignserver");
        }
    });
    mnInDesignServer.add(mntmInfraInDesignServerDownload);

    mnInDesignServer.addSeparator();

    JMenuItem mntmInfraInDesignServerStart = new JMenuItem("Start");
    mntmInfraInDesignServerStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "start_indesignserver");
        }
    });
    mnInDesignServer.add(mntmInfraInDesignServerStart);

    JMenuItem mntmInfraInDesignServerStop = new JMenuItem("Stop");
    mntmInfraInDesignServerStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "stop_indesignserver");
        }
    });
    mnInDesignServer.add(mntmInfraInDesignServerStop);

    mnInfrastructure.add(mnInDesignServer);

    mnInfrastructure.addSeparator();

    JMenuItem mntmInfraInstall = new JMenuItem("All in One Setup");
    mntmInfraInstall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "infrastructure");
        }
    });
    mnInfrastructure.add(mntmInfraInstall);

    JMenu mnOther = new JMenu("Other");
    menuBar.add(mnOther);

    JMenu mntmAemDownload = new JMenu("AEM & License files (VPN)");

    JMenuItem mntmAemLoad = new JMenuItem("Download Latest AEM Load");
    mntmAemLoad.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_L, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmAemLoad.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_load");
        }
    });
    mntmAemDownload.add(mntmAemLoad);

    JMenuItem mntmAemSnapshot = new JMenuItem("Download Latest AEM Snapshot");
    mntmAemSnapshot.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_T, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmAemSnapshot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_snapshot");
        }
    });
    mntmAemDownload.add(mntmAemSnapshot);

    JMenuItem mntmAemDownloadAEM62 = new JMenuItem("Download AEM 6.2");
    mntmAemDownloadAEM62.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_aem62");
        }
    });
    mntmAemDownload.add(mntmAemDownloadAEM62);

    JMenuItem mntmAemDownloadAEM61 = new JMenuItem("Download AEM 6.1");
    mntmAemDownloadAEM61.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_aem61");
        }
    });
    mntmAemDownload.add(mntmAemDownloadAEM61);

    JMenuItem mntmAemDownloadAEM60 = new JMenuItem("Download AEM 6.0");
    mntmAemDownloadAEM60.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_aem60");
        }
    });
    mntmAemDownload.add(mntmAemDownloadAEM60);

    JMenuItem mntmAemDownloadCQ561 = new JMenuItem("Download CQ 5.6.1");
    mntmAemDownloadCQ561.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_cq561");
        }
    });
    mntmAemDownload.add(mntmAemDownloadCQ561);

    JMenuItem mntmAemDownloadCQ56 = new JMenuItem("Download CQ 5.6");
    mntmAemDownloadCQ56.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_cq56");
        }
    });
    mntmAemDownload.add(mntmAemDownloadCQ56);

    JMenuItem mntmAemDownloadOthers = new JMenuItem("Other Releases & License files");
    mntmAemDownloadOthers.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.openWebpage(AemDemoUtils.getActualPropertyValue(defaultProperties, personalProperties,
                    AemDemoConstants.OPTIONS_DOWNLOAD));
        }
    });
    mntmAemDownload.add(mntmAemDownloadOthers);

    mnOther.add(mntmAemDownload);

    JMenuItem mntmAemHotfix = new JMenuItem("Download Latest Hotfixes (PackageShare)");
    mntmAemHotfix.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_F, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmAemHotfix.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_hotfixes_packages");
        }
    });
    mnOther.add(mntmAemHotfix);

    JMenuItem mntmAemAcs = new JMenuItem("Download Latest ACS Commons and Tools");
    mntmAemAcs.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmAemAcs.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "download_acs");
        }
    });
    mnOther.add(mntmAemAcs);

    // Adding the menu bar
    frameMain.setJMenuBar(menuBar);

    // Adding other form elements
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(24, 163, 650, 230);
    frameMain.getContentPane().add(scrollPane);

    final JTextArea textArea = new JTextArea("");
    textArea.setEditable(false);
    scrollPane.setViewportView(textArea);

    // List of demo machines available
    JScrollPane scrollDemoList = new JScrollPane();
    scrollDemoList.setBounds(24, 34, 208, 100);
    frameMain.getContentPane().add(scrollDemoList);
    listModelDemoMachines = AemDemoUtils.listDemoMachines(buildFile.getParentFile().getAbsolutePath());
    listDemoMachines = new JList(listModelDemoMachines);
    listDemoMachines.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    listDemoMachines.setSelectedIndex(AemDemoUtils.getSelectedIndex(listDemoMachines,
            this.getDefaultProperties(), this.getPersonalProperties(), AemDemoConstants.OPTIONS_BUILD_DEFAULT));
    scrollDemoList.setViewportView(listDemoMachines);

    // Capturing the output stream of ANT commands
    AemDemoOutputStream out = new AemDemoOutputStream(textArea);
    System.setOut(new PrintStream(out));

    JButton btnStart = new JButton("Start");
    btnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            AemDemoUtils.antTarget(AemDemo.this, "start");

        }
    });

    btnStart.setBounds(250, 29, 117, 29);
    frameMain.getContentPane().add(btnStart);

    // Set Start as the default button
    JRootPane rootPane = SwingUtilities.getRootPane(btnStart);
    rootPane.setDefaultButton(btnStart);

    JButton btnInfo = new JButton("Details");
    btnInfo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            AemDemoUtils.antTarget(AemDemo.this, "details");

        }
    });
    btnInfo.setBounds(250, 59, 117, 29);
    frameMain.getContentPane().add(btnInfo);

    // Rebuild action
    JButton btnRebuild = new JButton("Rebuild");
    btnRebuild.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            if (AemDemo.this.getBuildInProgress()) {

                JOptionPane.showMessageDialog(null,
                        "A Demo Environment is currently being built. Please wait until it is finished.");

            } else {

                final AemDemoRebuild dialogRebuild = new AemDemoRebuild(AemDemo.this);
                dialogRebuild.setModal(true);
                dialogRebuild.setVisible(true);
                dialogRebuild.getDemoBuildName().requestFocus();
                ;

            }

        }
    });

    btnRebuild.setBounds(250, 89, 117, 29);
    frameMain.getContentPane().add(btnRebuild);

    // Stop action 
    JButton btnStop = new JButton("Stop");
    btnStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            int dialogResult = JOptionPane.showConfirmDialog(null,
                    "Are you sure you really want to stop the running instances?", "Warning",
                    JOptionPane.YES_NO_OPTION);
            if (dialogResult == JOptionPane.NO_OPTION) {
                return;
            }
            AemDemoUtils.antTarget(AemDemo.this, "stop");

        }
    });
    btnStop.setBounds(500, 29, 117, 29);
    frameMain.getContentPane().add(btnStop);

    JButton btnExit = new JButton("Exit");
    btnExit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(-1);
        }
    });
    btnExit.setBounds(550, 408, 117, 29);
    frameMain.getContentPane().add(btnExit);

    JButton btnClear = new JButton("Clear");
    btnClear.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            textArea.setText("");
        }
    });
    btnClear.setBounds(40, 408, 117, 29);
    frameMain.getContentPane().add(btnClear);

    JButton btnBackup = new JButton("Backup");
    btnBackup.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "backup");
        }
    });
    btnBackup.setBounds(500, 59, 117, 29);
    frameMain.getContentPane().add(btnBackup);

    JButton btnRestore = new JButton("Restore");
    btnRestore.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AemDemoUtils.antTarget(AemDemo.this, "restore");
        }
    });
    btnRestore.setBounds(500, 89, 117, 29);
    frameMain.getContentPane().add(btnRestore);

    JButton btnDelete = new JButton("Delete");
    btnDelete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int dialogResult = JOptionPane.showConfirmDialog(null,
                    "Are you sure you really want to permanently delete the selected demo configuration?",
                    "Warning", JOptionPane.YES_NO_OPTION);
            if (dialogResult == JOptionPane.NO_OPTION) {
                return;
            }
            AemDemoUtils.antTarget(AemDemo.this, "uninstall");
        }
    });
    btnDelete.setBounds(500, 119, 117, 29);
    frameMain.getContentPane().add(btnDelete);

    JLabel lblSelectYourDemo = new JLabel("Select your Demo Environment");
    lblSelectYourDemo.setBounds(24, 10, 219, 16);
    frameMain.getContentPane().add(lblSelectYourDemo);

    JLabel lblCommandOutput = new JLabel("Command Output");
    lblCommandOutput.setBounds(24, 143, 160, 16);
    frameMain.getContentPane().add(lblCommandOutput);

    // Initializing and launching the ticker
    String tickerOn = AemDemoUtils.getPropertyValue(buildFile, "demo.ticker");
    if (tickerOn == null || (tickerOn != null && tickerOn.equals("true"))) {
        AemDemoMarquee mp = new AemDemoMarquee(AemDemoConstants.Credits, 60);
        mp.setBounds(140, 440, 650, 30);
        frameMain.getContentPane().add(mp);
        mp.start();
    }

    // Launching the download tracker task
    AemDemoDownload aemDownload = new AemDemoDownload(AemDemo.this);
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    executor.scheduleAtFixedRate(aemDownload, 0, 5, TimeUnit.SECONDS);

    // Loading up the README.md file
    String line = null;
    try {
        FileReader fileReader = new FileReader(
                buildFile.getParentFile().getAbsolutePath() + File.separator + "README.md");
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        while ((line = bufferedReader.readLine()) != null) {
            if (line.indexOf("AEM Demo Machine!") > 0) {
                line = line + " (version: " + aemDemoMachineVersion + ")";
            }
            if (!line.startsWith("Double"))
                System.out.println(line);
        }
        bufferedReader.close();
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }

}

From source file:search2go.UIFrame.java

public void identify(boolean fullProcess) {
    if ("Stop".equals(btnGTermIdent.getText())) {
        identButton.activate();//from  w ww  . j a v  a  2  s .  c om
        try {
            if (os.isWindows()) {
                Runtime.getRuntime().exec("cmd /C TaskKill -IM blastx.exe -F");
                Runtime.getRuntime().exec("cmd /C TaskKill -IM blastn.exe -F");
                Runtime.getRuntime().exec("cmd /C TaskKill -IM blastp.exe -F");
            } else {
                Runtime.getRuntime().exec("killAll -KILL blastx");
                Runtime.getRuntime().exec("killAll -KILL blastn");
                Runtime.getRuntime().exec("killAll -KILL blastp");
            }
        } catch (IOException ex) {
            System.out.println("Error closing child processes");
        }
        prgIdentification.setIndeterminate(false);
    } else if (currentProj.checkStage(2)) {
        if (currentProj.isAvaialable()) {
            pnlChartHolder.removeAll();
            lstQueries.clearSelection();
            lstQueries.setModel(new DefaultListModel());
            txtTermInfo.setText("");

            tblGOFreq.clearSelection();
            DefaultTableModel d = new DefaultTableModel();
            d.setColumnCount(2);
            d.setColumnIdentifiers(new String[] { "GO ID", "Frequency" });
            tblGOFreq.setModel(d);

            identSequences = new ArrayList<>();

            resetIdentCount();
            for (int i = 0; i < 3; i++) {
                if (currentProj.getTargetDBString().contains(targetDBs[i])) {
                    JTextArea tempHolder = new JTextArea();
                    ProcessSequence identSequence = new ProcessSequence(currentProj,
                            new ProcessSequenceFiller(tempHolder, Integer.toString(i)) {
                                private final JTextArea sequenceOutput = tempHolder;

                                @Override
                                public void run() {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            for (String record : sequenceOutput.getText().split("\n")) {
                                                String name = record.split("\t")[0];
                                                GTerm nextGTerm = new GTerm(
                                                        name.substring(0, name.indexOf("[")),
                                                        name.substring(name.indexOf("[")));
                                                nextGTerm.setTopLevel(topLevels[Integer.parseInt(getNotes())]);
                                                nextGTerm.setFrequency(Integer.parseInt(record.split("\t")[1]));
                                                gTerms.addGTerm(nextGTerm);
                                            }
                                            incIdentCount();
                                        }
                                    }).start();
                                }
                            });
                    identSequences.add(identSequence);
                    Process checkFullIdent = new Process(tempHolder);
                    Path checkFullIdentPath = new Path("Processes");
                    checkFullIdentPath.append("gotFullGTerms.py");
                    checkFullIdent.setScriptCommand(checkFullIdentPath.toEscString());
                    checkFullIdent.addParameter("dir", currentProj.getPath().toEscString());
                    checkFullIdent.addParameter("db", targetDBs[i]);
                    identSequence.addProcess(checkFullIdent);
                    ProcessSequenceFiller doFullCheckOutputGetter = new ProcessSequenceFiller(tempHolder,
                            targetDBs[i]) {
                        @Override
                        public void run() {
                            if (this.getOutBox().getText().contains("false")) {
                                this.getOutBox().setText("");
                                Process mapSequenceGO = new Process(this.getOutBox());
                                Path mapSequenceGOPath = new Path("Processes");
                                mapSequenceGOPath.append("mapSequenceGO.py");
                                mapSequenceGO.setScriptCommand(mapSequenceGOPath.toEscString());
                                mapSequenceGO.addParameter("dir", currentProj.getPath().toEscString());
                                mapSequenceGO.addParameter("db", this.getNotes());
                                this.getParentSequence(0).addProcess(mapSequenceGO);

                                Process parseConverts = new Process(this.getOutBox());
                                Path parseConvertsPath = new Path("Processes");
                                parseConvertsPath.append("parseConvertedIDs.py");
                                parseConverts.setScriptCommand(parseConvertsPath.toEscString());
                                parseConverts.addParameter("dir", currentProj.getPath().toEscString());
                                parseConverts.addParameter("db", this.getNotes());
                                this.getParentSequence(0).addProcess(parseConverts);

                                identSequence.addProcess(new ProcessSequenceFiller(tempHolder) {
                                    @Override
                                    public void run() {
                                        tempHolder.setText("");
                                        try {
                                            this.finish();
                                        } catch (IOException ex) {
                                            System.out.println("Error finishing identification process filler");
                                        }
                                    }

                                });
                            }
                            this.getOutBox().setText("");
                            Process getMatchedQueryFreq = new Process(this.getOutBox());
                            Path getMatchedQueryFreqPath = new Path("Processes");
                            getMatchedQueryFreqPath.append("getMatchedQueryFreq.py");
                            getMatchedQueryFreq.setScriptCommand(getMatchedQueryFreqPath.toEscString());
                            getMatchedQueryFreq.addParameter("dir", currentProj.getPath().toEscString());
                            getMatchedQueryFreq.addParameter("db", this.getNotes());
                            this.getParentSequence(0).addProcess(getMatchedQueryFreq);
                            try {
                                this.finish();
                            } catch (IOException ex) {
                                System.out.println("Error finishing identification process filler");
                            }
                        }
                    };

                    identSequence.addProcess(doFullCheckOutputGetter);
                    try {
                        gTerms.getGTerms().clear();
                        identSequence.start();
                        identButton.setStopTargets(
                                identSequences.toArray(new ProcessSequence[identSequences.size()]));
                        if (currentProj.willDoCC())
                            currentProj.setStage(0, 2);
                        if (currentProj.willDoBP())
                            currentProj.setStage(1, 2);
                        if (currentProj.willDoBP())
                            currentProj.setStage(2, 2);
                        prgIdentification.setIndeterminate(true);
                    } catch (IOException ex) {
                        Logger.getLogger(UIFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            identButton.activate();
        } else
            javax.swing.JOptionPane.showMessageDialog(this,
                    "Another function is currently being performed on this project, please wait until completion or manually stop the process.");
    } else {
        System.out.println(currentProj.getStage());
        javax.swing.JOptionPane.showMessageDialog(this,
                "Mapping data unavailable. Please complete mapping step or switch to a project with completed mapping to continue.");
    }

}

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Insert standard prefixes in the assertions text area.
 * /*from   ww  w .  j a v  a  2s.c  o m*/
 * The user must choose the format (syntax) to use.
 */
private void insertPrefixes() {
    String whichFormat;
    int formatIndex;
    String[] formatsToChoose;
    List<String> formatsAvail;
    StringBuffer prefixesToAdd;
    JTextArea areaToUpdate;

    formatsAvail = new ArrayList<String>();

    for (int format = 0; format < FORMATS.length; ++format) {
        if (STANDARD_PREFIXES[format].length > 0) {
            formatsAvail.add(FORMATS[format]);
        }
    }

    // SPARQL is a special case - not an RDF serialization
    formatsAvail.add("SPARQL (tab)");

    formatsToChoose = new String[formatsAvail.size()];
    for (int format = 0; format < formatsAvail.size(); ++format) {
        formatsToChoose[format] = formatsAvail.get(format);
    }

    whichFormat = (String) JOptionPane.showInputDialog(this, "Choose the format for the prefixes",
            "Choose Format", JOptionPane.QUESTION_MESSAGE, null, formatsToChoose, null);

    LOGGER.debug("Chosen format for prefixes: " + whichFormat);

    if (whichFormat != null) {
        formatIndex = getIndexValue(FORMATS, whichFormat);

        // SPARQL - special case - not an RDF serialization format
        if (formatIndex == UNKNOWN) {
            formatIndex = STANDARD_PREFIXES.length - 1;
            areaToUpdate = sparqlInput;
        } else {
            areaToUpdate = assertionsInput;
        }

        LOGGER.debug("Chosen format index for prefixes: " + formatIndex);

        if (formatIndex >= 0) {
            String currentData;

            currentData = areaToUpdate.getText();

            prefixesToAdd = new StringBuffer();
            for (int prefix = 0; prefix < STANDARD_PREFIXES[formatIndex].length; ++prefix) {
                prefixesToAdd.append(STANDARD_PREFIXES[formatIndex][prefix]);
                prefixesToAdd.append('\n');
            }

            areaToUpdate.setText(prefixesToAdd.toString() + currentData);
        }
    }
}

From source file:interfaces.InterfazPrincipal.java

private void botonRegistrarAbonoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonRegistrarAbonoActionPerformed
    // TODO add your handling code here:
    try {/*from w ww .  j a v a2s  .  co m*/

        String identificacionCliente = mostrarIdentificacionCliente.getText();
        Double abono = Double.parseDouble(abonoClente.getText());

        if (abono <= 0.0) {
            throw new Exception();
        }

        ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
        ControladorFactura controladorFactura = new ControladorFactura();

        Calendar calendario = Calendar.getInstance();
        String dia = Integer.toString(calendario.get(Calendar.DATE));
        String mes = Integer.toString(calendario.get(Calendar.MONTH));
        String annio = Integer.toString(calendario.get(Calendar.YEAR));
        Date date = new Date();
        DateFormat hourFormat = new SimpleDateFormat("HH:mm:ss");
        String hora = hourFormat.format(date);

        String fecha = annio + "-" + mes + "-" + dia + " " + hora;
        /*
         * -----------------Tomar el abono y los pagos-----------------
         * Procedimiento
         * 1 Tomar flujos de deuda de cada factura con estado fiado
         * 2 Tomar abonos de abono de cada factura con estado fiado
         * 3 Calcular la resta de estos dos para deteminar lo que se debe por factura
         * 4 Cancelar con el flujo la factura y si lo debido es 0 colocar estado pagado
         * 5 Mostrar una informacin en un JOptionPane y recalcular la deuda
         * 
         */
        DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoClientes.getModel();
        ArrayList<String> codigoFactura = new ArrayList<>();
        ArrayList<Double> totalDebe = new ArrayList<>();

        JTextArea area = new JTextArea(10, 30);
        String informe = "\t Registro flujo pago del abono \n\n";
        informe += "Factura \t Pago \t Queda pagada? \n\n";

        int numeroRegistros = -1;
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            //System.out.println("Entro al for " + i);
            //Se necesita 0: Factura ID, 1 Tipo, 3 Valor
            // Codigofactura contiene los cogidos de las facturas
            // totalDebe contiene lo que debe de las facturas, la posicion coincide con la lista CodigoFactura
            String factura_id = String.valueOf(modeloClientes.getValueAt(i, 0));
            String tipo_flujo = String.valueOf(modeloClientes.getValueAt(i, 1));
            Double valor = Double.parseDouble(String.valueOf(modeloClientes.getValueAt(i, 3)));
            if (codigoFactura.contains(factura_id)) {

                if (tipo_flujo.equals("abono")) {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) - valor);
                } else {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) + valor);
                }
            } else {
                numeroRegistros++;
                codigoFactura.add(factura_id);
                if (tipo_flujo.equals("abono")) {
                    totalDebe.add(-valor);
                } else {
                    totalDebe.add(valor);
                }
            }

        }
        //System.out.println(Arrays.toString(codigoFactura.toArray()));
        //System.out.println(Arrays.toString(totalDebe.toArray()));
        Double debeTotal = 0d;
        for (int i = 0; i < totalDebe.size(); i++) {
            debeTotal += totalDebe.get(i);

        }

        if (debeTotal < abono) {
            JOptionPane.showMessageDialog(this,
                    "El monto es superior a lo que debe el cliente, por favor indique otro monto", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        for (int i = 0; i < totalDebe.size(); i++) {
            //Tomar flujos
            if (abono > 0.0) {
                Double pago = totalDebe.get(i) - abono;

                //Pago igual a 0 significa que se pag la factura
                if (pago == 0) {
                    //Registrar flujo
                    String[] value = { codigoFactura.get(i), "abono", fecha, String.valueOf(abono) };
                    //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                    controladorFlujoFactura.insertFlujo_Factura(value);

                    controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");
                    informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                    //Romper el for
                    break;
                } else {

                    //Pago mayor que 0, es decir se queda debiendo
                    if (pago > 0) {

                        //Registrar flujo
                        String[] value = { codigoFactura.get(i), "abono", fecha, String.valueOf(abono) };
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.insertFlujo_Factura(value);
                        //Como el abono ahora es menor que 0 debe romperse el for
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tNO\n";

                        break;

                    } else {
                        //Caso final pago menor 0, es decir el abono paga la factura pero queda disponible para otras facturas
                        //Registrar flujo
                        String[] value = { codigoFactura.get(i), "abono", fecha,
                                String.valueOf(totalDebe.get(i)) };
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.insertFlujo_Factura(value);

                        controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");

                        //Ajustamos ahora el abono restando lo que debe la factura
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                        abono -= totalDebe.get(i);
                    }

                }
            } else {
                //Romper el for
                break;
            }

        }

        //Reordenar y volver a consultar
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            modeloClientes.removeRow(i);
        }

        modeloClientes.setRowCount(0);

        //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
        ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                " where factura_id in (select factura_id from Factura where cliente_id = "
                        + String.valueOf(identificacionCliente) + " and estado=\"fiado\") order by factura_id");
        double pago = 0.0;

        for (int i = 0; i < flujosCliente.size(); i++) {
            String[] datos = flujosCliente.get(i);
            Object[] rowData = { datos[1], datos[2], datos[3], datos[4] };
            modeloClientes.addRow(rowData);
            if (datos[2].equals("deuda")) {
                pago += Double.parseDouble(datos[4]);
            } else {
                pago -= Double.parseDouble(datos[4]);
            }
        }

        textoTotalDebe.setText(String.valueOf(pago));
        TablaDeSaldoClientes.setModel(modeloClientes);
        area.setText(informe);
        JScrollPane panelInformePago = new JScrollPane(area);
        JOptionPane.showMessageDialog(this, panelInformePago);

    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe ingresar un valor numrico mayor que 0 en el abono ");
    }
}

From source file:interfaces.InterfazPrincipal.java

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
    // TODO add your handling code here:

    try {/*from www.  j av a2  s.  c om*/

        String identificacionCliente = mostrarIDProveedor.getText();
        Double abono = Double.parseDouble(jTextFieldAbonoProveedor.getText());

        if (abono <= 0.0 || identificacionCliente.equals("")) {
            throw new Exception();
        }

        ControladorFlujoCompras controladorFlujoFactura = new ControladorFlujoCompras();
        ControladorCompraProveedor controladorCompraProveedor = new ControladorCompraProveedor();

        Calendar calendario = Calendar.getInstance();
        String dia = Integer.toString(calendario.get(Calendar.DATE));
        String mes = Integer.toString(calendario.get(Calendar.MONTH));
        String annio = Integer.toString(calendario.get(Calendar.YEAR));
        Date date = new Date();
        DateFormat hourFormat = new SimpleDateFormat("HH:mm:ss");
        String hora = hourFormat.format(date);

        String fecha = annio + "-" + mes + "-" + dia + " " + hora;
        /*
         * -----------------Tomar el abono y los pagos-----------------
         * Procedimiento
         * 1 Tomar flujos de deuda de cada factura con estado fiado
         * 2 Tomar abonos de abono de cada factura con estado fiado
         * 3 Calcular la resta de estos dos para deteminar lo que se debe por factura
         * 4 Cancelar con el flujo la factura y si lo debido es 0 colocar estado pagado
         * 5 Mostrar una informacin en un JOptionPane y recalcular la deuda
         * 
         */
        DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoProveedor.getModel();
        ArrayList<String> codigoFactura = new ArrayList<>();
        ArrayList<Double> totalDebe = new ArrayList<>();

        JTextArea area = new JTextArea(10, 30);
        String informe = "\t Registro flujo pago del abono \n\n";
        informe += "Factura \t Pago \t Queda pagada? \n\n";

        int numeroRegistros = -1;
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            //System.out.println("Entro al for " + i);
            //Se necesita 0: Factura ID, 1 Tipo, 3 Valor
            // Codigofactura contiene los cogidos de las facturas
            // totalDebe contiene lo que debe de las facturas, la posicion coincide con la lista CodigoFactura
            String factura_id = String.valueOf(modeloClientes.getValueAt(i, 0));
            String tipo_flujo = String.valueOf(modeloClientes.getValueAt(i, 1));
            Double valor = Double.parseDouble(String.valueOf(modeloClientes.getValueAt(i, 3)));
            if (codigoFactura.contains(factura_id)) {

                if (tipo_flujo.equals("abono")) {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) - valor);
                } else {
                    totalDebe.set(numeroRegistros, totalDebe.get(numeroRegistros) + valor);
                }
            } else {
                numeroRegistros++;
                codigoFactura.add(factura_id);
                if (tipo_flujo.equals("abono")) {
                    totalDebe.add(-valor);
                } else {
                    totalDebe.add(valor);
                }
            }

        }
        //System.out.println(Arrays.toString(codigoFactura.toArray()));
        //System.out.println(Arrays.toString(totalDebe.toArray()));
        System.out.println(totalDebe);
        double debeTotal = 0d;
        for (int i = 0; i < totalDebe.size(); i++) {
            debeTotal += totalDebe.get(i);
        }

        if (debeTotal < abono) {
            JOptionPane.showMessageDialog(this, "El monto a pagar no puede ser superior a lo que se debe",
                    "Error del sistema", JOptionPane.ERROR_MESSAGE);
            return;
        }
        for (int i = 0; i < totalDebe.size(); i++) {
            //Tomar flujos
            if (abono > 0.0) {
                Double pago = totalDebe.get(i) - abono;

                //Pago igual a 0 significa que se pag la factura
                if (pago == 0) {
                    //Registrar flujo
                    //String[] value = {codigoFactura.get(i), "abono", fecha, String.valueOf(abono)};
                    //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                    controladorFlujoFactura.registrarFlujoAbono(codigoFactura.get(i), String.valueOf(abono));

                    //controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");
                    informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                    //Romper el for
                    break;
                } else {

                    //Pago mayor que 0, es decir se queda debiendo
                    if (pago > 0) {

                        //Registrar flujo
                        //String[] value = {codigoFactura.get(i), "abono", fecha, String.valueOf(abono)};
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.registrarFlujoAbono(codigoFactura.get(i),
                                String.valueOf(abono));
                        //Como el abono ahora es menor que 0 debe romperse el for
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tNO\n";

                        break;

                    } else {
                        //Caso final pago menor 0, es decir el abono paga la factura pero queda disponible para otras facturas
                        //Registrar flujo
                        //String[] value = {codigoFactura.get(i), "abono", fecha, String.valueOf(totalDebe.get(i))};
                        //String [] selection = {"factura_id","tipo_flujo","fecha","valor"};
                        controladorFlujoFactura.registrarFlujoAbono(codigoFactura.get(i),
                                String.valueOf(totalDebe.get(i)));

                        //controladorFactura.cambiarEstadoFactura(codigoFactura.get(i), "pagada");
                        //Ajustamos ahora el abono restando lo que debe la factura
                        informe += codigoFactura.get(i) + "\t" + String.valueOf(abono) + "\tSI\n";
                        abono -= totalDebe.get(i);
                    }

                }
            } else {
                //Romper el for
                break;
            }

        }

        //Reordenar y volver a consultar
        for (int i = 0; i < modeloClientes.getRowCount(); i++) {
            modeloClientes.removeRow(i);
        }

        modeloClientes.setRowCount(0);

        //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
        ArrayList<Flujo_Compra> flujosProveedor = controladorFlujoFactura.obtenerFlujosCompras(
                " where ID_CompraProveedor in (select ID_CompraProveedor from Compra_Proveedores where IDProveedor = "
                        + String.valueOf(identificacionCliente) + ") order by ID_CompraProveedor");
        double pago = 0.0;

        for (int i = 0; i < flujosProveedor.size(); i++) {
            Flujo_Compra datos = flujosProveedor.get(i);
            Object[] rowData = { datos.getID_CompraProveedor(), datos.getTipo_flujo(), datos.getFecha(),
                    datos.getMonto() };

            if (datos.getTipo_flujo().equals("deuda")) {
                pago += Double.parseDouble(datos.getMonto() + "");
            } else {
                pago -= Double.parseDouble(datos.getMonto() + "");
            }

            modeloClientes.addRow(rowData);
        }

        TablaDeSaldoProveedor.setModel(modeloClientes);
        deudaActualProveedor.setText(String.valueOf(pago));

        //Mostrar en table de clientes los datos
        botonRegistrarAbono.setEnabled(true);

        area.setText(informe);
        JScrollPane panelInformePago = new JScrollPane(area);
        JOptionPane.showMessageDialog(this, panelInformePago);

    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe ingresar un valor numrico mayor que 0 en el abono ");
    }

}