Example usage for java.lang ProcessBuilder environment

List of usage examples for java.lang ProcessBuilder environment

Introduction

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

Prototype

Map environment

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

Click Source Link

Usage

From source file:br.on.daed.services.pdf.DadosMagneticos.java

public static byte[] gerarPDF(String ano, String tipo)
        throws IOException, InterruptedException, UnsupportedOperationException {

    File tmpFolder;/*from  w  w  w. jav a 2s.c  om*/
    String folderName;

    Double anoDouble = Double.parseDouble(ano);
    List<String> dados = Arrays.asList(TIPO_DADOS_MAGNETICOS);

    byte[] ret = null;

    if (anoDouble >= ANO_MAGNETICO[0] && anoDouble < ANO_MAGNETICO[1] && dados.contains(tipo)) {

        do {

            folderName = "/tmp/dislin" + Double.toString(System.currentTimeMillis() * Math.random());
            tmpFolder = new File(folderName);

        } while (tmpFolder.exists());

        tmpFolder.mkdir();

        ProcessBuilder processBuilder = new ProcessBuilder("/opt/declinacao-magnetica/./gerar", ano, tipo);

        processBuilder.directory(tmpFolder);

        processBuilder.environment().put("LD_LIBRARY_PATH", "/usr/local/dislin");

        Process proc = processBuilder.start();

        proc.waitFor();

        ProcessHelper.outputProcess(proc);

        File arquivoServido = new File(folderName + "/dislin.pdf");

        FileInputStream fis = new FileInputStream(arquivoServido);

        ret = IOUtils.toByteArray(fis);

        processBuilder = new ProcessBuilder("rm", "-r", folderName);

        tmpFolder = new File("/");

        processBuilder.directory(tmpFolder);

        Process delete = processBuilder.start();

        delete.waitFor();

    } else {
        throw new UnsupportedOperationException("Entrada invlida");
    }
    return ret;
}

From source file:com.thoughtworks.gauge.util.GaugeUtil.java

public static void setGaugeEnvironmentsTo(ProcessBuilder processBuilder, GaugeSettingsModel settings) {
    Map<String, String> env = processBuilder.environment();
    env.put(Constants.GAUGE_HOME, settings.getHomePath());
}

From source file:com.yahoo.storm.yarn.TestIntegration.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static int execute(List<String> cmd) throws InterruptedException, IOException {
    LOG.info(Joiner.on(" ").join(cmd));
    ProcessBuilder pb = new ProcessBuilder(cmd);
    Map env = pb.environment();
    env.putAll(System.getenv());//from  w  w w.j  a  v a 2s . co m
    env.put(Environment.PATH.name(),
            "bin:" + storm_home + File.separator + "bin:" + env.get(Environment.PATH.name()));
    String yarn_conf_dir = yarn_site_xml.getParent().toString();
    env.put("STORM_YARN_CONF_DIR", yarn_conf_dir);
    List<URL> logback_xmls = Utils.findResources("logback.xml");
    if (logback_xmls != null && logback_xmls.size() >= 1) {
        String logback_xml = logback_xmls.get(0).getFile();
        LOG.debug("logback_xml:" + yarn_conf_dir + File.separator + "logback.xml");
        FileUtils.copyFile(new File(logback_xml), new File(yarn_conf_dir + File.separator + "logback.xml"));
    }
    List<URL> log4j_properties = Utils.findResources("log4j.properties");
    if (log4j_properties != null && log4j_properties.size() >= 1) {
        String log4j_properties_file = log4j_properties.get(0).getFile();
        LOG.debug("log4j_properties_file:" + yarn_conf_dir + File.separator + "log4j.properties");
        FileUtils.copyFile(new File(log4j_properties_file),
                new File(yarn_conf_dir + File.separator + "log4j.properties"));
    }

    Process proc = pb.start();
    Util.redirectStreamAsync(proc.getInputStream(), System.out);
    Util.redirectStreamAsync(proc.getErrorStream(), System.err);
    int status = proc.waitFor();
    return status;
}

From source file:it.crs4.pydoop.mapreduce.pipes.Application.java

/**
 * Run a given command in a subprocess, including threads to copy its stdout
 * and stderr to our stdout and stderr./*from w  w w .  ja v  a2  s  .  c  o m*/
 * @param command the command and its arguments
 * @param env the environment to run the process in
 * @return a handle on the process
 * @throws IOException
 */
static Process runClient(List<String> command, Map<String, String> env) throws IOException {
    ProcessBuilder builder = new ProcessBuilder(command);
    if (env != null) {
        builder.environment().putAll(env);
    }
    Process result = builder.start();
    return result;
}

