Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

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

Prototype

File directory

To view the source code for java.lang ProcessBuilder directory.

Click Source Link

Usage

From source file:au.com.permeance.liferay.portlet.patchingtoolinfo.cli.PatchingToolCommandRunner.java

public void runCommand() throws Exception {

    if (LOG.isDebugEnabled()) {
        LOG.debug("running patching tool command ...");
    }/*from   w  ww  .  j  a  v a  2 s .com*/

    try {

        ProcessBuilder processBuilder = configureProcessBuilder();

        // NOTE: ProcessBuilder#environent is initialised with System.getenv()
        // @see http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#environment%28%29

        if (LOG.isDebugEnabled()) {
            LOG.debug("processBuilder : " + processBuilder);
            List<String> commandList = processBuilder.command();
            LOG.debug("command environment : " + processBuilder.environment());
            LOG.debug("command list : " + commandList);
            LOG.debug("command directory : " + processBuilder.directory());
        }

        if (LOG.isDebugEnabled()) {
            List<String> commandList = processBuilder.command();
            String processCommandStr = StringHelper.flattenStringList(commandList);
            LOG.debug("running patching tool command : " + processCommandStr);
        }

        Process process = processBuilder.start();

        if (LOG.isDebugEnabled()) {
            LOG.debug("process : " + process);
        }

        // NOTE: Java 1.8 supports Process#waitFor with a timeout
        // eg. boolean finished = iostat.waitFor(100, TimeUnit.MILLISECONDS);

        int processExitValue = process.waitFor();

        List<String> processOutputLines = IOUtils.readLines(process.getInputStream());

        List<String> processErrorLines = IOUtils.readLines(process.getErrorStream());

        this.patchingToolResults = new PatchingToolResults(processExitValue, processOutputLines,
                processErrorLines);

        if (LOG.isDebugEnabled()) {
            LOG.debug("patchingToolResults: " + patchingToolResults);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("patching tool returned exit code " + this.patchingToolResults.getExitValue());
            LOG.debug("patching tool returned " + this.patchingToolResults.getOutputLines().size()
                    + " output lines");
            LOG.debug("--- COMMAND OUTPUT ---");
            LOG.debug(processOutputLines);
            LOG.debug("patching tool returned " + this.patchingToolResults.getErrorLines().size()
                    + " error lines");
            LOG.debug("--- COMMAND ERROR ---");
            LOG.debug(processErrorLines);
        }

        // NOTE: Command shell may return lines in the error stream that are warning messages, not errors.
        // Hence, we cannot rely upon content in the error stream as a valid error.

        if (this.patchingToolResults.getExitValue() != 0) {
            StringBuilder sb = new StringBuilder();
            String errorLine1 = null;
            if (this.patchingToolResults.hasErrorLines()) {
                errorLine1 = this.patchingToolResults.getErrorLines().get(0);
            }
            if (errorLine1 == null) {
                sb.append("Error running patching tool command.");
                sb.append(" See portal logs for more details.");
            } else {
                sb.append("Error running patching tool command : ");
                sb.append(errorLine1);
            }
            String errMsg = sb.toString();
            throw new Exception(errMsg);
        }

    } catch (Exception e) {

        String msg = "Error executing patching tool command : " + e.getMessage();
        LOG.error(msg, e);
        throw new Exception(msg, e);
    }
}

From source file:jenkins.plugins.tanaguru.TanaguruRunnerBuilder.java

/**
 * /*  w w  w  .ja va2 s  . c  o m*/
 * @param tanaguruRunner
 * @param scenario
 * @param workspace
 */
