Example usage for org.apache.commons.exec.environment EnvironmentUtils getProcEnvironment

List of usage examples for org.apache.commons.exec.environment EnvironmentUtils getProcEnvironment

Introduction

In this page you can find the example usage for org.apache.commons.exec.environment EnvironmentUtils getProcEnvironment.

Prototype

public static Map<String, String> getProcEnvironment() throws IOException 

Source Link

Document

Find the list of environment variables for this process.

Usage

From source file:com.oneops.inductor.ProcessRunner.java

/**
 * Returns env variables to be used for the cmd. Right now env var
 * is explicitly set only for local workorders (chef-solo commands).
 *
 * @param cmd    command array/*from   w ww  .  j  av  a  2  s  .c om*/
 * @param logKey log key
 * @return env vars map or <code>null</code> if there is no env
 * vars configured or for remote wo command.
 */
private Map<String, String> getEnvVars(String logKey, String[] cmd) {
    Map<String, String> envVars = null;
    if ("chef-solo".equalsIgnoreCase(cmd[0])) {
        if (!config.getEnvVars().isEmpty()) {
            try {
                // Env = Process Env +  Inductor config env.
                envVars = EnvironmentUtils.getProcEnvironment();
                envVars.putAll(config.getEnvVars());
            } catch (IOException e) {
                logger.warn(logKey + " Can't get the process env: " + e.getMessage());
            }
        }
    }
    return envVars;
}

From source file:com.virtualparadigm.packman.processor.JPackageManager.java

public static boolean installPackage(File packageFile, File targetRootDir, File packageManagerDataDir,
        File localConfigurationFile, boolean developmentMode) {
    logger.info("PackageManager::installPackage - installing package: " + packageFile.getAbsolutePath());
    boolean status = false;
    if (packageFile != null) {
        File tempDir = JPackageManager.prepare(packageFile, packageManagerDataDir);

        Properties packageProperties = JPackageManager.validate(tempDir);

        if (packageProperties != null) {
            JPackageManager.configure(tempDir, localConfigurationFile);

            File autorunPreDir = new File(tempDir.getAbsolutePath() + "/" + AUTORUN_DIR_NAME + "/"
                    + INSTALL_DIR_NAME + "/" + INSTALL_PRE_DIR_NAME);
            File autorunPostDir = new File(tempDir.getAbsolutePath() + "/" + AUTORUN_DIR_NAME + "/"
                    + INSTALL_DIR_NAME + "/" + INSTALL_POST_DIR_NAME);

            Map<String, String> environmentVariableMap = null;
            try {
                environmentVariableMap = (Map<String, String>) EnvironmentUtils.getProcEnvironment();
                environmentVariableMap.put(JPackageManager.RUNTIME_TEMP_DIR_KEY, tempDir.getAbsolutePath());
                environmentVariableMap.put(JPackageManager.RUNTIME_DEST_DIR_KEY,
                        targetRootDir.getAbsolutePath());
                environmentVariableMap.put(JPackageManager.RUNTIME_WORKING_DIR_KEY,
                        System.getProperty("user.dir"));
                try {
                    environmentVariableMap
                            .put(JPackageManager.RUNTIME_TOOL_ROOT_DIR_KEY,
                                    new File(JPackageManager.class.getProtectionDomain().getCodeSource()
                                            .getLocation().toURI().getPath()).getParentFile()
                                                    .getAbsolutePath());
                } catch (URISyntaxException urie) {
                    logger.error("", urie);
                }// ww  w .  j  a  va2  s .c  o m
            } catch (IOException ioe) {
                logger.error("", ioe);
            }

            JPackageManager.autorun(autorunPreDir, environmentVariableMap);

            JPackageManager.deploy(targetRootDir, tempDir);

            JPackageManager.autorun(autorunPostDir, environmentVariableMap);
            //                JPackageManager.autorun(new File(tempDir.getAbsolutePath() + "/" + AUTORUN_DIR_NAME + "/" + INSTALL_DIR_NAME));

            JPackageManager.finalize(packageProperties.getProperty(PACKAGE_NAME_KEY),
                    packageProperties.getProperty(PACKAGE_VERSION_KEY), packageManagerDataDir, targetRootDir);

            status = true;
        }

        if (!developmentMode) {
            JPackageManager.cleanup(tempDir);
        }
    }
    return status;
}

