Example usage for java.lang Process getOutputStream

List of usage examples for java.lang Process getOutputStream

Introduction

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

Prototype

public abstract OutputStream getOutputStream();

Source Link

Document

Returns the output stream connected to the normal input of the process.

Usage

From source file:uk.ac.kcl.iop.brc.core.pipeline.common.service.DocumentConversionService.java

private File makeTiffFromPDF(DNCWorkCoordinate coordinate, File input) throws IOException, TikaException {
    File output = File.createTempFile(coordinate.getFileName(), ".tiff");
    String[] cmd = { getImageMagickProg(), "-density", "300", input.getPath(), "-depth", "8", "-quality", "1",
            output.getPath() };/*from   ww w.ja v a  2s  .  c  o m*/
    Process process = new ProcessBuilder(cmd).start();
    IOUtils.closeQuietly(process.getOutputStream());
    InputStream processInputStream = process.getInputStream();
    logStream(processInputStream);
    FutureTask<Integer> waitTask = new FutureTask<>(process::waitFor);
    Thread waitThread = new Thread(waitTask);
    waitThread.start();
    try {
        waitTask.get(240, TimeUnit.SECONDS);
        return output;
    } catch (Exception e) {
        logger.error(e.getMessage());
        waitThread.interrupt();
        process.destroy();
        Thread.currentThread().interrupt();
        waitTask.cancel(true);
    } finally {
        IOUtils.closeQuietly(processInputStream);
        process.destroy();
        waitThread.interrupt();
        waitTask.cancel(true);
    }
    return null;
}

From source file:richtercloud.document.scanner.ocr.TesseractOCREngine.java

/**
 * Don't invoke {@code recognizeImage} from multiple threads.
 *
 * @param image//  w w  w. j a v a2s  .  co  m
 * @throws IllegalArgumentException if {@code image} is {@code null}
 * @throws IllegalStateException if another recognition is currently running
 * @return {@code null} if the recognition has been canceled using {@link #cancelRecognizeImage() } or the recognition process crashed or the recognition result otherwise
 */
@Override
public String recognizeImage0(BufferedImage image) throws IllegalStateException {
    if (!lock.tryLock()) {
        throw new IllegalStateException("This tesseract OCR engine is already used from another thread.");
    }
    try {
        Iterator<String> languagesItr = this.languages.iterator();
        String lanuguageString = languagesItr.next();
        while (languagesItr.hasNext()) {
            lanuguageString += "+" + languagesItr.next();
        }
        ProcessBuilder tesseractProcessBuilder = new ProcessBuilder(this.getBinary(), "-l", lanuguageString,
                "stdin", "stdout").redirectOutput(ProcessBuilder.Redirect.PIPE);
        Process tesseractProcess = tesseractProcessBuilder.start();
        setBinaryProcess(tesseractProcess);
        ImageIO.write(image, "png", tesseractProcess.getOutputStream());
        tesseractProcess.getOutputStream().flush();
        tesseractProcess.getOutputStream().close(); //sending EOF not an option because it's not documented what is expected (sending -1 once or twice doesn't have any effect, also with flush)
        int tesseractProcessExitValue = tesseractProcess.waitFor();
        if (tesseractProcessExitValue != 0) {
            //tesseractProcess.destroy might cause IOException, but
            //termination with exit value != 0 might occur as well
            return null;
        }
        StringWriter tesseractResultWriter = new StringWriter();
        IOUtils.copy(tesseractProcess.getInputStream(), tesseractResultWriter);
        String tesseractResult = tesseractResultWriter.toString();
        LOGGER.debug("OCR result: {}", tesseractResult);
        return tesseractResult;
    } catch (InterruptedException ex) {
        //InterruptedException is an IOException
        return null; //might at one point be thrown due to Process.destroy
        //cancelation
    } catch (IOException ex) {
        if (ex.getMessage().equals("Stream closed")) {
            return null; //result of Process.destroy
        }
        throw new RuntimeException(ex);
    } finally {
        lock.unlock();
    }
}

From source file:mitm.common.sms.transport.gnokii.Gnokii.java

/**
 * Sends the message to the number.//from w w  w.  j a  v  a2  s. c  o  m
 */