From source file:org.apache.hyracks.control.nc.service.NCService.java

/**
 * Attempts to launch the "real" NCDriver, based on the configuration
 * information gathered so far.// w w w. j  a  v a 2 s  .  c  o m
 * @return true if the process was successfully launched and has now
 * exited with a 0 (normal) exit code. false if some configuration error
 * prevented the process from being launched or the process returned
 * a non-0 (abnormal) exit code.
 */
private static boolean launchNCProcess() {
    try {
        ProcessBuilder pb = new ProcessBuilder(buildCommand());
        configEnvironment(pb.environment());
        // QQQ inheriting probably isn't right
        pb.inheritIO();

        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("Launching NCDriver process");
        }

        // Logfile
        if (!"-".equals(config.logdir)) {
            pb.redirectErrorStream(true);
            File log = new File(config.logdir);
            if (!log.mkdirs()) {
                if (!log.isDirectory()) {
                    throw new IOException(config.logdir + ": cannot create");
                }
                // If the directory IS there, all is well
            }
            File logfile = new File(config.logdir, "nc-" + ncId + ".log");
            // Don't care if this succeeds or fails:
            logfile.delete();
            pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logfile));
            if (LOGGER.isLoggable(Level.INFO)) {
                LOGGER.info("Logging to " + logfile.getCanonicalPath());
            }
        }
        proc = pb.start();

        boolean waiting = true;
        int retval = 0;
        while (waiting) {
            try {
                retval = proc.waitFor();
                waiting = false;
            } catch (InterruptedException ignored) {
            }
        }
        LOGGER.info("NCDriver exited with return value " + retval);
        if (retval == 99) {
            LOGGER.info("Terminating NCService based on return value from NCDriver");
            exit(0);
        }
        return retval == 0;
    } catch (Exception e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, "Configuration from CC broken", e);
        }
        return false;
    }
}

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 .jav  a2s .  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:org.jsweet.util.ProcessUtil.java

