Example usage for java.util.concurrent Executors newScheduledThreadPool

List of usage examples for java.util.concurrent Executors newScheduledThreadPool

Introduction

In this page you can find the example usage for java.util.concurrent Executors newScheduledThreadPool.

Prototype

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 

Source Link

Document

Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.

Usage

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

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

    // Initialize properties
    setDefaultProperties(AemDemoUtils/*w  ww.ja v a2 s.  c om*/
            .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:com.jivesoftware.os.upena.deployable.UpenaMain.java

public void run(String[] args) throws Exception {

    HealthFactory.initialize(BindInterfaceToConfiguration::bindDefault, new HealthCheckRegistry() {

        @Override//from  w w  w .j a  v a 2s  .c o m
        public void register(HealthChecker<?> healthChecker) {

        }

        @Override
        public void unregister(HealthChecker<?> healthChecker) {

        }
    });

    Properties buildProperties = new Properties();
    String upenaVersion = "";
    try {
        buildProperties.load(UpenaMain.class.getClassLoader().getResourceAsStream("build.properties"));
        upenaVersion = buildProperties.getProperty("my.version", "") + " "
                + buildProperties.getProperty("my.timestamp", "") + " sha:"
                + buildProperties.getProperty("git.commit.id", "");
    } catch (Exception x) {
        LOG.warn("Failed to locate build.properties");
    }

    String workingDir = System.getProperty("user.dir");
    long start = System.currentTimeMillis();
    Exception failed = null;
    while (start + TimeUnit.SECONDS.toMillis(10) > System.currentTimeMillis()) {
        try {
            File lockFile = new File(workingDir, "onlyLetOneRunningAtATime");
            lockFile.createNewFile();
            FileChannel.open(lockFile.toPath(), StandardOpenOption.WRITE).lock();
            failed = null;
            break;
        } catch (Exception x) {
            failed = x;
            LOG.warn("Failed to acquire lock on onlyLetOneRunningAtATime", x);
            Thread.sleep(1000);
        }
    }
    if (failed != null) {
        throw failed;
    }

    JDIAPI jvmapi = null;
    try {
        jvmapi = new JDIAPI();
    } catch (NoClassDefFoundError x) {
        LOG.warn(
                "Failed to local tools.jar. Please manually add to classpath. Breakpoint debugger will be disabled.");
    }

    String hostname = args[0];

    int loopbackPort = Integer.parseInt(System.getProperty("amza.loopback.port", "1174"));
    int port = Integer.parseInt(System.getProperty("amza.port", "1175"));
    String multicastGroup = System.getProperty("amza.discovery.group", "225.4.5.6");
    int multicastPort = Integer.parseInt(System.getProperty("amza.discovery.port", "1123"));
    String clusterDiscoveryName = (args.length > 1 ? args[1] : null);

    String datacenter = System.getProperty("host.datacenter", "unknownDatacenter");
    String rack = System.getProperty("host.rack", "unknownRack");
    String publicHost = System.getProperty("public.host.name", hostname);

    UpenaRingHost ringHost = new UpenaRingHost(hostname, port); // TODO include rackId

    // todo need a better way to create writer id.
    int writerId = new Random().nextInt(512);
    TimestampedOrderIdProvider orderIdProvider = new OrderIdProviderImpl(
            new ConstantWriterIdProvider(writerId));

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    RowsStorageProvider rowsStorageProvider = rowsStorageProvider(orderIdProvider);

    boolean sslEnable = Boolean.parseBoolean(System.getProperty("ssl.enabled", "true"));
    String sslKeystorePassword = System.getProperty("ssl.keystore.password", "password");
    String sslKeystorePath = System.getProperty("ssl.keystore.path", "./certs/sslKeystore");
    String sslKeyStoreAlias = System.getProperty("ssl.keystore.alias", "upenanode").toLowerCase();
    boolean sslAutoGenerateSelfSignedCert = Boolean
            .parseBoolean(System.getProperty("ssl.keystore.autoGenerate", "true"));

    File sslKeystore = new File(sslKeystorePath);
    if (sslEnable) {
        SelfSigningCertGenerator selfSigningCertGenerator = new SelfSigningCertGenerator();
        if (sslKeystore.exists()) {
            if (!selfSigningCertGenerator.validate(sslKeyStoreAlias, sslKeystorePassword, sslKeystore)) {
                LOG.error("SSL keystore validation failed. keyStoreAlias:{} sslKeystore:{}", sslKeyStoreAlias,
                        sslKeystore);
                System.exit(1);
            }
        } else {
            sslKeystore.getParentFile().mkdirs();
            if (sslAutoGenerateSelfSignedCert) {
                selfSigningCertGenerator.create(sslKeyStoreAlias, sslKeystorePassword, sslKeystore);
            } else {
                LOG.error("Failed to locate mandatory sslKeystore:{}", sslKeystore);
                System.exit(1);
            }
        }
    }

    String consumerKey = System.getProperty("upena.consumerKey", clusterDiscoveryName);
    if (consumerKey == null) {
        consumerKey = "upena";
        LOG.warn("Please provide a stronger consumerKey via -Dupena.consumerKey");
    }
    String finalConsumerKey = consumerKey;

    String secret = System.getProperty("upena.secret");
    if (secret == null) {
        secret = "secret";
        LOG.warn("Please provide a stronger secret via -Dupena.secret");
    }
    String finalSecret = secret;

    OAuthSigner authSigner = (request) -> {
        CommonsHttpOAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(finalConsumerKey, finalSecret);
        oAuthConsumer.setMessageSigner(new HmacSha1MessageSigner());
        oAuthConsumer.setTokenWithSecret(finalConsumerKey, finalSecret);
        return oAuthConsumer.sign(request);
    };
    UpenaSSLConfig upenaSSLConfig = new UpenaSSLConfig(sslEnable, sslAutoGenerateSelfSignedCert, authSigner);

    UpenaAmzaService upenaAmzaService = null;
    if (!new File("./state").exists()) {
        UpdatesSender changeSetSender = new HttpUpdatesSender(sslEnable, sslAutoGenerateSelfSignedCert,
                authSigner);
        UpdatesTaker tableTaker = new HttpUpdatesTaker(sslEnable, sslAutoGenerateSelfSignedCert, authSigner);

        UpenaAmzaServiceConfig upenaAmzaServiceConfig = new UpenaAmzaServiceConfig();
        upenaAmzaService = new UpenaAmzaServiceInitializer().initialize(upenaAmzaServiceConfig, orderIdProvider,
                new com.jivesoftware.os.upena.amza.storage.FstMarshaller(
                        FSTConfiguration.getDefaultConfiguration()),
                rowsStorageProvider, rowsStorageProvider, rowsStorageProvider, changeSetSender, tableTaker,
                Optional.<SendFailureListener>absent(), Optional.<UpenaTakeFailureListener>absent(),
                (changes) -> {
                });

        /*upenaAmzaService.start(ringHost, upenaAmzaServiceConfig.resendReplicasIntervalInMillis,
            upenaAmzaServiceConfig.applyReplicasIntervalInMillis,
            upenaAmzaServiceConfig.takeFromNeighborsIntervalInMillis,
            upenaAmzaServiceConfig.checkIfCompactionIsNeededIntervalInMillis,
            upenaAmzaServiceConfig.compactTombstoneIfOlderThanNMillis);*/

        LOG.info("-----------------------------------------------------------------------");
        LOG.info("|      OLD Amza Service Online");
        LOG.info("-----------------------------------------------------------------------");
    } else {
        LOG.info("-----------------------------------------------------------------------");
        LOG.info("|      OLD Amza Data is decomissionable");
        LOG.info("-----------------------------------------------------------------------");
    }

    BAInterner baInterner = new BAInterner();

    AtomicReference<Callable<RingTopology>> topologyProvider = new AtomicReference<>(); // bit of a hack
    InstanceDescriptor instanceDescriptor = new InstanceDescriptor(datacenter, rack, "", "", "", "", "", "", "",
            "", 0, "", "", "", 0L, true);
    ConnectionDescriptorsProvider noAuthConnectionsProvider = (connectionDescriptorsRequest,
            expectedReleaseGroup) -> {
        try {
            RingTopology systemRing = topologyProvider.get().call();
            List<ConnectionDescriptor> descriptors = Lists.newArrayList(Iterables.transform(systemRing.entries,
                    input -> new ConnectionDescriptor(instanceDescriptor, sslEnable, false,
                            new HostPort(input.ringHost.getHost(), input.ringHost.getPort()),
                            Collections.emptyMap(), Collections.emptyMap())));
            return new ConnectionDescriptorsResponse(200, Collections.emptyList(), "", descriptors,
                    connectionDescriptorsRequest.getRequestUuid());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };

    TenantsServiceConnectionDescriptorProvider<String> noAuthConnectionPoolProvider = new TenantsServiceConnectionDescriptorProvider<>(
            Executors.newScheduledThreadPool(1), "", noAuthConnectionsProvider, "", "", 10_000); // TODO config
    noAuthConnectionPoolProvider.start();

    ConnectionDescriptorsProvider connectionsProvider = (connectionDescriptorsRequest,
            expectedReleaseGroup) -> {
        try {
            RingTopology systemRing = topologyProvider.get().call();
            List<ConnectionDescriptor> descriptors = Lists.newArrayList(Iterables.transform(systemRing.entries,
                    input -> new ConnectionDescriptor(instanceDescriptor, sslEnable, true,
                            new HostPort(input.ringHost.getHost(), input.ringHost.getPort()),
                            Collections.emptyMap(), Collections.emptyMap())));
            return new ConnectionDescriptorsResponse(200, Collections.emptyList(), "", descriptors,
                    connectionDescriptorsRequest.getRequestUuid());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };

    TenantsServiceConnectionDescriptorProvider<String> connectionPoolProvider = new TenantsServiceConnectionDescriptorProvider<>(
            Executors.newScheduledThreadPool(1), "", connectionsProvider, "", "", 10_000); // TODO config
    connectionPoolProvider.start();

    HttpDeliveryClientHealthProvider clientHealthProvider = new HttpDeliveryClientHealthProvider("", null, "",
            5000, 100);

    TenantRoutingHttpClientInitializer<String> nonSigningClientInitializer = new TenantRoutingHttpClientInitializer<>(
            null);

    TenantAwareHttpClient<String> systemTakeClient = nonSigningClientInitializer
            .builder(noAuthConnectionPoolProvider, // TODO config
                    clientHealthProvider)
            .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000)
            .socketTimeoutInMillis(60_000).build(); // TODO expose to conf
    TenantAwareHttpClient<String> stripedTakeClient = nonSigningClientInitializer
            .builder(noAuthConnectionPoolProvider, // TODO config
                    clientHealthProvider)
            .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000)
            .socketTimeoutInMillis(60_000).build(); // TODO expose to conf

    TenantRoutingHttpClientInitializer<String> tenantRoutingHttpClientInitializer = new TenantRoutingHttpClientInitializer<>(
            new OAuthSignerProvider(() -> authSigner));

    TenantAwareHttpClient<String> ringClient = tenantRoutingHttpClientInitializer
            .builder(connectionPoolProvider, // TODO config
                    clientHealthProvider)
            .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000)
            .socketTimeoutInMillis(60_000).build(); // TODO expose to conf
    AmzaStats amzaStats = new AmzaStats();

    AmzaService amzaService = startAmza(workingDir, amzaStats, baInterner, writerId,
            new RingHost(datacenter, rack, ringHost.getHost(), ringHost.getPort()),
            new RingMember(ringHost.getHost() + ":" + ringHost.getPort()), authSigner, systemTakeClient,
            stripedTakeClient, ringClient, topologyProvider, clusterDiscoveryName, multicastGroup,
            multicastPort);

    EmbeddedClientProvider embeddedClientProvider = new EmbeddedClientProvider(amzaService);

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Amza Service Online");
    LOG.info("-----------------------------------------------------------------------");

    ObjectMapper storeMapper = new ObjectMapper();
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    UpenaConfigStore upenaConfigStore = new UpenaConfigStore(orderIdProvider, storeMapper, upenaAmzaService,
            amzaService, embeddedClientProvider);

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Upena Config Store Online");
    LOG.info("-----------------------------------------------------------------------");

    ExecutorService instanceChangedThreads = Executors.newFixedThreadPool(32);

    AtomicReference<UbaService> ubaServiceReference = new AtomicReference<>();
    UpenaStore upenaStore = new UpenaStore(storeMapper, upenaAmzaService, (instanceChanges) -> {
        instanceChangedThreads.submit(() -> {
            UbaService got = ubaServiceReference.get();
            if (got != null) {
                try {
                    got.instanceChanged(instanceChanges);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }, (changes) -> {
    }, (change) -> {
        LOG.info("TODO: tie into conductor. " + change);
    }, amzaService, embeddedClientProvider);
    //upenaStore.attachWatchers();

    ChaosService chaosService = new ChaosService(upenaStore);
    SecureRandom random = new SecureRandom();
    PasswordStore passwordStore = (key) -> {
        String password = System.getProperty("sauth.keystore.password");
        if (password == null) {
            File passwordFile = new File(workingDir, "keystore/" + key + ".key");
            if (passwordFile.exists()) {
                password = Files.toString(passwordFile, StandardCharsets.UTF_8);
            } else {
                passwordFile.getParentFile().mkdirs();
                password = new BigInteger(130, random).toString(32);
                Files.write(password, passwordFile, StandardCharsets.UTF_8);
            }
        }
        return password;
    };

    SessionStore sessionStore = new SessionStore(TimeUnit.MINUTES.toMillis(60), TimeUnit.MINUTES.toMillis(30));

    AtomicReference<UpenaHealth> upenaHealthProvider = new AtomicReference<>();
    InstanceHealthly instanceHealthly = (key, version) -> {
        UpenaHealth upenaHealth = upenaHealthProvider.get();
        if (upenaHealth == null) {
            return false;
        }
        ConcurrentMap<RingHost, NodeHealth> ringHostNodeHealth = upenaHealth.buildClusterHealth();
        for (NodeHealth nodeHealth : ringHostNodeHealth.values()) {
            for (NannyHealth nannyHealth : nodeHealth.nannyHealths) {
                if (nannyHealth.instanceDescriptor.instanceKey.equals(key.getKey())) {
                    return nannyHealth.serviceHealth.fullyOnline
                            ? nannyHealth.serviceHealth.version.equals(version)
                            : false;
                }
            }
        }
        return false;
    };
    UpenaService upenaService = new UpenaService(passwordStore, sessionStore, upenaStore, chaosService,
            instanceHealthly);

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Upena Service Online");
    LOG.info("-----------------------------------------------------------------------");

    File defaultPathToRepo = new File(new File(System.getProperty("user.dir"), ".m2"), "repository");
    PathToRepo localPathToRepo = new PathToRepo(
            new File(System.getProperty("pathToRepo", defaultPathToRepo.getAbsolutePath())));
    RepositoryProvider repositoryProvider = new RepositoryProvider(localPathToRepo);

    Host host = new Host(publicHost, datacenter, rack, ringHost.getHost(), ringHost.getPort(), workingDir, null,
            null);
    HostKey hostKey = new HostKeyProvider().getNodeKey(upenaStore.hosts, host);

    String hostInstanceId = System.getProperty("host.instance.id", hostKey.getKey());
    host = new Host(publicHost, datacenter, rack, ringHost.getHost(), ringHost.getPort(), workingDir,
            hostInstanceId, null);

    UbaLog ubaLog = (what, why, how) -> {
        try {
            upenaStore.record("Uba", what, System.currentTimeMillis(), why,
                    ringHost.getHost() + ":" + ringHost.getPort(), how);
        } catch (Exception x) {
            x.printStackTrace(); // Hmm lame
        }
    };

    OktaLog oktaLog = (who, what, why, how) -> {
        try {
            upenaStore.record("okta:" + who, what, System.currentTimeMillis(), why,
                    ringHost.getHost() + ":" + ringHost.getPort(), how);
        } catch (Exception x) {
            x.printStackTrace(); // Hmm lame
        }
    };

    OktaCredentialsMatcher.oktaLog = oktaLog;
    OktaRealm.oktaLog = oktaLog;

    UpenaClient upenaClient = new UpenaClient() {
        @Override
        public InstanceDescriptorsResponse instanceDescriptor(
                InstanceDescriptorsRequest instanceDescriptorsRequest) throws Exception {
            return upenaService.instanceDescriptors(instanceDescriptorsRequest);
        }

        @Override
        public void updateKeyPair(String instanceKey, String publicKey) throws Exception {
            Instance i = upenaStore.instances.get(new InstanceKey(instanceKey));
            if (i != null) {
                LOG.info("Updating publicKey for {}", instanceKey);
                upenaStore.instances.update(new InstanceKey(instanceKey),
                        new Instance(i.clusterKey, i.hostKey, i.serviceKey, i.releaseGroupKey, i.instanceId,
                                i.enabled, i.locked, publicKey, i.restartTimestampGMTMillis, i.ports));
            }
        }

    };

    final UbaService ubaService = new UbaServiceInitializer().initialize(passwordStore, upenaClient,
            repositoryProvider, hostKey.getKey(), workingDir,
            new UbaCoordinate(datacenter, rack, publicHost, host.hostName, "localhost", loopbackPort), null,
            ubaLog);

    UpenaHealth upenaHealth = new UpenaHealth(amzaService, upenaSSLConfig, upenaConfigStore, ubaService,
            new RingHost(datacenter, rack, ringHost.getHost(), ringHost.getPort()), hostKey);
    upenaHealthProvider.set(upenaHealth);

    DiscoveredRoutes discoveredRoutes = new DiscoveredRoutes();
    ShiroRequestHelper shiroRequestHelper = new ShiroRequestHelper(TimeUnit.DAYS.toMillis(1)); // TODO expose Sys prop?

    String shiroConfigLocation = System.getProperty("shiro.ini.location", "classpath:shiro.ini"); // classpath:oktashiro.ini

    UpenaJerseyEndpoints jerseyEndpoints = new UpenaJerseyEndpoints(shiroConfigLocation)
            .addInjectable(ShiroRequestHelper.class, shiroRequestHelper)
            .addEndpoint(UpenaClusterRestEndpoints.class).addEndpoint(UpenaHostRestEndpoints.class)
            .addEndpoint(UpenaServiceRestEndpoints.class).addEndpoint(UpenaReleaseRestEndpoints.class)
            .addEndpoint(UpenaInstanceRestEndpoints.class).addEndpoint(UpenaTenantRestEndpoints.class)
            .addInjectable(upenaHealth).addInjectable(upenaService).addInjectable(upenaStore)
            .addInjectable(upenaConfigStore).addInjectable(ubaService)
            //.addEndpoint(AmzaReplicationRestEndpoints.class)
            //.addInjectable(UpenaAmzaInstance.class, upenaAmzaService)
            .addEndpoint(UpenaEndpoints.class).addEndpoint(UpenaConnectivityEndpoints.class)
            .addEndpoint(UpenaManagedDeployableEndpoints.class).addEndpoint(UpenaHealthEndpoints.class)
            .addEndpoint(UpenaRepoEndpoints.class).addInjectable(DiscoveredRoutes.class, discoveredRoutes)
            .addInjectable(UpenaRingHost.class, ringHost).addInjectable(HostKey.class, hostKey)
            .addInjectable(UpenaAutoRelease.class, new UpenaAutoRelease(repositoryProvider, upenaStore))
            .addInjectable(PathToRepo.class, localPathToRepo);

    PercentileHealthCheckConfig phcc = bindDefault(PercentileHealthCheckConfig.class);
    PercentileHealthChecker authFilterHealthCheck = new PercentileHealthChecker(phcc);
    AuthValidationFilter authValidationFilter = new AuthValidationFilter(authFilterHealthCheck);
    authValidationFilter.addEvaluator(new NoAuthEvaluator(), "/", "/swagger.json", "/ui/*", // Handled by Shiro
            "/repo/*" // Cough
    );

    OAuth1Signature verifier = new OAuth1Signature(new OAuthServiceLocatorShim());
    OAuthSecretManager oAuthSecretManager = new OAuthSecretManager() {
        @Override
        public void clearCache() {
        }

        @Override
        public String getSecret(String id) throws AuthValidationException {
            return id.equals(finalConsumerKey) ? finalSecret : null;
        }

        @Override
        public void verifyLastSecretRemovalTime() throws Exception {
        }
    };
    AuthValidator<OAuth1Signature, OAuth1Request> oAuthValidator = new DefaultOAuthValidator(
            Executors.newScheduledThreadPool(1), Long.MAX_VALUE, oAuthSecretManager, 60_000, false, false);
    oAuthValidator.start();
    authValidationFilter.addEvaluator(new NoAuthEvaluator(), "/repo/*", "/amza/rows/stream/*",
            "/amza/rows/taken/*", "/amza/pong/*", "/amza/invalidate/*");
    authValidationFilter.addEvaluator(new OAuthEvaluator(oAuthValidator, verifier), "/upena/*", "/amza/*");

    // TODO something better someday
    String upenaApiUsername = System.getProperty("upena.api.username", null);
    String upenaApiPassword = System.getProperty("upena.api.password", null);

    if (upenaApiUsername != null && upenaApiPassword != null) {
        authValidationFilter.addEvaluator(containerRequestContext -> {
            String authCredentials = containerRequestContext.getHeaderString("Authorization");
            if (authCredentials == null) {
                return AuthStatus.not_handled;
            }

            final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", "");
            String usernameAndPassword = null;
            try {
                byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
                usernameAndPassword = new String(decodedBytes, "UTF-8");
            } catch (IOException e) {
                return AuthStatus.denied;
            }
            final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
            final String username = tokenizer.nextToken();
            final String password = tokenizer.nextToken();

            boolean authenticationStatus = upenaApiUsername.equals(username)
                    && upenaApiPassword.equals(password);

            return authenticationStatus ? AuthStatus.authorized : AuthStatus.denied;
        }, "/api/*");
    }

    jerseyEndpoints.addContainerRequestFilter(authValidationFilter);

    String region = System.getProperty("aws.region", null);
    String roleArn = System.getProperty("aws.roleArn", null);

    AWSClientFactory awsClientFactory = new AWSClientFactory(region, roleArn);

    String accountName = System.getProperty("account.name",
            clusterDiscoveryName == null ? "" : clusterDiscoveryName);
    String humanReadableUpenaClusterName = datacenter + " - " + accountName;
    injectUI(upenaVersion, awsClientFactory, storeMapper, mapper, jvmapi, amzaService, localPathToRepo,
            repositoryProvider, hostKey, ringHost, upenaSSLConfig, port, sessionStore, ubaService, upenaHealth,
            upenaStore, upenaConfigStore, jerseyEndpoints, humanReadableUpenaClusterName, discoveredRoutes);

    injectAmza(baInterner, amzaStats, jerseyEndpoints, amzaService, ringClient);

    InitializeRestfulServer initializeRestfulServer = new InitializeRestfulServer(false, port, "UpenaNode",
            sslEnable, sslKeyStoreAlias, sslKeystorePassword, sslKeystorePath, 128, 10_000);

    buildSwagger();
    initializeRestfulServer.addClasspathResource("/resources");
    initializeRestfulServer.addContextHandler("/", jerseyEndpoints);

    RestfulServer restfulServer = initializeRestfulServer.build();
    restfulServer.start();

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Jetty Service Online");
    LOG.info("-----------------------------------------------------------------------");

    UpenaJerseyEndpoints loopbackJerseyEndpoints = new UpenaJerseyEndpoints(null)
            .addEndpoint(UpenaLoopbackEndpoints.class).addEndpoint(UpenaConfigRestEndpoints.class)
            .addInjectable(SessionStore.class, sessionStore)
            .addInjectable(DiscoveredRoutes.class, discoveredRoutes).addInjectable(upenaConfigStore)
            .addInjectable(upenaStore).addInjectable(upenaHealth)
            .addInjectable(UpenaService.class, upenaService);

    InitializeRestfulServer initializeLoopbackRestfulServer = new InitializeRestfulServer(
            Boolean.parseBoolean(System.getProperty("amza.loopback.strict", "true")), loopbackPort, "UpenaNode",
            false, sslKeyStoreAlias, sslKeystorePassword, sslKeystorePath, 128, 10_000);
    initializeLoopbackRestfulServer.addClasspathResource("/resources");
    initializeLoopbackRestfulServer.addContextHandler("/", loopbackJerseyEndpoints);

    RestfulServer loopbackRestfulServer = initializeLoopbackRestfulServer.build();
    loopbackRestfulServer.start();

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Jetty Service Online");
    LOG.info("-----------------------------------------------------------------------");

    if (ubaService != null) {
        Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(() -> {
            try {
                ubaService.nanny();
            } catch (Exception ex) {
                LOG.error("Nanny failure", ex);
            }
        }, 15, 15, TimeUnit.SECONDS);
        LOG.info("-----------------------------------------------------------------------");
        LOG.info("|      Uba Service Online");
        LOG.info("-----------------------------------------------------------------------");
    }
    ubaServiceReference.set(ubaService);

    /*String peers = System.getProperty("manual.peers");
    if (peers != null) {
    String[] hostPortTuples = peers.split(",");
    for (String hostPortTuple : hostPortTuples) {
        String hostPort = hostPortTuple.trim();
        if (hostPort.length() > 0 && hostPort.contains(":")) {
            String[] host_port = hostPort.split(":");
            try {
                UpenaRingHost anotherRingHost = new UpenaRingHost(host_port[0].trim(), Integer.parseInt(host_port[1].trim()));
                List<UpenaRingHost> ring = upenaAmzaService.getRing("master");
                if (!ring.contains(anotherRingHost)) {
                    LOG.info("Adding host to the cluster: " + anotherRingHost);
                    upenaAmzaService.addRingHost("master", anotherRingHost);
                }
            } catch (Exception x) {
                LOG.warn("Malformed hostPortTuple {}", hostPort);
            }
        } else {
            LOG.warn("Malformed hostPortTuple {}", hostPort);
        }
    }
    }*/

    String vpc = System.getProperty("aws.vpc", null);
    UpenaAWSLoadBalancerNanny upenaAWSLoadBalancerNanny = new UpenaAWSLoadBalancerNanny(vpc, upenaStore,
            hostKey, awsClientFactory);

    Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(() -> {
        try {
            upenaAWSLoadBalancerNanny.ensureSelf();
        } catch (Exception x) {
            LOG.warn("Failures while nannying load loadbalancer.", x);
        }
    }, 1, 1, TimeUnit.MINUTES); // TODO better

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|     Waiting for amza to be ready....");
    LOG.info("-----------------------------------------------------------------------");
    while (!amzaService.isReady()) {
        Thread.sleep(1000);
    }

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|     Begin Migration");
    LOG.info("-----------------------------------------------------------------------");

    upenaStore.init(orderIdProvider, Integer.parseInt(System.getProperty("min.service.port", "10000")),
            Integer.parseInt(System.getProperty("max.service.port", String.valueOf(Short.MAX_VALUE))), false);

    upenaConfigStore.init();

    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|     End Migration");
    LOG.info("-----------------------------------------------------------------------");

    addManualPeers(amzaService);

    Host gotHost = upenaStore.hosts.get(hostKey);
    if (gotHost == null || !gotHost.equals(host)) {
        upenaStore.hosts.update(hostKey, host);
    }
}

From source file:com.android.dialer.voicemail.VoicemailPlaybackPresenter.java

private static synchronized ScheduledExecutorService getScheduledExecutorServiceInstance() {
    if (mScheduledExecutorService == null) {
        mScheduledExecutorService = Executors.newScheduledThreadPool(NUMBER_OF_THREADS_IN_POOL);
    }//  w ww .  ja  v a  2 s  .c o  m
    return mScheduledExecutorService;
}

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

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

    // Initialize properties
    setDefaultProperties(AemDemoUtils/*from   w  ww . j  a  va 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:org.cloudifysource.usm.UniversalServiceManagerBean.java

/*********
 * Called to notify USM that the service has stopped. This may be due to a USM shutdown, a USM command, or an
 * unexpected service failure./*w w  w .j  a v a 2 s  . c o m*/
 */
public void onProcessDeath() {
    logger.info("Detected death of underlying process");
    // we use this to cancel start detection, if it is still running

    synchronized (this.stateMutex) {

        if (this.state != USMState.RUNNING) {
            // process is shutting down or restarting, nothing to do now.
            return;
        }

        try {
            // unexpected process failure
            getUsmLifecycleBean().firePostStop(StopReason.PROCESS_FAILURE);
        } catch (final Exception e) {
            logger.log(Level.SEVERE,
                    "The Post Stop event failed to execute after an anexpected failure of the process: "
                            + e.getMessage(),
                    e);
        }

        // kill all current tasks, and create new thread pool for tasks
        this.executors.shutdownNow();

        this.state = USMState.LAUNCHING;
        this.executors = Executors.newScheduledThreadPool(THREAD_POOL_SIZE);

        // Restart USM
        new Thread(new Runnable() {

            @Override
            public void run() {

                try {
                    Thread.sleep(postDeathWaitPeriodMillis);
                } catch (final InterruptedException e) {
                    // ignore
                }
                try {
                    logger.info("Relaunching process");
                    launch();
                    logger.info("Finished Relaunching process after unexpected process death");
                } catch (final USMException e) {
                    logger.log(Level.SEVERE,
                            "Failed to re-launch the external process after a previous failure: "
                                    + e.getMessage(),
                            e);
                    logger.severe("Marking this USM as failed so it will be recycled by GSM");
                    markUSMAsFailed(e);
                } catch (final TimeoutException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * reset report threadpool if necessary.
 */// ww  w  .j  a  va2s.c  om
public void renewReportThreadPool() {
    if (mReportExecutorService == null || mReportExecutorService.isShutdown()) {
        mReportExecutorService = Executors.newScheduledThreadPool(SpeedTestConst.THREAD_POOL_REPORT_SIZE);
    }
}

From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java

private void startPU(String springXml) throws IOException, ClassNotFoundException {
    if (logger.isDebugEnabled()) {
        logger.debug(logMessage("Starting PU with [" + springXml + "]"));
    }/*from w  w w . j  a v a2  s  .  c o  m*/

    String puName = (String) context.getInitParameter("puName");
    String puPath = (String) context.getInitParameter("puPath");
    String codeserver = context.getExportCodebase();

    org.openspaces.pu.sla.SLA sla = getSLA(getServiceBeanContext());

    Integer instanceId = this.instanceId;
    Integer backupId = this.backupId;

    // Derive instanceId and backupId if not explicitly set
    if (instanceId == null) {
        boolean hasBackups = sla.getNumberOfBackups() > 0;
        if (hasBackups) {
            instanceId = clusterGroup;
            //the first instance is primary so no backupid
            if (context.getServiceBeanConfig().getInstanceID().intValue() > 1) {
                backupId = (context.getServiceBeanConfig().getInstanceID().intValue() - 1);
            }
        } else {
            instanceId = context.getServiceBeanConfig().getInstanceID().intValue();
        }
    }

    //set cluster info
    clusterInfo = new ClusterInfo();
    String clusterSchema = sla.getClusterSchema();
    if (clusterSchema != null) {
        clusterInfo.setSchema(clusterSchema);
        int slaMax = getSLAMax(context);
        int numberOfInstances = Math.max(slaMax, sla.getNumberOfInstances());
        clusterInfo.setNumberOfInstances(numberOfInstances);
    } else {
        clusterInfo.setNumberOfInstances(sla.getNumberOfInstances());
    }
    clusterInfo.setNumberOfBackups(sla.getNumberOfBackups());
    clusterInfo.setInstanceId(instanceId);
    clusterInfo.setBackupId(backupId);
    clusterInfo.setName(puName);

    ClusterInfoParser.guessSchema(clusterInfo);

    logger.info(logMessage("ClusterInfo [" + clusterInfo + "]"));

    MarshalledObject beanLevelPropertiesMarshObj = (MarshalledObject) getServiceBeanContext()
            .getInitParameter("beanLevelProperties");
    BeanLevelProperties beanLevelProperties;
    if (beanLevelPropertiesMarshObj != null) {
        beanLevelProperties = (BeanLevelProperties) beanLevelPropertiesMarshObj.get();
        logger.info(logMessage("BeanLevelProperties " + beanLevelProperties));
    } else {
        beanLevelProperties = new BeanLevelProperties();
    }
    beanLevelProperties.getContextProperties()
            .putAll(ClusterInfoPropertyPlaceholderConfigurer.createProperties(clusterInfo));

    // set a generic work location that can be used by container providers
    File workLocation = new File(SystemInfo.singleton().locations().work());
    workLocation.mkdirs();

    beanLevelProperties.getContextProperties().setProperty("com.gs.work", workLocation.getAbsolutePath());

    boolean downloadPU = false;
    //create PU Container
    ProcessingUnitContainerProvider factory;
    // identify if this is a web app
    final InputStream webXml = openUrlStream(codeserver + puPath + "/WEB-INF/web.xml");
    // identify if this is a .NET one
    final InputStream puConfig = openUrlStream(codeserver + puPath + "/pu.config");
    // identify if this is a .NET interop one
    final InputStream puInteropConfig = openUrlStream(codeserver + puPath + "/pu.interop.config");

    String processingUnitContainerProviderClass;
    if (webXml != null) {
        webXml.close();
        downloadPU = true;
        String jeeContainer = JeeProcessingUnitContainerProvider.getJeeContainer(beanLevelProperties);
        String[] classesToLoad = null;
        if ("jetty".equals(jeeContainer)) {
            // pre load the jetty server class so the static shutdown thread will be loaded under it
            classesToLoad = new String[] { "org.eclipse.jetty.server.Server" };
        }
        // setup class loaders correcly
        try {
            Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
            ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(
                    new String[] { JeeProcessingUnitContainerProvider.getJeeContainerJarPath(jeeContainer) }));
            ((ServiceClassLoader) contextClassLoader)
                    .setParentClassLoader(SharedServiceData.getJeeClassLoader(jeeContainer, classesToLoad));
        } catch (Exception e) {
            throw new CannotCreateContainerException("Failed to configure JEE class loader", e);
        } finally {
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        }

        String className = StringUtils.capitalize(jeeContainer) + "JeeProcessingUnitContainerProvider";
        processingUnitContainerProviderClass = "org.openspaces.pu.container.jee." + jeeContainer + "."
                + className;
    } else if (puConfig != null) {
        puConfig.close();
        downloadPU = true;
        processingUnitContainerProviderClass = DotnetProcessingUnitContainerProvider.class.getName();
    } else if (puInteropConfig != null) {
        puInteropConfig.close();
        downloadPU = true;
        processingUnitContainerProviderClass = IntegratedProcessingUnitContainerProvider.class.getName();
    } else {
        processingUnitContainerProviderClass = IntegratedProcessingUnitContainerProvider.class.getName();
        if (beanLevelProperties.getContextProperties().getProperty("pu.download", "true")
                .equalsIgnoreCase("true")) {
            downloadPU = true;
        }
    }

    if (beanLevelProperties != null) {
        processingUnitContainerProviderClass = beanLevelProperties.getContextProperties().getProperty(
                ProcessingUnitContainerProvider.CONTAINER_CLASS_PROP, processingUnitContainerProviderClass);
    }

    if (downloadPU) {
        String deployName = puName + "_" + clusterInfo.getRunningNumberOffset1();

        String deployedProcessingUnitsLocation = workLocation.getAbsolutePath() + "/processing-units";

        int uuid = Math.abs(new Random().nextInt());

        deployPath = new File(
                deployedProcessingUnitsLocation + "/" + deployName.replace('.', '_') + "_" + uuid);
        FileSystemUtils.deleteRecursively(deployPath);
        deployPath.mkdirs();

        // backward compatible
        beanLevelProperties.getContextProperties().setProperty("jee.deployPath", deployPath.getAbsolutePath());
        beanLevelProperties.getContextProperties().setProperty("dotnet.deployPath",
                deployPath.getAbsolutePath());

        beanLevelProperties.getContextProperties().setProperty(
                ProcessingUnitContainerProvider.CONTEXT_PROPERTY_DEPLOY_PATH, deployPath.getAbsolutePath());

        try {
            if (isOnGsmHost()) {
                copyPu(puPath, deployPath);
            } else {
                long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                        new File(deployedProcessingUnitsLocation));
                logDownloadSize(size);
            }
        } catch (MalformedURLException mle) {
            logger.warn("Could not determine if GSC and GSM are on the same host", mle);
            // fallback to download
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                    new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        } catch (UnknownHostException unhe) {
            logger.warn("Could not determine if GSC and GSM are on the same host", unhe);
            // fallback to download
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                    new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        } catch (RemoteException re) {
            logger.warn("Could not determine if GSC and GSM are on the same host", re);
            // fallback to download
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                    new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        }

        // go over listed files that needs to be resolved with properties
        for (Map.Entry entry : beanLevelProperties.getContextProperties().entrySet()) {
            String key = (String) entry.getKey();
            if (key.startsWith("com.gs.resolvePlaceholder")) {
                String path = (String) entry.getValue();
                File input = new File(deployPath, path);
                if (logger.isDebugEnabled()) {
                    logger.debug("Resolving placeholder for file [" + input.getAbsolutePath() + "]");
                }
                BeanLevelPropertiesUtils.resolvePlaceholders(beanLevelProperties, input);
            }
        }
    }

    boolean sharedLibEnabled;
    if (beanLevelProperties.getContextProperties().containsKey("pu.shared-lib.enable")) {
        sharedLibEnabled = beanLevelProperties.getContextProperties().getProperty("pu.shared-lib")
                .equals("true");
    } else {
        sharedLibEnabled = System.getProperty("com.gs.pu.shared-lib.enable", "false").equals("true");
    }

    final boolean disableManifestClassPathJars = Boolean.getBoolean("com.gs.pu.manifest.classpath.disable");
    final boolean disableManifestClassPathCommonPuJars = Boolean
            .getBoolean("com.gs.pu.manifest.classpath.common.disable");

    // this is used to inject the manifest jars to the webapp classloader (if exists)
    List<URL> manifestClassPathJars = new ArrayList<URL>();

    CommonClassLoader commonClassLoader = CommonClassLoader.getInstance();
    // handles class loader libraries
    if (downloadPU) {
        List<URL> libUrls = new ArrayList<URL>();
        File libDir = new File(deployPath, "lib");
        if (libDir.exists()) {
            File[] libFiles = BootIOUtils.listFiles(libDir);
            for (File libFile : libFiles) {
                libUrls.add(libFile.toURI().toURL());
            }
        }

        if (!disableManifestClassPathJars) {
            File manifestFile = new File(deployPath, JarFile.MANIFEST_NAME);

            if (manifestFile.isFile()) {
                try {
                    InputStream manifestStream = new FileInputStream(manifestFile);
                    manifestClassPathJars = getManifestClassPathJars(puName, manifestStream);
                    libUrls.addAll(manifestClassPathJars);
                } catch (IOException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn(failedReadingManifest(puName), e);
                    }
                }
            }

        }

        // add to common class loader
        List<URL> sharedlibUrls = new ArrayList<URL>();
        File sharedlibDir = new File(deployPath, "shared-lib");
        if (sharedlibDir.exists()) {
            File[] sharedlibFiles = BootIOUtils.listFiles(sharedlibDir);
            for (File sharedlibFile : sharedlibFiles) {
                sharedlibUrls.add(sharedlibFile.toURI().toURL());
            }
        }
        sharedlibDir = new File(deployPath, "WEB-INF/shared-lib");
        if (sharedlibDir.exists()) {
            File[] sharedlibFiles = BootIOUtils.listFiles(sharedlibDir);
            for (File sharedlibFile : sharedlibFiles) {
                sharedlibUrls.add(sharedlibFile.toURI().toURL());
            }
        }

        if (sharedLibEnabled) {
            ((ServiceClassLoader) contextClassLoader).setSlashPath(deployPath.toURI().toURL());
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }

            commonClassLoader.addComponent(puName, sharedlibUrls.toArray(new URL[sharedlibUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Common Class Loader " + sharedlibUrls));
            }
        } else {
            if (sharedlibUrls.size() > 0) {
                logger.warn("Using old 'shared-lib' directory, will add jars under it as if it was 'lib'");
            }
            libUrls.addAll(sharedlibUrls);

            // add pu-common jar files
            String gsLibOpt = Locator.getLibOptional();
            String gsPuCommon = System.getProperty("com.gs.pu-common", gsLibOpt + "pu-common");

            final String gsLibOptSecurity = Locator.getLibOptionalSecurity();
            libUrls.addAll(Arrays.asList(BootUtil.toURLs(new String[] { gsPuCommon, gsLibOptSecurity })));

            if (ScalaIdentifier.isScalaLibInClassPath()) {
                String gsLibPlatform = Locator.getLibPlatform();
                // note that we assume BootUtil.toURLs does not work recursively here
                // i.e, only gs-openspaces-scala.jar will be added and not all the files under /lib
                String gsLibPlatformScala = gsLibPlatform + "scala";
                libUrls.addAll(Arrays.asList(BootUtil.toURLs(new String[] { gsLibPlatformScala })));
            }

            if (!disableManifestClassPathJars && !disableManifestClassPathCommonPuJars) {
                URLClassLoader urlClassLoader = new URLClassLoader(BootUtil.toURLs(new String[] { gsPuCommon }),
                        null /* parent */);
                InputStream puCommonManifestMF = urlClassLoader.getResourceAsStream(JarFile.MANIFEST_NAME);
                if (puCommonManifestMF != null) {
                    List<URL> manifestClassPathComonPuJars = getManifestClassPathJars(puName,
                            puCommonManifestMF);
                    manifestClassPathJars.addAll(manifestClassPathComonPuJars);
                    libUrls.addAll(manifestClassPathComonPuJars);
                }
            }

            ((ServiceClassLoader) contextClassLoader).setSlashPath(deployPath.toURI().toURL());
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }
        }
        try {
            prepareWebApplication(deployPath, clusterInfo, beanLevelProperties);
        } catch (Exception e) {
            throw new CannotCreateContainerException("Failed to bootstrap web application", e);
        }
    } else {
        // add to service class loader
        List<URL> libUrls = new ArrayList<URL>();
        WebsterFile libDir = new WebsterFile(new URL(codeserver + puPath + "/lib"));
        File[] libFiles = libDir.listFiles();
        for (int i = 0; i < libFiles.length; i++) {
            libUrls.add(new URL(codeserver + puPath + "/lib/" + libFiles[i].getName()));
        }

        if (!disableManifestClassPathJars) {
            InputStream manifestStream = readManifestFromCodeServer(puName, puPath, codeserver, workLocation);
            if (manifestStream != null) {
                manifestClassPathJars = getManifestClassPathJars(puName, manifestStream);
                libUrls.addAll(manifestClassPathJars);
            }
        }

        // add to common class loader
        WebsterFile sharedlibDir = new WebsterFile(new URL(codeserver + puPath + "/shared-lib"));
        File[] sharedlibFiles = sharedlibDir.listFiles();
        List<URL> sharedlibUrls = new ArrayList<URL>();
        for (File sharedlibFile : sharedlibFiles) {
            sharedlibUrls.add(new URL(codeserver + puPath + "/shared-lib/" + sharedlibFile.getName()));
        }
        sharedlibDir = new WebsterFile(new URL(codeserver + puPath + "/WEB-INF/shared-lib"));
        sharedlibFiles = sharedlibDir.listFiles();
        for (File sharedlibFile : sharedlibFiles) {
            sharedlibUrls.add(new URL(codeserver + puPath + "/WEB-INF/shared-lib/" + sharedlibFile.getName()));
        }

        if (sharedLibEnabled) {
            ((ServiceClassLoader) contextClassLoader).setSlashPath(new URL(codeserver + puPath + "/"));
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }

            commonClassLoader.addComponent(puName, sharedlibUrls.toArray(new URL[sharedlibUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Common Class Loader " + sharedlibUrls));
            }
        } else {
            if (sharedlibUrls.size() > 0) {
                logger.warn("Using old 'shared-lib' directory, will add jars under it as if it was 'lib'");
            }
            libUrls.addAll(sharedlibUrls);
            ((ServiceClassLoader) contextClassLoader).setSlashPath(new URL(codeserver + puPath + "/"));
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }
        }
    }

    // handle mule os if there is one class loader
    try {
        contextClassLoader.loadClass("org.mule.api.MuleContext");
        ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] {
                SystemInfo.singleton().locations().lib() + "/optional/openspaces/mule-os.jar" }));
    } catch (Throwable e) {
        // no mule
    }

    //apply the following only if the pu has the rest element
    if (springXml.contains("<os-core:rest")) {
        String jeeContainer = JeeProcessingUnitContainerProvider.getJeeContainer(beanLevelProperties);
        // pre load the jetty server class so the static shutdown thread will be loaded under it

        String[] classesToLoad = new String[] { "org.eclipse.jetty.server.Server" };
        String jettyJars = System.getProperty("com.gigaspaces.rest.jetty",
                JeeProcessingUnitContainerProvider.getJeeContainerJarPath(jeeContainer));
        // setup class loaders correctly
        try {
            Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
            ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { jettyJars,
                    SystemInfo.singleton().locations().lib()
                            + "/platform/jetty/org.apache.jasper.glassfish-2.2.2.v201112011158.jar",
                    SystemInfo.singleton().locations().lib() + "/optional/spring/spring-web-4.1.1.RELEASE.jar",
                    SystemInfo.singleton().locations().lib()
                            + "/optional/spring/spring-webmvc-4.1.1.RELEASE.jar",
                    SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-core-2.3.0.jar",
                    SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-databind-2.3.0.jar",
                    SystemInfo.singleton().locations().lib()
                            + "/optional/jackson/jackson-annotations-2.3.0.jar",
                    SystemInfo.singleton().locations().lib() + "/platform/rest/xap-rest.jar" }));
            ((ServiceClassLoader) contextClassLoader)
                    .setParentClassLoader(SharedServiceData.getJeeClassLoader(jeeContainer, classesToLoad));
        } catch (Exception e) {
            throw new CannotCreateContainerException("Failed to configure class loader", e);
        } finally {
            //TODO check if we need this
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        }
    }

    //apply the following only if the pu has the mapdb-blob-store element
    if (springXml.contains("<blob-store:mapdb-blob-store")) {
        String mapdbJar = System.getProperty("com.gigaspaces.blobstore.mapdb",
                SystemInfo.singleton().locations().lib() + "/optional/blobstore/mapdb-blobstore.jar");

        Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
        ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { mapdbJar }));
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }

    //apply the following only if the pu has the rocksdb-blob-store element
    if (springXml.contains("<blob-store:rocksdb-blob-store")
            || springXml.contains("class=\"com.gigaspaces.blobstore.rocksdb.RocksDBBlobStoreHandler\"")) {
        String rocksdbJar = System.getProperty("com.gigaspaces.blobstore.rocksdb",
                SystemInfo.singleton().locations().lib() + "/optional/blobstore/rocksdb-blobstore.jar");

        Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
        ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { rocksdbJar }));
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }

    final Map<String, String> puTags = buildPuTags(clusterInfo);
    MetricRegistrator puMetricRegistrator = metricManager.createRegistrator("pu", puTags);
    this.metricRegistrators = metricManager.registerProcessMetrics(puTags);
    this.metricRegistrators.add(puMetricRegistrator);
    for (Map.Entry<String, String> entry : puTags.entrySet())
        beanLevelProperties.getContextProperties().setProperty("metrics." + entry.getKey(), entry.getValue());
    //inject quiesce state changed event in order let space know to be initialized in quiesced mode
    if (quiesceDetails != null && quiesceDetails.getStatus() == QuiesceState.QUIESCED) {
        beanLevelProperties.getContextProperties().setProperty("quiesce.token",
                quiesceDetails.getToken().toString());
        beanLevelProperties.getContextProperties().setProperty("quiesce.description",
                quiesceDetails.getDescription());
    }
    factory = createContainerProvider(processingUnitContainerProviderClass);
    factory.setDeployPath(deployPath);
    factory.setClassLoader(contextClassLoader);
    factory.setManifestUrls(manifestClassPathJars);

    // only load the spring xml file if it is not a web application (if it is a web application, we will load it with the Bootstrap servlet context loader)
    if (webXml == null && factory instanceof ApplicationContextProcessingUnitContainerProvider) {
        if (StringUtils.hasText(springXml)) {
            // GS-9350: if this is a processing unit with gateway declarations, always try to
            // re-load the pu.xml to support "hot-deploy" (refresh)
            if (springXml.contains("os-gateway:")) {
                String deployPath = beanLevelProperties.getContextProperties().getProperty("deployPath");
                if (StringUtils.hasText(deployPath)) {
                    String newSpringXml = readFile(deployPath + "/META-INF/spring/pu.xml");
                    if (StringUtils.hasText(newSpringXml)) {
                        springXml = newSpringXml; //override with new one
                    }
                }
            }
            Resource resource = new ByteArrayResource(springXml.getBytes());
            ((ApplicationContextProcessingUnitContainerProvider) factory).addConfigLocation(resource);
        }
    }
    factory.setClusterInfo(clusterInfo);
    factory.setBeanLevelProperties(beanLevelProperties);
    factory.setMetricRegistrator(puMetricRegistrator);

    container = factory.createContainer();

    // set the context class loader to the web app class loader if there is one
    // this menas that from now on, and the exported service, will use the context class loader
    ClassLoader webAppClassLoader = SharedServiceData.removeWebAppClassLoader(clusterInfo.getUniqueName());
    if (webAppClassLoader != null) {
        contextClassLoader = webAppClassLoader;
    }
    Thread.currentThread().setContextClassLoader(contextClassLoader);

    buildMembersAliveIndicators();
    buildUndeployingEventListeners();
    buildDumpProcessors();

    ArrayList<Object> serviceDetails = buildServiceDetails();

    buildServiceMonitors();

    buildInvocableServices();

    this.puDetails = new PUDetails(context.getParentServiceID(), clusterInfo, beanLevelProperties,
            serviceDetails.toArray(new Object[serviceDetails.size()]));

    if (container instanceof ApplicationContextProcessingUnitContainer) {
        ApplicationContext applicationContext = ((ApplicationContextProcessingUnitContainer) container)
                .getApplicationContext();

        // inject the application context to all the monitors and schedule them
        // currently use the number of threads in relation to the number of monitors
        int numberOfThreads = watchTasks.size() / 5;
        if (numberOfThreads == 0) {
            numberOfThreads = 1;
        }
        executorService = Executors.newScheduledThreadPool(numberOfThreads);
        for (WatchTask watchTask : watchTasks) {
            if (watchTask.getMonitor() instanceof ApplicationContextMonitor) {
                ((ApplicationContextMonitor) watchTask.getMonitor()).setApplicationContext(applicationContext);
            }
            executorService.scheduleAtFixedRate(watchTask, watchTask.getMonitor().getPeriod(),
                    watchTask.getMonitor().getPeriod(), TimeUnit.MILLISECONDS);
        }
    }
}

