Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

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

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:com.tw.go.plugin.task.GoPluginImpl.java

private int executeCommand(String workingDirectory, Map<String, String> environmentVariables, String... command)
        throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.directory(new File(workingDirectory));
    if (environmentVariables != null && !environmentVariables.isEmpty()) {
        processBuilder.environment().putAll(environmentVariables);
    }/*from  w  ww. ja v  a  2s .c  o  m*/
    Process process = processBuilder.start();

    JobConsoleLogger.getConsoleLogger().readOutputOf(process.getInputStream());
    JobConsoleLogger.getConsoleLogger().readErrorOf(process.getErrorStream());

    return process.waitFor();
}

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();//from   ww w  .j  a  v  a2  s  . com
    env.putAll(System.getenv());
    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:ca.phon.media.FFMpegMediaExporter.java

@Override
public void performTask() {
    super.setStatus(TaskStatus.RUNNING);

    // check options
    if (inputFile != null) {
        File f = new File(inputFile);
        if (!f.exists()) {
            IOException ex = new IOException("File not found");
            super.err = ex;
            super.setStatus(TaskStatus.ERROR);
            return;
        }/*from w  ww. j ava 2  s  .  c o  m*/
    } else {
        IllegalArgumentException ex = new IllegalArgumentException("Input file cannot be null");
        super.err = ex;
        super.setStatus(TaskStatus.ERROR);
        return;
    }

    if (outputFile != null) {
        File f = new File(outputFile);
        File pf = f.getParentFile();

        if (!pf.exists()) {
            // try to create directories
            if (!pf.mkdirs()) {
                IOException ex = new IOException("Could not create output directory");
                super.err = ex;
                super.setStatus(TaskStatus.ERROR);
                return;
            }
        } else {
            if (!pf.isDirectory()) {
                IOException ex = new IOException(pf.getAbsolutePath() + " exists but is not a directory");
                super.err = ex;
                super.setStatus(TaskStatus.ERROR);
                return;
            }
        }
    } else {
        IllegalArgumentException ex = new IllegalArgumentException("Ouput file cannot be null");
        super.err = ex;
        super.setStatus(TaskStatus.ERROR);
        return;
    }

    List<String> cmdLine = getCmdLine();

    // setup process builder
    ProcessBuilder processBuilder = new ProcessBuilder(cmdLine);
    processBuilder.redirectErrorStream(true);
    try {
        // create process
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            LOGGER.info(line);
        }
        reader.close();

        super.setStatus(TaskStatus.FINISHED);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        super.err = ex;
        super.setStatus(TaskStatus.ERROR);
    }

}

From source file:archive_v1.Archive_Form.java

