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:org.apache.pig.impl.streaming.StreamingUtil.java

/**
 * Set up the run-time environment of the managed process.
 * //w  w w . j  a  va2s .  co  m
 * @param pb
 *            {@link ProcessBuilder} used to exec the process
 */
private static void setupEnvironment(ProcessBuilder pb) {
    String separator = ":";
    Configuration conf = UDFContext.getUDFContext().getJobConf();
    Map<String, String> env = pb.environment();
    addJobConfToEnvironment(conf, env);

    // Add the current-working-directory to the $PATH
    File dir = pb.directory();
    String cwd = (dir != null) ? dir.getAbsolutePath() : System.getProperty("user.dir");

    String envPath = env.get(PATH);
    if (envPath == null) {
        envPath = cwd;
    } else {
        envPath = envPath + separator + cwd;
    }
    env.put(PATH, envPath);
}

From source file:org.mpi.vasco.util.commonfunc.FileOperations.java

/**
 * Execute shell commands./*from w  w w.j a v  a 2 s  .c  o m*/
 */
public static void executeShellCommands(String shellFilePath) {
    Debug.println("execute shell command " + shellFilePath);
    String dirPath = getToLevelDir(shellFilePath);
    Debug.println("get top level dir " + dirPath);
    makeScriptExecutable(shellFilePath);

    List<String> commands = new ArrayList<String>();
    commands.add("sh");
    commands.add(shellFilePath);
    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(new File(dirPath));
    pb.redirectErrorStream(true);
    Process process;
    try {
        process = pb.start();
        //Read output
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        while ((line = br.readLine()) != null)
            if (!line.equals(previous)) {
                previous = line;
                out.append(line).append('\n');
                Debug.println(line);
            }

        //Check result
        if (process.waitFor() == 0)
            Debug.println("Success!");
        else {
            System.out.println("Failed!");
            System.err.println(out.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    /*try {
       Process proc = Runtime.getRuntime().exec("cd " +dirPath +" && sh "+shellFilePath);
         InputStream stdin = proc.getInputStream();
         InputStreamReader isr = new InputStreamReader(stdin);
         BufferedReader br = new BufferedReader(isr);
         String line = null;
         System.out.println("<OUTPUT>");
         while ( (line = br.readLine()) != null)
      System.out.println(line);
       System.out.println("</OUTPUT>");
       try {
       if(proc.waitFor() == 0){
          Debug.println("command succeeds");
       }else{
          Debug.println("command failed");
       }
    } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }
       } catch (IOException e) {
    // TODO Auto-generated catch block
       e.printStackTrace();
    } */

}

From source file:org.openo.nfvo.jujuvnfmadapter.common.EntityUtils.java

/**
 * execute local command/*from w  w w.  j ava  2 s  .com*/
 * <br/>
 * 
 * @param dir the command path
 * @param command
 * @return response msg
 * @since NFVO 0.5
 */
public static ExeRes execute(String dir, List<String> command) {
    ExeRes er = new ExeRes();
    StringBuilder sb = new StringBuilder();
    try {
        if (SwitchController.isDebugModel()) {
            String resContent = new String(
                    FileUtils.readFile(new File(JujuConfigUtil.getValue("juju_cmd_res_file")), "UTF-8"));
            er.setBody(resContent);
            return er;
        }
        ProcessBuilder pb = new ProcessBuilder(command);
        if (StringUtils.isNotBlank(dir)) {
            pb.directory(new File(dir));
        }
        pb.redirectErrorStream(true);
        Process p = pb.start();

        // wait the process result
        buildProcessResult(er, p);

        InputStream in = p.getInputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) > 0) {
            sb.append(new String(buffer, 0, length));
        }
        in.close();
        er.setBody(sb.toString());
    } catch (Exception e) {
        er.setCode(ExeRes.FAILURE);
        er.setBody(e.getMessage());
        LOG.error("execute the command failed:{}", command, e);
    }
    return er;
}

From source file:me.philnate.textmanager.updates.Updater.java

/**
 * backups database in order some unexpected error occurs while update
 * happens/*from   ww  w .  j  a  v a  2 s  . c  o  m*/
 */
public static void backUp() {
    final ProcessBuilder dump = new ProcessBuilder(
            new File(installPath, getProgram("bin/mongodump")).toString(), "-h", "localhost:27017", "-o",
            backUpPath.getAbsolutePath(), "--db", "textManager");
    dump.directory(installPath);
    // try {
    new NotifyingThread() {

        @Override
        protected void doRun() {
            try {
                printOutputStream(dump);
            } catch (IOException e) {
                LOG.error("Error while doing backup of db files", e);
                Throwables.propagate(e);
            }
        }
    }.run();
}

From source file:com.ikanow.aleph2.harvest.logstash.utils.LogstashUtils.java

/** Builds a process to execute
 * @param global//  w  w w.  j a  v a  2  s  .  c  om
 * @param bucket_config
 * @param logstash_config
 * @param requested_docs
 * @param bucket_path if this is present, will log output to /tmp/unique_sig
 * @param context 
 * @return
 */
public static ProcessBuilder buildLogstashTest(final LogstashHarvesterConfigBean global,
        final LogstashBucketConfigBean bucket_config, final String logstash_config, final long requested_docs,
        final Optional<String> bucket_path) {

    final String log_file = System.getProperty("java.io.tmpdir") + File.separator
            + BucketUtils.getUniqueSignature(bucket_path.orElse("DNE"), Optional.empty());
    try { //(delete log file if it exists)
        new File(log_file).delete();
    } catch (Exception e) {
    }

    ArrayList<String> args = new ArrayList<String>();
    args.addAll(Arrays.asList(global.binary_path(), "-e", logstash_config));
    if (bucket_path.isPresent()) {
        args.addAll(Arrays.asList("-l", log_file));
    }
    if (0L == requested_docs) {
        args.add("-t"); // test mode, must faster
    } //TESTED

    if (bucket_config.debug_verbosity()) {
        args.add("--debug");
    } else {
        args.add("--verbose");
    }
    ProcessBuilder logstashProcessBuilder = new ProcessBuilder(args);
    logstashProcessBuilder = logstashProcessBuilder.directory(new File(global.working_dir()))
            .redirectErrorStream(true);
    logstashProcessBuilder.environment().put("JAVA_OPTS", "");

    return logstashProcessBuilder;
}

From source file:org.apache.asterix.installer.test.ReplicationIT.java

private static Process remoteInvoke(String cmd) throws Exception {
    ProcessBuilder pb = new ProcessBuilder("vagrant", "ssh", "cc", "-c", "MANAGIX_HOME=/tmp/asterix/ " + cmd);
    File cwd = new File(asterixProjectDir.toString() + "/" + CLUSTER_BASE);
    pb.directory(cwd);
    pb.redirectErrorStream(true);//from w ww .  j a v a  2s . c o  m
    Process p = pb.start();
    p.waitFor();
    return p;
}

From source file:me.philnate.textmanager.updates.Updater.java

/**
 * rolls back any made backups as something in the upgrade went wrong
 *//*from  w w  w .jav  a 2s  .c  om*/
private static void rollback() {
    final ProcessBuilder restore = new ProcessBuilder(
            new File(installPath, getProgram("bin/mongorestore")).toString(), "--drop", "-h", "localhost:27017",
            "--db", "textManager", backUpPath.getAbsolutePath());
    restore.directory(installPath);
    new NotifyingThread() {

        @Override
        protected void doRun() {
            try {
                printOutputStream(restore);
            } catch (IOException e) {
                LOG.error("Error while doing rollback of db files", e);
                Throwables.propagate(e);
            }
        }
    };
}

From source file:org.cloudifysource.azure.AbstractCliAzureDeploymentTest.java

public static String runCliCommands(File cliExecutablePath, List<List<String>> commands, boolean isDebug)
        throws IOException, InterruptedException {
    if (!cliExecutablePath.isFile()) {
        throw new IllegalArgumentException(cliExecutablePath + " is not a file");
    }/*from   ww w  .  j  a  v a2  s . c om*/

    File workingDirectory = cliExecutablePath.getAbsoluteFile().getParentFile();
    if (!workingDirectory.isDirectory()) {
        throw new IllegalArgumentException(workingDirectory + " is not a directory");
    }

    int argsCount = 0;
    for (List<String> command : commands) {
        argsCount += command.size();
    }

    // needed to properly intercept error return code
    String[] cmd = new String[(argsCount == 0 ? 0 : 1) + 4 /* cmd /c call cloudify.bat ["args"] */];
    int i = 0;
    cmd[i] = "cmd";
    i++;
    cmd[i] = "/c";
    i++;
    cmd[i] = "call";
    i++;
    cmd[i] = cliExecutablePath.getAbsolutePath();
    i++;
    if (argsCount > 0) {
        cmd[i] = "\"";
        //TODO: Use StringBuilder
        for (List<String> command : commands) {
            if (command.size() > 0) {
                for (String arg : command) {
                    if (cmd[i].length() > 0) {
                        cmd[i] += " ";
                    }
                    cmd[i] += arg;
                }
                cmd[i] += ";";
            }
        }
        cmd[i] += "\"";
    }
    final ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.directory(workingDirectory);
    pb.redirectErrorStream(true);

    String extCloudifyJavaOptions = "";

    if (isDebug) {
        extCloudifyJavaOptions += "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9000 -Xnoagent -Djava.compiler=NONE";
    }

    pb.environment().put("EXT_CLOUDIFY_JAVA_OPTIONS", extCloudifyJavaOptions);
    final StringBuilder sb = new StringBuilder();

    logger.info("running: " + cliExecutablePath + " " + Arrays.toString(cmd));

    // log std output and redirected std error
    Process p = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = reader.readLine();
    while (line != null) {
        sb.append(line).append('\n');
        line = reader.readLine();
        logger.info(line);
    }

    final String readResult = sb.toString();
    final int exitValue = p.waitFor();

    logger.info("Exit value = " + exitValue);
    if (exitValue != 0) {
        Assert.fail("Cli ended with error code: " + exitValue);
    }
    return readResult;
}

From source file:net.pms.util.ProcessUtil.java

public static void reboot(ArrayList<String> cmd, Map<String, String> env, String startdir,
        String... UMSOptions) {/*ww  w . ja v a 2  s  .c om*/
    final ArrayList<String> reboot = getUMSCommand();
    if (UMSOptions.length > 0) {
        reboot.addAll(Arrays.asList(UMSOptions));
    }
    if (cmd == null) {
        // We're doing a straight reboot
        cmd = reboot;
    } else {
        // We're running a script that will eventually restart UMS
        if (env == null) {
            env = new HashMap<>();
        }
        // Tell the script how to restart UMS
        env.put("RESTART_CMD", StringUtils.join(reboot, " "));
        env.put("RESTART_DIR", System.getProperty("user.dir"));
    }
    if (startdir == null) {
        startdir = System.getProperty("user.dir");
    }

    System.out.println("starting: " + StringUtils.join(cmd, " "));

    final ProcessBuilder pb = new ProcessBuilder(cmd);
    if (env != null) {
        pb.environment().putAll(env);
    }
    pb.directory(new File(startdir));
    System.out.println("in directory: " + pb.directory());
    try {
        pb.start();
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
    System.exit(0);
}

From source file:edu.stanford.epad.common.dicom.DCM4CHEEUtil.java

public static void dcmsnd(String inputPathFile, boolean throwException) throws Exception {
    InputStream is = null;/*  ww w  .j a v  a 2  s .  co  m*/
    InputStreamReader isr = null;
    BufferedReader br = null;

    try {
        String dcmServerTitlePort = aeTitle + "@localhost:" + dicomServerPort;
        dcmServerTitlePort = dcmServerTitlePort.trim();
        log.info("Sending file - command: ./dcmsnd " + dcmServerTitlePort + " " + inputPathFile);
        String[] command = { "./dcmsnd", dcmServerTitlePort, inputPathFile };
        ProcessBuilder pb = new ProcessBuilder(command);
        String dicomBinDirectoryPath = EPADConfig.getEPADWebServerDICOMBinDir();
        log.info("DICOM binary directory: " + dicomBinDirectoryPath);
        pb.directory(new File(dicomBinDirectoryPath));
        Process process = pb.start();
        process.getOutputStream();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.info("./dcmsend output: " + line);
        }

        try {
            int exitValue = process.waitFor();
            log.info("dcmsnd exit value is: " + exitValue);
            if (sb.toString().contains("Sent 0 objects")) {
                log.warning("Zero objects sent to dcm4che, some error has occurred");
                throw new Exception("Error sending files to dcm4che");
            }

        } catch (InterruptedException e) {
            log.warning("Error sending DICOM files in: " + inputPathFile, e);
        }
        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error")) {
            throw new IllegalStateException("Failed for: " + cmdLineOutput);
        }
    } catch (Exception e) {
        if (e instanceof IllegalStateException && throwException) {
            throw e;
        }
        log.warning("dcmsnd failed: " + e.getMessage());
        if (throwException) {
            throw new IllegalStateException("dcmsnd failed", e);
        }
    } catch (OutOfMemoryError oome) {
        log.warning("dcmsnd ran out of memory", oome);
        if (throwException) {
            throw new IllegalStateException("dcmsnd ran out of memory", oome);
        }
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
    }
}