private void linkToTanaguruWebapp(TanaguruRunner tanaguruRunner, String scenarioName, String scenario,
        File contextDir, String projectName) throws IOException, InterruptedException {

    File insertProcedureFile = TanaguruRunnerBuilder.createTempFile(contextDir, SQL_PROCEDURE_SCRIPT_NAME,
            IOUtils.toString(getClass().getResourceAsStream(SQL_PROCEDURE_NAME)));

    String script = IOUtils.toString(getClass().getResourceAsStream(INSERT_ACT_NAME))
            .replace("$host", TanaguruInstallation.get().getDatabaseHost())
            .replace("$user", TanaguruInstallation.get().getDatabaseLogin())
            .replace("$port", TanaguruInstallation.get().getDatabasePort())
            .replace("$passwd", TanaguruInstallation.get().getDatabasePassword())
            .replace("$db", TanaguruInstallation.get().getDatabaseName())
            .replace("$procedureFileName", TMP_FOLDER_NAME + SQL_PROCEDURE_SCRIPT_NAME);

    File insertActFile = TanaguruRunnerBuilder.createTempFile(contextDir, INSERT_ACT_SCRIPT_NAME, script);

    ProcessBuilder pb = new ProcessBuilder(TMP_FOLDER_NAME + INSERT_ACT_SCRIPT_NAME,
            TanaguruInstallation.get().getTanaguruLogin(), projectName.replaceAll("'", "'\"'\"'"),
            scenarioName.replaceAll("'", "'\"'\"'"),
            TanaguruRunnerBuilder.forceVersion1ToScenario(scenario.replaceAll("'", "'\"'\"'")),
            tanaguruRunner.auditId);

    pb.directory(contextDir);
    pb.redirectErrorStream(true);

    Process p = pb.start();
    p.waitFor();

    FileUtils.deleteQuietly(insertActFile);
    FileUtils.deleteQuietly(insertProcedureFile);
}

From source file:hydrograph.ui.graph.job.JobManager.java

/**
 * Kill remote process.//  w w w.  ja va 2s .com
 *
 * @param job the job
 * @param gefCanvas the gef canvas
 */
private void killRemoteProcess(Job job, DefaultGEFCanvas gefCanvas) {

    String gradleCommand = getKillJobCommand(job);
    String[] runCommand = new String[3];
    if (OSValidator.isWindows()) {
        String[] command = { Messages.CMD, "/c", gradleCommand };
        runCommand = command;

    } else if (OSValidator.isMac()) {
        String[] command = { Messages.SHELL, "-c", gradleCommand };
        runCommand = command;
    }

    ProcessBuilder processBuilder = new ProcessBuilder(runCommand);
    processBuilder.directory(new File(job.getJobProjectDirectory()));
    processBuilder.redirectErrorStream(true);
    try {
        Process process = processBuilder.start();
        if (gefCanvas != null)
            logKillProcessLogsAsyncronously(process, job, gefCanvas);
    } catch (IOException e) {
        logger.debug("Unable to kill the job", e);
    }
}

From source file:jenkins.plugins.asqatasun.AsqatasunRunnerBuilder.java

/**
 * /*from   www  .j a va  2  s. com*/
 * @param asqatasunRunner
 * @param scenario
 * @param workspace
 */