public void execArchive(int compress) {
    String execArchiveCommand = null;
    if (compress == 0) {
        execArchiveCommand = "cd /u01 && tar cvf /dev/st0 archive";
    } else {/*  w  ww.ja  v a 2 s  . c o m*/
        execArchiveCommand = "cd /u01 && tar czf /dev/st0 archive";
    }
    Process proc = null;
    String output = null;
    try {

        ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", execArchiveCommand);
        builder.redirectErrorStream(true);
        proc = builder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        output = reader.readLine();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.ppedregal.typescript.maven.TscMojo.java

private boolean useBinary(String[] args) throws MojoExecutionException {
    if (useTsc) {

        // lets try execute the 'tsc' executable directly
        List<String> arguments = new ArrayList<String>();
        arguments.add("tsc");
        if (libraryDirectory.exists()) {
            File[] libFiles = libraryDirectory.listFiles();
            if (libFiles != null) {
                for (File libFile : libFiles) {
                    if (libFile.getName().endsWith(".d.ts") && libFile.exists()) {
                        String path = libFile.getAbsolutePath();
                        if (!watching) {
                            getLog().info("Adding library file " + libFile);
                        }/*  ww  w .ja  v  a 2  s  . c  om*/
                        arguments.add(path);
                    }
                }
            }
        }
        for (String arg : args) {
            arguments.add(arg);
        }

        getLog().debug("About to execute command: " + arguments);
        ProcessBuilder builder = new ProcessBuilder(arguments);
        try {
            Process process = builder.start();
            redirectOutput(process.getInputStream(), false);
            redirectOutput(process.getErrorStream(), true);

            int value = process.waitFor();
            if (value != 0) {
                getLog().error("Failed to execute tsc. Return code: " + value);
            } else {
                getLog().debug("Compiled file successfully");
            }
        } catch (IOException e) {
            getLog().error("Failed to execute tsc: " + e);
            throw createMojoExecutionException(e);
        } catch (InterruptedException e) {
            throw new MojoExecutionException(e.getMessage());
        }
        return true;
    }
    return false;
}

From source file:metadata.etl.dataset.hdfs.HdfsMetadataEtl.java

private void extractLocal() throws Exception {

    URL localJarUrl = classLoader.getResource("jar/schemaFetch.jar");
    String homeDir = System.getProperty("user.home");
    String remoteJarFile = homeDir + "/.wherehows/schemaFetch.jar";
    File dest = new File(remoteJarFile);
    try {/*w  w  w .  j  a v  a2 s  . c  o m*/
        FileUtils.copyURLToFile(localJarUrl, dest);
    } catch (Exception e) {
        logger.error(e.toString());
    }

    String outputSchemaFile = prop.getProperty(Constant.HDFS_SCHEMA_LOCAL_PATH_KEY);
    String outputSampleDataFile = prop.getProperty(Constant.HDFS_SAMPLE_LOCAL_PATH_KEY);
    String cluster = prop.getProperty(Constant.HDFS_CLUSTER_KEY);
    String whiteList = prop.getProperty(Constant.HDFS_WHITE_LIST_KEY);
    String numOfThread = prop.getProperty(Constant.HDFS_NUM_OF_THREAD_KEY, String.valueOf(1));
    String hdfsUser = prop.getProperty(Constant.HDFS_REMOTE_USER_KEY);
    // String hdfsKeyTab = prop.getProperty(Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY);
    String hdfsExtractLogFile = outputSchemaFile + ".log";

    String[] hadoopCmd = { "hadoop", "jar", remoteJarFile,
            "-D" + Constant.HDFS_SCHEMA_REMOTE_PATH_KEY + "=" + outputSchemaFile,
            "-D" + Constant.HDFS_SAMPLE_REMOTE_PATH_KEY + "=" + outputSampleDataFile,
            "-D" + Constant.HDFS_CLUSTER_KEY + "=" + cluster,
            "-D" + Constant.HDFS_WHITE_LIST_KEY + "=" + whiteList,
            "-D" + Constant.HDFS_NUM_OF_THREAD_KEY + "=" + numOfThread,
            "-D" + Constant.HDFS_REMOTE_USER_KEY + "=" + hdfsUser, "-Dlog.file.name=hdfs_schema_fetch" };
    // delete the line (no kerberos needed): "-D" + Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY + "=" + hdfsKeyTab,
    ProcessBuilder pb = new ProcessBuilder(hadoopCmd);
    File logFile = new File(hdfsExtractLogFile);
    pb.redirectErrorStream(true);
    pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile));
    Process process = pb.start();
    int pid = -1;
    if (process.getClass().getName().equals("java.lang.UNIXProcess")) {
        /* get the PID on unix/linux systems */
        try {
            Field f = process.getClass().getDeclaredField("pid");
            f.setAccessible(true);
            pid = f.getInt(process);
        } catch (Throwable e) {
        }
    }
    logger.info("executue command [PID=" + pid + "]: " + hadoopCmd);

    // wait until this process finished.
    int execResult = process.waitFor();

    // if the process failed, log the error and throw exception
    if (execResult > 0) {
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String errString = "HDFS Metadata Extract Error:\n";
        String line = "";
        while ((line = br.readLine()) != null)
            errString = errString.concat(line).concat("\n");
        logger.error("*** Process  failed, status: " + execResult);
        logger.error(errString);
        throw new Exception("Process + " + pid + " failed");
    }

}

