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:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * Stops the Screen video capture//from  w  w  w . j a v a 2s .c  om
 */
private void stopScreenVideoCapture() {
    Log.i(TAG, "enter stopScreenVideoCapture at " + System.currentTimeMillis());

    Process sh = null;
    DataOutputStream os = null;
    int pid = 0, exitValue = -1;
    try {
        pid = mAroUtils.getProcessID("ffmpeg");
    } catch (IOException e1) {
        Log.e(TAG, "IOException in stopScreenVideoCapture", e1);
    } catch (InterruptedException e1) {
        Log.e(TAG, "exception in stopScreenVideoCapture", e1);
    }
    if (DEBUG) {
        Log.i(TAG, "stopScreenVideoCapture=" + pid);
    }
    if (pid != 0) {
        try {
            sh = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(sh.getOutputStream());
            String command = "kill -15 " + pid + "\n";
            os.writeBytes(command);

            command = "exit\n";
            os.writeBytes(command);
            os.flush();

            //clear the streams so that it doesnt block the process
            //sh.inputStream is actually the output from the process
            StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", false);
            new Thread(stdoutClearer).start();
            StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true);
            new Thread(stderrClearer).start();

            exitValue = sh.waitFor();
            if (exitValue == 0) {
                mVideoRecording = false;
            }

            if (DEBUG) {
                Log.i(TAG, "successfully returned from kill -15; exitValue= " + exitValue);
            }
        } catch (IOException e) {
            Log.e(TAG, "exception in stopScreenVideoCapture", e);
        } catch (InterruptedException e) {
            Log.e(TAG, "exception in stopScreenVideoCapture", e);
        } finally {
            try {
                kill9Ffmpeg();

                if (os != null) {
                    os.close();
                }
                if (sh != null) {
                    sh.destroy();
                }
            } catch (Exception e) {
                Log.e(TAG, "exception in stopScreenVideoCapture finally block", e);
            }
            if (DEBUG) {
                Log.i(TAG, "Stopped Video Capture in stopScreenVideoCapture()");
            }
        }
    }

    if (DEBUG) {
        Log.i(TAG, "exit stopScreenVideoCapture");
    }
}

From source file:de.teamgrit.grit.checking.compile.HaskellCompileChecker.java

/**
 * checkProgram invokes the Haskell compiler on a given file and reports
 * the output.//from   ww  w.j  a  v  a  2 s  .co  m
 * 
 * @param pathToProgramFile
 *            Specifies the file or folder containing that should be
 *            compiled. (accepts .lhs and .hs files)
 * @param compilerName
 *            The compiler to be used (usually ghc).
 * @param compilerFlags
 *            Additional flags to be passed to the compiler.
 * @throws FileNotFoundException
 *             Is thrown when the file in pathToProgramFile cannot be
 *             opened
 * @throws BadCompilerSpecifiedException
 *             Is thrown when the given compiler cannot be called
 * @return A {@link CompilerOutput} that contains all compiler messages and
 *         flags on how the compile run went.
 * @throws BadFlagException
 *             When ghc doesn't recognize a flag, this exception is thrown.
 */