From source file:com.boundlessgeo.wps.grass.GrassProcesses.java

/**
 * Define environment variable for independent grass operation.
 * see: http://grasswiki.osgeo.org/wiki/GRASS_and_Shell
 * @param geodb//from   w w w  .j ava 2 s  .co  m
 * @param location
 * @param mapset
 * @return
 * @throws IOException
 */
private static Map<String, String> customEnv(File geodb, File location, File mapset) throws IOException {
    Map<String, String> env = EnvironmentUtils.getProcEnvironment();
    // GRASS ENV
    File GISBASE = new File(EXEC).getParentFile();
    String GRASS_VERSION = "7.0.0";
    EnvironmentUtils.addVariableToEnvironment(env, "GISBASE=" + GISBASE);
    EnvironmentUtils.addVariableToEnvironment(env, "GRASS_VERSION=" + GRASS_VERSION);

    File GISRC = new File(System.getProperty("user.home"),
            ".grassrc." + GRASS_VERSION + "." + location.getName());
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(GISRC))) {
        writer.write("GISDBASE: " + geodb);
        writer.newLine();
        writer.write("LOCATION_NAME: " + location.getName());
        writer.newLine();
        writer.write("MAPSET: PERMANENT");
        writer.newLine();
        writer.write("GRASS_GUI: text");
        writer.newLine();
    }
    EnvironmentUtils.addVariableToEnvironment(env, "GISRC=" + GISRC);

    // SYSTEM ENV
    String bin = new File(GISBASE, "bin").getAbsolutePath();
    String scripts = new File(GISBASE, "scripts").getAbsolutePath();
    String lib = new File(GISBASE, "lib").getAbsolutePath();
    if (SYSTEM == Env.WINDOWS) {
        String PATH = env.get("PATH") + pathSeparator + bin + pathSeparator + scripts + pathSeparator + lib;
        EnvironmentUtils.addVariableToEnvironment(env, "PATH=" + PATH);
    } else {
        String PATH = env.get("PATH") + pathSeparator + bin + pathSeparator + scripts;
        EnvironmentUtils.addVariableToEnvironment(env, "PATH=" + PATH);
        if (SYSTEM == Env.LINUX) {
            String LD_LIBRARY_PATH = (env.containsKey("LD_LIBRARY_PATH")
                    ? env.get("LD_LIBRARY_PATH") + pathSeparator
                    : "") + lib;
            EnvironmentUtils.addVariableToEnvironment(env, "LD_LIBRARY_PATH=" + LD_LIBRARY_PATH);
        } else if (SYSTEM == Env.MAC) {
            String DYLD_LIBRARY_PATH = (env.containsKey("DYLD_LIBRARY_PATH")
                    ? env.get("DYLD_LIBRARY_PATH") + pathSeparator
                    : "") + lib;
            EnvironmentUtils.addVariableToEnvironment(env, "DYLD_LIBRARY_PATH=" + DYLD_LIBRARY_PATH);
        }
    }
    return env;
}

From source file:it.drwolf.ridire.index.cwb.CWBCollocatesExtractor.java