From source file:com.kdmanalytics.toif.adaptor.SplintAdaptor.java

@Override
public String getGeneratorVersion() {
    final String[] commands = { "splint", "-help", "version" };
    ProcessBuilder splint = new ProcessBuilder(commands);
    try {//  www.j  a v a  2  s .  c o  m
        Process splintInstance = splint.start();
        InputStream in = splintInstance.getErrorStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        String strLine;

        while ((strLine = br.readLine()) != null) {
            String[] stringArray = strLine.split(" ");

            if (stringArray[1].trim().equals("3.1.2")) {
                return stringArray[1].trim();
            } else {
                System.err.println(getAdaptorName() + ": Generator " + stringArray[1]
                        + " found, only version 3.1.2 has been tested");
                return stringArray[1].trim();
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
}

From source file:fr.amap.lidar.PtgScanConversion.java

public void toLaz(SimpleScan scan, File outputDirectory, boolean laz, boolean exportIntensity)
        throws IOException, InterruptedException, UnsupportedOperationException, Exception {

    /***Convert rxp to txt***/

    Mat4D transfMatrix = Mat4D.multiply(scan.sopMatrix, scan.popMatrix);

    Mat3D rotation = new Mat3D();
    rotation.mat = new double[] { transfMatrix.mat[0], transfMatrix.mat[1], transfMatrix.mat[2],
            transfMatrix.mat[4], transfMatrix.mat[5], transfMatrix.mat[6], transfMatrix.mat[8],
            transfMatrix.mat[9], transfMatrix.mat[10] };

    File outputTxtFile = new File(
            outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".txt");

    try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputTxtFile))) {
        PTGScan ptgScan = new PTGScan();
        ptgScan.openScanFile(scan.file);

        LPointShotExtractor shots = new LPointShotExtractor(ptgScan);
        Iterator<LShot> iterator = shots.iterator();

        while (iterator.hasNext()) {

            LShot shot = iterator.next();
            shot.direction.normalize();/*from  www.  j  a  v a 2s  .  c om*/

            Vec4D origin = Mat4D.multiply(transfMatrix,
                    new Vec4D(shot.origin.x, shot.origin.y, shot.origin.z, 1.0d));
            Vec3D direction = Mat3D.multiply(rotation,
                    new Vec3D(shot.direction.x, shot.direction.y, shot.direction.z));

            for (int i = 0; i < shot.ranges.length; i++) {

                double x = origin.x + direction.x * shot.ranges[i];
                double y = origin.y + direction.y * shot.ranges[i];
                double z = origin.z + direction.z * shot.ranges[i];

                if (exportIntensity) {
                    writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.ranges.length + " "
                            + shot.point.intensity + "\n");
                } else {
                    writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.ranges.length + "\n");
                }

            }

        }
    }

    /***Convert txt to laz***/
    String propertyValue = System.getProperty("user.dir");
    System.out.println("Current jar directory : " + propertyValue);

    String txtToLasPath;

    String osName = getOSName();

    switch (osName) {
    case "windows":
    case "linux":
        txtToLasPath = propertyValue + File.separator + "LASTools" + File.separator + osName + File.separator
                + "txt2las";
        break;
    default:
        throw new UnsupportedOperationException("Os architecture not supported");
    }

    if (osName.equals("windows")) {
        txtToLasPath = txtToLasPath + ".exe";
    }

    File outputLazFile;
    if (laz) {
        outputLazFile = new File(
                outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".laz");
    } else {
        outputLazFile = new File(
                outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".las");
    }

    String[] commandLine;

    if (exportIntensity) {
        commandLine = new String[] { txtToLasPath, "-i", outputTxtFile.getAbsolutePath(), "-o",
                outputLazFile.getAbsolutePath(), "-parse", "xyzrni" };
    } else {
        commandLine = new String[] { txtToLasPath, "-i", outputTxtFile.getAbsolutePath(), "-o",
                outputLazFile.getAbsolutePath(), "-parse", "xyzrn" };
    }

    System.out.println("Command line : "
            + ArrayUtils.toString(commandLine).replaceAll(",", " ").replaceAll("}", "").replace("{", ""));

    ProcessBuilder pb = new ProcessBuilder(commandLine);
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);

    Process p = pb.start();

    p.waitFor();

}