private void linkToWebapp(AsqatasunRunner asqatasunRunner, String scenarioName, String scenario,
        File contextDir, PrintStream printStream, boolean isDebug, String projectName)
        throws IOException, InterruptedException {

    File insertProcedureFile = AsqatasunRunnerBuilder.createTempFile(contextDir, SQL_PROCEDURE_SCRIPT_NAME,
            IOUtils.toString(getClass().getResourceAsStream(SQL_PROCEDURE_NAME)));
    if (isDebug) {
        printStream.print("insertProcedureFile created : " + insertProcedureFile.getAbsolutePath());
        printStream.print("with content : " + FileUtils.readFileToString(insertProcedureFile));
    }
    String script = IOUtils.toString(getClass().getResourceAsStream(INSERT_ACT_NAME))
            .replace("$host", AsqatasunInstallation.get().getDatabaseHost())
            .replace("$user", AsqatasunInstallation.get().getDatabaseLogin())
            .replace("$port", AsqatasunInstallation.get().getDatabasePort())
            .replace("$passwd", AsqatasunInstallation.get().getDatabasePassword())
            .replace("$db", AsqatasunInstallation.get().getDatabaseName())
            .replace("$procedureFileName", TMP_FOLDER_NAME + SQL_PROCEDURE_SCRIPT_NAME);

    File insertActFile = AsqatasunRunnerBuilder.createTempFile(contextDir, INSERT_ACT_SCRIPT_NAME, script);

    ProcessBuilder pb = new ProcessBuilder(TMP_FOLDER_NAME + INSERT_ACT_SCRIPT_NAME,
            AsqatasunInstallation.get().getAsqatasunLogin(), projectName.replaceAll("'", QUOTES),
            scenarioName.replaceAll("'", QUOTES),
            AsqatasunRunnerBuilder.forceVersion1ToScenario(scenario.replaceAll("'", QUOTES)),
            asqatasunRunner.getAuditId());

    pb.directory(contextDir);
    pb.redirectErrorStream(true);

    Process p = pb.start();
    p.waitFor();

    FileUtils.forceDelete(insertActFile);
    FileUtils.forceDelete(insertProcedureFile);
}

From source file:com.github.lindenb.mscheduler.MScheduler.java

private int build(final String argv[]) {
    Transaction txn = null;//from   w  w w .jav  a2s  .c  o  m
    BufferedReader in = null;
    String makeExecutable = "make";
    try {
        this.options
                .addOption(Option.builder(OPTION_MAKE_EXECUTABLE).hasArg(true).longOpt(OPTION_MAKE_EXECUTABLE)
                        .argName("MAKE").desc("make executable. Default: " + makeExecutable).build());

        this.options.addOption(Option.builder(OPTION_MAKEFILEIN).hasArg(true).longOpt("makefile").argName("DIR")
                .desc("debug Makefile").build());

        final CommandLineParser parser = new DefaultParser();
        this.cmdLine = parser.parse(this.options, argv);
        final List<String> args = this.cmdLine.getArgList();

        if (cmdLine.hasOption(OPTION_MAKE_EXECUTABLE)) {
            makeExecutable = cmdLine.getOptionValue(OPTION_MAKE_EXECUTABLE);
        }

        if (cmdLine.hasOption(OPTION_HELP)) {
            return printHelp("build");
        }

        if (parseWorkingDirectory() != 0)
            return -1;

        if (!cmdLine.hasOption(OPTION_MAKEFILEIN)) {
            LOG.error("option -" + OPTION_MAKEFILEIN + " undefined");
            return -1;
        }
        final File makefileIn = new File(cmdLine.getOptionValue(OPTION_MAKEFILEIN));
        if (!makefileIn.exists()) {
            System.err.println("Option -" + OPTION_MAKEFILEIN + " file doesn't exists: " + makefileIn);
            return -1;
        }

        if (!makefileIn.isFile()) {
            System.err.println("Option -" + OPTION_MAKEFILEIN + " this is not a file : " + makefileIn);
            return -1;
        }
        if (!makefileIn.isAbsolute() || makefileIn.getParentFile() == null) {
            System.err.println("Option -" + OPTION_MAKEFILEIN + " path is not absolute : " + makefileIn);
            return -1;
        }

        if (openEnvironement(txn, true, false) != 0) {
            return -1;
        }

        final List<String> cmdargs = new ArrayList<>();
        cmdargs.add(makeExecutable);
        cmdargs.add("-ndr");
        cmdargs.add("-C");
        cmdargs.add(makefileIn.getParentFile().getPath());
        cmdargs.add("-f");
        cmdargs.add(makefileIn.getName());
        for (final String arg : args)
            cmdargs.add(arg);

        LOG.info("invoking make :" + String.join(" ", cmdargs));
        final ProcessBuilder procbuilder = new ProcessBuilder(cmdargs);
        procbuilder.directory(makefileIn.getParentFile());

        final Process proc = procbuilder.start();
        final StreamBoozer sb = new StreamBoozer(proc.getErrorStream(), System.err, "[make]");
        sb.start();

        LOG.info("Reading graph");
        in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        final Graph graph = Graph.parse(in);
        IoUtils.close(in);
        in = null;
        final Task.Binding taskBinding = new Task.Binding();
        int nTargets = 0;
        LOG.info("inserting targets");
        final DatabaseEntry key = new DatabaseEntry();
        final DatabaseEntry data = new DatabaseEntry();
        for (final Target t : graph.getTargets()) {
            if (nTargets++ % 100 == 0)
                LOG.info("inserting " + t.getName() + " " + nTargets);
            final Task task = new Task(t);

            //skip those targets, eg. "Makefile"
            if (task.shellScriptLines.isEmpty() && task.getPrerequisites().isEmpty()) {
                task.targetStatus = TaskStatus.COMPLETED;
            }

            StringBinding.stringToEntry(t.getName(), key);
            taskBinding.objectToEntry(task, data);
            if (this.targetsDatabase.put(txn, key, data) != OperationStatus.SUCCESS) {
                LOG.error("Cannot insert " + task);
                return -1;
            }
        }

        LOG.info("inserting metadata");
        StringBinding.stringToEntry(BASEDIRKEY, key);
        StringBinding.stringToEntry(makefileIn.getParentFile().getPath(), data);
        if (this.metaDatabase.put(txn, key, data) != OperationStatus.SUCCESS) {
            LOG.error("Cannot insert " + BASEDIRKEY);
            return -1;
        }

        return 0;
    } catch (Exception err) {
        LOG.error("Boum", err);
        return -1;
    } finally {
        close();
    }
}