private File tabulate() throws IOException {
    EnvironmentUtils.addVariableToEnvironment(EnvironmentUtils.getProcEnvironment(), "LC_ALL=C");
    File tmpAwk = File.createTempFile("ridireAWK", ".awk");
    String awk = this.createAWKString();
    FileUtils.writeStringToFile(tmpAwk, awk);
    File tmpTabulate = File.createTempFile("ridireTAB", ".tab");
    String tabulate = this.createTabulateString(tmpAwk, tmpTabulate);
    File tempSh = File.createTempFile("ridireSH", ".sh");
    FileUtils.writeStringToFile(tempSh, tabulate);
    tempSh.setExecutable(true);//from w  w  w  . j  ava  2  s.c o m
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBCollocatesExtractor.CWB_COLLOCATES_EXTRACTOR_TIMEOUT);
    executor.setWatchdog(watchdog);
    CommandLine commandLine = new CommandLine(this.cqpExecutable);
    commandLine.addArgument("-f").addArgument(tempSh.getAbsolutePath()).addArgument("-D")
            .addArgument(this.cqpCorpusName).addArgument("-r").addArgument(this.cqpRegistry);
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tmpAwk);
    FileUtils.deleteQuietly(tempSh);
    return tmpTabulate;
}

From source file:it.drwolf.ridire.index.cwb.CWBPatternSearcher.java

private Integer getCQPQueryResultsSize(File queryFile, String cqpSizeQuery)
        throws ExecuteException, IOException {
    EnvironmentUtils.addVariableToEnvironment(EnvironmentUtils.getProcEnvironment(), "LC_ALL=C");
    Executor executor = new DefaultExecutor();
    File tempSize = File.createTempFile("ridireSZ", ".size");
    File tempSh = File.createTempFile("ridireSH", ".sh");
    CommandLine commandLine = new CommandLine(this.cqpExecutable);
    commandLine.addArgument("-f").addArgument(queryFile.getAbsolutePath()).addArgument("-D")
            .addArgument(this.cqpCorpusName).addArgument("-r").addArgument(this.cqpRegistry);
    String commLineString = commandLine.toString() + " > " + tempSize.getAbsolutePath();
    FileUtils.writeStringToFile(tempSh, commLineString);
    tempSh.setExecutable(true);/*from   w  w  w . java 2  s. c o m*/
    executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBPatternSearcher.TIMEOUT);
    executor.setWatchdog(watchdog);
    commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    Integer size = 0;
    List<String> lines = FileUtils.readLines(tempSize);
    if (lines.size() > 0) {
        size = Integer.parseInt(lines.get(0).trim());
    }
    FileUtils.deleteQuietly(tempSh);
    FileUtils.deleteQuietly(tempSize);
    return size;
}

From source file:org.apache.bigtop.itest.hive.HiveHelper.java

public static Map<String, String> execCommand(CommandLine commandline, Map<String, String> envVars) {

    System.out.println("Executing command:");
    System.out.println(commandline.toString());
    Map<String, String> env = null;
    Map<String, String> entry = new HashMap<String, String>();
    try {//w  w w  .  j  av a  2 s  . c o  m
        env = EnvironmentUtils.getProcEnvironment();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to get process environment: " + e1.getMessage());
        e1.printStackTrace();
    }
    if (envVars != null) {
        for (String key : envVars.keySet()) {
            env.put(key, envVars.get(key));
        }
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 10000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(streamHandler);
    try {
        executor.execute(commandline, env, resultHandler);
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString() + e.getMessage());
        e.printStackTrace();
        return entry;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString() + e.getMessage());
        e.printStackTrace();
        return entry;
    }

    try {
        resultHandler.waitFor();
        /*System.out.println("Command output: "+outputStream.toString());*/
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString());
        return entry;
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        /*System.out.println("Command output: "+outputStream.toString());*/
        LOG.debug("exitValue: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString());
        e.printStackTrace();
        return entry;
    }
}

From source file:org.apache.geode.examples.replicated.ReplicatedTest.java

@Before
public void setup() throws IOException {
    // ignores test if running on windows
    assumeThat(System.getProperty("os.name").startsWith("Windows"), is(false));

    locatorPort = getAvailablePort();/*from  w w w  .j  av  a  2  s . c  o m*/
    environment = EnvironmentUtils.getProcEnvironment();
    EnvironmentUtils.addVariableToEnvironment(environment, GEODE_LOCATOR_PORT + locatorPort);
    logger.fine("Locator port: " + locatorPort);
}

From source file:org.apache.tika.parser.geo.topic.GeoParser.java

