Example usage for java.lang ProcessBuilder ProcessBuilder

List of usage examples for java.lang ProcessBuilder ProcessBuilder

Introduction

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

Prototype

public ProcessBuilder(String... command) 

Source Link

Document

Constructs a process builder with the specified operating system program and arguments.

Usage

From source file:jmupen.JMupenUpdater.java

public static void restartApplication() {
    final String javaBin;
    if (JMupenUtils.getOs().equalsIgnoreCase("win")) {
        javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java.exe";
    } else {/* www  .j av a2  s.co m*/
        javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
    }
    File currentJar = null;
    try {
        currentJar = getJarFile();
    } catch (URISyntaxException ex) {
        System.err.println("Malformed JAR URL " + ex.getLocalizedMessage());
    }

    if (currentJar == null) {
        return;
    }

    /* is it a jar file? */
    if (!currentJar.getName().endsWith(".jar")) {
        return;
    }

    /* Build command: java -jar application.jar */
    final ArrayList<String> command = new ArrayList<String>();
    command.add(javaBin);
    command.add("-jar");
    command.add(currentJar.getPath());

    final ProcessBuilder builder = new ProcessBuilder(command);
    try {
        builder.start();
    } catch (IOException ex) {
        System.err.println("Error restarting app. " + ex.getLocalizedMessage());
    }
    System.exit(0);
}

From source file:com.twinsoft.convertigo.engine.localbuild.BuildLocally.java

private String runCommand(File launchDir, String command, List<String> parameters, boolean mergeError)
        throws Throwable {
    if (is(OS.win32)) {
        // Works for cordova and npm
        command += ".cmd";
    }/*  w w  w. j  a v  a 2s  .c om*/

    String shellFullpath = command;
    String paths = getLocalBuildAdditionalPath();
    paths = (paths.length() > 0 ? paths + File.pathSeparator : "") + System.getenv("PATH");

    String defaultPaths = null;
    if (is(OS.mac) || is(OS.linux)) {
        defaultPaths = "/usr/local/bin";
    } else if (is(OS.win32)) {
        String programFiles = System.getenv("ProgramW6432");
        if (programFiles != null && programFiles.length() > 0) {
            defaultPaths = programFiles + File.separator + "nodejs";
        }

        programFiles = System.getenv("ProgramFiles");
        if (programFiles != null && programFiles.length() > 0) {
            defaultPaths = (defaultPaths == null ? "" : defaultPaths + File.pathSeparator) + programFiles
                    + File.separator + "nodejs";
        }

        String appData = System.getenv("APPDATA");
        if (appData != null && appData.length() > 0) {
            defaultPaths = (defaultPaths == null ? "" : defaultPaths + File.pathSeparator) + appData
                    + File.separator + "npm";
        }
    }
    paths += File.pathSeparator + defaultPaths;

    // Checks if the command is already full path 
    if (!(new File(shellFullpath).exists())) {
        // Else search where the "exec" is and build the absolute path for this "exec"
        shellFullpath = getFullPath(paths, command);

        // If the "exec" is not found then it search it elsewhere
        if (shellFullpath == null) {
            shellFullpath = command;
        }
    }

    // Prepares the command
    parameters.add(0, shellFullpath);
    ProcessBuilder pb = new ProcessBuilder(parameters);
    // Set the directory from where the command will be executed
    pb.directory(launchDir.getCanonicalFile());

    Map<String, String> pbEnv = pb.environment();
    // must set "Path" for Windows 8.1 64
    pbEnv.put(pbEnv.get("PATH") == null ? "Path" : "PATH", paths);

    // Specific to npm command
    if (shellFullpath.endsWith("npm") || shellFullpath.endsWith("npm.cmd")) {

        // Set the proxy for npm
        String proxyMode = EnginePropertiesManager
                .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_MODE);
        if (proxyMode.equals(ProxyMode.manual.getValue())) {
            String proxyAuthMethod = EnginePropertiesManager
                    .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_METHOD);

            if (proxyAuthMethod.equals(ProxyMethod.anonymous.getValue())
                    || proxyAuthMethod.equals(ProxyMethod.basic.getValue())) {
                String proxyHost = EnginePropertiesManager
                        .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_HOST);
                String proxyPort = EnginePropertiesManager
                        .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_PORT);

                String npmProxy = proxyHost + ":" + proxyPort;

                if (proxyAuthMethod.equals(ProxyMethod.basic.getValue())) {
                    String proxyUser = EnginePropertiesManager
                            .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_USER);
                    String proxyPassword = EnginePropertiesManager
                            .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_PASSWORD);

                    npmProxy = proxyUser + ":" + proxyPassword + "@" + npmProxy;
                }

                pbEnv.put("http-proxy", "http://" + npmProxy);
                pbEnv.put("https-proxy", "http://" + npmProxy);
            }
        }
    }

    pb.redirectErrorStream(mergeError);

    Engine.logEngine.info("Executing command : " + parameters);

    process = pb.start();

    cmdOutput = "";
    // Logs the output
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String line;
                processCanceled = false;

                BufferedReader bis = new BufferedReader(new InputStreamReader(process.getInputStream()));
                while ((line = bis.readLine()) != null) {
                    Engine.logEngine.info(line);
                    BuildLocally.this.cmdOutput += line;
                }
            } catch (IOException e) {
                Engine.logEngine.error("Error while executing command", e);
            }
        }
    }).start();

    if (!mergeError) {
        // Logs the error output
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String line;
                    processCanceled = false;

                    BufferedReader bis = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    while ((line = bis.readLine()) != null) {
                        Engine.logEngine.error(line);
                        errorLines += line;
                    }
                } catch (IOException e) {
                    Engine.logEngine.error("Error while executing command", e);
                }
            }
        }).start();
    }

    int exitCode = process.waitFor();

    if (exitCode != 0 && exitCode != 127) {
        throw new Exception(
                "Exit code " + exitCode + " when running the command '" + command + "' with parameters : '"
                        + parameters + "'. The output of the command is : '" + cmdOutput + "'");
    }

    return cmdOutput;
}