From source file:com.netflix.genie.server.jobmanager.impl.JobManagerImpl.java

/**
 * Set/initialize environment variables for this job.
 *
 * @param processBuilder The process builder to use
 * @throws GenieException if there is any error in initialization
 */// w  w  w  . ja  v  a  2s  .  c  om
protected void setupCommonProcess(final ProcessBuilder processBuilder) throws GenieException {
    LOG.info("called");

    //Get the directory to stage all the work out of
    final String baseUserWorkingDir = this.getBaseUserWorkingDirectory();

    //Save the base user working directory
    processBuilder.environment().put("BASE_USER_WORKING_DIR", baseUserWorkingDir);

    //Set the process working directory
    processBuilder.directory(this.createWorkingDirectory(baseUserWorkingDir));

    //Copy any attachments from the job.
    this.copyAttachments();

    LOG.info("Setting job working dir , conf dir and jar dir");
    // setup env for current job, conf and jar directories directories
    processBuilder.environment().put("CURRENT_JOB_WORKING_DIR", this.jobDir);
    processBuilder.environment().put("CURRENT_JOB_CONF_DIR", this.jobDir + "/conf");
    processBuilder.environment().put("CURRENT_JOB_JAR_DIR", this.jobDir + "/jars");

    if (this.job.getFileDependencies() != null && !this.job.getFileDependencies().isEmpty()) {
        processBuilder.environment().put("CURRENT_JOB_FILE_DEPENDENCIES",
                StringUtils.replaceChars(this.job.getFileDependencies(), ',', ' '));
    }

    // set the cluster related conf files
    processBuilder.environment().put("S3_CLUSTER_CONF_FILES",
            convertCollectionToString(this.cluster.getConfigs()));

    this.setCommandAndApplicationForJob(processBuilder);

    if (StringUtils.isNotBlank(this.job.getEnvPropFile())) {
        processBuilder.environment().put("JOB_ENV_FILE", this.job.getEnvPropFile());
    }

    // this is for the generic joblauncher.sh to use to create username
    // on the machine if needed
    processBuilder.environment().put("USER_NAME", this.job.getUser());

    processBuilder.environment().put("GROUP_NAME", this.getGroupName());

    // set the java home
    final String javaHome = ConfigurationManager.getConfigInstance()
            .getString("com.netflix.genie.server.java.home");
    if (StringUtils.isNotBlank(javaHome)) {
        processBuilder.environment().put("JAVA_HOME", javaHome);
    }

    // Set an ARN if one is available for role assumption with S3
    final String arn = ConfigurationManager.getConfigInstance()
            .getString("com.netflix.genie.server.aws.iam.arn");
    if (StringUtils.isNotBlank(arn)) {
        processBuilder.environment().put("ARN", arn);
    }

    // set the genie home
    final String genieHome = ConfigurationManager.getConfigInstance()
            .getString("com.netflix.genie.server.sys.home");
    if (StringUtils.isBlank(genieHome)) {
        final String msg = "Property com.netflix.genie.server.sys.home is not set correctly";
        LOG.error(msg);
        throw new GenieServerException(msg);
    }
    processBuilder.environment().put("XS_SYSTEM_HOME", genieHome);

    // set the archive location
    // unless user has explicitly requested for it to be disabled
    if (!this.job.isDisableLogArchival()) {
        final String s3ArchiveLocation = ConfigurationManager.getConfigInstance()
                .getString("com.netflix.genie.server.s3.archive.location");
        if (StringUtils.isNotBlank(s3ArchiveLocation)) {
            processBuilder.environment().put("S3_ARCHIVE_LOCATION", s3ArchiveLocation);
        }
    }
}

