Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

In this page you can find the example usage for java.lang ProcessBuilder start.

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:azkaban.execapp.AzkabanExecutorServer.java

/**
 * Azkaban using Jetty//from   w  w w  . ja va 2  s  .co m
 *
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws Exception {
    // Redirect all std out and err messages into log4j
    StdOutErrRedirect.redirectOutAndErrToLog();

    logger.info("Starting Jetty Azkaban Executor...");
    Props azkabanSettings = AzkabanServer.loadProps(args);

    if (azkabanSettings == null) {
        logger.error("Azkaban Properties not loaded.");
        logger.error("Exiting Azkaban Executor Server...");
        return;
    }

    // Setup time zone
    if (azkabanSettings.containsKey(DEFAULT_TIMEZONE_ID)) {
        String timezone = azkabanSettings.getString(DEFAULT_TIMEZONE_ID);
        System.setProperty("user.timezone", timezone);
        TimeZone.setDefault(TimeZone.getTimeZone(timezone));
        DateTimeZone.setDefault(DateTimeZone.forID(timezone));

        logger.info("Setting timezone to " + timezone);
    }

    app = new AzkabanExecutorServer(azkabanSettings);

    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            try {
                logTopMemoryConsumers();
            } catch (Exception e) {
                logger.info(("Exception when logging top memory consumers"), e);
            }

            String host = app.getHost();
            int port = app.getPort();
            try {
                logger.info(String.format("Removing executor(host: %s, port: %s) entry from database...", host,
                        port));
                app.getExecutorLoader().removeExecutor(host, port);
            } catch (ExecutorManagerException ex) {
                logger.error(String.format("Exception when removing executor(host: %s, port: %s)", host, port),
                        ex);
            }

            logger.warn("Shutting down executor...");
            try {
                app.shutdownNow();
            } catch (Exception e) {
                logger.error("Error while shutting down http server.", e);
            }
        }

        public void logTopMemoryConsumers() throws Exception, IOException {
            if (new File("/bin/bash").exists() && new File("/bin/ps").exists()
                    && new File("/usr/bin/head").exists()) {
                logger.info("logging top memeory consumer");

                java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder("/bin/bash", "-c",
                        "/bin/ps aux --sort -rss | /usr/bin/head");
                Process p = processBuilder.start();
                p.waitFor();

                InputStream is = p.getInputStream();
                java.io.BufferedReader reader = new java.io.BufferedReader(new InputStreamReader(is));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    logger.info(line);
                }
                is.close();
            }
        }
    });
}

From source file:de.prozesskraft.pkraft.Startinstance.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file/*from  w  ww . j  a  v a 2s  .  com*/
    ----------------------------*/
    java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Startinstance.class) + "/"
            + "../etc/pkraft-startinstance.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option obasedir = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[optional, default .] base directory where instance shourd run.")
            //            .isRequired()
            .create("basedir");

    Option odefinition = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[optional] definition file of the process you want to start an instance from.")
            //            .isRequired()
            .create("definition");

    Option onostart = OptionBuilder.withArgName("")
            //            .hasArg()
            .withDescription(
                    "[optional] oppresses the start of the instance. (only create the process-instance)")
            //            .isRequired()
            .create("nostart");

    Option opdomain = OptionBuilder.withArgName("STRING").hasArg()
            .withDescription("[optional] domain of the process (mandatory if you omit -definition)")
            //            .isRequired()
            .create("pdomain");

    Option opname = OptionBuilder.withArgName("STRING").hasArg().withDescription(
            "[optional] name of the process you want to start an instance from (mandatory if you omit -definition)")
            //            .isRequired()
            .create("pname");

    Option opversion = OptionBuilder.withArgName("STRING").hasArg().withDescription(
            "[optional] version of the process you want to start an instance from (mandatory if you omit -definition)")
            //            .isRequired()
            .create("pversion");

    Option ocommitfile = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg()
            .withDescription("[optional] this file will be committed as file. omit KEY= if KEY==FILENAME.")
            //            .isRequired()
            .create("commitfile");

    Option ocommitvariable = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg()
            .withDescription("[optional] this string will be committed as a variable. omit KEY= if KEY==VALUE")
            //            .isRequired()
            .create("commitvariable");

    Option ocommitfiledummy = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg().withDescription(
            "[optional] use this parameter like --commitfile. the file will not be checked against the process interface and therefore allows to commit files which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output files for accelerated tests of complex processes or the like.")
            //            .isRequired()
            .create("commitfiledummy");

    Option ocommitvariabledummy = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg().withDescription(
            "[optional] use this parameter like --commitvariable. the variable will not be checked against the process interface and therefore allows to commit variables which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output variables for accelerated tests of complex processes or the like.")
            //            .isRequired()
            .create("commitvariabledummy");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(obasedir);
    options.addOption(odefinition);
    options.addOption(onostart);
    options.addOption(opname);
    options.addOption(opversion);
    options.addOption(ocommitfile);
    options.addOption(ocommitvariable);
    options.addOption(ocommitfiledummy);
    options.addOption(ocommitvariabledummy);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("startinstance", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition")) && (!(commandline.hasOption("pname"))
            || !(commandline.hasOption("pversion")) || !(commandline.hasOption("pdomain")))) {
        System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory");
        exiter();
    }

    if ((commandline.hasOption("definition") && ((commandline.hasOption("pversion"))
            || (commandline.hasOption("pname")) || (commandline.hasOption("pdomain"))))) {
        System.err.println("you must not use option -definition with -pversion or -pname or -pdomain");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    Process p1 = new Process();
    String pathToDefinition = "";

    if (commandline.hasOption("definition")) {
        pathToDefinition = commandline.getOptionValue("definition");
    } else if (commandline.hasOption("pname") && commandline.hasOption("pversion")
            && commandline.hasOption("pdomain")) {
        pathToDefinition.replaceAll("/+$", "");
        pathToDefinition = ini.get("process", "domain-installation-directory") + "/"
                + commandline.getOptionValue("pdomain") + "/" + commandline.getOptionValue("pname") + "/"
                + commandline.getOptionValue("pversion") + "/process.xml";
    } else {
        System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory");
        exiter();
    }

    // check ob das ermittelte oder uebergebene xml-file ueberhaupt existiert
    java.io.File xmlDefinition = new java.io.File(pathToDefinition);
    if (!(xmlDefinition.exists()) || !(xmlDefinition.isFile())) {
        System.err.println("process definition does not exist: " + pathToDefinition);
        exiter();
    }

    p1.setInfilexml(xmlDefinition.getCanonicalPath());
    Process p2 = null;

    try {
        p2 = p1.readXml();
    } catch (JAXBException e1) {
        System.err.println(e1.getMessage());
    }

    // das processBinary vorneweg schon mal erstellen, da es sein kann das das committen laenger dauert und ein pradar-attend den neuen prozess schon mal aufnehmen will
    // root-verzeichnis erstellen
    if (commandline.hasOption("basedir")) {
        p2.setBaseDir(commandline.getOptionValue("basedir"));
    }

    p2.makeRootdir();

    // den pfad fuers binary setzen
    p2.setOutfilebinary(p2.getRootdir() + "/process.pmb");

    System.err.println("info: writing process instance " + p2.getOutfilebinary());

    // binary schreiben
    p2.writeBinary();

    // step, an den die commits gehen, soll 'root' sein.
    Step stepRoot = p2.getRootStep();

    // committen von files (ueber einen glob)
    if (commandline.hasOption("commitfile")) {
        for (String actOptionCommitfile : commandline.getOptionValues("commitfile")) {
            String[] parts = actOptionCommitfile.split("=");
            File userFile = new File();

            if (parts.length == 1) {
                userFile.setKey(new java.io.File(parts[0]).getName());
                userFile.setGlob(parts[0]);
            } else if (parts.length == 2) {
                userFile.setKey(parts[0]);
                userFile.setGlob(parts[1]);
            } else {
                System.err.println("error in option -commitfile " + actOptionCommitfile);
                exiter();
            }

            // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden
            // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen
            for (Commit actCommit : stepRoot.getCommit()) {
                // alle files des aktuellen commits
                for (File actFile : actCommit.getFile()) {
                    if (actFile.getKey().equals(userFile.getKey())) {
                        // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden
                        if (actFile.getGlob() != null) {
                            // wenn die maximale erlaubte anzahl noch nicht erreicht ist
                            if (actCommit.getFile(actFile.getKey()).size() < actFile.getMaxoccur()) {
                                File newFile = actFile.clone();
                                newFile.setGlob(userFile.getGlob());
                                System.err.println("entering file into commit '" + actCommit.getName() + "' ("
                                        + newFile.getKey() + "=" + newFile.getGlob() + ")");
                                actCommit.addFile(newFile);
                                break;
                            } else {
                                System.err.println("fatal: you only may commit " + actFile.getMaxoccur() + " "
                                        + actFile.getKey() + "-files into commit " + actCommit.getName());
                                exiter();
                            }
                        }
                        // ansonsten das bereits vorhandene file im commit mit den daten befuellen
                        else {
                            actFile.setGlob(userFile.getGlob());
                            actFile.setGlobdir(p2.getBaseDir());
                            System.err.println("entering file into commit '" + actCommit.getName() + "' ("
                                    + actFile.getKey() + "=" + actFile.getGlob() + ")");
                            break;
                        }
                    }
                }
            }
        }
    }

    // committen von files (ueber einen glob)
    if (commandline.hasOption("commitfiledummy")) {
        // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit
        Commit commitFiledummy = new Commit();
        commitFiledummy.setName("fileDummy");
        stepRoot.addCommit(commitFiledummy);

        for (String actOptionCommitfiledummy : commandline.getOptionValues("commitfiledummy")) {
            String[] parts = actOptionCommitfiledummy.split("=");
            File userFile = new File();
            commitFiledummy.addFile(userFile);

            if (parts.length == 1) {
                userFile.setKey(new java.io.File(parts[0]).getName());
                userFile.setGlob(parts[0]);
            } else if (parts.length == 2) {
                userFile.setKey(parts[0]);
                userFile.setGlob(parts[1]);
            } else {
                System.err.println("error in option -commitfiledummy " + actOptionCommitfiledummy);
                exiter();
            }
            userFile.setGlobdir(p2.getBaseDir());
            System.err.println("entering (dummy-)file into commit '" + commitFiledummy.getName() + "' ("
                    + userFile.getKey() + "=" + userFile.getGlob() + ")");
        }
    }

    if (commandline.hasOption("commitvariable")) {
        for (String actOptionCommitvariable : commandline.getOptionValues("commitvariable")) {
            if (actOptionCommitvariable.matches(".+=.+")) {
                String[] parts = actOptionCommitvariable.split("=");
                Variable userVariable = new Variable();

                if (parts.length == 1) {
                    userVariable.setKey("default");
                    userVariable.setValue(parts[0]);
                } else if (parts.length == 2) {
                    userVariable.setKey(parts[0]);
                    userVariable.setValue(parts[1]);
                } else {
                    System.err.println("error in option -commitvariable");
                    exiter();
                }
                //                  commit.addVariable(variable);

                // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden
                // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen
                for (Commit actCommit : stepRoot.getCommit()) {
                    // alle files des aktuellen commits
                    for (Variable actVariable : actCommit.getVariable()) {
                        if (actVariable.getKey().equals(userVariable.getKey())) {
                            // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden
                            if (actVariable.getGlob() != null) {
                                // wenn die maximale erlaubte anzahl noch nicht erreicht ist
                                if (actCommit.getVariable(actVariable.getKey()).size() < actVariable
                                        .getMaxoccur()) {
                                    Variable newVariable = actVariable.clone();
                                    newVariable.setValue(userVariable.getValue());
                                    System.err.println("entering variable into commit '" + actCommit.getName()
                                            + "' (" + newVariable.getKey() + "=" + newVariable.getValue()
                                            + ")");
                                    actCommit.addVariable(newVariable);
                                    break;
                                } else {
                                    System.err.println("fatal: you only may commit " + actVariable.getMaxoccur()
                                            + " " + actVariable.getKey() + "-variable(s) into commit "
                                            + actCommit.getName());
                                    exiter();
                                }
                            }
                            // ansonsten das bereits vorhandene file im commit mit den daten befuellen
                            else {
                                actVariable.setValue(userVariable.getValue());
                                System.err.println("entering variable into commit '" + actCommit.getName()
                                        + "' (" + actVariable.getKey() + "=" + actVariable.getValue() + ")");
                                break;
                            }
                        }
                    }
                }
            } else {
                System.err.println("-commitvariable " + actOptionCommitvariable
                        + " does not match pattern \"NAME=VALUE\".");
                exiter();
            }

        }
    }

    if (commandline.hasOption("commitvariabledummy")) {
        // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit
        Commit commitVariabledummy = new Commit();
        commitVariabledummy.setName("variableDummy");
        stepRoot.addCommit(commitVariabledummy);

        for (String actOptionCommitvariabledummy : commandline.getOptionValues("commitvariabledummy")) {
            String[] parts = actOptionCommitvariabledummy.split("=");
            Variable userVariable = new Variable();
            commitVariabledummy.addVariable(userVariable);

            if (parts.length == 1) {
                userVariable.setKey(parts[0]);
                userVariable.setValue(parts[0]);
            } else if (parts.length == 2) {
                userVariable.setKey(parts[0]);
                userVariable.setValue(parts[1]);
            } else {
                System.err.println("error in option -commitvariabledummy");
                exiter();
            }

            System.err.println("entering variable into commit '" + commitVariabledummy.getName() + "' ("
                    + userVariable.getKey() + "=" + userVariable.getValue() + ")");
        }
    }

    //      if (commandline.hasOption("basedir"))
    //      {
    //         p2.setBaseDir(commandline.getOptionValue("basedir"));
    //      }

    //         commit.doIt();
    stepRoot.commit();

    // root-verzeichnis erstellen
    p2.makeRootdir();

    // den pfad fuers binary setzen
    //      p2.setOutfilebinary(p2.getRootdir() + "/process.pmb");

    System.err.println("info: writing process instance " + p2.getOutfilebinary());

    // binary schreiben
    p2.writeBinary();

    try {
        Thread.sleep(1500, 0);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //         Runtime.getRuntime().exec("process-manager -help");

    // starten nur, falls es nicht abgewaehlt wurde
    if (!commandline.hasOption("nostart")) {
        System.err.println("info: starting processmanager for instance " + p2.getOutfilebinary());
        String aufrufString = ini.get("apps", "pkraft-manager") + " -instance " + p2.getOutfilebinary();
        System.err.println("calling: " + aufrufString);

        ArrayList<String> processSyscallWithArgs = new ArrayList<String>(
                Arrays.asList(aufrufString.split(" ")));

        ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs);

        //      ProcessBuilder pb = new ProcessBuilder("processmanager -instance "+p2.getOutfilebinary());
        //      Map<String,String> env = pb.environment();
        //      String path = env.get("PATH");
        //      System.out.println("PATH: "+path);
        //      
        java.lang.Process p = pb.start();
        System.err.println("pid: " + p.hashCode());
    } else {
        System.err.println("info: NOT starting processmanager for instance " + p2.getOutfilebinary());
    }

}