@Override
public CompilerOutput checkProgram(Path pathToProgramFile, String compilerName, List<String> compilerFlags)
        throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException {

    Process compilerProcess = null;

    try {
        // create compiler invocation.
        List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName,
                compilerFlags);

        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);

        // make sure the compiler stays in its directory.
        compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile());

        compilerProcess = compilerProcessBuilder.start();
        // this will never happen because createCompilerInvocation never
        // throws this Exception. Throw declaration needs to be in method
        // declaration because of the implemented Interface although we
        // never use it in the HaskellCompileChecker
    } catch (CompilerOutputFolderExistsException e) {
        LOGGER.severe("A problem while compiling, which never should happen, occured" + e.getMessage());
    } catch (BadCompilerSpecifiedException e) {
        throw new BadCompilerSpecifiedException(e.getMessage());
    } catch (IOException e) {

        // If we cannot call the compiler we return a CompilerOutput
        // initialized with false, false, indicating
        // that the compiler wasn't invoked properly and that there was no
        // clean Compile.
        CompilerOutput compilerInvokeError = new CompilerOutput();
        compilerInvokeError.setClean(false);
        compilerInvokeError.setCompilerInvoked(false);
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok ghc reports
    // nothing in the errorStream.
    InputStream compilerOutputStream = compilerProcess.getErrorStream();
    InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream);
    BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader);
    String line;

    CompilerOutput compilerOutput = new CompilerOutput();
    compilerOutput.setCompilerInvoked(true);

    List<String> compilerOutputLines = new LinkedList<>();

    try {
        while ((line = compilerOutputBuffer.readLine()) != null) {
            compilerOutputLines.add(line);
        }
        // Errors are separated via an empty line (""). But after the
        // the last error the OutputBuffer has nothing more to write.
        // In order to recognize the last error we insert an empty String
        // at the end of the list.
        // Only needs to be done when there are errors.
        if (compilerOutputLines.size() != 0) {
            line = "";
            compilerOutputLines.add(line);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();

    } catch (IOException e) {

        // Reading might go wrong here if ghc should unexpectedly die
        LOGGER.severe("Error while reading from compiler stream.");
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    // ghc -c generates a .o(object) and a .hi(haskell interface) file.
    // But we don't need those files so they can be deleted.
    // The generated files have the same name like our input file so we
    // can just exchange the file endings in order to get the
    // correct file paths for deletion
    if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) {

        // we use a file walker in order to find all files in the folder
        // and its subfolders
        RegexDirectoryWalker dirWalker = new RegexDirectoryWalker(".+\\.([Ll])?[Hh][Ss]");
        try {
            Files.walkFileTree(pathToProgramFile, dirWalker);
        } catch (IOException e) {
            LOGGER.severe("Could not walk submission " + pathToProgramFile.toString()
                    + " while building copiler invocation: " + e.getMessage());
        }

        for (Path candidatePath : dirWalker.getFoundFiles()) {
            File candidateFile = candidatePath.toFile();
            if (!candidateFile.isDirectory()) {
                String extension = FilenameUtils.getExtension(candidateFile.toString());
                if (extension.matches("[Ll]?[Hh][Ss]")) {
                    File ghcGeneratedObject = new File(
                            FilenameUtils.removeExtension(candidateFile.toString()) + ".o");
                    File ghcGeneratedInterface = new File(
                            FilenameUtils.removeExtension(candidateFile.toString()) + ".hi");
                    ghcGeneratedObject.delete();
                    ghcGeneratedInterface.delete();
                }
            }
        }
    } else {
        String extension = FilenameUtils.getExtension(pathToProgramFile.toString());
        if (extension.matches("[Ll]?[Hh][Ss]")) {
            File ghcGeneratedObject = new File(
                    FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".o");
            File ghcGeneratedInterface = new File(
                    FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".hi");
            ghcGeneratedObject.delete();
            ghcGeneratedInterface.delete();
        }

    }

    // if there are no errors there is no Output to handle
    if (compilerOutputLines.size() != 0) {
        compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput);
    } else {
        compilerOutput.setClean(true);
    }
    return compilerOutput;
}

From source file:org.auraframework.integration.test.archetype.AuraArchetypeSimpleTestMANUAL.java