public static void runCmd(File directory, Consumer<String> stdoutConsumer, String... cmd) {
    System.out.println("run command: " + StringUtils.join(cmd, " "));

    String[] args;//  w w  w  .j a v a  2 s  .  c  om
    if (System.getProperty("os.name").startsWith("Windows")) {
        args = new String[] { "cmd", "/c" };
    } else {
        args = new String[0];
    }
    args = ArrayUtils.addAll(args, cmd);

    System.out.println("run command: '" + StringUtils.join(args, " ") + "' in directory " + directory);
    // logger.fine("run command: " + StringUtils.join(args, " "));
    int code = -1;
    try {

        ProcessBuilder processBuilder = new ProcessBuilder(args);
        processBuilder.redirectErrorStream(true);
        if (directory != null) {
            processBuilder.directory(directory);
        }
        if (!StringUtils.isBlank(EXTRA_PATH)) {
            processBuilder.environment().put("PATH",
                    processBuilder.environment().get("PATH") + File.pathSeparator + EXTRA_PATH);
        }

        Process process = processBuilder.start();

        try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = in.readLine()) != null) {
                if (stdoutConsumer != null) {
                    stdoutConsumer.accept(line);
                } else {
                    logger.info("OUT:" + line);
                }
            }
        }

        code = process.waitFor();
        if (code != 0) {
            throw new RuntimeException(
                    "error while exectuting: " + StringUtils.join(args, " ") + ", error code: " + code);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ikanow.aleph2.harvest.script.utils.ScriptUtils.java

/**
 * Creates a processbuilder pointed at the given script path and adds the working dir and environment vars for you.
 * Just runs a process that does "sh <script_file_path>"
 * @param script_file_path//from   www .ja va 2s . c  o m
 * @param working_dir
 * @return
 * @throws JsonProcessingException 
 * @throws ExecutionException 
 * @throws InterruptedException 
 */
public static ProcessBuilder createProcessBuilderForScriptFile(final String script_file_path,
        final String working_dir, final Optional<Long> test_requested_num_objects,
        final Optional<Long> test_max_runtime_s, final Map<String, String> user_args,
        final IHarvestContext context, final DataBucketBean bucket, final String aleph_global_root_path)
        throws JsonProcessingException, InterruptedException, ExecutionException {
    _logger.debug("create pb for script file: " + script_file_path);

    ArrayList<String> args = new ArrayList<String>();
    args.add("sh");
    args.add(script_file_path);
    final ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(new File(working_dir)).redirectErrorStream(true);
    pb.environment().put("JAVA_OPTS", "");
    if (test_requested_num_objects.isPresent())
        pb.environment().put(ENV_TEST_NUM_OBJ, test_requested_num_objects.get().toString());
    if (test_max_runtime_s.isPresent())
        pb.environment().put(ENV_TEST_MAX_RUNTIME_S, test_max_runtime_s.get().toString());
    //add in default env vars
    final String classpath = Stream
            .concat(context.getHarvestContextLibraries(Optional.empty()).stream(),
                    context.getHarvestLibraries(Optional.of(bucket)).get().values().stream())
            .collect(Collectors.joining(":"));
    pb.environment().put(ENV_MODULE_PATH,
            context.getHarvestContextLibraries(Optional.empty()).stream().collect(Collectors.joining(":")));
    pb.environment().put(ENV_LIBRARY_PATH, context.getHarvestLibraries(Optional.of(bucket)).get().values()
            .stream().collect(Collectors.joining(":")));
    pb.environment().put(ENV_CLASS_PATH, classpath);
    pb.environment().put(ENV_BUCKET_HDFS_PATH, aleph_global_root_path + "/data" + bucket.full_name());
    pb.environment().put(ENV_BUCKET_SIGNATURE,
            BucketUtils.getUniqueSignature(bucket.full_name(), Optional.empty()));
    pb.environment().put(ENV_BUCKET_PATH, bucket.full_name());
    pb.environment().put(ENV_BUCKET_STR, BeanTemplateUtils.toJson(bucket).toString());
    //add user args   as env vars
    user_args.forEach((k, val) -> pb.environment().put(k, val));
    return pb;
}

From source file:uk.ac.sanger.cgp.wwdocker.actions.Local.java

public static int execCommand(String command, Map envs, boolean shellCmd) {
    ProcessBuilder pb;
    if (shellCmd) {
        pb = new ProcessBuilder("/bin/sh", "-c", command);
    } else {//from  w  ww  .  j a  v a 2  s .  c om
        pb = new ProcessBuilder(command.split(" "));
    }
    Map<String, String> pEnv = pb.environment();
    pEnv.putAll(envs);
    logger.info("Executing: " + command);
    int exitCode = -1;
    Process p = null;
    File tempOut = null;
    File tempErr = null;
    try {
        tempOut = File.createTempFile("wwdExec", ".out");
        tempErr = File.createTempFile("wwdExec", ".err");
        pb.redirectOutput(tempOut);
        pb.redirectError(tempErr);
        p = pb.start();
        exitCode = p.waitFor();
    } catch (InterruptedException | IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (tempOut != null && tempErr != null) {
            try {
                logger.info(IOUtils.toString(new FileInputStream(tempOut)));
                logger.error(IOUtils.toString(new FileInputStream(tempErr)));
                tempOut.delete();
                tempErr.delete();
            } catch (IOException e) {
                logger.error("Failed to get output from log files");
            }
        }
        if (p != null) {
            p.destroy();
            exitCode = p.exitValue();
        }
    }
    logger.trace("Exit code: " + exitCode);
    return exitCode;
}

From source file:uk.ac.sanger.cgp.wwdocker.actions.Local.java

public static Map<String, String> execCapture(String command, Map envs, boolean shellCmd) {
    Map<String, String> result = new HashMap();
    ProcessBuilder pb;
    if (shellCmd) {
        pb = new ProcessBuilder("/bin/sh", "-c", command);
    } else {//from w  ww.j a va  2 s .co  m
        pb = new ProcessBuilder(command.split(" "));
    }
    Map<String, String> pEnv = pb.environment();
    if (envs != null) {
        pEnv.putAll(envs);
    }
    logger.info("Executing: " + command);
    int exitCode = -1;
    Process p = null;
    File tempOut = null;
    File tempErr = null;
    try {
        tempOut = File.createTempFile("wwdExec", ".out");
        tempErr = File.createTempFile("wwdExec", ".err");
        pb.redirectOutput(tempOut);
        pb.redirectError(tempErr);
        p = pb.start();
        exitCode = p.waitFor();
    } catch (InterruptedException | IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (tempOut != null && tempErr != null) {
            try {
                result.put("stdout", StringUtils.chomp(IOUtils.toString(new FileInputStream(tempOut))));
                result.put("stderr", StringUtils.chomp(IOUtils.toString(new FileInputStream(tempErr))));
                tempOut.delete();
                tempErr.delete();
                logger.info(result.get("stdout"));
                logger.error(result.get("stderr"));
            } catch (IOException e) {
                logger.error("Failed to get output from log files");
            }
        }
        if (p != null) {
            p.destroy();
            exitCode = p.exitValue();
        }
    }
    result.put("exitCode", Integer.toString(exitCode));
    return result;
}