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:uk.ac.ox.it.ords.api.database.services.impl.hibernate.SQLServicePostgresImpl.java

@Override
public void importSQLFileToDatabase(String hostName, String databaseName, File sqlFile, int databaseId)
        throws Exception {
    DatabaseServer server = ServerConfigurationService.Factory.getInstance().getDatabaseServer(hostName);
    //Subject s = SecurityUtils.getSubject();
    //String principalName = s.getPrincipal().toString();
    //User u = this.getUserByPrincipal(principalName);
    //RestoreEmailService emailService = RestoreEmailService.Factory.getInstance();
    //emailService.setEmail(u.getEmail());
    //emailService.setDatabaseName(databaseName);

    Properties properties = ConfigurationConverter.getProperties(MetaConfiguration.getConfiguration());
    String postgres_bin = "";
    if (properties.containsKey("ords.postgresql.bin.path")) {
        postgres_bin = properties.getProperty("ords.postgresql.bin.path");
    }//  w  w w .j a va 2  s .  c o m
    ProcessBuilder processBuilder = new ProcessBuilder(postgres_bin + "psql", "-d", databaseName, "-h",
            hostName, "-U", server.getUsername(), "-f", sqlFile.toString());
    processBuilder.environment().put("PGPASSWORD", server.getPassword());
    DatabaseUploadService uploadService = DatabaseUploadService.Factory.getInstance();
    try {
        Process process = processBuilder.start();
        uploadService.setImportProgress(databaseId, OrdsPhysicalDatabase.ImportType.IN_PROGRESS);
        InputStream is = process.getInputStream();
        InputStreamReader reader = new InputStreamReader(is);
        BufferedReader buffer = new BufferedReader(reader);
        String line;
        while ((line = buffer.readLine()) != null) {
            System.out.println(line);
            if (log.isDebugEnabled()) {
                log.debug(line);
            }
        }
        //emailService.sendRestoreSuccessfulMessage();
        uploadService.setImportProgress(databaseId, OrdsPhysicalDatabase.ImportType.FINISHED);
    } catch (Exception e) {
        log.error("ERROR", e);
        try {
            //emailService.sendRestoreUnsuccessfulMessage(e.toString());
            uploadService.setImportProgress(databaseId, OrdsPhysicalDatabase.ImportType.FAILED);
        } catch (Exception e1) {
            log.error("ERROR", e1);
            e1.printStackTrace();
        }
    }
}

From source file:org.jenkinci.plugins.mock_slave.MockSlaveLauncher.java

@Override
public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException {
    listener.getLogger().println("Launching");
    File portFile = File.createTempFile("jenkins-port", "");
    final ProcessBuilder pb = new ProcessBuilder("java", "-jar", Which.jarFile(Which.class).getAbsolutePath(),
            "-tcp", portFile.getAbsolutePath());
    final EnvVars cookie = EnvVars.createCookie();
    pb.environment().putAll(cookie);
    final Process proc = pb.start();
    new StreamCopyThread("stderr copier for remote agent on " + computer.getDisplayName(),
            proc.getErrorStream(), listener.getLogger()).start();
    while (portFile.length() == 0) {
        Thread.sleep(100);//ww  w.ja  va2 s. co m
    }
    int port = Integer.parseInt(FileUtils.readFileToString(portFile));
    listener.getLogger().println("connecting to localhost:" + port);
    Socket s = new Socket(getLoopbackAddress(), port);
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    if (latency > 0 || bandwidth > 0) {
        listener.getLogger().printf("throttling with latency=%dms bandwidth=%dbps%n", latency, bandwidth);
        Throttler t = new Throttler(latency, bandwidth, is, os);
        is = t.is();
        os = t.os();
    }
    computer.setChannel(is, os, listener.getLogger(), new Channel.Listener() {
        @Override
        public void onClosed(Channel channel, IOException cause) {
            try {
                ProcessTree.get().killAll(proc, cookie);
            } catch (InterruptedException e) {
                LOGGER.log(Level.INFO, "interrupted", e);
            }
        }
    });
    LOGGER.log(Level.INFO, "slave agent launched for {0}", computer.getDisplayName());
}

From source file:com.gordoni.opal.ScenarioSet.java

public void subprocess(String cmd, String prefix, String... args) throws IOException, InterruptedException {
    String real_cwd = System.getProperty("user.dir");
    List<String> arguments = new ArrayList<String>(Arrays.asList(args));
    arguments.add(0, real_cwd + "/" + cmd);
    ProcessBuilder pb = new ProcessBuilder(arguments);
    Map<String, String> env = pb.environment();
    env.put("OPAL_FILE_PREFIX", cwd + "/" + prefix);
    pb.redirectError(Redirect.INHERIT);/*from   w w w  .j av  a  2 s .c om*/
    Process p = pb.start();

    InputStream stdout = p.getInputStream();
    byte buf[] = new byte[8192];
    while (stdout.read(buf) != -1) {
    }
    p.waitFor();
    assert (p.exitValue() == 0);
}