From source file:com.searchcode.app.jobs.IndexSvnRepoJob.java

public RepositoryChanged updateSvnRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger()//from w  ww. j  a  v  a  2  s . c o  m
            .info("SVN: attempting to pull latest from " + repoRemoteLocation + " for " + repoName);

    try {
        String previousRevision = this.getCurrentRevision(repoLocations, repoName);
        Singleton.getLogger().info("SVN: update previous revision " + previousRevision);

        ProcessBuilder processBuilder;
        if (useCredentials) {
            processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "update");
        } else {
            processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "update", "--username", repoUserName,
                    "--password", repoPassword);
        }

        processBuilder.directory(new File(repoLocations + repoName));
        Process process = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;

        while ((line = br.readLine()) != null) {
            Singleton.getLogger().info("svn update: " + line);
        }

        String currentRevision = this.getCurrentRevision(repoLocations, repoName);
        Singleton.getLogger().info("SVN: update current revision " + currentRevision);

        if (!previousRevision.equals(currentRevision)) {
            return this.getDiffBetweenRevisions(repoLocations, repoName, previousRevision);
        }
    } catch (IOException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}

From source file:interactivespaces.util.process.BaseNativeApplicationRunner.java

/**
 * Attempt the run./*from  w  ww .  j a v a  2s . com*/
 *
 * @param firstTime
 *          {@code true} if this is the first attempt
 *
 * @return the process that was created
 *
 * @throws InteractiveSpacesException
 *           was not able to start the process the first time
 */
private Process attemptRun(boolean firstTime) throws InteractiveSpacesException {
    try {
        ProcessBuilder builder = new ProcessBuilder(commandLine);

        Map<String, String> processEnvironment = builder.environment();
        if (cleanEnvironment) {
            processEnvironment.clear();
        }
        modifyEnvironment(processEnvironment, environment);

        builder.directory(executableFolder);

        log.info(String.format("Starting up native code in folder %s", executableFolder.getAbsolutePath()));

        return builder.start();
    } catch (Exception e) {
        // Placed here so we can get the exception when thrown.
        if (firstTime) {
            runnerState.set(NativeApplicationRunnerState.STARTUP_FAILED);
            handleApplicationStartupFailed();

            throw new InteractiveSpacesException("Can't start up native application " + appName, e);
        }

        return null;
    }
}

From source file:edu.stolaf.cs.wmrserver.streaming.PipeMapRed.java