From source file:cu.uci.uengine.runner.impl.FileRunner.java

private ProcessBuilder buildProcessBuilder(Limits limits, String language, String inputPath, File outFile,
        File errFile, String command, String id, boolean trusted) {
    List<String> uengineArgs = new ArrayList<>();
    uengineArgs.add(properties.getProperty("python.path"));
    uengineArgs.add(properties.getProperty("uengine.script"));

    uengineArgs.add("--identifier");
    uengineArgs.add(id);//from   w  ww  .  j a va2s  . c om
    uengineArgs.add("--language");
    uengineArgs.add(language);
    uengineArgs.add("--input");
    uengineArgs.add(inputPath);
    uengineArgs.add("--output");
    uengineArgs.add(outFile.getAbsolutePath());
    uengineArgs.add("--errors");
    uengineArgs.add(errFile.getAbsolutePath());
    uengineArgs.add("--time-limit");
    uengineArgs.add(String.valueOf(limits.getMaxCaseExecutionTime()));
    uengineArgs.add("--memory-limit");
    uengineArgs.add(String.valueOf(limits.getMaxMemory()));

    if (trusted)
        uengineArgs.add("--trusted");

    uengineArgs.add("--program");
    uengineArgs.addAll(Arrays.asList(command.split(" ")));

    String[] uengineArgsArray = uengineArgs.toArray(new String[0]);

    if (log.isTraceEnabled()) {
        log.trace(Arrays.toString(uengineArgsArray));
    }

    return new ProcessBuilder(uengineArgsArray);
}

From source file:io.hops.hopsworks.common.util.HopsUtils.java

/**
 * Retrieves the global hadoop classpath.
 *
 * @param params/*from  ww  w. j a  va  2s .c om*/
 * @return hadoop global classpath
 */