From source file:org.sonar.runner.api.CommandExecutor.java

int execute(Command command, StreamConsumer stdOut, StreamConsumer stdErr, long timeoutMilliseconds,
        @Nullable ProcessMonitor processMonitor) {
    ExecutorService executorService = null;
    Process process = null;//from   w  w w .ja v  a2  s .  com
    StreamGobbler outputGobbler = null;
    StreamGobbler errorGobbler = null;
    try {
        ProcessBuilder builder = new ProcessBuilder(command.toStrings());
        builder.directory(command.directory());
        builder.environment().putAll(command.envVariables());
        process = builder.start();

        outputGobbler = new StreamGobbler(process.getInputStream(), stdOut);
        errorGobbler = new StreamGobbler(process.getErrorStream(), stdErr);
        outputGobbler.start();
        errorGobbler.start();

        executorService = Executors.newSingleThreadExecutor();
        final Future<Integer> futureTask = executeProcess(executorService, process);
        if (processMonitor != null) {
            monitorProcess(processMonitor, executorService, process);
        }

        int exitCode = futureTask.get(timeoutMilliseconds, TimeUnit.MILLISECONDS);
        waitUntilFinish(outputGobbler);
        waitUntilFinish(errorGobbler);
        verifyGobbler(command, outputGobbler, "stdOut");
        verifyGobbler(command, errorGobbler, "stdErr");
        return exitCode;

    } catch (TimeoutException te) {
        process.destroy();
        throw new CommandException("Timeout exceeded: " + timeoutMilliseconds + " ms", command, te);

    } catch (CommandException e) {
        throw e;

    } catch (Exception e) {
        throw new CommandException("Fail to execute command", command, e);

    } finally {
        waitUntilFinish(outputGobbler);
        waitUntilFinish(errorGobbler);
        closeStreams(process);
        if (executorService != null) {
            executorService.shutdown();
        }
    }
}

From source file:com.asakusafw.testdriver.DefaultJobExecutor.java

private int runCommand(List<String> commandLine, Map<String, String> environmentVariables) throws IOException {
    LOG.info(MessageFormat.format(Messages.getString("DefaultJobExecutor.infoEchoCommandLine"), //$NON-NLS-1$
            toCommandLineString(commandLine)));

    ProcessBuilder builder = new ProcessBuilder(commandLine);
    builder.redirectErrorStream(true);//from   ww  w  .  j a va  2s.  c  o  m
    builder.environment().putAll(environmentVariables);
    File hadoopCommand = configurations.getHadoopCommand();
    if (hadoopCommand != null) {
        builder.environment().put("HADOOP_CMD", hadoopCommand.getAbsolutePath()); //$NON-NLS-1$
    }
    builder.directory(new File(System.getProperty("user.home", "."))); //$NON-NLS-1$ //$NON-NLS-2$

    int exitCode;
    Process process = builder.start();
    try (InputStream is = process.getInputStream()) {
        InputStreamThread it = new InputStreamThread(is);
        it.start();
        exitCode = process.waitFor();
        it.join();
    } catch (InterruptedException e) {
        throw new IOException(
                MessageFormat.format(Messages.getString("DefaultJobExecutor.errorExecutionInterrupted"), //$NON-NLS-1$
                        toCommandLineString(commandLine)),
                e);
    } finally {
        process.getOutputStream().close();
        process.getErrorStream().close();
        process.destroy();
    }
    return exitCode;
}

From source file:org.dbgl.util.FileUtils.java

private static void executeCommand(final DosboxVersion dbversion, final List<String> execCommands,
        final File cwd, Map<String, String> env, final boolean waitFor) throws IOException {
    StringBuffer cmd = new StringBuffer();
    try {//from  w w  w .  j  a v  a  2s .co m
        File dir = (cwd == null) ? DOSROOT_DIR_FILE : cwd;
        if (PlatformUtils.IS_OSX && dbversion != null && dbversion.isUsingCurses()) {
            String terminalCommand = StringUtils.join(execCommands, ' ');
            execCommands.clear();
            execCommands.add("osascript");
            execCommands.add("-e");
            execCommands.add("tell application \"Terminal\" to do script \"cd '" + dir + "'; " + terminalCommand
                    + "; exit;\"");
        }
        System.out.print(StringUtils.join(execCommands, ' '));
        ProcessBuilder pb = new ProcessBuilder(execCommands.toArray(new String[execCommands.size()]));
        pb.directory(dir);
        Map<String, String> environment = pb.environment();
        if (env != null) {
            environment.putAll(env);
            System.out.print(env);
        }
        System.out.println();
        Process proc = pb.start();
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "DOSBox stderr");
        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "DOSBox stdout");
        outputGobbler.start();
        errorGobbler.start();
        if (waitFor) {
            try {
                proc.waitFor();
            } catch (InterruptedException e) {
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException(Settings.getInstance().msg("general.error.startdosbox", new Object[] { cmd }));
    }
}