public String sendSMS(String phoneNumber, String message) throws GnokiiException {
    List<String> cmd = new LinkedList<String>();

    cmd.add(GNOKII_BIN);
    cmd.add("--sendsms");
    cmd.add(phoneNumber);

    if (maxMessageSize != DEFAULT_MAX_MESSAGE_SIZE) {
        cmd.add("-l");
        cmd.add(Integer.toString(maxMessageSize));
    }

    if (requestForDeliveryReport) {
        cmd.add("-r");
    }

    try {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();

        byte[] bytes = MiscStringUtils.toAsciiBytes(message);

        IOUtils.write(bytes, process.getOutputStream());

        process.getOutputStream().close();

        String output = IOUtils.toString(process.getInputStream());

        int exitValue;

        try {
            exitValue = process.waitFor();
        } catch (InterruptedException e) {
            throw new GnokiiException("Error sending SMS. Output: " + output);
        }

        if (exitValue != 0) {
            throw new GnokiiException("Error sending SMS. Output: " + output);
        }

        return output;
    } catch (IOException e) {
        throw new GnokiiException(e);
    }
}

From source file:org.apache.hadoop.ha.ShellCommandFencer.java

@Override
public boolean tryFence(HAServiceTarget target, String cmd) {
    ProcessBuilder builder;//from  w  w  w. j a v  a 2  s  .  c  o  m

    if (!Shell.WINDOWS) {
        builder = new ProcessBuilder("bash", "-e", "-c", cmd);
    } else {
        builder = new ProcessBuilder("cmd.exe", "/c", cmd);
    }

    setConfAsEnvVars(builder.environment());
    addTargetInfoAsEnvVars(target, builder.environment());

    Process p;
    try {
        p = builder.start();
        p.getOutputStream().close();
    } catch (IOException e) {
        LOG.warn("Unable to execute " + cmd, e);
        return false;
    }

    String pid = tryGetPid(p);
    LOG.info("Launched fencing command '" + cmd + "' with " + ((pid != null) ? ("pid " + pid) : "unknown pid"));

    String logPrefix = abbreviate(cmd, ABBREV_LENGTH);
    if (pid != null) {
        logPrefix = "[PID " + pid + "] " + logPrefix;
    }

    // Pump logs to stderr
    StreamPumper errPumper = new StreamPumper(LOG, logPrefix, p.getErrorStream(),
            StreamPumper.StreamType.STDERR);
    errPumper.start();

    StreamPumper outPumper = new StreamPumper(LOG, logPrefix, p.getInputStream(),
            StreamPumper.StreamType.STDOUT);
    outPumper.start();

    int rc;
    try {
        rc = p.waitFor();
        errPumper.join();
        outPumper.join();
    } catch (InterruptedException ie) {
        LOG.warn("Interrupted while waiting for fencing command: " + cmd);
        return false;
    }

    return rc == 0;
}

From source file:cz.cuni.mff.ksi.jinfer.autoeditor.BububuEditor.java

/**
 * Draws automaton and waits until user picks two states and clicks
 * 'continue' button.//ww w  .  j a v a 2 s .  c o  m
 *
 * @param automaton automaton to be drawn
 * @return if user picks exactly two states returns Pair of them otherwise null
 */