@Test
public void testProjectCreation() throws Throwable {
    Process jettyProcess = null;
    workspace = new File(IOUtil.newTempDir("archetype"));
    try {/* w w w  . ja  v  a 2  s. c  o  m*/
        // create a workspace to place the project files in
        workspace.mkdirs();

        // generate a project from the archetype
        Process genProcess = startProcess(workspace,
                ImmutableList.of("mvn", "archetype:generate", "-DarchetypeRepository=" + archRepo,
                        "-DarchetypeCatalog=" + archCatalog, "-DarchetypeGroupId=" + archetype.groupId,
                        "-DarchetypeArtifactId=" + archetype.artifactId,
                        "-DarchetypeVersion=" + archetype.version, "-DgroupId=" + project.groupId,
                        "-DartifactId=" + project.artifactId, "-Dversion=" + project.version,
                        "-Dpackage=" + projectPackage, "-DinteractiveMode=false"));
        goldMavenOutput(genProcess, "-creation.txt", "Failed to generate artifact!");

        File projectDir = new File(workspace, project.artifactId);
        assertDirectory(projectDir);
        verifyGeneratedResources(projectDir);

        // build the new project
        Process buildProcess = startProcess(projectDir, ImmutableList.of("mvn", "install"));
        goldMavenOutput(buildProcess, "-install.txt", "Failed to build new project!");

        // get a free port for jetty
        ServerSocket socket = new ServerSocket(0);
        int jettyPort = socket.getLocalPort();
        socket.close();

        // start up jetty
        jettyProcess = startProcess(projectDir,
                ImmutableList.of("mvn", "jetty:run", "-Djetty.port=" + jettyPort));

        int status = 0;
        for (int i = 0; i < 30; i++) {
            try {
                HttpGet get = obtainGetMethod("/");
                HttpResponse response = perform(get);
                status = getStatusCode(response);
                get.releaseConnection();
                break;
            } catch (ConnectException ce) {
                // expected, before server is listening
                Thread.sleep(1000);
            }
        }
        assertEquals("Failed to connect to server", HttpStatus.SC_OK, status);

        verifyDefaultDocument();
        verifySampleComponents();
    } catch (Throwable t) {
        // if any errors in Jetty requests, let's print out the Jetty
        // console output for diag before killing the
        // test
        if (jettyProcess != null) {
            InputStream is = jettyProcess.getInputStream();
            int len = is.available();
            byte[] buf = new byte[len];
            is.read(buf);
            System.err.println(new String(buf));
        }
        throw t;
    } finally {
        // kill Jetty
        if (jettyProcess != null) {
            try {
                jettyProcess.exitValue();
            } catch (IllegalThreadStateException e) {
                jettyProcess.destroy();
            }
        }
        // cleanup generated workspace
        IOUtil.delete(workspace);
    }
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * Starts the video capture of the device desktop by reading frame buffer
 * using ffmpeg command//from   w ww . j  av  a 2s .  c o  m
 */
private void startScreenVideoCapture() {
    Process sh = null;
    DataOutputStream os = null;
    try {
        if (DEBUG) {
            Log.e(TAG, "Starting Video Capture");
        }
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        String Command = "cd " + ARODataCollector.INTERNAL_DATA_PATH + " \n";
        os.writeBytes(Command);
        Command = "chmod 777 ffmpeg \n";
        os.writeBytes(Command);
        Command = "./ffmpeg -f fbdev -vsync 2 -r 3 -i /dev/graphics/fb0 /sdcard/ARO/" + TRACE_FOLDERNAME
                + "/video.mp4 2> /data/ffmpegout.txt \n";
        os.writeBytes(Command);
        Command = "exit\n";
        os.writeBytes(Command);
        os.flush();
        sh.waitFor();
    } catch (IOException e) {
        Log.e(TAG, "exception in startScreenVideoCapture", e);
    } catch (InterruptedException e) {
        Log.e(TAG, "exception in startScreenVideoCapture", e);
    } finally {
        try {
            if (DEBUG) {
                Log.e(TAG, "Stopped Video Capture in startScreenVideoCapture");
            }
            os.close();
            // Reading start time of Video from ffmpegout file
            mApp.readffmpegStartTimefromFile();
        } catch (IOException e) {
            Log.e(TAG, "IOException in reading video start time", e);
        } catch (NumberFormatException e) {
            Log.e(TAG, "NumberFormatException in reading video start time", e);
        }
        try {
            // Recording start time of video
            mApp.writeVideoTraceTime(Double.toString(mApp.getAROVideoCaptureStartTime()));
            mApp.closeVideoTraceTimeFile();
        } catch (IOException e) {
            Log.e(TAG, "IOException in writing video start time", e);
        }
        if (mApp.getTcpDumpStartFlag() && !mApp.getARODataCollectorStopFlag()) {
            mApp.setVideoCaptureFailed(true);
        }
        try {
            mApp.setAROVideoCaptureRunningFlag(false);
            sh.destroy();
        } catch (Exception e) {
            Log.e(TAG, "Failed to destroy shell during Video Capture termination");
        }
    }
}

From source file:cz.cuni.amis.planning4j.validation.external.ValValidator.java

@Override
public IValidationResult validate(IPDDLFileDomainProvider domainProvider,
        IPDDLFileProblemProvider problemProvider, List<ActionDescription> plan) {
    File mainExecutable = new File(validatorDirectory,
            getValidatorFolderName() + File.separatorChar + getValidatorExecutableName());
    if (!mainExecutable.exists()) {
        String toolMessage = "Could not find validator executable '" + getValidatorExecutableName()
                + "' in directory " + validatorDirectory.getAbsolutePath();
        throw new ValidationException(toolMessage);
    }//  ww  w  .ja v a  2 s .  c om
    FileWriter planWriter = null;
    Process process = null;
    try {

        /**
         * Write the plan to a temp file
         */
        File planTempFile = File.createTempFile("plan", ".soln");
        planWriter = new FileWriter(planTempFile);
        for (ActionDescription action : plan) {
            planWriter.write(action.getStartTime() + ": (" + action.getName() + " ");
            for (String param : action.getParameters()) {
                planWriter.write(param + " ");
            }
            planWriter.write(") [" + action.getDuration() + "]\n");
        }

        planWriter.close();
        planWriter = null;
        /**
         * Invoke the validator
         */
        ProcessBuilder processBuilder = new ProcessBuilder(mainExecutable.getAbsolutePath(), "-s", //silent mode for simple parsing - only errors are printed to the stdout
                domainProvider.getDomainFile().getAbsolutePath(),
                problemProvider.getProblemFile().getAbsolutePath(), planTempFile.getAbsolutePath());

        logger.info("Starting VAL validator.");
        if (logger.isDebugEnabled()) {
            logger.debug("The command: " + processBuilder.command());
        }
        process = processBuilder.start();

        Scanner outputScanner = new Scanner(process.getInputStream());

        StringBuilder consoleOutputBuilder = new StringBuilder();

        boolean hasNonEmptyLines = false;
        if (logger.isTraceEnabled()) {
            logger.trace("Validator output:");
        }
        while (outputScanner.hasNextLine()) {
            String line = outputScanner.nextLine();
            if (!consoleOutputBuilder.toString().isEmpty()) {
                consoleOutputBuilder.append("\n");
            }
            if (!line.trim().isEmpty()) {
                hasNonEmptyLines = true;
            }
            consoleOutputBuilder.append(line);
            if (logger.isTraceEnabled()) {
                logger.trace(line);
            }
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Validator output end.");
        }

        try {
            //clean the error stream. Otherwise this might prevent the process from being terminated / cleared from the process table
            IOUtils.toString(process.getErrorStream());
        } catch (IOException ex) {
            logger.warn("Could not clear error stream.", ex);
        }

        process.waitFor();
        boolean valid = !hasNonEmptyLines; //validator is run in silent mode, so any output means plan is not valid.
        logger.info("Validation finished. Result is: " + valid);
        return new ValidationResult(valid, consoleOutputBuilder.toString());
    } catch (Exception ex) {
        if (planWriter != null) {
            try {
                planWriter.close();
            } catch (Exception ignored) {
            }
        }
        if (process != null) {
            process.destroy();
            try {
                //clean the streams so that the process does not hang in the process table
                IOUtils.toString(process.getErrorStream());
                IOUtils.toString(process.getInputStream());
            } catch (Exception ignored) {
                logger.warn("Could not clear output/error stream.", ignored);
            }
        }
        throw new ValidationException("Error during validation", ex);
    }
}

From source file:org.auraframework.archetype.AuraArchetypeSimpleTestMANUAL.java

public void testProjectCreation() throws Throwable {
    Process jettyProcess = null;
    workspace = new File(
            System.getProperty("java.io.tmpdir") + File.separator + getName() + System.currentTimeMillis());
    try {//from w  w  w .  j  ava 2  s . c  om
        // create a workspace to place the project files in
        workspace.mkdirs();

        // generate a project from the archetype
        Process genProcess = startProcess(workspace,
                ImmutableList.of("mvn", "archetype:generate", "-DarchetypeRepository=" + archRepo,
                        "-DarchetypeCatalog=" + archCatalog, "-DarchetypeGroupId=" + archetype.groupId,
                        "-DarchetypeArtifactId=" + archetype.artifactId,
                        "-DarchetypeVersion=" + archetype.version, "-DgroupId=" + project.groupId,
                        "-DartifactId=" + project.artifactId, "-Dversion=" + project.version,
                        "-Dpackage=" + projectPackage, "-DinteractiveMode=false"));
        goldMavenOutput(genProcess, "-creation.txt", "Failed to generate artifact!");

        File projectDir = new File(workspace, project.artifactId);
        assertDirectory(projectDir);
        verifyGeneratedResources(projectDir);

        // build the new project
        Process buildProcess = startProcess(projectDir, ImmutableList.of("mvn", "install"));
        goldMavenOutput(buildProcess, "-install.txt", "Failed to build new project!");

        // get a free port for jetty
        ServerSocket socket = new ServerSocket(0);
        int jettyPort = socket.getLocalPort();
        socket.close();

        // start up jetty
        jettyProcess = startProcess(projectDir,
                ImmutableList.of("mvn", "jetty:run", "-Djetty.port=" + jettyPort));

        int status = 0;
        for (int i = 0; i < 30; i++) {
            try {
                HttpGet get = obtainGetMethod("/");
                HttpResponse response = perform(get);
                status = getStatusCode(response);
                get.releaseConnection();
                break;
            } catch (ConnectException ce) {
                // expected, before server is listening
                Thread.sleep(1000);
            }
        }
        assertEquals("Failed to connect to server", HttpStatus.SC_OK, status);

        verifyDefaultDocument();
        verifySampleComponents();
    } catch (Throwable t) {
        // if any errors in Jetty requests, let's print out the Jetty
        // console output for diag before killing the
        // test
        if (jettyProcess != null) {
            InputStream is = jettyProcess.getInputStream();
            int len = is.available();
            byte[] buf = new byte[len];
            is.read(buf);
            System.err.println(new String(buf));
        }
        throw t;
    } finally {
        // kill Jetty
        if (jettyProcess != null) {
            try {
                jettyProcess.exitValue();
            } catch (IllegalThreadStateException e) {
                jettyProcess.destroy();
            }
        }
        // cleanup generated workspace
        IOUtil.delete(workspace);
    }
}

From source file:org.moyrax.javascript.shell.Global.java

/**
 * If any of in, out, err is null, the corresponding process stream will be
 * closed immediately, otherwise it will be closed as soon as all data will be
 * read from/written to process/*from www . j  a  v  a  2s  .  c  om*/
 */
private static int runProcess(String[] cmd, String[] environment, InputStream in, OutputStream out,
        OutputStream err) throws IOException {
    Process p;
    if (environment == null) {
        p = Runtime.getRuntime().exec(cmd);
    } else {
        p = Runtime.getRuntime().exec(cmd, environment);
    }
    PipeThread inThread = null, errThread = null;
    try {
        InputStream errProcess = null;
        try {
            if (err != null) {
                errProcess = p.getErrorStream();
            } else {
                p.getErrorStream().close();
            }
            InputStream outProcess = null;
            try {
                if (out != null) {
                    outProcess = p.getInputStream();
                } else {
                    p.getInputStream().close();
                }
                OutputStream inProcess = null;
                try {
                    if (in != null) {
                        inProcess = p.getOutputStream();
                    } else {
                        p.getOutputStream().close();
                    }

                    if (out != null) {
                        // Read process output on this thread
                        if (err != null) {
                            errThread = new PipeThread(true, errProcess, err);
                            errThread.start();
                        }
                        if (in != null) {
                            inThread = new PipeThread(false, in, inProcess);
                            inThread.start();
                        }
                        pipe(true, outProcess, out);
                    } else if (in != null) {
                        // No output, read process input on this thread
                        if (err != null) {
                            errThread = new PipeThread(true, errProcess, err);
                            errThread.start();
                        }
                        pipe(false, in, inProcess);
                        in.close();
                    } else if (err != null) {
                        // No output or input, read process err
                        // on this thread
                        pipe(true, errProcess, err);
                        errProcess.close();
                        errProcess = null;
                    }

                    // wait for process completion
                    for (;;) {
                        try {
                            p.waitFor();
                            break;
                        } catch (InterruptedException ex) {
                        }
                    }

                    return p.exitValue();
                } finally {
                    // pipe will close stream as well, but for reliability
                    // duplicate it in any case
                    if (inProcess != null) {
                        inProcess.close();
                    }
                }
            } finally {
                if (outProcess != null) {
                    outProcess.close();
                }
            }
        } finally {
            if (errProcess != null) {
                errProcess.close();
            }
        }
    } finally {
        p.destroy();
        if (inThread != null) {
            for (;;) {
                try {
                    inThread.join();
                    break;
                } catch (InterruptedException ex) {
                }
            }
        }
        if (errThread != null) {
            for (;;) {
                try {
                    errThread.join();
                    break;
                } catch (InterruptedException ex) {
                }
            }
        }
    }
}

From source file:Exec.java

/**
 * Description of the Method/*from   ww  w. ja  va  2s . c o  m*/
 * 
 * @param command
 *            Description of the Parameter
 * @param input
 *            Description of the Parameter
 * @param successCode
 *            Description of the Parameter
 * @param timeout
 *            Description of the Parameter
 * @param lazy
 *            Description of the Parameter
 * @return Description of the Return Value
 */
public static ExecResults execOptions(String command, String input, int successCode, int timeout,
        boolean lazy) {
    Process child = null;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ByteArrayOutputStream errors = new ByteArrayOutputStream();
    ExecResults results = new ExecResults(command, input, successCode, timeout);
    BitSet interrupted = new BitSet(1);
    boolean lazyQuit = false;
    ThreadWatcher watcher;

    try {
        // start the command
        child = Runtime.getRuntime().exec(command);

        // get the streams in and out of the command
        InputStream processIn = child.getInputStream();
        InputStream processError = child.getErrorStream();
        OutputStream processOut = child.getOutputStream();

        // start the clock running
        if (timeout > 0) {
            watcher = new ThreadWatcher(child, interrupted, timeout);
            new Thread(watcher).start();
        }

        // Write to the child process' input stream
        if ((input != null) && !input.equals("")) {
            try {
                processOut.write(input.getBytes());
                processOut.flush();
                processOut.close();
            } catch (IOException e1) {
                results.setThrowable(e1);
            }
        }

        // Read from the child process' output stream
        // The process may get killed by the watcher at any time
        int c = 0;

        try {
            while (true) {
                if (interrupted.get(0) || lazyQuit) {
                    break;
                }

                // interrupted
                c = processIn.read();

                if (c == -1) {
                    break;
                }

                // end of stream
                output.write(c);

                if (lazy && (processIn.available() < 1)) {
                    lazyQuit = true;
                }

                // if lazy and nothing then quit (after at least one read)
            }

            processIn.close();
        } catch (IOException e2) {
            results.setThrowable(e2);
        } finally {
            if (interrupted.get(0)) {
                results.setInterrupted();
            }

            results.setOutput(output.toString());
        }

        // Read from the child process' error stream
        // The process may get killed by the watcher at any time
        try {
            while (true) {
                if (interrupted.get(0) || lazyQuit) {
                    break;
                }

                // interrupted
                c = processError.read();

                if (c == -1) {
                    break;
                }

                // end of stream
                output.write(c);

                if (lazy && (processError.available() < 1)) {
                    lazyQuit = true;
                }

                // if lazy and nothing then quit (after at least one read)
            }

            processError.close();
        } catch (IOException e3) {
            results.setThrowable(e3);
        } finally {
            if (interrupted.get(0)) {
                results.setInterrupted();
            }

            results.setErrors(errors.toString());
        }

        // wait for the return value of the child process.
        if (!interrupted.get(0) && !lazyQuit) {
            int returnCode = child.waitFor();
            results.setReturnCode(returnCode);

            if (returnCode != successCode) {
                results.setError(ExecResults.BADRETURNCODE);
            }
        }
    } catch (InterruptedException i) {
        results.setInterrupted();
    } catch (Throwable t) {
        results.setThrowable(t);
    } finally {
        if (child != null) {
            child.destroy();
        }
    }

    return (results);
}

From source file:Exec.java

/**
 * Description of the Method//from   w w  w  .ja v a2 s  .c  om
 * 
 * @param command
 *            Description of the Parameter
 * @param input
 *            Description of the Parameter
 * @param successCode
 *            Description of the Parameter
 * @param timeout
 *            Description of the Parameter
 * @param lazy
 *            Description of the Parameter
 * @return Description of the Return Value
 */
public static ExecResults execOptions(String[] command, String input, int successCode, int timeout,
        boolean lazy) {
    Process child = null;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ByteArrayOutputStream errors = new ByteArrayOutputStream();
    ExecResults results = new ExecResults(command[0], input, successCode, timeout);
    BitSet interrupted = new BitSet(1);
    boolean lazyQuit = false;
    ThreadWatcher watcher;

    try {
        // start the command
        child = Runtime.getRuntime().exec(command);

        // get the streams in and out of the command
        InputStream processIn = child.getInputStream();
        InputStream processError = child.getErrorStream();
        OutputStream processOut = child.getOutputStream();

        // start the clock running
        if (timeout > 0) {
            watcher = new ThreadWatcher(child, interrupted, timeout);
            new Thread(watcher).start();
        }

        // Write to the child process' input stream
        if ((input != null) && !input.equals("")) {
            try {
                processOut.write(input.getBytes());
                processOut.flush();
                processOut.close();
            } catch (IOException e1) {
                results.setThrowable(e1);
            }
        }

        // Read from the child process' output stream
        // The process may get killed by the watcher at any time
        int c = 0;

        try {
            while (true) {
                if (interrupted.get(0) || lazyQuit) {
                    break;
                }

                // interrupted
                c = processIn.read();

                if (c == -1) {
                    break;
                }

                // end of stream
                output.write(c);

                if (lazy && (processIn.available() < 1)) {
                    lazyQuit = true;
                }

                // if lazy and nothing then quit (after at least one read)
            }

            processIn.close();
        } catch (IOException e2) {
            results.setThrowable(e2);
        } finally {
            if (interrupted.get(0)) {
                results.setInterrupted();
            }

            results.setOutput(output.toString());
        }

        // Read from the child process' error stream
        // The process may get killed by the watcher at any time
        try {
            while (true) {
                if (interrupted.get(0) || lazyQuit) {
                    break;
                }

                // interrupted
                c = processError.read();

                if (c == -1) {
                    break;
                }

                // end of stream
                output.write(c);

                if (lazy && (processError.available() < 1)) {
                    lazyQuit = true;
                }

                // if lazy and nothing then quit (after at least one read)
            }

            processError.close();
        } catch (IOException e3) {
            results.setThrowable(e3);
        } finally {
            if (interrupted.get(0)) {
                results.setInterrupted();
            }

            results.setErrors(errors.toString());
        }

        // wait for the return value of the child process.
        if (!interrupted.get(0) && !lazyQuit) {
            int returnCode = child.waitFor();
            results.setReturnCode(returnCode);

            if (returnCode != successCode) {
                results.setError(ExecResults.BADRETURNCODE);
            }
        }
    } catch (InterruptedException i) {
        results.setInterrupted();
    } catch (Throwable t) {
        results.setThrowable(t);
    } finally {
        if (child != null) {
            child.destroy();
        }
    }

    return (results);
}

From source file:com.ah.be.common.NmsUtil.java

public static ImageInfo getImageInfoFromFile(String imageFile) {
    if (!(new File(imageFile).exists()))
        return null;

    String[] exeCmds = new String[] { "bash", "-c", "" };
    exeCmds[2] = "od -S13 -N200 " + imageFile;

    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    ImageInfo imageInfo = null;//from   ww w .  j a  va2  s.co  m
    Process process = null;

    try {
        process = Runtime.getRuntime().exec(exeCmds);
        inputStream = process.getInputStream();

        bufferedReader = new BufferedReader(new InputStreamReader(inputStream), 2048);

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            if (imageInfo == null)
                imageInfo = new ImageInfo();

            if (line.contains("Type:")) {
                String type = line.substring(line.indexOf("Type:") + "Type:".length(), line.lastIndexOf("$"))
                        .trim();
                imageInfo.setType(type);
            } else if (line.contains("Reversion:")) {
                String reversion = line
                        .substring(line.indexOf("Reversion:") + "Reversion:".length(), line.lastIndexOf("$"))
                        .trim();
                imageInfo.setReversion(reversion);
            } else if (line.contains("DATE:")) {
                String date = line.substring(line.indexOf("DATE:") + "DATE:".length(), line.lastIndexOf("$"))
                        .trim();
                imageInfo.setDate(date);
            } else if (line.contains("Size:")) {
                String size = line.substring(line.indexOf("Size:") + "Size:".length(), line.lastIndexOf("$"))
                        .trim();
                imageInfo.setSize(size);
            }
        }

        if (imageInfo != null)
            imageInfo.getTargetNameByTypeAndVersion();

    } catch (IOException e) {
        log.error("get the image info of file: " + imageFile + " failed.", e);
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ioe) {
                log.error("close buffered reader failed.", ioe);
            }
        }

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ioe) {
                log.error("close input stream failed.", ioe);
            }
        }

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

    return imageInfo;
}