From source file:azkaban.webapp.AzkabanWebServer.java

/**
 * Azkaban using Jetty/*from  w  w w.  j a  v  a2  s .c  o m*/
 *
 * @param args
 */
public static void main(String[] args) throws Exception {
    logger.info("Starting Jetty Azkaban Web Server...");
    Props azkabanSettings = AzkabanServer.loadProps(args);

    if (azkabanSettings == null) {
        logger.error("Azkaban Properties not loaded.");
        logger.error("Exiting Azkaban...");
        return;
    }

    int maxThreads = azkabanSettings.getInt("jetty.maxThreads", DEFAULT_THREAD_NUMBER);
    boolean isStatsOn = azkabanSettings.getBoolean("jetty.connector.stats", true);
    logger.info("Setting up connector with stats on: " + isStatsOn);

    boolean ssl;
    int port;
    final Server server = new Server();
    if (azkabanSettings.getBoolean("jetty.use.ssl", true)) {
        int sslPortNumber = azkabanSettings.getInt("jetty.ssl.port", DEFAULT_SSL_PORT_NUMBER);
        port = sslPortNumber;
        ssl = true;
        logger.info(
                "Setting up Jetty Https Server with port:" + sslPortNumber + " and numThreads:" + maxThreads);

        SslSocketConnector secureConnector = new SslSocketConnector();
        secureConnector.setPort(sslPortNumber);
        secureConnector.setKeystore(azkabanSettings.getString("jetty.keystore"));
        secureConnector.setPassword(azkabanSettings.getString("jetty.password"));
        secureConnector.setKeyPassword(azkabanSettings.getString("jetty.keypassword"));
        secureConnector.setTruststore(azkabanSettings.getString("jetty.truststore"));
        secureConnector.setTrustPassword(azkabanSettings.getString("jetty.trustpassword"));
        secureConnector.setHeaderBufferSize(MAX_HEADER_BUFFER_SIZE);

        // set up vulnerable cipher suites to exclude
        List<String> cipherSuitesToExclude = azkabanSettings.getStringList("jetty.excludeCipherSuites");
        logger.info("Excluded Cipher Suites: " + String.valueOf(cipherSuitesToExclude));
        if (cipherSuitesToExclude != null && !cipherSuitesToExclude.isEmpty()) {
            secureConnector.setExcludeCipherSuites(cipherSuitesToExclude.toArray(new String[0]));
        }

        server.addConnector(secureConnector);
    } else {
        ssl = false;
        port = azkabanSettings.getInt("jetty.port", DEFAULT_PORT_NUMBER);
        SocketConnector connector = new SocketConnector();
        connector.setPort(port);
        connector.setHeaderBufferSize(MAX_HEADER_BUFFER_SIZE);
        server.addConnector(connector);
    }

    // setting stats configuration for connectors
    for (Connector connector : server.getConnectors()) {
        connector.setStatsOn(isStatsOn);
    }

    String hostname = azkabanSettings.getString("jetty.hostname", "localhost");
    azkabanSettings.put("server.hostname", hostname);
    azkabanSettings.put("server.port", port);
    azkabanSettings.put("server.useSSL", String.valueOf(ssl));

    app = new AzkabanWebServer(server, azkabanSettings);

    boolean checkDB = azkabanSettings.getBoolean(AzkabanDatabaseSetup.DATABASE_CHECK_VERSION, false);
    if (checkDB) {
        AzkabanDatabaseSetup setup = new AzkabanDatabaseSetup(azkabanSettings);
        setup.loadTableInfo();
        if (setup.needsUpdating()) {
            logger.error("Database is out of date.");
            setup.printUpgradePlan();

            logger.error("Exiting with error.");
            System.exit(-1);
        }
    }

    try {
        JdbcExecutorLoader jdbcExecutorLoader = new JdbcExecutorLoader(azkabanSettings);
        jdbcExecutorLoader.updateExecutableJobsOnStartUp();
    } catch (Exception e) {
        logger.warn("There could be some jobs KILLED by this server restart event,"
                + "but their status still erroneously being shown as RUNNING." + "Please run the SQL "
                + "[update execution_jobs join execution_flows"
                + " on execution_jobs.exec_id = execution_flows.exec_id"
                + " set execution_jobs.status = 70 where"
                + " execution_jobs.status = 30 and execution_flows.status = 70]"
                + "on the database to rectify their status", e);
    }

    QueuedThreadPool httpThreadPool = new QueuedThreadPool(maxThreads);
    server.setThreadPool(httpThreadPool);

    String staticDir = azkabanSettings.getString("web.resource.dir", DEFAULT_STATIC_DIR);
    logger.info("Setting up web resource dir " + staticDir);
    Context root = new Context(server, "/", Context.SESSIONS);
    root.setMaxFormContentSize(MAX_FORM_CONTENT_SIZE);

    String defaultServletPath = azkabanSettings.getString("azkaban.default.servlet.path", "/index");
    root.setResourceBase(staticDir);
    ServletHolder indexRedirect = new ServletHolder(new IndexRedirectServlet(defaultServletPath));
    root.addServlet(indexRedirect, "/");
    ServletHolder index = new ServletHolder(new ProjectServlet());
    root.addServlet(index, "/index");

    ServletHolder staticServlet = new ServletHolder(new DefaultServlet());
    root.addServlet(staticServlet, "/css/*");
    root.addServlet(staticServlet, "/js/*");
    root.addServlet(staticServlet, "/images/*");
    root.addServlet(staticServlet, "/fonts/*");
    root.addServlet(staticServlet, "/favicon.ico");

    root.addServlet(new ServletHolder(new ProjectManagerServlet()), "/manager");
    root.addServlet(new ServletHolder(new ExecutorServlet()), "/executor");
    root.addServlet(new ServletHolder(new HistoryServlet()), "/history");
    root.addServlet(new ServletHolder(new ScheduleServlet()), "/schedule");
    root.addServlet(new ServletHolder(new JMXHttpServlet()), "/jmx");
    root.addServlet(new ServletHolder(new TriggerManagerServlet()), "/triggers");
    root.addServlet(new ServletHolder(new StatsServlet()), "/stats");
    root.addServlet(new ServletHolder(new AboutServlet()), "/about");
    root.addServlet(new ServletHolder(new FileEditorServlet()), "/fileeditor");

    ServletHolder restliHolder = new ServletHolder(new RestliServlet());
    restliHolder.setInitParameter("resourcePackages", "azkaban.restli");
    root.addServlet(restliHolder, "/restli/*");

    String viewerPluginDir = azkabanSettings.getString("viewer.plugin.dir", "plugins/viewer");
    loadViewerPlugins(root, viewerPluginDir, app.getVelocityEngine());

    // triggerplugin
    String triggerPluginDir = azkabanSettings.getString("trigger.plugin.dir", "plugins/triggers");
    Map<String, TriggerPlugin> triggerPlugins = loadTriggerPlugins(root, triggerPluginDir, app);
    app.setTriggerPlugins(triggerPlugins);
    // always have basic time trigger
    // TODO: find something else to do the job
    app.getTriggerManager().start();

    root.setAttribute(ServerConstants.AZKABAN_SERVLET_CONTEXT_KEY, app);
    try {
        server.start();
    } catch (Exception e) {
        logger.warn(e);
        Utils.croak(e.getMessage(), 1);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            try {
                logTopMemoryConsumers();
            } catch (Exception e) {
                logger.info(("Exception when logging top memory consumers"), e);
            }

            logger.info("Shutting down http server...");
            try {
                app.close();
                server.stop();
                server.destroy();
            } catch (Exception e) {
                logger.error("Error while shutting down http server.", e);
            }
            logger.info("kk thx bye.");
        }

        public void logTopMemoryConsumers() throws Exception, IOException {
            if (new File("/bin/bash").exists() && new File("/bin/ps").exists()
                    && new File("/usr/bin/head").exists()) {
                logger.info("logging top memeory consumer");

                java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder("/bin/bash", "-c",
                        "/bin/ps aux --sort -rss | /usr/bin/head");
                Process p = processBuilder.start();
                p.waitFor();

                InputStream is = p.getInputStream();
                java.io.BufferedReader reader = new java.io.BufferedReader(new InputStreamReader(is));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    logger.info(line);
                }
                is.close();
            }
        }
    });
    logger.info("Server running on " + (ssl ? "ssl" : "") + " port " + port + ".");
}