public static String getHadoopClasspathGlob(String... params) {
    ProcessBuilder pb = new ProcessBuilder(params);
    try {
        Process process = pb.start();
        int errCode = process.waitFor();
        if (errCode != 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        }
        //Now we must remove the yarn shuffle library as it creates issues for 
        //Zeppelin Spark Interpreter
        StringBuilder classpath = new StringBuilder();

        for (String path : sb.toString().split(File.pathSeparator)) {
            if (!path.contains("yarn") && !path.contains("jersey") && !path.contains("servlet")) {
                classpath.append(path).append(File.pathSeparator);
            }
        }
        if (classpath.length() > 0) {
            return classpath.toString().substring(0, classpath.length() - 1);
        }

    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(HopsUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:com.mcapanel.bukkit.BukkitServer.java

public void setServerJar(String jar) {
    serverJar = new File(jar);

    processBuilder = new ProcessBuilder(new String[] { "java", "-Djline.terminal=jline.UnsupportedTerminal",
            "-Xms" + minMemory, "-Xmx" + maxMemory, "-jar", serverJar.getAbsolutePath() });

    processBuilder.directory(serverJar.getParentFile());

    bukkitConfig = new BukkitConfig(serverJar);
}

From source file:com.photon.phresco.plugins.xcode.XcodeBuild.java

/**
 * Execute the xcode command line utility.
 */// w w  w.j  av  a2s  . c o m
public void execute() throws MojoExecutionException {
    if (!xcodeCommandLine.exists()) {
        throw new MojoExecutionException(
                "Invalid path, invalid xcodebuild file: " + xcodeCommandLine.getAbsolutePath());
    }
    /*
     * // Compute archive name String archiveName =
     * project.getBuild().getFinalName() + ".cust"; File finalDir = new
     * File(buildDirectory, archiveName);
     * 
     * // Configure archiver MavenArchiver archiver = new MavenArchiver();
     * archiver.setArchiver(jarArchiver); archiver.setOutputFile(finalDir);
     */

    try {
        if (!SdkVerifier.isAvailable(sdk)) {
            throw new MojoExecutionException("Selected version " + sdk + " is not available!");
        }
    } catch (IOException e2) {
        throw new MojoExecutionException("SDK verification failed!");
    } catch (InterruptedException e2) {
        throw new MojoExecutionException("SDK verification interrupted!");
    }

    try {
        init();
        configure();
        ProcessBuilder pb = new ProcessBuilder(xcodeCommandLine.getAbsolutePath());
        // Include errors in output
        pb.redirectErrorStream(true);

        List<String> commands = pb.command();
        if (xcodeProject != null) {
            commands.add("-project");
            commands.add(xcodeProject);
        }
        if (StringUtils.isNotBlank(configuration)) {
            commands.add("-configuration");
            commands.add(configuration);
        }

        if (StringUtils.isNotBlank(sdk)) {
            commands.add("-sdk");
            commands.add(sdk);
        }

        commands.add("OBJROOT=" + buildDirectory);
        commands.add("SYMROOT=" + buildDirectory);
        commands.add("DSTROOT=" + buildDirectory);

        if (StringUtils.isNotBlank(xcodeTarget)) {
            commands.add("-target");
            commands.add(xcodeTarget);
        }

        if (StringUtils.isNotBlank(gccpreprocessor)) {
            commands.add("GCC_PREPROCESSOR_DEFINITIONS=" + gccpreprocessor);
        }

        if (unittest) {
            commands.add("clean");
            commands.add("build");
        }

        getLog().info("List of commands" + pb.command());
        // pb.command().add("install");
        pb.directory(new File(basedir));
        Process child = pb.start();

        // Consume subprocess output and write to stdout for debugging
        InputStream is = new BufferedInputStream(child.getInputStream());
        int singleByte = 0;
        while ((singleByte = is.read()) != -1) {
            // output.write(buffer, 0, bytesRead);
            System.out.write(singleByte);
        }

        child.waitFor();
        int exitValue = child.exitValue();
        getLog().info("Exit Value: " + exitValue);
        if (exitValue != 0) {
            throw new MojoExecutionException("Compilation error occured. Resolve the error(s) and try again!");
        }

        if (!unittest) {
            //In case of unit testcases run, the APP files will not be generated.
            createdSYM();
            createApp();
        }
        /*
         * child.waitFor();
         * 
         * InputStream in = child.getInputStream(); InputStream err =
         * child.getErrorStream(); getLog().error(sb.toString());
         */
    } catch (IOException e) {
        getLog().error("An IOException occured.");
        throw new MojoExecutionException("An IOException occured", e);
    } catch (InterruptedException e) {
        getLog().error("The clean process was been interrupted.");
        throw new MojoExecutionException("The clean process was been interrupted", e);
    } catch (MojoFailureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    File directory = new File(this.basedir + "/pom.xml");
    this.project.getArtifact().setFile(directory);
}

From source file:com.ecofactor.qa.automation.platform.ops.impl.IOSOperations.java

/**
 * Start Appium server.//from w  w  w  .  j av  a 2  s .co m
 * @see com.ecofactor.qa.automation.mobile.ops.impl.AbstractMobileOperations#startAppiumServer()
 */
@Override
public void startAppiumServer() {

    final String deviceId = getDeviceIdParam();
    startProxyServer(deviceId);
    setLogString(LogSection.START, "Start appium server", true);
    try {
        final ProcessBuilder process = new ProcessBuilder(
                arrayToList("node", ".", "-U", deviceId, "-p", DEFAULT_PORT));
        process.directory(new File("/Applications/Appium.app/Contents/Resources/node_modules/appium/"));
        process.redirectOutput(new File("outPut.txt"));
        process.redirectError(new File("error.txt"));
        startProcessBuilder(process);
    } catch (Exception e) {
        LOGGER.error("ERROR in starting Appium Server. Cause: ", e);
    }
    setLogString(LogSection.END, "Appium server started", true);
}

From source file:io.hops.hopsworks.common.security.PKIUtils.java

public static String getSubjectFromCSR(String csr) throws IOException, InterruptedException {
    File csrFile = File.createTempFile(System.getProperty("java.io.tmpdir"), ".csr");
    FileUtils.writeStringToFile(csrFile, csr);
    List<String> cmds = new ArrayList<>();
    //openssl req -in certs-dir/hops-site-certs/csr.pem -noout -subject
    cmds.add("openssl");
    cmds.add("req");
    cmds.add("-in");
    cmds.add(csrFile.getAbsolutePath());
    cmds.add("-noout");
    cmds.add("-subject");

    StringBuilder sb = new StringBuilder("/usr/bin/ ");
    for (String s : cmds) {
        sb.append(s).append(" ");
    }//from  w ww.j av  a2s .  c o  m
    logger.info(sb.toString());
    Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true)
            .start();
    BufferedReader br = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));
    String line;
    StringBuilder lines = new StringBuilder("");
    while ((line = br.readLine()) != null) {
        logger.info(line);
        lines.append(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed to get subject. Exit value: " + exitValue);
    }
    return lines.toString();
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call Rtrace to run the simulation/*w  w w  .  j  av a2 s  . c  o  m*/
 * @param config Radiance Configuration
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param args
 * @param model
 * @param in
 * @param out
 * @param err
 * @param process
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runRtrace(RadianceConfig config, String WorkDir, String args, String model, String in,
        String out, String err, ProcessWrapper process) {

    int ExitValue = -99;

    try {
        StringBuilder buf = new StringBuilder(config.getResolvedRadianceBinDir());
        buf.append(File.separator).append("rtrace");

        List<String> command = new ArrayList<>();
        command.add(buf.toString());
        String[] arglist = args.split("\\s+");
        command.addAll(Arrays.asList(arglist));
        command.add(model);
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir());
        builder.redirectError(new File(WorkDir + File.separator + err));
        builder.redirectOutput(new File(WorkDir + File.separator + out));
        builder.redirectInput(new File(WorkDir + File.separator + in));

        Process proc = builder.start();
        if (process != null) {
            process.setWrappedProc(proc);
        }
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing Rtrace", ex);
    }

    // Return Radiance exit value
    return ExitValue;
}