public void configure(JobConf job) {
    try {/*ww w  .  ja  v  a2 s.c om*/
        String argv = getPipeCommand(job);

        joinDelay_ = job.getLong("stream.joindelay.milli", 0);

        job_ = job;
        fs_ = FileSystem.get(job_);

        nonZeroExitIsFailure_ = job_.getBoolean("stream.non.zero.exit.is.failure", true);

        doPipe_ = getDoPipe();
        if (!doPipe_)
            return;

        setStreamJobDetails(job);

        String[] argvSplit = splitArgs(argv);
        String prog = argvSplit[0];
        File currentDir = new File(".").getAbsoluteFile();
        if (new File(prog).isAbsolute()) {
            // we don't own it. Hope it is executable
        } else {
            // Try to find executable in unpacked job JAR and make absolute if
            // present. Otherwise, leave it as relative to be resolved against PATH
            File jarDir = new File(job.getJar()).getParentFile();
            File progFile = new File(jarDir, argvSplit[0]);
            if (progFile.isFile()) {
                progFile.setExecutable(true);
                argvSplit[0] = progFile.getAbsolutePath();
            }
        }

        logprintln("PipeMapRed exec " + Arrays.asList(argvSplit));
        Hashtable<String, String> childEnv = new Hashtable();
        addJobConfToEnvironment(job_, childEnv);
        addEnvironment(childEnv, job_.get("stream.addenvironment"));
        // add TMPDIR environment variable with the value of java.io.tmpdir
        envPut(childEnv, "TMPDIR", System.getProperty("java.io.tmpdir"));

        // Start the process
        ProcessBuilder builder = new ProcessBuilder(argvSplit);
        // The process' environment initially inherits all vars from the parent --
        // only setting those we add/override
        builder.environment().putAll(childEnv);
        // Set the working directory to the job jars directory
        // This is a bad idea... fix this.
        builder.directory(new File(job.getJar()).getParentFile());
        sim = builder.start();

        clientOut_ = new DataOutputStream(new BufferedOutputStream(sim.getOutputStream(), BUFFER_SIZE));
        clientIn_ = new DataInputStream(new BufferedInputStream(sim.getInputStream(), BUFFER_SIZE));
        clientErr_ = new DataInputStream(new BufferedInputStream(sim.getErrorStream()));
        startTime_ = System.currentTimeMillis();

        errThread_ = new MRErrorThread();
        errThread_.start();
    } catch (Exception e) {
        logStackTrace(e);
        LOG.error("configuration exception", e);
        throw new RuntimeException("configuration exception", e);
    }
}

From source file:gov.pnnl.goss.gridappsd.simulation.SimulationManagerImpl.java

/**
 * This method is called by Process Manager to start a simulation
 * @param simulationId/*from   www.j a  v a 2 s  .  c om*/
 * @param simulationFile
 */