From source file:de.prozesskraft.ptest.Launch.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try/*from  ww w .ja v  a  2  s  . c  om*/
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Launch.class) + "/" + "../etc/ptest-launch.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ospl = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory] directory with sample input data")
            //            .isRequired()
            .create("spl");

    Option oinstancedir = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory, default: .] directory where the test will be performed")
            //            .isRequired()
            .create("instancedir");

    Option ocall = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory, default: random call in spl-directory] file with call-string")
            //            .isRequired()
            .create("call");

    Option oaltapp = OptionBuilder.withArgName("STRING").hasArg()
            .withDescription(
                    "[optional] alternative app. this String replaces the first line of the .call-file.")
            //            .isRequired()
            .create("altapp");

    Option oaddopt = OptionBuilder.withArgName("STRING").hasArg()
            .withDescription("[optional] add an option to the call.")
            //            .isRequired()
            .create("addopt");

    Option onolaunch = new Option("nolaunch",
            "only create instance directory, copy all spl files, but do NOT launch the process");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(ospl);
    options.addOption(oinstancedir);
    options.addOption(ocall);
    options.addOption(oaltapp);
    options.addOption(oaddopt);
    options.addOption(onolaunch);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("launch", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     " + web);
        System.out.println("author: " + author);
        System.out.println("version:" + version);
        System.out.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    boolean error = false;
    String spl = null;
    String instancedir = null;
    String call = null;
    String altapp = null;
    ArrayList<String> addopt = new ArrayList<String>();

    // spl initialisieren
    if (commandline.hasOption("spl")) {
        spl = commandline.getOptionValue("spl");
    } else {
        System.err.println("option -spl is mandatory");
        error = true;
    }

    // instancedir initialisieren
    if (commandline.hasOption("instancedir")) {
        instancedir = commandline.getOptionValue("instancedir");
    } else {
        instancedir = System.getProperty("user.dir");
    }

    // call initialisieren
    if (commandline.hasOption("call")) {
        call = commandline.getOptionValue("call");
    }

    // altapp initialisieren
    if (commandline.hasOption("altapp")) {
        altapp = commandline.getOptionValue("altapp");
    }

    // addopt initialisieren
    if (commandline.hasOption("addopt")) {
        for (String actString : commandline.getOptionValues("addopt")) {
            addopt.add(actString);
        }
    }

    // wenn fehler, dann exit
    if (error) {
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    // das erste spl-objekt geben lassen
    Spl actSpl = new Splset(spl).getSpl().get(0);

    // den call, result und altapp ueberschreiben
    actSpl.setName("default");

    if (call != null) {
        actSpl.setCall(new java.io.File(call));
    }
    if (actSpl.getCall() == null) {
        System.err.println("error: no call information found");
        System.exit(1);
    }

    if (altapp != null) {
        actSpl.setAltapp(altapp);
    }

    if (addopt.size() > 0) {
        actSpl.setAddopt(addopt);
    }

    actSpl.setResult(null);

    // das instancedir erstellen
    java.io.File actSplInstanceDir = new java.io.File(instancedir);
    System.err.println("info: creating directory " + actSplInstanceDir.getCanonicalPath());
    actSplInstanceDir.mkdirs();

    // Inputdaten in das InstanceDir exportieren
    actSpl.exportInput(actSplInstanceDir);

    // exit, wenn --nolaunch
    if (commandline.hasOption("nolaunch")) {
        System.err.println("info: exiting, because of -nolaunch");
        System.exit(0);
    }

    // das logfile des Syscalls (zum debuggen des programms "process syscall" gedacht)
    String AbsLogSyscallWrapper = actSplInstanceDir.getCanonicalPath() + "/.log";
    String AbsStdout = actSplInstanceDir.getCanonicalPath() + "/.stdout.txt";
    String AbsStderr = actSplInstanceDir.getCanonicalPath() + "/.stderr.txt";
    String AbsPid = actSplInstanceDir.getCanonicalPath() + "/.pid";

    // beim starten von syscall werden parameter mit whitespaces an diesen auseinandergeschnitten und der nachfolgende aufruf schlaeft fehl
    // deshalb sollen whitespaces durch eine 'zeichensequenz' ersetzt werden
    // syscall ersetzt die zeichensequenz wieder zurueck in ein " "
    ArrayList<String> callFuerSyscall = actSpl.getCallAsArrayList();
    ArrayList<String> callFuerSyscallMitTrennzeichen = new ArrayList<String>();
    for (String actString : callFuerSyscall) {
        callFuerSyscallMitTrennzeichen.add(actString.replaceAll("\\s+", "%WHITESPACE%"));
    }

    try {
        // den Aufrufstring fuer die externe App (process syscall --version 0.6.0)) splitten
        // beim aufruf muss das erste argument im path zu finden sein, sonst gibt die fehlermeldung 'no such file or directory'
        ArrayList<String> processSyscallWithArgs = new ArrayList<String>(
                Arrays.asList(ini.get("apps", "pkraft-syscall").split(" ")));

        // die sonstigen argumente hinzufuegen
        processSyscallWithArgs.add("-call");
        processSyscallWithArgs.add(String.join(" ", callFuerSyscallMitTrennzeichen));
        //         processSyscallWithArgs.add("\""+call+"\"");
        processSyscallWithArgs.add("-stdout");
        processSyscallWithArgs.add(AbsStdout);
        processSyscallWithArgs.add("-stderr");
        processSyscallWithArgs.add(AbsStderr);
        processSyscallWithArgs.add("-pid");
        processSyscallWithArgs.add(AbsPid);
        processSyscallWithArgs.add("-mylog");
        processSyscallWithArgs.add(AbsLogSyscallWrapper);
        processSyscallWithArgs.add("-maxrun");
        processSyscallWithArgs.add("" + 3000);

        // erstellen prozessbuilder
        ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs);

        // erweitern des PATHs um den prozesseigenen path
        //         Map<String,String> env = pb.environment();
        //         String path = env.get("PATH");
        //         log("debug", "$PATH="+path);
        //         path = this.parent.getAbsPath()+":"+path;
        //         env.put("PATH", path);
        //         log("info", "path: "+path);

        // setzen der aktuellen directory (in der syscall ausgefuehrt werden soll)
        java.io.File directory = new java.io.File(instancedir);
        System.err.println("info: setting execution directory to: " + directory.getCanonicalPath());
        pb.directory(directory);

        // zum debuggen ein paar ausgaben
        //         java.lang.Process p1 = Runtime.getRuntime().exec("date >> ~/tmp.debug.work.txt");
        //         p1.waitFor();
        //         java.lang.Process p2 = Runtime.getRuntime().exec("ls -la "+this.getParent().getAbsdir()+" >> ~/tmp.debug.work.txt");
        //         p2.waitFor();
        //         java.lang.Process pro = Runtime.getRuntime().exec("nautilus");
        //         java.lang.Process superpro = Runtime.getRuntime().exec(processSyscallWithArgs.toArray(new String[processSyscallWithArgs.size()]));
        //         p3.waitFor();

        System.err.println("info: calling: " + pb.command());

        // starten des prozesses
        java.lang.Process sysproc = pb.start();

        // einfangen der stdout- und stderr des subprozesses
        InputStream is_stdout = sysproc.getInputStream();
        InputStream is_stderr = sysproc.getErrorStream();

        // Send your InputStream to an InputStreamReader:
        InputStreamReader isr_stdout = new InputStreamReader(is_stdout);
        InputStreamReader isr_stderr = new InputStreamReader(is_stderr);

        // That needs to go to a BufferedReader:
        BufferedReader br_stdout = new BufferedReader(isr_stdout);
        BufferedReader br_stderr = new BufferedReader(isr_stderr);

        //         // oeffnen der OutputStreams zu den Ausgabedateien
        //         FileWriter fw_stdout = new FileWriter(sStdout);
        //         FileWriter fw_stderr = new FileWriter(sStderr);

        // zeilenweise in die files schreiben
        String line_out = new String();
        String line_err = new String();

        while (br_stdout.readLine() != null) {
        }

        //         while (((line_out = br_stdout.readLine()) != null) || ((line_err = br_stderr.readLine()) != null))
        //         {
        //            if (!(line_out == null))
        //            {
        //               System.out.println(line_out);
        //               System.out.flush();
        //            }
        //            if (!(line_err == null))
        //            {
        //               System.err.println(line_err);
        //               System.err.flush();
        //            }
        //         }

        int exitValue = sysproc.waitFor();

        //         fw_stdout.close();
        //         fw_stderr.close();

        System.err.println("exitvalue: " + exitValue);

        sysproc.destroy();

        System.exit(exitValue);

        //         alternativer aufruf
        //         java.lang.Process sysproc = Runtime.getRuntime().exec(StringUtils.join(args_for_syscall, " "));

        //         log("info", "call executed. pid="+sysproc.hashCode());

        // wait 2 seconds for becoming the pid-file visible
        //         Thread.sleep(2000);

        //         int exitValue = sysproc.waitFor();

        //         // der prozess soll bis laengstens
        //         if(exitValue != 0)
        //         {
        //            System.err.println("error: call returned a value indicating an error: "+exitValue);
        //         }
        //         else
        //         {
        //            System.err.println("info: call returned value: "+exitValue);
        //         }

        //         System.err.println("info: "+new Date().toString());
        //         System.err.println("info: bye");
        //
        //         sysproc.destroy();
        //
        //         System.exit(sysproc.exitValue());
    } catch (Exception e2) {
        System.err.println("error: " + e2.getMessage());
        System.exit(1);
    }

}