From source file:edu.umass.cs.gigapaxos.PaxosManager.java

/**
 * This test method is deprecated and will either be removed or
 * significantly revamped. Use TESTPaxosMain instead to run a single machine
 * test with multiple virtual nodes./*from  w w w  .java 2 s.c o  m*/
 * 
 * @param args
 * @throws InterruptedException
 * @throws IOException
 * @throws JSONException
 */
@Deprecated
static void test(String[] args) throws InterruptedException, IOException, JSONException {
    int[] members = TESTPaxosConfig.getDefaultGroup();
    int numNodes = members.length;

    SampleNodeConfig<Integer> snc = new SampleNodeConfig<Integer>(2000);
    snc.localSetup(Util.arrayToIntSet(members));

    @SuppressWarnings("unchecked")
    PaxosManager<Integer>[] pms = new PaxosManager[numNodes];
    TESTPaxosApp[] apps = new TESTPaxosApp[numNodes];

    /* We always test with the first member crashed. This also ensures that
     * the system is fault-tolerant to the failure of the default
     * coordinator, which in our policy is the first (or lowest numbered)
     * node. */
    TESTPaxosConfig.crash(members[0]);
    /* We disable sending replies to client in PaxosManager's unit-test. To
     * test with clients, we rely on other tests in TESTPaxosMain
     * (single-machine) or on TESTPaxosNode and TESTPaxosClient for
     * distributed testing. */
    TESTPaxosConfig.setSendReplyToClient(false);

    /* This setting is "guilty until proven innocent", i.e., each node will
     * start out assuming that all other nodes are dead. This is probably
     * too pessimistic as it will cause every node to run for coordinator
     * when it starts up but is good for testing. */
    FailureDetection.setParanoid();

    // Set up paxos managers and apps with nio
    for (int i = 0; i < numNodes; i++) {
        System.out.println("Initiating PaxosManager at node " + members[i]);
        JSONNIOTransport<Integer> niot = new JSONNIOTransport<Integer>(members[i], snc,
                new PacketDemultiplexerDefault(), true);
        apps[i] = new TESTPaxosApp(niot); // app, PM reuse nio
        pms[i] = new PaxosManager<Integer>(members[i], snc, niot, apps[i]);
    }

    System.out.println("Initiated all " + numNodes + " paxos managers with failure detectors..\n");

    /* We don't rigorously test with multiple groups as they are
     * independent, but this is useful for memory testing. */
    int numPaxosGroups = 2;
    String[] names = new String[numPaxosGroups];
    for (int i = 0; i < names.length; i++)
        names[i] = "paxos" + i;

    System.out.println("Creating " + numPaxosGroups + " paxos groups each with " + numNodes
            + " members each, one each at each of the " + numNodes + " nodes");
    for (int node = 0; node < numNodes; node++) {
        int k = 1;
        for (int group = 0; group < numPaxosGroups; group++) {
            // creating a paxos instance may induce recovery from disk
            pms[node].createPaxosInstance(names[group], 0, Util.arrayToIntSet(members), apps[node], null, null,
                    false);
            if (numPaxosGroups > 1000 && ((group % k == 0 && ((k *= 2) > 0)) || group % 100000 == 0)) {
                System.out.print(group + " ");
            }
        }
        System.out.println("..node" + members[node] + " done");
    }
    Thread.sleep(1000);

    /* Wait for all paxos managers to finish recovery. Recovery is finished
     * when initiateRecovery() is complete. At this point, all the paxos
     * groups at that node would have also rolled forward. */
    int maxRecoverySlot = -1;
    int maxRecoveredNode = -1;
    for (int i = 0; i < numNodes; i++) {
        while (!TESTPaxosConfig.isCrashed(members[i]) && !TESTPaxosConfig.getRecovered(members[i], names[0])) {
            log.info("Waiting for node " + members[i] + " to recover ");
            pms[i].waitToRecover();
        }
        log.info("Node" + members[i] + " finished recovery including rollback;\n" + names[0]
                + " recovered at slot " + apps[i].getNumCommitted(names[0]));
        // need max recovery slot for names[0] below
        maxRecoverySlot = Math.max(maxRecoverySlot, apps[i].getNumCommitted(names[0]));
        maxRecoveredNode = i;
    }

    System.out.println("all nodes done creating groups.");

    /*********** Finished creating paxos instances for testing *****************/

    /************* Begin ClientRequestTask **************************/
    ScheduledExecutorService execpool = Executors.newScheduledThreadPool(5);
    class ClientRequestTask implements Runnable {
        private final RequestPacket request;
        private final PaxosManager<Integer> paxosManager;

        ClientRequestTask(RequestPacket req, PaxosManager<Integer> pm) {
            request = req;
            paxosManager = pm;
        }

        public void run() {
            try {
                JSONObject reqJson = request.toJSONObject();
                JSONPacket.putPacketType(reqJson, PaxosPacketType.PAXOS_PACKET.getInt());
                paxosManager.propose(request.getPaxosID(), request, null);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    /************* End ClientRequestTask **************************/

    /* Create and schedule requests. All requests are scheduled immediately
     * to test concurrency */
    int numRequests = 1000;
    RequestPacket[] reqs = new RequestPacket[numRequests];
    ScheduledFuture<?>[] futures = new ScheduledFuture[numRequests];
    int numExceptions = 0;
    double scheduledDelay = 0;
    for (int i = 0; i < numRequests; i++) {
        reqs[i] = new RequestPacket(i, "[ Sample write request numbered " + i + " ]", false);
        reqs[i].putPaxosID(names[0], 0);
        JSONObject reqJson = reqs[i].toJSONObject();
        JSONPacket.putPacketType(reqJson, PaxosPacketType.PAXOS_PACKET.getInt());
        try {
            ClientRequestTask crtask = new ClientRequestTask(reqs[i], pms[1]);
            futures[i] = (ScheduledFuture<?>) execpool.schedule(crtask, (long) scheduledDelay,
                    TimeUnit.MILLISECONDS);
            scheduledDelay += 0;
        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }
    }
    /* Any exceptions below could occur because of exceptions inside paxos.
     * Scheduling a request will invoke PaxosManager.propose() that will
     * cause it to send the request to the corresponding
     * PaxosInstanceStateMachine. */
    log.info("Waiting for request scheduling to complete.");
    for (int i = 0; i < numRequests; i++) {
        try {
            futures[i].get();
        } catch (Exception e) {
            e.printStackTrace();
            numExceptions++;
        }
    }
    log.info("Request scheduling complete; numExceptions=" + numExceptions);
    Thread.sleep(1000);

    /* Wait for scheduled requests to finish being processed by paxos. We
     * check for this by checking that at least one node has executed up to
     * the slot number maxRecoverySlot + numRequests. */
    while (apps[maxRecoveredNode].getNumCommitted(names[0]) < maxRecoverySlot + numRequests) {
        apps[maxRecoveredNode].waitToFinish();
        ;
    }
    log.info("Node" + maxRecoveredNode + " has executed up to slot " + (maxRecoverySlot + numRequests));

    /* The code below waits for all uncrashed replicas to finish executing
     * up to the same slot and will then assert the SMR invariant, i.e.,
     * they all made the same state transitions up to that slot. */
    int numCommitted = 0;
    for (int i = 0; i < numNodes; i++) {
        for (int j = i + 1; j < numNodes; j++) {
            if (TESTPaxosConfig.isCrashed(members[i]) || TESTPaxosConfig.isCrashed(members[j]))
                continue; // ignore crashed nodes

            int committed1 = apps[i].getNumCommitted(names[0]);
            int committed2 = apps[j].getNumCommitted(names[0]);
            // Wait for the other node to catch up
            while (committed1 != committed2) {
                if (committed1 > committed2)
                    apps[j].waitToFinish(names[0], committed1);
                else if (committed1 < committed2)
                    apps[i].waitToFinish(names[0], committed2);
                log.info("Waiting : (slot1,hash1)=(" + committed1 + "," + apps[i].getHash(names[0])
                        + "(; (slot2,hash2=" + committed2 + "," + apps[j].getHash(names[0]) + ")");
                Thread.sleep(1000);
                committed1 = apps[i].getNumCommitted(names[0]);
                committed2 = apps[j].getNumCommitted(names[0]);
            }
            // Both nodes caught up to the same slot
            assert (committed1 == committed2) : "numCommitted@" + i + "=" + committed1 + ", numCommitted@" + j
                    + "=" + committed2;
            // Assert state machine replication invariant
            numCommitted = apps[i].getNumCommitted(names[0]);
            assert (apps[i].getHash(names[0]) == apps[j].getHash(names[0])) : ("Waiting : (slot1,hash1)=("
                    + committed1 + "," + apps[i].getHash(names[0]) + "(; (slot2,hash2=" + committed2 + ","
                    + apps[j].getHash(names[0]) + ")");
            ; // end of SMR invariant
        }
    }

    /* Print preempted requests if any. These could happen during
     * coordinator changes. Preempted requests are converted to no-ops and
     * forwarded to the current presumed coordinator by paxos. */
    String preemptedReqs = "[ ";
    int numPreempted = 0;
    for (int i = 0; i < numRequests; i++) {
        if (!TESTPaxosConfig.isCommitted(reqs[i].requestID)) {
            preemptedReqs += (i + " ");
            numPreempted++;
        }
    }
    preemptedReqs += "]";

    System.out.println("\n\nTest completed. Executed " + numCommitted + " requests consistently including "
            + (numRequests - numPreempted) + " of " + numRequests + " received requests;\nPreempted requests = "
            + preemptedReqs + "; numExceptions=" + numExceptions + "; average message log time="
            + Util.df(DelayProfiler.get("logDelay")) + "ms.\n"
            + "\nNote that it is possible for the test to be successful even if the number of consistently\n"
            + "executed requests is less than the number of received requests as paxos only guarantees\n"
            + "consistency, i.e., that all replicas executed requests in the same order, not that all requests\n"
            + "issued will get executed. The latter property can be achieved by clients reissuing requests\n"
            + "until successfully executed. With reissuals, clients do need to worry about double execution,\n"
            + "so they should be careful. A client is not guaranteed to get a failure message if the request fails,\n"
            + "e.g., if the replica receiving a request dies immediately. If the client uses a timeout to detect\n"
            + "failure and thereupon reissue its request, it is possible that both the original and re-issued\n"
            + "requests are executed. Clients can get around this problem by using sequence numbers within\n"
            + "their app, reading the current sequence number, and then trying to commit their write provided the\n"
            + "sequence number has not changed in the meantime. There are other alternatives, but all of these\n"
            + "are application-specific; they are not paxos's problem\n");
    for (int i = 0; i < numNodes; i++) {
        System.out.println(pms[i].printLog(names[0]));
    }
    execpool.shutdownNow();
    for (PaxosManager<Integer> pm : pms)
        pm.close();
}