@Override
public void startSimulation(int simulationId, File simulationFile, SimulationConfig simulationConfig) {

    try {
        logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                new Date().getTime(), "Starting simulation " + simulationId, LogLevel.INFO,
                ProcessStatus.STARTING, true), GridAppsDConstants.username);
    } catch (Exception e2) {
        log.warn("Error while reporting status " + e2.getMessage());
    }

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {

            Process gridlabdProcess = null;
            Process fncsProcess = null;
            Process fncsBridgeProcess = null;
            Process vvoAppProcess = null;
            InitializedTracker isInitialized = new InitializedTracker();
            try {

                File defaultLogDir = simulationFile.getParentFile();

                //Start FNCS
                //TODO, verify no errors on this
                String broker_location = "tcp://*:5570";
                if (simulationConfig != null && simulationConfig.model_creation_config != null
                        && simulationConfig.model_creation_config.schedule_name != null
                        && simulationConfig.model_creation_config.schedule_name.trim().length() > 0) {
                    broker_location = "tcp://" + simulationConfig.getSimulation_broker_location() + ":"
                            + String.valueOf(simulationConfig.getSimulation_broker_port());
                    File serviceDir = serviceManager.getServiceConfigDirectory();
                    //copy zipload_schedule.player file
                    try {
                        RunCommandLine.runCommand("cp " + serviceDir.getAbsolutePath() + File.separator + "etc"
                                + File.separator + "zipload_schedule.player "
                                + simulationFile.getParentFile().getAbsolutePath() + File.separator
                                + simulationConfig.model_creation_config.schedule_name + ".player");
                    } catch (Exception e) {
                        log.warn("Could not copy player file to working directory");
                    }
                }

                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(), "Calling " + getPath(GridAppsDConstants.FNCS_PATH) + " 2",
                        LogLevel.INFO, ProcessStatus.STARTING, true), GridAppsDConstants.username);

                ProcessBuilder fncsBuilder = new ProcessBuilder(getPath(GridAppsDConstants.FNCS_PATH), "2");
                fncsBuilder.redirectErrorStream(true);
                fncsBuilder.redirectOutput(
                        new File(defaultLogDir.getAbsolutePath() + File.separator + "fncs.log"));
                Map<String, String> fncsEnvironment = fncsBuilder.environment();
                fncsEnvironment.put("FNCS_BROKER", broker_location);
                fncsProcess = fncsBuilder.start();
                // Watch the process
                watch(fncsProcess, "FNCS");
                //TODO: check if FNCS is started correctly and send publish simulation status accordingly

                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(), "FNCS Co-Simulator started", LogLevel.INFO, ProcessStatus.RUNNING,
                        true), GridAppsDConstants.username);

                //client.publish(GridAppsDConstants.topic_simulationStatus+simulationId, "FNCS Co-Simulator started");

                //Start GridLAB-D
                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(),
                        "Calling " + getPath(GridAppsDConstants.GRIDLABD_PATH) + " " + simulationFile,
                        LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username);
                ProcessBuilder gridlabDBuilder = new ProcessBuilder(getPath(GridAppsDConstants.GRIDLABD_PATH),
                        simulationFile.getAbsolutePath());
                gridlabDBuilder.redirectErrorStream(true);
                gridlabDBuilder.redirectOutput(
                        new File(defaultLogDir.getAbsolutePath() + File.separator + "gridlabd.log"));
                //launch from directory containing simulation files
                gridlabDBuilder.directory(simulationFile.getParentFile());
                gridlabdProcess = gridlabDBuilder.start();
                // Watch the process
                watch(gridlabdProcess, "GridLABD");

                //TODO: check if GridLAB-D is started correctly and send publish simulation status accordingly

                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(), "GridLAB-D started", LogLevel.INFO, ProcessStatus.RUNNING, true),
                        GridAppsDConstants.username);

                //Start VVO Application
                //TODO filname really should be constant
                String vvoInputFile = simulationFile.getParentFile().getAbsolutePath() + File.separator
                        + "vvo_inputs.json";
                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(),
                        "Calling " + "python " + getPath(GridAppsDConstants.VVO_APP_PATH) + " " + simulationId
                                + " " + vvoInputFile,
                        LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username);
                ProcessBuilder vvoAppBuilder = new ProcessBuilder("python",
                        getPath(GridAppsDConstants.VVO_APP_PATH), "-f", vvoInputFile, "" + simulationId);
                vvoAppBuilder.redirectErrorStream(true);
                vvoAppBuilder.redirectOutput(
                        new File(defaultLogDir.getAbsolutePath() + File.separator + "vvo_app.log"));
                vvoAppProcess = vvoAppBuilder.start();
                // Watch the process
                watch(vvoAppProcess, "VVO Application");

                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(), "FNCS-GOSS Bridge started", LogLevel.INFO, ProcessStatus.RUNNING,
                        true), GridAppsDConstants.username);

                //Start GOSS-FNCS Bridge
                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(),
                        "Calling " + "python " + getPath(GridAppsDConstants.FNCS_BRIDGE_PATH) + " "
                                + simulationConfig.getSimulation_name(),
                        LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username);

                ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python",
                        getPath(GridAppsDConstants.FNCS_BRIDGE_PATH), simulationConfig.getSimulation_name(),
                        broker_location);
                fncsBridgeBuilder.redirectErrorStream(true);
                fncsBridgeBuilder.redirectOutput(
                        new File(defaultLogDir.getAbsolutePath() + File.separator + "fncs_goss_bridge.log"));
                fncsBridgeProcess = fncsBridgeBuilder.start();
                // Watch the process
                watch(fncsBridgeProcess, "FNCS GOSS Bridge");

                //TODO: check if bridge is started correctly and send publish simulation status accordingly

                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(), "FNCS-GOSS Bridge started", LogLevel.INFO, ProcessStatus.RUNNING,
                        true), GridAppsDConstants.username);

                //Subscribe to fncs-goss-bridge output topic
                client.subscribe(GridAppsDConstants.topic_FNCS_output,
                        new GossFncsResponseEvent(logManager, isInitialized, simulationId));

                int initAttempts = 0;
                while (!isInitialized.isInited && initAttempts < MAX_INIT_ATTEMPTS) {
                    //Send 'isInitialized' call to fncs-goss-bridge to check initialization until it is initialized.
                    //TODO add limiting how long it checks for initialized, or cancel if the fncs process exits
                    //This call would return true/false for initialization and simulation output of time step 0.
                    logManager.log(
                            new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                                    new Date().getTime(),
                                    "Checking fncs is initialized, currently " + isInitialized.isInited,
                                    LogLevel.INFO, ProcessStatus.RUNNING, true),
                            GridAppsDConstants.username);

                    client.publish(GridAppsDConstants.topic_FNCS_input, "{\"command\": \"isInitialized\"}");
                    initAttempts++;
                    Thread.sleep(1000);

                }

                if (initAttempts < MAX_INIT_ATTEMPTS) {
                    logManager.log(
                            new LogMessage(Integer.toString(simulationId), new Date().getTime(),
                                    "FNCS Initialized", LogLevel.INFO, ProcessStatus.RUNNING, true),
                            GridAppsDConstants.username);

                    //Send the timesteps by second for the amount of time specified in the simulation config
                    sendTimesteps(simulationConfig, simulationId);
                } else {
                    logManager.log(
                            new LogMessage(Integer.toString(simulationId), new Date().getTime(),
                                    "FNCS Initialization Failed", LogLevel.ERROR, ProcessStatus.ERROR, true),
                            GridAppsDConstants.username);

                }

                //call to stop the fncs broker
                client.publish(GridAppsDConstants.topic_FNCS_input, "{\"command\":  \"stop\"}");
                logManager.log(new LogMessage(Integer.toString(simulationId), new Date().getTime(),
                        "Simulation " + simulationId + " complete", LogLevel.INFO, ProcessStatus.COMPLETE,
                        true), GridAppsDConstants.username);
            } catch (Exception e) {
                log.error("Error during simulation", e);
                try {
                    logManager.log(new LogMessage(Integer.toString(simulationId), new Date().getTime(),
                            "Simulation error: " + e.getMessage(), LogLevel.ERROR, ProcessStatus.ERROR, true),
                            GridAppsDConstants.username);
                } catch (Exception e1) {
                    log.error("Error while reporting error status", e);
                }
            } finally {
                //shut down fncs broker and gridlabd and bridge if still running
                if (fncsProcess != null) {
                    fncsProcess.destroy();
                }
                if (gridlabdProcess != null) {
                    gridlabdProcess.destroy();
                }
                if (fncsBridgeProcess != null) {
                    fncsBridgeProcess.destroy();
                }
            }
        }
    });

    thread.start();
}