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:net.ostis.scpdev.m4scp.editors.M4ScpMultiPageEditor.java

/**
 * Calculates the contents of page 1 when the it is activated.
 *//*  w w w . j a v a  2s  . c  om*/
protected void pageChange(int newPageIndex) {
    super.pageChange(newPageIndex);

    if (newPageIndex == 1) {
        Validate.isInstanceOf(IFileEditorInput.class, m4scpEditor.getEditorInput());
        final IFileEditorInput m4scpInput = (IFileEditorInput) m4scpEditor.getEditorInput();
        final IFile m4scpSource = m4scpInput.getFile();

        final ByteArrayOutputStream out = new ByteArrayOutputStream();

        final Job convertJob = new Job("Convert m4scp to scs") {
            @Override
            protected IStatus run(IProgressMonitor monitor) {
                String m4 = ScCoreModule.getM4Path();
                String m4scp = ScCoreModule.getM4ScpPath();

                ProcessBuilder psb = new ProcessBuilder(m4, m4scp, m4scpSource.getRawLocation().toOSString());

                try {
                    Process ps = psb.start();
                    IOUtils.copy(ps.getInputStream(), out);

                    if (ps.waitFor() == 0)
                        return Status.OK_STATUS;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return Status.CANCEL_STATUS;
            }
        };

        convertJob.setPriority(Job.INTERACTIVE);
        convertJob.schedule();

        try {
            convertJob.join();
            if (convertJob.getResult() == Status.OK_STATUS)
                scsEditor.setInput(new StorageEditorInput(new InMemoryStorage(out.toString())));
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:com.jpmorgan.cakeshop.bean.QuorumConfigBean.java

public void createKeys(final String keyName, final String destination)
        throws IOException, InterruptedException {
    constellationConfig = destination;/*  w  w  w  .j  a  v  a  2 s  . c  o  m*/
    File dir = new File(destination);
    Boolean createKeys = true;

    if (!dir.exists()) {
        dir.mkdirs();
    } else {
        String[] fileNames = dir.list();
        if (fileNames.length >= 4) {
            for (String fileName : fileNames) {
                if (fileName.endsWith(".key") || fileName.endsWith(".pub")) {
                    createKeys = false;
                    break;
                }
            }
        }
    }

    if (createKeys) {
        //create keys
        ProcessBuilder pb = new ProcessBuilder(getKeyGen(), destination.concat(keyName));
        Process process = pb.start();
        try (Scanner scanner = new Scanner(process.getInputStream())) {
            boolean flag = scanner.hasNext();
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(process.getOutputStream()))) {
                while (flag) {
                    String line = scanner.next();
                    if (line.isEmpty()) {
                        continue;
                    }
                    if (line.contains("[none]:")) {
                        writer.newLine();
                        writer.flush();
                        writer.newLine();
                        writer.flush();
                        flag = false;
                    }
                }
            }
        }

        int ret = process.waitFor();
        if (ret != 0) {
            LOG.error(
                    "Failed to generate keys. Please make sure that berkeley db is installed properly. Version of berkeley db is 6.2.23");
        } else {
            //create archive keys
            pb = new ProcessBuilder(getKeyGen(), destination.concat(keyName.concat("a")));
            process = pb.start();
            try (Scanner scanner = new Scanner(process.getInputStream())) {
                boolean flag = scanner.hasNext();
                try (BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(process.getOutputStream()))) {
                    while (flag) {
                        String line = scanner.next();
                        if (line.isEmpty()) {
                            continue;
                        }
                        if (line.contains("[none]:")) {
                            writer.write(" ");
                            writer.flush();
                            writer.newLine();
                            writer.flush();
                            flag = false;
                        }
                    }
                }
            }

            ret = process.waitFor();
            if (ret != 0) {
                LOG.error(
                        "Failed to generate keys. Please make sure that berkeley db is installed properly. Version of berkeley db is 6.2.23");
            }
        }

        if (process.isAlive()) {
            process.destroy();
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.rftagger.RfTagger.java

private void ensureTaggerRunning() throws AnalysisEngineProcessException {
    if (process == null) {
        try {//from w  w  w  . j  a  v  a2 s .  c  o m
            PlatformDetector pd = new PlatformDetector();
            String platform = pd.getPlatformId();
            getLogger().info("Load binary for platform: [" + platform + "]");

            File executableFile = runtimeProvider.getFile("rft-annotate");

            List<String> cmd = new ArrayList<>();
            cmd.add(executableFile.getAbsolutePath());
            cmd.add("-q"); // quiet mode
            cmd.add(modelProvider.getResource().getAbsolutePath());
            ProcessBuilder pb = new ProcessBuilder();
            pb.redirectError(Redirect.INHERIT);
            pb.command(cmd);
            process = pb.start();

            writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), getEncoding()));
            reader = new BufferedReader(new InputStreamReader(process.getInputStream(), getEncoding()));
        } catch (Exception e) {
            throw new AnalysisEngineProcessException(e);
        }
    }
}

From source file:dk.deck.remoteconsole.proxy.LocalExecutor.java

public void execute(String command, String[] arguments, final PrintStream out, final PrintStream error)
        throws IOException, InterruptedException {
    List<String> args = new ArrayList<String>();
    args.add(command);/*from   www . java 2  s.c  o m*/
    args.addAll(Arrays.asList(arguments));
    ProcessBuilder builder = new ProcessBuilder(args);
    //        Map<String, String> env = builder.environment();
    //        System.out.println("Env:");
    //        for (Map.Entry<String, String> entry : env.entrySet()) {
    //            System.out.println(entry.getKey() + "=" + entry.getValue());
    //        }
    final Process p = builder.start();
    Runnable copyOutput = new Runnable() {

        @Override
        public void run() {
            try {
                IOUtils.copyLarge(p.getInputStream(), out);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    };
    Runnable copyError = new Runnable() {

        @Override
        public void run() {
            try {
                IOUtils.copyLarge(p.getErrorStream(), error);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    };
    new Thread(copyOutput).start();
    new Thread(copyError).start();

    int exitValue = p.waitFor();
    if (exitValue != 0) {
        throw new IllegalStateException("Exit value for dump was " + exitValue);
    }
}

From source file:net.urlgrey.mythpodcaster.transcode.FFMpegTranscoderImpl.java

public void transcode(File workingDirectory, GenericTranscoderConfigurationItem genericConfig, File inputFile,
        File outputFile) throws Exception {
    LOG.info("transcode started: inputFile [" + inputFile.getAbsolutePath() + "], outputFile ["
            + outputFile.getAbsolutePath() + "]");

    FFMpegTranscoderConfigurationItem config = (FFMpegTranscoderConfigurationItem) genericConfig;
    List<String> commandList = new ArrayList<String>();
    commandList.add(niceLocation);//from   w w w .  j a  v  a  2  s  . c o m
    commandList.add("-n");
    commandList.add(Integer.toString(config.getNiceness()));
    commandList.add(ffmpegLocation);
    commandList.add("-i");
    commandList.add(inputFile.getAbsolutePath());
    commandList.addAll(config.getParsedEncoderArguments());
    commandList.add(outputFile.getAbsolutePath());
    ProcessBuilder pb = new ProcessBuilder(commandList);

    // Needed for ffmpeg
    pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:");
    pb.redirectErrorStream(true);
    pb.directory(workingDirectory);
    Process process = null;

    try {
        // Get the ffmpeg process
        process = pb.start();
        // We give a couple of secs to complete task if needed
        Future<List<String>> stdout = pool.submit(new OutputMonitor(process.getInputStream()));
        List<String> result = stdout.get(config.getTimeout(), TimeUnit.SECONDS);
        process.waitFor();
        final int exitValue = process.exitValue();
        LOG.info("FFMPEG exit value: " + exitValue);
        if (exitValue != 0) {
            for (String line : result) {
                LOG.error(line);
            }
            throw new Exception("FFMpeg return code indicated failure: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new Exception("FFMpeg process interrupted by another thread", e);
    } catch (ExecutionException ee) {
        throw new Exception("Something went wrong parsing FFMpeg output", ee);
    } catch (TimeoutException te) {
        // We could not get the result before timeout
        throw new Exception("FFMpeg process timed out", te);
    } catch (RuntimeException re) {
        // Unexpected output from FFMpeg
        throw new Exception("Something went wrong parsing FFMpeg output", re);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    LOG.debug("transcoding finished");
}

From source file:com.scooter1556.sms.server.io.AdaptiveStreamingProcess.java

private void postProcess(String path, String format) {
    // Process for transcoding
    Process postProcess = null;/*from   www.ja v a2  s . c  o m*/

    LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME,
            "Post processing segment " + path + " with format '" + format + "'", null);

    try {
        // Generate post-process command
        List<String> command = new ArrayList<>();
        command.add(transcoder.getPath().toString());
        command.add("-i");
        command.add(path);
        command.add("-c:a");
        command.add("copy");
        command.add("-f");
        command.add(format);
        command.add(path + ".tmp");

        LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME,
                StringUtils.join(command, " "), null);

        ProcessBuilder processBuilder = new ProcessBuilder(command);
        postProcess = processBuilder.start();
        new NullStream(postProcess.getInputStream()).start();

        // Wait for process to finish
        postProcess.waitFor();

        // Rename file once complete
        File temp = new File(path + ".tmp");
        File segment = new File(path + "." + format);

        if (temp.exists()) {
            temp.renameTo(segment);
        }
    } catch (IOException ex) {
        LogService.getInstance().addLogEntry(Level.ERROR, CLASS_NAME, "Failed to post-process file " + path,
                ex);
    } catch (InterruptedException ex) {
        //Do nothing...
    } finally {
        if (postProcess != null) {
            postProcess.destroy();
        }
    }
}

From source file:fitnesse.testsystems.CommandRunner.java

public void asynchronousStart() throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.environment().putAll(determineEnvironment());
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Starting process " + asList(command));
    }//from  w w  w .  j  a va 2  s .  c  om
    process = processBuilder.start();

    sendCommandStartedEvent();
    redirectOutputs(process, executionLogListener);
}

From source file:net.fenyo.gnetwatch.actions.ExternalCommand.java

/**
 * Launches a process but do not wait for its completion.
 * any thread.//  www .j a v  a2s . c  o  m
 * @param none.
 * @return void.
 * @throws IOException i/o exception <bold>before</bold> reading the process output stream.
 */
public synchronized void fork() throws IOException {
    final ProcessBuilder pb = new ProcessBuilder(cmdLine);
    pb.directory(new File(directory));
    pb.redirectErrorStream(merge);
    process = pb.start();

    if (process == null)
        throw new IOException("null process");

    reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
}

From source file:com.github.mojos.distribute.PackageMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {

    if (version != null) {
        packageVersion = version;/*from ww w .  j  av a2s.  co m*/
    }

    //Copy sourceDirectory
    final File sourceDirectoryFile = new File(sourceDirectory);
    final File buildDirectory = Paths.get(project.getBuild().getDirectory(), "py").toFile();

    try {
        FileUtils.copyDirectory(sourceDirectoryFile, buildDirectory);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to copy source", e);
    }

    final File setup = Paths.get(buildDirectory.getPath(), "setup.py").toFile();
    final boolean setupProvided = setup.exists();

    final File setupTemplate = setupProvided ? setup
            : Paths.get(buildDirectory.getPath(), "setup-template.py").toFile();

    try {
        if (!setupProvided) {
            //update VERSION to latest version
            List<String> lines = new ArrayList<String>();
            final InputStream inputStream = new BufferedInputStream(new FileInputStream(setupTemplate));
            try {
                lines.addAll(IOUtils.readLines(inputStream));
            } finally {
                inputStream.close();
            }

            int index = 0;
            for (String line : lines) {
                line = line.replace(VERSION, packageVersion);
                line = line.replace(PROJECT_NAME, packageName);
                lines.set(index, line);
                index++;
            }

            final OutputStream outputStream = new FileOutputStream(setup);
            try {
                IOUtils.writeLines(lines, "\n", outputStream);
            } finally {
                outputStream.flush();
                outputStream.close();
            }
        }

        //execute setup script
        ProcessBuilder processBuilder = new ProcessBuilder(pythonExecutable, setup.getCanonicalPath(),
                "bdist_egg");
        processBuilder.directory(buildDirectory);
        processBuilder.redirectErrorStream(true);

        Process pr = processBuilder.start();
        int exitCode = pr.waitFor();
        BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line = "";
        while ((line = buf.readLine()) != null) {
            getLog().info(line);
        }

        if (exitCode != 0) {
            throw new MojoExecutionException("python setup.py returned error code " + exitCode);
        }

    } catch (FileNotFoundException e) {
        throw new MojoExecutionException("Unable to find " + setup.getPath(), e);
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to read " + setup.getPath(), e);
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Unable to execute python " + setup.getPath(), e);
    }

}

From source file:com.scooter1556.sms.server.io.AdaptiveStreamingProcess.java

@Override
public void run() {
    try {/*  w w  w .  j  a va2 s .  c o m*/
        for (String[] command : commands) {
            LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME,
                    StringUtils.join(command, " "), null);

            // Clean stream directory
            FileUtils.cleanDirectory(streamDirectory);

            ProcessBuilder processBuilder = new ProcessBuilder(command);
            process = processBuilder.start();
            new NullStream(process.getInputStream()).start();
            TranscodeAnalysisStream transcodeAnalysis = new TranscodeAnalysisStream(id,
                    StringUtils.join(command, " "), process.getErrorStream());
            transcodeAnalysis.start();

            // Wait for process to finish
            int code = process.waitFor();

            // Check for error
            if (code == 1) {
                LogService.getInstance().addLogEntry(Level.WARN, CLASS_NAME,
                        "Transcode command failed for job " + id + ". Attempting alternatives if available...",
                        null);
            } else {
                LogService.getInstance().addLogEntry(Level.INFO, CLASS_NAME,
                        "Transcode finished for job " + id + " (fps=" + transcodeAnalysis.getFps() + ")", null);
                break;
            }
        }
    } catch (IOException ex) {
        LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME,
                "Error occured whilst transcoding.", ex);
    } catch (InterruptedException ex) {
        // Do nothing...
    } finally {
        if (process != null) {
            process.destroy();
        }

        if (watcher != null) {
            watcher.stop();
        }

        if (postProcessExecutor != null && !postProcessExecutor.isTerminated()) {
            postProcessExecutor.shutdownNow();
        }

        ended = true;
    }
}