Example usage for java.lang Process destroy

List of usage examples for java.lang Process destroy

Introduction

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

Prototype

public abstract void destroy();

Source Link

Document

Kills the process.

Usage

From source file:uk.ac.kcl.iop.brc.core.pipeline.dncpipeline.service.PythonService.java

/**
 * Runs the Python interpreter./*from  w  w  w. j av  a2  s .c  o m*/
 * @param args List of arguments to be supplied to the python command.
 * @return Result from python string
 * @throws IOException
 */
public String runFile(List<String> args) throws IOException {
    LinkedList<String> list = new LinkedList<>(args);
    list.addFirst("python");
    ProcessBuilder processBuilder = new ProcessBuilder(list);
    Process p = processBuilder.start();
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    StringWriter stringWriter = new StringWriter();
    in.lines().forEach(stringWriter::append);
    p.destroy();
    return stringWriter.toString();
}

From source file:com.ikon.servlet.TextToSpeechServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String cmd = "espeak -v mb-es1 -f input.txt | mbrola -e /usr/share/mbrola/voices/es1 - -.wav "
            + "| oggenc -Q - -o output.ogg";
    String text = WebUtils.getString(request, "text");
    String docPath = WebUtils.getString(request, "docPath");
    response.setContentType("audio/ogg");
    FileInputStream fis = null;//  w  w  w .jav  a2 s  .  c  o  m
    OutputStream os = null;

    try {
        if (!text.equals("")) {
            FileUtils.writeStringToFile(new File("input.txt"), text);
        } else if (!docPath.equals("")) {
            InputStream is = OKMDocument.getInstance().getContent(null, docPath, false);
            Document doc = OKMDocument.getInstance().getProperties(null, docPath);
            DocConverter.getInstance().doc2txt(is, doc.getMimeType(), new File("input.txt"));
        }

        // Convert to voice
        ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", cmd);
        Process process = pb.start();
        process.waitFor();
        String info = IOUtils.toString(process.getInputStream());
        process.destroy();

        if (process.exitValue() == 1) {
            log.warn(info);
        }

        // Send to client
        os = response.getOutputStream();
        fis = new FileInputStream("output.ogg");
        IOUtils.copy(fis, os);
        os.flush();
    } catch (InterruptedException e) {
        log.warn(e.getMessage(), e);
    } catch (IOException e) {
        log.warn(e.getMessage(), e);
    } catch (PathNotFoundException e) {
        log.warn(e.getMessage(), e);
    } catch (AccessDeniedException e) {
        log.warn(e.getMessage(), e);
    } catch (RepositoryException e) {
        log.warn(e.getMessage(), e);
    } catch (DatabaseException e) {
        log.warn(e.getMessage(), e);
    } catch (ConversionException e) {
        log.warn(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(os);
    }
}

From source file:org.apache.htrace.core.TracerId.java

/**
 * <p>Get the process ID by executing a shell and printing the PPID (parent
 * process ID).</p>//from  ww  w  . j  a  va2  s  .com
 *
 * This method of getting the process ID doesn't depend on any undocumented
 * features of the virtual machine, and should work on almost any UNIX
 * operating system.
 */
private static long getOsPidFromShellPpid() {
    Process p = null;
    StringBuilder sb = new StringBuilder();
    try {
        p = new ProcessBuilder("/usr/bin/env", "sh", "-c", "echo $PPID").redirectErrorStream(true).start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line.trim());
        }
        int exitVal = p.waitFor();
        if (exitVal != 0) {
            throw new IOException("Process exited with error code " + Integer.valueOf(exitVal).toString());
        }
    } catch (InterruptedException e) {
        LOG.error("Interrupted while getting operating system pid from " + "the shell.", e);
        return 0L;
    } catch (IOException e) {
        LOG.error("Error getting operating system pid from the shell.", e);
        return 0L;
    } finally {
        if (p != null) {
            p.destroy();
        }
    }
    try {
        return Long.parseLong(sb.toString());
    } catch (NumberFormatException e) {
        LOG.error("Error parsing operating system pid from the shell.", e);
        return 0L;
    }
}