@Override
public List<State<T>> drawAutomatonToPickStates(final Automaton<T> automaton) {

    final DirectedSparseMultigraph<State<T>, Step<T>> graph = new DirectedSparseMultigraph<State<T>, Step<T>>();
    final Map<State<T>, Set<Step<T>>> automatonDelta = automaton.getDelta();

    // Get vertices = states of automaton
    for (Entry<State<T>, Set<Step<T>>> entry : automatonDelta.entrySet()) {
        graph.addVertex(entry.getKey());
    }

    // Get edges of automaton
    for (Entry<State<T>, Set<Step<T>>> entry : automatonDelta.entrySet()) {
        for (Step<T> step : entry.getValue()) {
            graph.addEdge(step, step.getSource(), step.getDestination());
        }
    }

    Map<State<T>, Point2D> positions = new HashMap<State<T>, Point2D>();

    ProcessBuilder p = new ProcessBuilder(Arrays.asList("/usr/bin/dot", "-Tplain"));
    try {
        Process k = p.start();
        k.getOutputStream().write((new AutomatonToDot<T>()).convertToDot(automaton, symbolToString).getBytes());
        k.getOutputStream().flush();
        BufferedReader b = new BufferedReader(new InputStreamReader(k.getInputStream()));
        k.getOutputStream().close();

        Scanner s = new Scanner(b);
        s.next();
        s.next();
        double width = s.nextDouble();
        double height = s.nextDouble();
        double windowW = 500;
        double windowH = 300;

        while (s.hasNext()) {
            if (s.next().equals("node")) {
                int nodeName = s.nextInt();
                double x = s.nextDouble();
                double y = s.nextDouble();
                for (State<T> state : automatonDelta.keySet()) {
                    if (state.getName() == nodeName) {
                        positions.put(state,
                                new Point((int) (windowW * x / width), (int) (windowH * y / height)));
                        break;
                    }
                }
            }
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    Transformer<State<T>, Point2D> trans = TransformerUtils.mapTransformer(positions);

    // TODO rio find suitable layout
    final Layout<State<T>, Step<T>> layout = new StaticLayout<State<T>, Step<T>>(graph, trans);

    //layout.setSize(new Dimension(300,300)); // sets the initial size of the space

    visualizationViewer = new VisualizationViewer<State<T>, Step<T>>(layout);
    //visualizationViewer.setPreferredSize(new Dimension(350,350)); //Sets the viewing area size

    visualizationViewer.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<State<T>>());
    visualizationViewer.getRenderContext().setEdgeLabelTransformer(new Transformer<Step<T>, String>() {
        @Override
        public String transform(Step<T> i) {
            return BububuEditor.this.symbolToString.toString(i.getAcceptSymbol());
        }
    });

    final PluggableGraphMouse gm = new PluggableGraphMouse();
    gm.add(new PickingUnlimitedGraphMousePlugin<State<T>, Step<T>>());
    visualizationViewer.setGraphMouse(gm);

    // Call GUI in a special thread. Required by NB.
    synchronized (this) {
        WindowManager.getDefault().invokeWhenUIReady(new Runnable() {

            @Override
            public void run() {
                // Pass this as argument so the thread will be able to wake us up.
                AutoEditorTopComponent.findInstance().drawAutomatonBasicVisualizationServer(BububuEditor.this,
                        visualizationViewer, "Please select two states to be merged together.");
            }
        });

        try {
            // Sleep on this.
            this.wait();
        } catch (InterruptedException e) {
            return null;
        }
    }

    /* AutoEditorTopComponent wakes us up. Get the result and return it.
     * VisualizationViewer should give us the information about picked vertices.
     */
    final Set<State<T>> pickedSet = visualizationViewer.getPickedVertexState().getPicked();
    List<State<T>> lst = new ArrayList<State<T>>(pickedSet);
    return lst;
}

From source file:org.apache.pig.impl.builtin.ShellBagEvalFunc.java

private void startProcess() throws IOException {
    Process p = Runtime.getRuntime().exec(cmd);
    is = p.getInputStream();/* w  ww  . j  a  va 2  s .c om*/
    os = p.getOutputStream();
    es = p.getErrorStream();

    new Thread() {
        @Override
        public void run() {
            byte b[] = new byte[256];
            int rc;
            try {
                while ((rc = es.read(b)) > 0) {
                    System.err.write(b, 0, rc);
                }
            } catch (Exception e) {
                log.error(e);
            }
        }
    }.start();

    processThread = new Thread() {
        @Override
        public void run() {
            while (true) {
                DataBag bag;
                try {
                    bag = bags.take();
                } catch (InterruptedException e) {
                    continue;
                }
                if (bag instanceof EndOfQueue)
                    break;
                try {
                    readBag(bag);
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
    };

    processThread.start();
}

From source file:hu.tvdr.serialport.serialport.java

public void SerialPortCall(File device, int baudrate, int flags) throws SecurityException, IOException {

    /* Check access permission */
    if (!device.canRead() || !device.canWrite()) {
        try {/*w  ww  . j av  a  2 s.  c  o  m*/
            /* Missing read/write permission, trying to chmod the file */
            Process su;
            su = Runtime.getRuntime().exec("/system/bin/su");
            String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
            su.getOutputStream().write(cmd.getBytes());
            if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
                throw new SecurityException();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new SecurityException();
        }
    }

    mFd = open(device.getAbsolutePath(), baudrate, flags);
    if (mFd == null) {
        Log.e(TAG, "native open returns null");
        throw new IOException();
    }
    mFileInputStream = new FileInputStream(mFd);
    mFileOutputStream = new FileOutputStream(mFd);
}

From source file:uk.ac.kcl.tika.parsers.PDFPreprocessorParser.java

private File makeTiffFromPDF(File input, File output, ImageMagickConfig config)
        throws IOException, TikaException {
    String[] cmd = { config.getImageMagickPath() + getImageMagickProg(), "-density", config.getDensity(),
            input.getPath(), "-depth", config.getDepth(), "-quality", config.getQuality(), output.getPath() };

    ProcessBuilder pb = new ProcessBuilder(cmd);
    //setEnv(config, pb);
    final Process process = pb.start();

    process.getOutputStream().close();
    InputStream out = process.getInputStream();
    InputStream err = process.getErrorStream();

    logStream("IMAGEMAGICK MSG", out, input);
    logStream("IMAGEMAGICK ERROR", err, input);

    FutureTask<Integer> waitTask = new FutureTask<Integer>(new Callable<Integer>() {
        public Integer call() throws Exception {
            return process.waitFor();
        }//from w  w  w .  ja  v  a 2 s.c om
    });

    Thread waitThread = new Thread(waitTask);
    waitThread.start();

    try {
        waitTask.get(config.getTimeout(), TimeUnit.SECONDS);
        return output;
    } catch (InterruptedException e) {
        waitThread.interrupt();
        process.destroy();
        Thread.currentThread().interrupt();
        throw new TikaException("ImageMagickOCRPDFParser interrupted", e);

    } catch (ExecutionException e) {
        // should not be thrown

    } catch (TimeoutException e) {
        waitThread.interrupt();
        process.destroy();
        throw new TikaException("ImageMagickOCRPDFParser timeout", e);
    }
    return null;
}

From source file:org.xlcloud.xsa.ext.hpc.service.process.ProcessExecutor.java

/**
 * Runs the specified command, and then writes lines from inputLines one by
 * one to the process input stream. Returns whole process output and its exit code.
 * //from  w w w .  j av a 2 s  . c  om
 * @param command
 * @param inputLines
 * @return
 * @throws InternalErrorException when there was an IOException or InterruptedException
 */
public ProcessExecutionResult run(List<String> command, List<String> inputLines) throws InternalErrorException {
    try {
        // run the command
        ProcessBuilder processBuilder = new ProcessBuilder(command).redirectErrorStream(true);
        Process process = processBuilder.start();

        // input all given lines
        if (!inputLines.isEmpty()) {
            BufferedWriter writer = new BufferedWriter(new PrintWriter(process.getOutputStream()));
            for (String inputLine : inputLines) {
                writer.write(inputLine);
                writer.newLine();
            }
            writer.close();
        }

        // read the whole output
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        // We avoid using readLine(), because we want to have a raw output (readLine() skips end-of-line chars).
        char[] buffer = new char[1024];
        int numRead;
        while ((numRead = reader.read(buffer)) != -1) {
            output.append(buffer, 0, numRead);
        }
        reader.close();

        ProcessExecutionResult result = new ProcessExecutionResult();
        result.setExitCode(process.waitFor());
        result.setOutput(output.toString());
        return result;
    } catch (IOException | InterruptedException e) {
        LOG.error(e.getMessage(), e);
        throw new InternalErrorException(
                "An error occurred when executing command: " + StringUtils.join(command, " "), e.getMessage());
    }
}

From source file:cz.cuni.mff.ksi.jinfer.autoeditor.automatonvisualizer.layouts.graphviz.GraphvizLayoutFactory.java

@SuppressWarnings("PMD")
private <T> Map<State<T>, Point2D> getGraphvizPositions(final byte[] graphInDotFormat,
        final Set<State<T>> automatonStates) throws GraphvizException, IOException {
    final Map<State<T>, Point2D> result = new HashMap<State<T>, Point2D>();

    // creates new dot process.
    final ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(GraphvizUtils.getPath(), "-Tplain"));
    final Process process = processBuilder.start();

    // write our graph into dot binary standart input
    process.getOutputStream().write(graphInDotFormat);
    process.getOutputStream().flush();//from   w  w  w.java  2 s . co  m

    // read from dot binary standard output
    final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    process.getOutputStream().close();

    final Scanner scanner = new Scanner(reader);
    // jumps some unnecessary information from output
    scanner.next();
    scanner.next();

    // get width and height of graph
    windowWidth = 100 + (int) Double.parseDouble(scanner.next());
    windowHeight = 100 + (int) Double.parseDouble(scanner.next());

    // parse output for graph vertex positions
    while (scanner.hasNext()) {
        final String n = scanner.next();
        if (n.equals("node")) {
            final int nodeName = Integer.parseInt(scanner.next());
            final double x = Double.parseDouble(scanner.next());
            final double y = Double.parseDouble(scanner.next());
            boolean found = false;
            for (State<T> state : automatonStates) {
                if (state.getName() == nodeName) {
                    result.put(state, new Point(50 + (int) (x), 50 + (int) (y)));
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new GraphvizException("Node with name " + nodeName + " was not found in automaton.");
            }
        }
    }

    return result;
}