public HashMap<String, ArrayList<String>> searchGeoNames(ArrayList<String> locationNameEntities)
        throws ExecuteException, IOException {
    CommandLine cmdLine = new CommandLine("lucene-geo-gazetteer");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    cmdLine.addArgument("-s");
    for (String name : locationNameEntities) {
        cmdLine.addArgument(name);// w  w w .  j av a 2  s .  co  m
    }

    LOG.fine("Executing: " + cmdLine);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    exec.setWatchdog(watchdog);
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment());
    String outputJson = outputStream.toString("UTF-8");
    JSONArray json = (JSONArray) JSONValue.parse(outputJson);

    HashMap<String, ArrayList<String>> returnHash = new HashMap<String, ArrayList<String>>();
    for (int i = 0; i < json.size(); i++) {
        JSONObject obj = (JSONObject) json.get(i);
        for (Object key : obj.keySet()) {
            String theKey = (String) key;
            JSONArray vals = (JSONArray) obj.get(theKey);
            ArrayList<String> stringVals = new ArrayList<String>(vals.size());
            for (int j = 0; j < vals.size(); j++) {
                String val = (String) vals.get(j);
                stringVals.add(val);
            }

            returnHash.put(theKey, stringVals);
        }
    }

    return returnHash;

}

From source file:org.apache.tika.parser.pot.PooledTimeSeriesParser.java

private String computePoT(File input) throws IOException, TikaException {

    CommandLine cmdLine = new CommandLine("pooled-time-series");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    cmdLine.addArgument("-f");
    cmdLine.addArgument(input.getAbsolutePath());
    LOG.trace("Executing: {}", cmdLine);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValue(0);//from  w  ww  . j a v  a 2 s .c  o  m
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    exec.setWatchdog(watchdog);
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment());
    return outputStream.toString("UTF-8");

}

From source file:org.apache.zeppelin.interpreter.remote.RemoteInterpreterManagedProcess.java

@Override
public void start(String userName, Boolean isUserImpersonate) {
    // start server process
    try {//  w w w.ja  v  a  2s . c  om
        port = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces();
    } catch (IOException e1) {
        throw new InterpreterException(e1);
    }

    CommandLine cmdLine = CommandLine.parse(interpreterRunner);
    cmdLine.addArgument("-d", false);
    cmdLine.addArgument(interpreterDir, false);
    cmdLine.addArgument("-p", false);
    cmdLine.addArgument(Integer.toString(port), false);
    if (isUserImpersonate && !userName.equals("anonymous")) {
        cmdLine.addArgument("-u", false);
        cmdLine.addArgument(userName, false);
    }
    cmdLine.addArgument("-l", false);
    cmdLine.addArgument(localRepoDir, false);

    executor = new DefaultExecutor();

    ByteArrayOutputStream cmdOut = new ByteArrayOutputStream();
    ProcessLogOutputStream processOutput = new ProcessLogOutputStream(logger);
    processOutput.setOutputStream(cmdOut);

    executor.setStreamHandler(new PumpStreamHandler(processOutput));
    watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);

    try {
        Map procEnv = EnvironmentUtils.getProcEnvironment();
        procEnv.putAll(env);

        logger.info("Run interpreter process {}", cmdLine);
        executor.execute(cmdLine, procEnv, this);
        running = true;
    } catch (IOException e) {
        running = false;
        throw new InterpreterException(e);
    }

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() - startTime < getConnectTimeout()) {
        if (!running) {
            try {
                cmdOut.flush();
            } catch (IOException e) {
                // nothing to do
            }
            throw new InterpreterException(new String(cmdOut.toByteArray()));
        }

        try {
            if (RemoteInterpreterUtils.checkIfRemoteEndpointAccessible("localhost", port)) {
                break;
            } else {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    logger.error("Exception in RemoteInterpreterProcess while synchronized reference "
                            + "Thread.sleep", e);
                }
            }
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Remote interpreter not yet accessible at localhost:" + port);
            }
        }
    }
    processOutput.setOutputStream(null);
}