From source file:org.ambraproject.action.debug.ProcessDumpAction.java

private String getProcessDump() throws Exception {
    Process process = null;
    String result;/*from  ww w  .ja  va 2 s .c o  m*/
    try {
        process = Runtime.getRuntime().exec("ps uaxwww");
        result = IOUtils.toString(process.getInputStream());
        process.waitFor();
    } finally {
        process.destroy();
    }
    return result;
}

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

private void cleanupFailure(Process pr, File newVideo) {
    LOG.debug("Cleaning up failing conversion job. Killing process {}", pr);
    pr.destroy();
    LOG.debug("Trying to remove new file (if any): {}", newVideo.toString());
    newVideo.delete();/*from w w  w .j av  a 2  s . com*/
}

From source file:com.netflix.genie.agent.execution.services.impl.LaunchJobServiceImpl.java

/**
 * {@inheritDoc}//w  w  w  .ja v a  2  s .  c  o  m
 */
@Override
public void kill() {
    killed.set(true);

    final Process process = processReference.get();

    if (process != null) {
        process.destroy();
    }
}

From source file:com.thoughtworks.go.helper.P4TestRepo.java

public void onTearDown() {
    Process process = (Process) ReflectionUtil.getField(p4dProcess, "process");
    process.destroy();
    FileUtils.deleteQuietly(tempRepo);/* www .ja  v  a 2 s .  c o m*/
    FileUtils.deleteQuietly(clientFolder);
}

From source file:com.diversityarrays.kdxplore.trialdesign.JobRunningTask.java

@Override
public Either<String, AlgorithmRunResult> generateResult(Closure<Void> arg0) throws Exception {

    AlgorithmRunResult result = new AlgorithmRunResult(algorithmName, algorithmFolder);
    ProcessBuilder pb = new ProcessBuilder(command);

    File tempAlgorithmOutputFile = new File(algorithmFolder, "stdout.txt");
    File tempAlgorithmErrorFile = new File(algorithmFolder, "stderr.txt");

    //pb.redirectErrorStream(true);
    tempAlgorithmErrorFile.createNewFile();
    tempAlgorithmOutputFile.createNewFile();

    pb.redirectOutput(tempAlgorithmOutputFile);
    pb.redirectError(tempAlgorithmErrorFile);

    Process process = pb.start();

    while (!process.waitFor(1000, TimeUnit.MILLISECONDS)) {
        if (backgroundRunner.isCancelRequested()) {
            process.destroy();
            throw new CancellationException();
        }//w  w w.  j a  v a2  s .co  m
    }

    int exitCode = process.exitValue();
    if (exitCode != 0) {
        String errtxt = Algorithms.readContent("Error Output: (code=" + exitCode + ")",
                new FileInputStream(tempAlgorithmErrorFile));
        return Either.left(errtxt);
    }

    if (!kdxploreOutputFile.exists()) {
        return Either.left("Missing output file: " + kdxploreOutputFile.getPath());
    }

    result.addTrialEntries(kdxploreOutputFile, userTrialEntries);

    return Either.right(result);
}

From source file:in.cs654.chariot.ashva.AshvaProcessor.java

/**
 * This function takes in request, executes the request and returns the response.
 * The request is written into /tmp/<request_id>.req file. While running the docker container, /tmp dir is mounted
 * to /tmp of the container. This enables ease of data exchange. TODO encryption
 * Docker runs the request and puts the result into /tmp/<request_id>.res.
 * If the request specifies a timeout, it is picked up, else default timeout is set for the process to run
 * @param request containing function_name and other required information
 * @return response of the request/*from  w w w. j  a  v  a  2  s  .co  m*/
 */
