Example usage for java.lang Process waitFor

List of usage examples for java.lang Process waitFor

Introduction

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

Prototype

public abstract int waitFor() throws InterruptedException;

Source Link

Document

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Usage

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

public void execute() throws MojoExecutionException, MojoFailureException {

    if (version != null) {
        packageVersion = version;// w  w w.j  a  v a  2s  .  com
    }

    //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:kaleidoscope.server.UploadHandler.java

public UploadHandler(final RestRequestHandler handler, final HttpServerRequest req,
        final Set<String> supportImageFormat) throws URISyntaxException {
    this.handler = handler;
    this.req = req;
    this.rootPath = handler.getRootPath();
    final String defaultOutfileExt = handler.getDefaultOutfileExt();
    final String defaultResize = handler.getDefaultResize();
    final int maxUploadFileSize = handler.getMaxUploadFileSize();
    final int maxThumbnailCount = handler.getMaxThumbnailCount();
    final int expireSec = handler.getExpireSec();
    final String readUrl = handler.getReadUrl();
    this.supportImageFormat = supportImageFormat;
    final String realCmd = Paths.get(getClass().getClassLoader().getResource(handler.getCmd()).toURI())
            .toString();/*from w  w w  .  j av a 2s .c o  m*/

    req.endHandler(new Handler<Void>() {
        @Override
        public void handle(Void event) {
            try {
                if (file == null) {
                    handler.requestEnd(req, HttpResponseStatus.BAD_REQUEST,
                            new Object[] { "required.param.file" });
                    return;
                } else if (FileUtils.getSize(file) > maxUploadFileSize) {
                    handler.requestEnd(req, HttpResponseStatus.BAD_REQUEST,
                            new Object[] { "max.upload.file.size", maxUploadFileSize });
                    return;
                } else if (supportImageFormat.contains(ext) != true) {
                    handler.requestEnd(req, HttpResponseStatus.BAD_REQUEST,
                            new Object[] { "invalid.image.format", supportImageFormat });
                    return;
                }

                String resizes = req.formAttributes().get("resizes");
                if ((resizes == null) || ((resizes = resizes.trim()).length() == 0)) {
                    resizes = defaultResize;
                }

                String[] resizeList = resizes.split(",");
                if (resizeList.length > maxThumbnailCount) {
                    handler.requestEnd(req, HttpResponseStatus.BAD_REQUEST,
                            new Object[] { "max.thumbnail.count", maxThumbnailCount });
                    return;
                }

                String outfilePrefix = path + "/" + basename;
                String outfileExt = req.formAttributes().get("outfileExt");
                if (StringUtils.isEmpty(outfileExt) == true) {
                    outfileExt = defaultOutfileExt;
                }

                Runtime runtime = Runtime.getRuntime();
                String command = realCmd + " " + Paths.get(file) + " " + Paths.get(outfilePrefix) + " "
                        + outfileExt + " " + resizes;
                Process process = runtime.exec(command);
                process.waitFor();

                log.debug("cmd=[{}], exitValue=[{}]", command, process.exitValue());

                JsonArray arr = new JsonArray();
                for (int i = 0; i < resizeList.length; i++) {
                    arr.add(readUrl + outfilePrefix.replaceAll(rootPath, "") + "_" + resizeList[i] + "."
                            + outfileExt);
                }

                Calendar expireDate = DateUtils.getCalendar(expireSec);
                expireDate.set(Calendar.SECOND, 0);
                JsonObject json = JsonUtils.getJson(HttpResponseStatus.OK).putArray("thumbnails", arr)
                        .putString("expireDate", DateUtils.DATE_FORMAT_ISO8601FMT.format(expireDate.getTime()));

                handler.requestEnd(req, HttpResponseStatus.OK, json);

                FileUtils.rmdir(file);
            } catch (Exception e) {
                log.error("e={}", e.getMessage(), e);
                handler.requestEnd(req, HttpResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage());
            }
        }
    });

    log.debug(
            "rootPath={}, cmd={}, defaultOutfileExt={}, defaultResize={}"
                    + ", maxUploadFileSize={}, maxThumbnailCount={}"
                    + ", expireSec={}, readUrl={}, supportImageFormat={}",
            new Object[] { rootPath, realCmd, defaultOutfileExt, defaultResize, maxUploadFileSize,
                    maxThumbnailCount, expireSec, readUrl, supportImageFormat });
}

From source file:org.obiba.rserver.service.RServerService.java

@PostConstruct
public void start() {

    if (rserveStatus == 0) {
        log.error("RServerService is already running");
        return;/*from   w  w  w . j a  v a 2 s .c o m*/
    }

    log.info("Start RServerService with {}", properties);

    // fresh start, try to kill any remains of R server
    try {
        newRConnection().shutdown();
    } catch (Exception e) {
        // ignore
    }

    try {
        // launch the Rserve daemon and wait for it to complete
        Process rserve = buildRProcess().start();
        rserveStatus = rserve.waitFor();
        if (rserveStatus == 0) {
            log.info("R server started");
        } else {
            log.error("R server start failed with status: {}", rserveStatus);
            rserveStatus = -1;
        }
    } catch (Exception e) {
        log.warn("R server start failed", e);
        rserveStatus = -1;
    }
}

From source file:abs.backend.erlang.ErlangTestDriver.java

/**
 * Complies code in workDir/*from w ww . ja v  a 2 s .com*/
 */
private void make(File workDir) throws Exception {
    ProcessBuilder pb = new ProcessBuilder("erl", "-pa", "ebin", "-noshell", "-noinput", "-eval",
            "case make:all() of up_to_date -> halt(0); _ -> halt(1) end.");
    pb.directory(workDir);
    pb.inheritIO();
    Process p = pb.start();
    Assert.assertEquals("Compile failed", 0, p.waitFor());
}

From source file:de.fhg.iais.asc.xslt.binaries.scale.ImageMagickScaler.java

private boolean scale(File source, File target, List<String> command) {
    File incomplete = target;// w  w  w.ja  v  a2s.  co  m

    // Execute convert
    try {
        ParentDirectoryUtils.forceCreateParentDirectoryOf(target);

        Process process = new ProcessBuilder(command).redirectErrorStream(true).start();

        IOUtils.copyLarge(process.getInputStream(), NULL_OUTPUT_STREAM);

        if (process.waitFor() == 0) {
            incomplete = null;
            if (target.isFile()) {
                return true;
            } else {
                System.out.println(target);
            }
        }

        LOG.error(createErrorPrefix(source, target) + ": convert failed");
    } catch (IOException e) {
        LOG.error(createErrorPrefix(source, target), e);
    } catch (InterruptedException e) {
        throw new RuntimeException();
    } finally {
        if (incomplete != null) {
            incomplete.delete();
        }
    }

    return false;
}

From source file:com.roquahacks.semafor4j.FrameNetService.java

public void runFNSemanticParsing() {
    try {//from   w  ww  .j a  va  2  s.com
        Process proc = Runtime.getRuntime().exec(FrameNetOptions.ABS_PATH_DRIVER_SCRIPT + " "
                + FrameNetOptions.ABS_PATH_FNDATA + FrameNetOptions.FN_FILE_NAME);
        proc.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.samsung.sjs.ABackendTest.java

public void compilerTest(BiFunction<CompilerOptions, String[], Process> compiler,
        Function<String, Process> evaluator, boolean execute_code, boolean verbose, String... extra) {
    try {//w w  w  .j  a va2 s  .c o  m
        String script = getInputScriptPath();
        System.out.println("Looking for test script: " + script);
        System.err.println("COMPILING: " + script);
        File scriptfile = new File(script);
        Path tmpdir = Files.createTempDirectory("__fawefwea8ew");
        tmpdir.toFile().deleteOnExit();
        String ccode = scriptfile.getName().replaceFirst(".js$", ".c");
        File cfile = File.createTempFile("___", ccode, tmpdir.toFile());
        String exec = ccode.replaceFirst(".c$", "");
        File execfile = File.createTempFile("___", exec, tmpdir.toFile());
        CompilerOptions opts = new CompilerOptions(CompilerOptions.Platform.Native,
                scriptfile.getAbsolutePath(), verbose, // -debugcompiler
                cfile.getAbsolutePath(), true /* use GC */, "clang", "emcc", execfile.getAbsolutePath(),
                baseDirectory(), false /* don't dump C compiler spew into JUnit console */,
                true /* apply field optimizations */, verbose /* emit type inference constraints to console */,
                verbose /* dump constraint solution to console */,
                null /* find runtime src for linking locally (not running from jar) */, shouldEncodeValues(),
                false /* TODO: x86Test passes explicit -m32 flag, rather than setting this */,
                false /* we don't care about error explanations */,
                null /* we don't care about error explanations */, false /* generate efl environment code */,
                3 /* pass C compiler -O3 */);
        if (doInterop()) {
            opts.enableInteropMode();
        }
        if (bootInterop()) {
            opts.startInInteropMode();
        }
        Compiler.compile(opts);
        Process clang = compiler.apply(opts, extra);
        clang.waitFor();
        if (clang.exitValue() != 0) {
            StringWriter w_stdout = new StringWriter(), w_stderr = new StringWriter();
            IOUtils.copy(clang.getInputStream(), w_stdout, Charset.defaultCharset());
            IOUtils.copy(clang.getErrorStream(), w_stderr, Charset.defaultCharset());
            String compstdout = w_stdout.toString();
            String compstderr = w_stderr.toString();
            System.err.println("!!!!!!!!!!!!! Compiler exited with value " + clang.exitValue());
            System.err.println("Compiler stdout: " + compstdout);
            System.err.println("Compiler stderr: " + compstderr);
        }
        assertTrue(clang.exitValue() == 0);
        if (execute_code) {
            File prefixedscript = prefixJS(tmpdir, scriptfile);
            assertSameProcessOutput(runNode(prefixedscript), evaluator.apply(execfile.getAbsolutePath()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        assertTrue(false);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.RSTAnnotator.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    // perform sanity check
    if (sanityCheckOnInit) {
        File rstParserSrcDir = new File(rstParserSrcDirPath);

        // create process
        ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

        // working dir must be set to the src dir of RST parser
        processBuilder.directory(rstParserSrcDir);

        // run the command
        processBuilder.command("python", new File(rstParserSrcDir, "sanity_check.py").getAbsolutePath());

        try {//from ww  w. j  a v a  2 s  . c  om
            Process process = processBuilder.start();

            // and wait
            int returnValue = process.waitFor();

            if (returnValue != 0) {
                throw new RuntimeException("Process exited with code " + returnValue);
            }

        } catch (IOException | InterruptedException e) {
            throw new ResourceInitializationException(e);
        }
    }
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

static void callSvn(File dir, String... commands) throws Exception {
    if (svn) {//  ww  w. ja  va 2s . co m
        List<String> cmds = new ArrayList<String>();
        cmds.add("svn");
        cmds.add("--non-interactive");
        cmds.addAll(Arrays.asList(commands));
        Process p = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]), new String[0], dir);
        if (p.waitFor() != 0) {
            IOUtils.copy(p.getErrorStream(), System.err);
        }
    }
}

From source file:com.liferay.blade.cli.command.ConvertThemeCommand.java

public void importTheme(String themePath) throws Exception {
    Process process = BladeUtil.startProcess("node -v", _themesDir);

    int nodeJSInstalledChecker = process.waitFor();

    if (nodeJSInstalledChecker != 0) {
        _bladeCLI.error("Please check that Node.js properly installed and on the user path.");

        return;//from   w w w . j a v a2 s  .  c om
    }

    process = BladeUtil.startProcess("yo liferay-theme:import -p \"" + themePath + "\" -c "
            + _compassSupport(themePath) + " --skip-install", _themesDir, _bladeCLI.out(), _bladeCLI.error());

    int errCode = process.waitFor();

    if (errCode == 0) {
        _bladeCLI.out("Theme " + themePath + " migrated successfully");

        File theme = new File(themePath);

        FileUtil.deleteDir(theme.toPath());
    } else {
        _bladeCLI.error("blade exited with code: " + errCode);
    }
}