From source file:com.peewah.distribuidosfinal.EntryPoint.java

public static void main(String[] args) {
    //1. Conexin con la base de datos
    String dbUrl = "jdbc:postgresql://localhost:5432/distribuidosfinal";
    try {//from w w w.  java2s .  c  o m
        connectionSource = new JdbcConnectionSource(dbUrl);
        ((JdbcConnectionSource) connectionSource).setUsername("csacanam");
        ((JdbcConnectionSource) connectionSource).setPassword("12345678");
    } catch (SQLException ex) {
        System.out.println("Error en la conexin a la base de datos");
    }

    // 2. Data Acces Object (DAO) pattern
    usuarioDao = null;
    sistemaOperativoDao = null;
    maquinaVirtualDao = null;
    maquinaAppDao = null;
    appDao = null;
    cookbookDao = null;
    cookbookAppDao = null;
    nodoDao = null;

    if (connectionSource != null) {
        try {
            usuarioDao = DaoManager.createDao(connectionSource, Usuario.class);
            sistemaOperativoDao = DaoManager.createDao(connectionSource, SistemaOperativo.class);
            maquinaVirtualDao = DaoManager.createDao(connectionSource, MaquinaVirtual.class);
            maquinaAppDao = DaoManager.createDao(connectionSource, MaquinaApp.class);
            appDao = DaoManager.createDao(connectionSource, App.class);
            cookbookDao = DaoManager.createDao(connectionSource, Cookbook.class);
            cookbookAppDao = DaoManager.createDao(connectionSource, CookbookApp.class);
            nodoDao = DaoManager.createDao(connectionSource, Nodo.class);

        } catch (SQLException ex) {
            System.out.println("Error en la creacin del DAO");
            System.err.println(ex.getMessage());
        }
    }

    // 3. Crear tabla Usuario si no existe
    try {
        TableUtils.createTableIfNotExists(connectionSource, Usuario.class);
        TableUtils.createTableIfNotExists(connectionSource, SistemaOperativo.class);
        TableUtils.createTableIfNotExists(connectionSource, MaquinaVirtual.class);
        TableUtils.createTableIfNotExists(connectionSource, App.class);
        TableUtils.createTableIfNotExists(connectionSource, MaquinaApp.class);
        TableUtils.createTableIfNotExists(connectionSource, Cookbook.class);
        TableUtils.createTableIfNotExists(connectionSource, CookbookApp.class);
        TableUtils.createTableIfNotExists(connectionSource, Nodo.class);

    } catch (SQLException ex) {
        System.out.println("Error creando las tablas");
    }

    //4. Asignacin de puerto
    ProcessBuilder process = new ProcessBuilder();
    Integer puerto;
    if (process.environment().get("PORT") != null) {
        puerto = Integer.parseInt(process.environment().get("PORT"));
    } else {
        puerto = 8080;
    }
    spark.SparkBase.port(puerto);

    //5. Habilitar Cross-origin resource sharing (CORS)
    options("/*", (Request rqst, Response rspns) -> {
        String accessControlRequestHeaders = rqst.headers("Access-Control-Request-Headers");
        if (accessControlRequestHeaders != null) {
            rspns.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
        }

        String accessControlRequestMethod = rqst.headers("Access-Control-Request-Method");
        if (accessControlRequestMethod != null) {
            rspns.header("Access-Control-Allow-Methods", accessControlRequestMethod);
        }
        return "OK";
    });

    before((Request rqst, Response rspns) -> {
        rspns.header("Access-Control-Allow-Origin", "*");
    });

    after((Request rqst, Response rspns) -> {
        rspns.type("application/json");
    });

    //6. Web services
    //Crear usuario
    post("/new-user", (Request rqst, Response rspns) -> {
        //Obtener datos como parmetros
        String nombre = rqst.queryParams("name");
        String username = rqst.queryParams("username");
        String password = rqst.queryParams("password");

        //Validar si no hay datos vacos
        if (nombre != null && !nombre.equals("") && username != null && !username.equals("") && password != null
                && !password.equals("")) {
            //Crear objeto usuario
            Usuario usuario = new Usuario();
            usuario.setNombre(nombre);
            usuario.setPassword(password);
            usuario.setUsername(username);

            //Crear objeto en base de datos
            try {
                usuarioDao.create(usuario);

                //Crear carpeta
                File file = new File("/tmp/" + username);
                if (!file.exists()) {
                    boolean success = file.mkdir();
                    if (!success) {
                        System.out.println("La carpeta no pudo ser creada");
                    }
                }

            } catch (SQLException ex) {
                System.out.println("Error creando el usuario");
                return false;
            }

        } else {
            System.out.println("No debes dejar campos vacos");
            return false;
        }

        System.out.println("Usuario creado");
        return true;
    });

    //Autenticar usuario
    post("/auth-user", (Request rqst, Response rspns) -> {
        //Obtener datos como parmetros
        String username = rqst.queryParams("username");
        String password = rqst.queryParams("password");

        //Validar si no hay datos vacos
        if (username != null && !username.equals("") && password != null && !password.equals("")) {

            //Validar la dupla usuario-password
            try {
                Usuario usuario = usuarioDao.queryForId(username);
                if (usuario != null && usuario.getPassword().equals(password)) {
                    return true;
                }

            } catch (SQLException ex) {
            }

        }

        return false;

    });

    //Listar sistemas operativos disponibles
    get("/list-so", (Request rqst, Response rspns) -> {
        List<SistemaOperativo> sistemasOperativos = new ArrayList<>();
        try {
            sistemasOperativos = sistemaOperativoDao.queryForAll();
        } catch (SQLException ex) {
            System.out.println("Error listando los sistemas operativos");
        }

        return sistemasOperativos;
    }, new JsonTransformer());

    //Crear mquina virtual
    post("/create-machine", (Request rqst, Response rspns) -> {
        try {
            //Obtener parmetros
            String username = rqst.queryParams("username");
            String nombreMaquina = rqst.queryParams("nombreMaquina");
            String nombreSO = rqst.queryParams("nombreSO");

            Usuario user = usuarioDao.queryForId(username);
            SistemaOperativo so = sistemaOperativoDao.queryForId(nombreSO);

            if (user != null && so != null) {
                //Crear mquina virtual
                MaquinaVirtual maquinaVirtual = new MaquinaVirtual();
                maquinaVirtual.setNombre(nombreMaquina);
                maquinaVirtual.setSistemaOperativo(sistemaOperativoDao.queryForId(nombreSO));
                maquinaVirtual.setUsername(usuarioDao.queryForId(username));

                maquinaVirtualDao.create(maquinaVirtual);

                //Crear carpeta
                String path = "/tmp/" + username + "/" + nombreMaquina;
                File file = new File(path);
                if (!file.exists()) {
                    boolean success = file.mkdir();

                    if (!success) {
                        System.out.println("No se pudo crear la carpeta para la mquina");
                    } else {

                        //Crear Vagrantfile
                        try (Writer writer = new BufferedWriter(
                                new OutputStreamWriter(new FileOutputStream(path + "/Vagrantfile"), "UTF-8"))) {
                            writer.write("VAGRANTFILE_API_VERSION = \"2\"\n");
                            writer.write("Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|\n");
                            writer.write("\n");
                            writer.write("end\n");
                        }

                    }
                }

                return true;
            } else {
                return false;
            }

        } catch (SQLException ex) {
            System.out.println("Error creando la mquina virtual");
            return false;
        }
    });

    //Eliminar usuario y sus mquinas virtuales asociadas
    post("/delete-user", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("usernameLogged");
        String nombreUsuario = rqst.queryParams("usernameToDelete");

        if (userLogged != null && !userLogged.equals("") && nombreUsuario != null && !userLogged.equals("")
                && userLogged.equals("admin")) {
            try {
                Usuario user = usuarioDao.queryForId(nombreUsuario);

                if (user != null) {
                    //Eliminar mquinas virtuales del usuario
                    Collection<MaquinaVirtual> maquinasUsuario = user.getMaquinasVirtuales();
                    for (MaquinaVirtual maquina : maquinasUsuario) {
                        //Eliminar apps de las mquinas virtuales del usuario
                        QueryBuilder<MaquinaApp, String> queryBuilder = maquinaAppDao.queryBuilder();
                        queryBuilder.where().eq(MaquinaApp.MACHINE_FIELD, maquina.getId());
                        PreparedQuery<MaquinaApp> preparedQuery = queryBuilder.prepare();

                        Collection<MaquinaApp> maquinasApps = maquinaAppDao.query(preparedQuery);
                        maquinaAppDao.delete(maquinasApps);

                        //Eliminar la mquina virtual
                        maquinaVirtualDao.delete(maquina);
                    }

                    //Eliminar usuario
                    usuarioDao.delete(user);

                    //Eliminar carpeta del usuario
                    FileUtils.deleteDirectory(new File("/tmp/" + nombreUsuario));

                    return true;
                } else {
                    return false;
                }

            } catch (SQLException ex) {
                System.out.println("Error eliminando el usuario");
                return false;
            }

        } else {
            System.out.println("No tiene permisos para realizar esta accin");
            return false;
        }
    });

    //Listar mquinas virtuales de un usuario
    get("/list-machines", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("username");
        return listMachines(username);
    }, new JsonTransformer());

    //Listar usuarios
    get("/list-users", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("usernameLogged");

        if (username.equals("admin")) {
            List<Usuario> usuarios = new ArrayList<>();
            try {
                usuarios = usuarioDao.queryForAll();
            } catch (SQLException ex) {
                System.out.println("Error listando los usuarios");
            }

            return usuarios;
        } else {
            System.out.println("No tiene permisos para realizar esta accin");
            return "No tiene permisos para realizar esta accin";
        }
    }, new JsonTransformer());

    // Agregar nodo a una mquina virtual
    post("/add-node", (Request rqst, Response rspns) -> {
        String nombreNodo = rqst.queryParams("nombreNodo");
        String ipPrivada = rqst.queryParams("ipPrivada");
        String ipPublica = rqst.queryParams("ipPublica");
        String mascaraRed = rqst.queryParams("mascaraRed");
        String cantidadMemoria = rqst.queryParams("cantidadMemoria");
        String cantidadCPU = rqst.queryParams("cantidadCPU");
        String interfazPuente = rqst.queryParams("interfazPuente");
        String parametrosJSON = rqst.queryParams("parametrosJSON");
        String nombreMaquina = rqst.queryParams("nombreMaquina");
        String userLogged = rqst.queryParams("userLogged");

        Usuario user = usuarioDao.queryForId(userLogged);

        if (user != null) {
            //Buscar mquina
            QueryBuilder<MaquinaVirtual, Integer> queryBuilder = maquinaVirtualDao.queryBuilder();
            queryBuilder.where().eq(MaquinaVirtual.USERNAME_FIELD, userLogged);
            queryBuilder.where().eq(MaquinaVirtual.NOMBRE_FIELD, nombreMaquina);
            PreparedQuery<MaquinaVirtual> preparedQuery = queryBuilder.prepare();
            List<MaquinaVirtual> maquinasUser = maquinaVirtualDao.query(preparedQuery);

            //Existe la mquina
            if (maquinasUser.size() > 0 && maquinasUser.get(0).getNombre().equals(nombreMaquina)) {
                //Crear nodo
                Nodo nodo = new Nodo();
                nodo.setNombre(nombreNodo);
                nodo.setCantidadCPU(cantidadCPU);
                nodo.setCantidadMemoria(cantidadMemoria);
                nodo.setInterfazPuente(interfazPuente);
                nodo.setIpPrivada(ipPrivada);
                nodo.setIpPublica(ipPublica);
                nodo.setMascaraRed(mascaraRed);
                nodo.setParametrosJSON(parametrosJSON);
                nodo.setMaquinaVirtual(maquinasUser.get(0));
                nodoDao.create(nodo);

                //Crear nodo en Vagrantfile
                insertarNodoEnVagrantFile("/tmp/" + userLogged + "/" + nombreMaquina, nodo);

                return true;

            }
        }

        return false;

    });

    //Listar apps para un SO
    get("/list-apps", (Request rqst, Response rspns) -> {
        String nameSO = rqst.queryParams("nombreSO");

        SistemaOperativo buscado = sistemaOperativoDao.queryForId(nameSO);

        if (buscado != null) {

            QueryBuilder<App, String> queryBuilder = appDao.queryBuilder();
            queryBuilder.where().eq(App.SO_FIELD, buscado.getNombre());
            PreparedQuery<App> preparedQuery = queryBuilder.prepare();

            Collection<App> aplicaciones = appDao.query(preparedQuery);

            return aplicaciones;
        } else {
            return "El SO buscado no existe";
        }

    }, new JsonTransformer());

    //Listar apps para una maquina virtual
    get("/list-app-installed", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("userLogged");
        String machineName = rqst.queryParams("nombreMaquina");

        List<MaquinaApp> maquinaApp;
        List<App> apps = new ArrayList<>();

        //Buscar si el usuario loggeado existe
        Usuario buscado;
        MaquinaVirtual buscada = null;
        try {
            buscado = usuarioDao.queryForId(userLogged);

            if (buscado != null) {
                //Lista de maquinas virtuales del usuario
                Collection<MaquinaVirtual> maquinasVirtuales = listMachines(userLogged);

                //Revisar si la maquina virtual buscada pertenece al usuario loggeado
                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(machineName)) {
                        buscada = maquina;
                        break;
                    }
                }

                if (buscada != null) {
                    //Obtener la lista de aplicaciones de la maquina virtual
                    QueryBuilder<MaquinaApp, String> queryBuilderN = maquinaAppDao.queryBuilder();
                    queryBuilderN.where().eq(MaquinaApp.MACHINE_FIELD, buscada.getId());
                    PreparedQuery<MaquinaApp> preparedQueryN = queryBuilderN.prepare();

                    maquinaApp = maquinaAppDao.query(preparedQueryN);

                    if (maquinaApp.size() > 0) {
                        for (MaquinaApp m : maquinaApp) {
                            apps.add(m.getApp());
                        }
                    }

                } else {
                    System.out.println("La maquina no existe para el usuario buscado");
                }
            } else {
                System.out.println("El usuario loggeado no existe");
            }

        } catch (SQLException ex) {
            System.out.println("Error listando las apps instaladas");
        }
        return apps;

    }, new JsonTransformer());

    //Listar nodos de una maquina virtual
    get("/list-node", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        //Inicializar la lista de nodos que se va a retornar
        Collection<Nodo> nodos = new ArrayList<>();

        //Validar que no hayan campos vacios
        if (userLogged != null && !userLogged.equals("") && nombreMaquina != null
                && !nombreMaquina.equals("")) {
            //Buscar el usuario loggeado
            Usuario user = usuarioDao.queryForId(userLogged);

            //Verificar que el usuario existe
            if (user != null) {
                //Obtener las maquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(userLogged);

                for (MaquinaVirtual m : maquinasVirtuales) {
                    if (m.getNombre().equals(nombreMaquina)) {
                        nodos = m.getNodos();
                    }
                }

            } else {
                System.out.println("El usuario loggeado no existe");
            }
        } else {
            System.out.println("No pueden haber parametros vacios");
        }

        return nodos;
    }, new JsonTransformer());

    //Eliminar maquina virtual y aplicaciones asociadas
    post("/delete-vm", (Request rqst, Response rspns) -> {
        String usernameLogged = rqst.queryParams("usernameLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual buscada = null;
        List<MaquinaApp> maquinaApp;

        //Verificar que los parametros recibidos no son null
        if (usernameLogged != null && !usernameLogged.equals("") && nombreMaquina != null
                && !nombreMaquina.equals("")) {

            Usuario user = usuarioDao.queryForId(usernameLogged);

            if (user != null) {
                //Obtener las maquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(usernameLogged);

                //Buscar la maquina virtual a eliminar dentro de las maquinas del usuario
                for (MaquinaVirtual m : maquinasVirtuales) {
                    if (m.getNombre().equals(nombreMaquina)) {
                        buscada = m;
                        break;
                    }
                }

                //Verificar que la maquina buscada pertenece al usuario en cuestion
                if (buscada != null) {
                    //Obtener la lista de aplicaciones de la maquina virtual
                    QueryBuilder<MaquinaApp, String> queryBuilder = maquinaAppDao.queryBuilder();
                    queryBuilder.where().eq(MaquinaApp.MACHINE_FIELD, buscada.getId());
                    PreparedQuery<MaquinaApp> preparedQuery = queryBuilder.prepare();

                    maquinaApp = maquinaAppDao.query(preparedQuery);

                    if (maquinaApp.size() > 0) {
                        //Eliminar las aplicaciones 
                        for (MaquinaApp i : maquinaApp) {
                            maquinaAppDao.delete(i);
                        }

                    } else {
                        System.out.println("No existen aplicaciones para la maquina virtual en cuestion");
                    }

                    //Eliminar mquina virtual
                    maquinaVirtualDao.delete(buscada);

                    //Eliminar carpeta de la maquina virtual
                    FileUtils.deleteDirectory(new File("/tmp/" + usernameLogged + "/" + nombreMaquina));
                    return true;

                }
            } else {
                System.out.println("EL usuario loggeado no existe");
            }

        } else {
            System.out.println("No pueden haber campos vacios");
        }

        return false;
    });

    //Correr mquina virtual
    post("/run-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant up");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Destruir mquina virtual
    post("/destroy-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant destroy -f");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Reanudar mquina virtual
    post("/resume-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant resume");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Asociar app a una mquina virtual
    post("/associate-app", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("username");
        String nombreMaquina = rqst.queryParams("nombreMaquina");
        String nombreApp = rqst.queryParams("nombreApp");

        Usuario user = usuarioDao.queryForId(username);

        if (user != null) {
            //Verificar si el usuario tiene la mquina
            List<MaquinaVirtual> maquinas = listMachines(username);

            MaquinaVirtual buscada = null;

            for (MaquinaVirtual maquina : maquinas) {
                if (maquina.getNombre().equals(nombreMaquina)) {
                    buscada = maquina;
                    break;
                }
            }

            if (buscada != null) {
                App app = appDao.queryForId(nombreApp);

                //Verificar si la app existe y si est para el mismo sistema operativo que tiene la mquina
                if (app != null && app.getSistemaOperativo().getNombre()
                        .equals(buscada.getSistemaOperativo().getNombre())) {
                    //Agregar a la base de datos
                    MaquinaApp maquinaApp = new MaquinaApp(buscada, app);
                    maquinaAppDao.create(maquinaApp);

                    //Crear registro en el Vagrantfile
                    String path = "/tmp/" + username + "/" + nombreMaquina;
                    insertarCookbooksANodos(new ArrayList(buscada.getNodos()), app, path);

                    return true;
                } else {
                    System.out.println("La app no existe");
                }
            } else {
                System.out.println("No se encontr la mquina en la lista del usuario");
            }
        } else {
            System.out.println("El usuario no existe");
        }

        return false;

    });

    //Listar todas las aplicaciones
    get("/list-apps-all", (Request rqst, Response rspns) -> {
        return appDao.queryForAll();
    }, new JsonTransformer());

    // Cargar datos de prueba
    get("/add-testdata", (Request rqst, Response rspns) -> {
        try {
            if (connectionSource != null) {
                TableUtils.createTableIfNotExists(connectionSource, Usuario.class);
                TableUtils.createTableIfNotExists(connectionSource, SistemaOperativo.class);
                TableUtils.createTableIfNotExists(connectionSource, MaquinaVirtual.class);
                TableUtils.createTableIfNotExists(connectionSource, App.class);
                TableUtils.createTableIfNotExists(connectionSource, MaquinaApp.class);
                TableUtils.createTableIfNotExists(connectionSource, Cookbook.class);
                TableUtils.createTableIfNotExists(connectionSource, CookbookApp.class);
                TableUtils.createTableIfNotExists(connectionSource, Nodo.class);
            }
            testData();
        } catch (SQLException ex) {
            return "Error agregando informacin de prueba";
        }

        return "OK";
    });

    //Eliminar datos de prueba
    get("/delete-testdata", (Request rqst, Response rspns) -> {
        try {
            TableUtils.dropTable(connectionSource, Usuario.class, true);
            TableUtils.dropTable(connectionSource, MaquinaVirtual.class, true);
            TableUtils.dropTable(connectionSource, SistemaOperativo.class, true);
            TableUtils.dropTable(connectionSource, App.class, true);
            TableUtils.dropTable(connectionSource, Cookbook.class, true);
            TableUtils.dropTable(connectionSource, MaquinaApp.class, true);
            TableUtils.dropTable(connectionSource, CookbookApp.class, true);
            TableUtils.dropTable(connectionSource, Nodo.class, true);
        } catch (SQLException ex) {
            return "Error eliminando la informacin";
        }

        return "OK";
    });

}