From source file:org.apache.storm.util.CoreUtil.java

@ClojureClass(className = "backtype.storm.util#launch-process")
public static java.lang.Process launchProcess(String command, Map<String, String> environment)
        throws IOException {
    String[] cmdlist = (new String("nohup " + command)).split(" ");
    ArrayList<String> buff = new ArrayList<String>();
    for (String tok : cmdlist) {
        if (!tok.isEmpty()) {
            buff.add(tok);// w  w w.  j  ava2  s.c o m
        }
    }

    ProcessBuilder builder = new ProcessBuilder(buff);
    Map<String, String> processEvn = builder.environment();
    for (Entry<String, String> entry : environment.entrySet()) {
        processEvn.put(entry.getKey(), entry.getValue());
    }
    builder.redirectErrorStream(true);
    return builder.start();
}

From source file:com.jstar.eclipse.services.JStar.java

public Process executeJStar(final IFolder workingDirectory, final IFolder folder, final String spec,
        final String logic, final String abs, final String jimpleFile, final PrintMode printMode,
        final String debugMode) throws IOException {

    final List<String> command = new ArrayList<String>();
    command.add(PreferenceConstants.getJStarExecutable());
    command.add("-e");
    command.add(printMode.getCmdOption());
    command.add("-l");
    command.add(logic);/*from w  w w.ja v  a  2s  . c  o m*/
    command.add("-a");
    command.add(abs);
    command.add("-s");
    command.add(spec);
    command.add("-f");
    command.add(jimpleFile);

    if (StringUtils.isNotBlank(debugMode)) {
        command.add("-d");
        command.add(debugMode);
    }

    ProcessBuilder pb = new ProcessBuilder(command);
    pb.directory(new File(workingDirectory.getLocation().toOSString()));

    Map<String, String> env = pb.environment();

    //TODO: jStar accepts only ':' as path separator
    env.put(PreferenceConstants.JSTAR_LOGIC_LIBRARY,
            PreferenceConstants.getJStarLogicLibrary() + ':' + folder.getLocation().toOSString());

    env.put(PreferenceConstants.JSTAR_ABS_LIBRARY,
            PreferenceConstants.getJStarAbsLibrary() + ':' + folder.getLocation().toOSString());

    env.put(PreferenceConstants.JSTAR_SPECS_LIBRARY,
            PreferenceConstants.getJStarSpecLibrary() + ':' + folder.getLocation().toOSString());

    env.put(PreferenceConstants.JSTAR_SMT_PATH, PreferenceConstants.getSmtPath());
    env.put(PreferenceConstants.JSTAR_SMT_ARGUMENTS, PreferenceConstants.getSmtAtguments());

    env.put(TERM, XTERMCOLOR);

    return pb.start();
}

From source file:uk.ac.ox.it.ords.api.database.services.impl.hibernate.SQLServicePostgresImpl.java

@Override
public File exportSQLFileFromDatabase(int dbId) throws Exception {
    OrdsPhysicalDatabase database = this.getPhysicalDatabaseFromID(dbId);
    DatabaseServer server = ServerConfigurationService.Factory.getInstance()
            .getDatabaseServer(database.getDatabaseServer());
    // create the file
    String databaseName = database.getDbConsumedName();
    File file = File.createTempFile("dump_" + databaseName, "sql");
    Properties properties = ConfigurationConverter.getProperties(MetaConfiguration.getConfiguration());
    String postgres_bin = "";
    if (properties.containsKey("ords.postgresql.bin.path")) {
        postgres_bin = properties.getProperty("ords.postgresql.bin.path");
    }//from w w  w .  j  av a2s. c  o m
    ProcessBuilder processBuilder = new ProcessBuilder(postgres_bin + "pg_dump", "-f", file.toString(), "-v",
            "-o", "-h", database.getDatabaseServer(), "-U", server.getUsername(), database.getDbConsumedName());

    processBuilder.environment().put("PGPASSWORD", server.getPassword());
    Process process = processBuilder.start();
    try {
        InputStream is = process.getInputStream();
        InputStreamReader reader = new InputStreamReader(is);
        BufferedReader buffer = new BufferedReader(reader);
        String line;
        while ((line = buffer.readLine()) != null) {
            System.out.println(line);
            if (log.isDebugEnabled()) {
                log.debug(line);
            }
        }
    } catch (Exception e) {
        log.error("ERROR", e);
    }
    return file;
}