private static BasicResponse handleTaskProcessingRequest(BasicRequest request) {
    final String requestID = request.getRequestId();
    try {
        final byte[] serializedBytes = AvroUtils.requestToBytes(request);
        final FileOutputStream fos = new FileOutputStream("/tmp/" + requestID + ".req");
        fos.write(serializedBytes);
        fos.close();
        String timeoutString = request.getExtraData().get("chariot_timeout");
        Long timeout;
        if (timeoutString != null) {
            timeout = Long.parseLong(timeoutString);
        } else {
            timeout = PROCESS_DEFAULT_TIMEOUT;
        }

        final String dockerImage = Mongo.getDockerImage(request.getDeviceId());
        final String cmd = "docker run -v /tmp:/tmp " + dockerImage + " /bin/chariot " + requestID;
        final Process process = Runtime.getRuntime().exec(cmd);
        TimeoutProcess timeoutProcess = new TimeoutProcess(process);
        timeoutProcess.start();
        try {
            timeoutProcess.join(timeout); // milliseconds
            if (timeoutProcess.exit != null) {
                File file = new File("/tmp/" + requestID + ".res");
                byte[] bytes = FileUtils.readFileToByteArray(file);
                LOGGER.info("Response generated for request " + requestID);
                return AvroUtils.bytesToResponse(bytes);
            } else {
                LOGGER.severe("Timeout in generating response for request " + requestID);
                return ResponseFactory.getTimeoutErrorResponse(request);
            }
        } catch (InterruptedException ignore) {
            timeoutProcess.interrupt();
            Thread.currentThread().interrupt();
            LOGGER.severe("Error in generating response for request " + requestID);
            return ResponseFactory.getErrorResponse(request);
        } finally {
            process.destroy();
        }
    } catch (IOException ignore) {
        LOGGER.severe("Error in generating response for request: " + requestID);
        return ResponseFactory.getErrorResponse(request);
    }
}

From source file:com.tascape.qa.th.Utils.java

/**
 * Executes command, and waits for the expected pass/fail phrase in console printout within timeout,
 *
 * @param command    command line/*from   www.  jav a  2s.co  m*/
 * @param pass       skip checking if null
 * @param fail       skip checking if null
 * @param timeout    set 0 for not to check the output message, otherwise, waiting for timeout
 * @param workingDir working directory
 *
 * @return console output as a list of strings
 *
 * @throws IOException          for command error
 * @throws InterruptedException when interrupted
 */
public static List<String> cmd(String[] command, final String pass, final String fail, final long timeout,
        final String workingDir) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(command);
    if (workingDir != null) {
        pb.directory(new File(workingDir));
    }
    pb.redirectErrorStream(true);
    LOG.debug("Running command: " + pb.command().toString().replace(",", ""));
    final Process p = pb.start();
    Thread thread;
    final List<String> output = new ArrayList<>();

    if (timeout == 0) {
        LOG.debug("This is a start-and-exit command");
        output.add(PASS);
        return output;
    } else {
        thread = new Thread() {
            @Override
            public void run() {
                try {
                    LOG.debug("Command timeouts in {} ms", timeout);
                    Thread.sleep(timeout);
                    try {
                        p.exitValue();
                    } catch (IllegalThreadStateException ex) {
                        LOG.debug("killing subprocess {} - {}", p, ex.getMessage());
                        p.destroy();
                    }
                } catch (InterruptedException ex) {
                    LOG.warn(ex.getMessage());
                }
            }
        };
        thread.setName(Thread.currentThread().getName() + "-" + p.hashCode());
        thread.setDaemon(true);
        thread.start();
    }

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String c = p + " - ";
    for (String line = stdIn.readLine(); line != null;) {
        LOG.trace("{}{}", c, line);
        output.add(line);
        try {
            line = stdIn.readLine();
        } catch (IOException ex) {
            LOG.warn(ex.getMessage());
            break;
        }
    }
    LOG.debug("Command exit code {}", p.waitFor());
    thread.interrupt();
    try {
        stdIn.close();
    } catch (IOException ex) {
        LOG.warn("", ex);
    }

    for (String s : output) {
        if (pass != null && (s.contains(pass) || s.matches(pass))) {
            output.add(PASS);
            break;
        } else if (fail != null && s.contains(fail)) {
            output.add(FAIL);
            break;
        }
    }
    return output;
}