From source file:Main.java

public static void changeFileMode(String f) throws IOException {

    String[] command = { "chmod", "777", f };
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.start();

}

From source file:com.floreantpos.main.Main.java

public static void restart() throws IOException, InterruptedException, URISyntaxException {
    final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    //      Properties properties = System.getProperties();
    //      Set<Object> keySet = properties.keySet();
    //      for (Object object : keySet) {
    //         PosLog.debug(getClass(),object + ":"+properties.getProperty((String) object));
    //      }/*  w ww .ja va2s  . com*/

    String classPath = System.getProperty("java.class.path"); //$NON-NLS-1$
    String mainClass = System.getProperty("sun.java.command"); //$NON-NLS-1$

    /* Build command: java -jar application.jar */
    final ArrayList<String> command = new ArrayList<String>();
    command.add(javaBin);
    command.add("-cp"); //$NON-NLS-1$
    command.add(classPath);
    command.add(mainClass);

    final ProcessBuilder builder = new ProcessBuilder(command);
    builder.start();
    System.exit(0);
}

From source file:Main.java

public static void runOSCommand(String command) {
    ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", command);
    try {//from www  .j  a  v a  2 s  . co m
        Process p = builder.start();
        p.waitFor(5000, TimeUnit.MILLISECONDS);
    } catch (IOException | InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:hu.bme.mit.trainbenchmark.sql.process.MySqlProcess.java

public static void run(final String command[]) throws IOException, InterruptedException {
    final ProcessBuilder pb = new ProcessBuilder(command);
    final Process p = pb.start();
    p.waitFor();//from   w w  w .ja  v a  2 s  . c o m

    final String stdOut = getInputAsString(p.getInputStream());
    final String stdErr = getInputAsString(p.getErrorStream());
    // System.out.println(stdOut);
    // System.out.println(stdErr);
}

From source file:com.adguard.compiler.PackageUtils.java

private static void execute(String... commands) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(commands);
    Process p = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;/*from ww w  .j a  v a 2s .co m*/
    while ((line = reader.readLine()) != null) {
        log.debug(line);
    }
    p.waitFor();
    if (p.exitValue() != 0) {
        reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((line = reader.readLine()) != null) {
            log.error(line);
        }
        throw new IOException("Command " + ArrayUtils.toString(commands) + " not success");
    }
}