From source file:bjerne.gallery.service.impl.VideoConversionServiceImpl.java

@Override
public void convertVideo(File origVideo, File newVideo, String conversionMode) throws IOException {
    long startTime = System.currentTimeMillis();
    if (newVideo.exists()) {
        LOG.debug("{} already exists. Trying to delete.", newVideo);
        newVideo.delete();//from   ww  w  .j  av a 2s  .  c o m
    }
    if (!newVideo.getParentFile().exists()) {
        boolean dirsCreated = newVideo.getParentFile().mkdirs();
        if (!dirsCreated) {
            String errorMessage = String.format("Could not create all dirs for %s", newVideo);
            LOG.error(errorMessage);
            throw new IOException(errorMessage);
        }
    }
    ProcessBuilder pb = new ProcessBuilder(generateCommandParamList(origVideo, newVideo, conversionMode));
    Process pr = null;
    Thread currentThread = Thread.currentThread();
    try {
        LOG.debug("Adding current thread: {}", currentThread);
        registerThread(currentThread);
        pr = pb.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        while (reader.ready()) {
            Thread.sleep(100);
            LOG.info("One line: {}", reader.readLine());
        }
        boolean waitResult = pr.waitFor(maxWaitTimeSeconds, TimeUnit.SECONDS);
        if (!waitResult) {
            String errorMessage = String.format(
                    "Waiting for video conversion exceeded maximum threshold of %s seconds",
                    maxWaitTimeSeconds);
            LOG.error(errorMessage);
            cleanupFailure(pr, newVideo);
            throw new IOException(errorMessage);
        }
        long duration = System.currentTimeMillis() - startTime;
        LOG.debug("Time in milliseconds to resize {}: {}", newVideo.toString(), duration);
    } catch (InterruptedException ie) {
        cleanupFailure(pr, newVideo);
        LOG.error("Was interrupted while waiting for conversion. Throwing IOException");
        throw new IOException(ie);
    } finally {
        unregisterThread(currentThread);
    }
}

From source file:com.github.psorobka.appium.StartServerMojo.java

@Override
public void execute() throws MojoExecutionException {
    try {/* ww w  . java2s  . c  o  m*/
        getLog().info("Starting Appium server...");
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command("appium", "--log-timestamp", "--log",
                new File(target, "appiumLog.txt").getAbsolutePath());
        processBuilder.redirectError(new File(target, "appiumErrorLog.txt"));
        processBuilder.redirectOutput(new File(target, "appiumOutputLog.txt"));
        getLog().debug("Appium server commands " + processBuilder.command());
        Process process = processBuilder.start();
        if (!Processes.newPidProcess(process).isAlive()) {
            throw new MojoExecutionException("Failed to start Appium server");
        }
        int pid = PidUtil.getPid(process);
        getLog().info("Appium server started");
        getLog().debug("Appium server PID " + pid);
        FileUtils.writeStringToFile(new File(target, "appium.pid"), Integer.toString(pid));
        //Dumb way to sleep until appium starts - file watcher would be better
        Thread.sleep(5000);
    } catch (IOException | InterruptedException ex) {
        throw new MojoExecutionException("Failed to start Appium server", ex);
    }
}