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:org.buildboost.hudson.plugins.boostscm.BuildBoostSCM.java

private void closeStreams(Process process) {
    if (process == null) {
        return;/*from  w w w .  j a  va2 s. c om*/
    }
    closeStream(process.getInputStream());
    closeStream(process.getOutputStream());
    closeStream(process.getErrorStream());
}

From source file:org.kalypso.optimize.SceJob.java

private void startSCEOptimization(final SceIOHandler sceIO, final ISimulationMonitor monitor)
        throws SimulationException {
    InputStreamReader inStream = null;
    InputStreamReader errStream = null;

    // FIXME: too much copy/paste from ProcessHelper; we can probably use process helper instead!
    ProcessControlThread procCtrlThread = null;
    try {//from w w  w  .  j  av  a 2 s . c om
        final String[] commands = new String[] { m_sceExe.getAbsolutePath() };

        final Process process = Runtime.getRuntime().exec(commands, null, m_sceDir);
        final long lTimeOut = 1000l * 60l * 15l;// 15 minutes
        procCtrlThread = new ProcessControlThread(process, lTimeOut);
        procCtrlThread.start();

        final StringBuffer outBuffer = new StringBuffer();
        final StringBuffer errBuffer = new StringBuffer();

        final Writer inputWriter = new PrintWriter(process.getOutputStream(), false);

        inStream = new InputStreamReader(process.getInputStream());
        errStream = new InputStreamReader(process.getErrorStream());

        final int stepMax = m_autoCalibration.getOptParameter().getMaxN();

        while (true) {
            final int step = sceIO.getStep();
            monitor.setProgress(100 * step / (stepMax + 1));
            if (step > stepMax) {
                final String monitorMsg = String.format(
                        "Optimierungsrechnung abgeschlossen, Ergebnisauswertung", step + 1, stepMax + 1);
                monitor.setMessage(monitorMsg);
            } else {
                final String monitorMsg = String.format("Optimierungsrechnung %d von %d", step + 1,
                        stepMax + 1);
                monitor.setMessage(monitorMsg);
            }

            if (inStream.ready()) {
                final char buffer[] = new char[100];
                final int bufferC = inStream.read(buffer);
                outBuffer.append(buffer, 0, bufferC);
            }
            if (errStream.ready()) {
                final char buffer[] = new char[100];
                final int bufferC = errStream.read(buffer);
                errBuffer.append(buffer, 0, bufferC);
            }
            if (monitor.isCanceled()) {
                process.destroy();
                procCtrlThread.endProcessControl();
                return;
            }
            try {
                process.exitValue();
                break;
            } catch (final IllegalThreadStateException e) {
                final OptimizeMonitor subMonitor = new OptimizeMonitor(monitor);
                sceIO.handleStreams(outBuffer, errBuffer, inputWriter, subMonitor);
            }
            Thread.sleep(100);
        }

        procCtrlThread.endProcessControl();
    } catch (final IOException e) {
        e.printStackTrace();
        throw new SimulationException("Fehler beim Ausfuehren", e);
    } catch (final InterruptedException e) {
        e.printStackTrace();
        throw new SimulationException("beim Ausfuehren unterbrochen", e);
    } finally {
        IOUtils.closeQuietly(inStream);
        IOUtils.closeQuietly(errStream);
        if (procCtrlThread != null && procCtrlThread.procDestroyed()) {
            throw new SimulationException("beim Ausfuehren unterbrochen",
                    new ProcessTimeoutException("Timeout bei der Abarbeitung der Optimierung"));
        }
    }
}

From source file:com.dreamlinx.automation.DINRelay.java

/**
 * This method runs the provided command in the current runtime environment
 * within the instance of this virtual machine.
 *
 * @param commandWithArgs Command and arguments.
 * @return Process/*from w ww  .ja v  a  2  s.  c om*/
 * @throws IOException
 */
private void runCommand(String[] commandWithArgs) throws IOException {
    Process p = Runtime.getRuntime().exec(commandWithArgs);
    try {
        // read and close all streams to prevent open handles
        InputStream i = p.getInputStream();
        while (i.available() > 0) {
            i.read();
        }
        i.close();
        i = p.getErrorStream();
        while (i.available() > 0) {
            i.read();
        }
        i.close();
        p.getOutputStream().close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sf.mavenjython.test.PythonTestMojo.java

public void execute() throws MojoExecutionException {
    // all we have to do is to run nose on the source directory
    List<String> l = new ArrayList<String>();
    if (program.equals("nose")) {
        l.add("nosetests.bat");
        l.add("--failure-detail");
        l.add("--verbose");
    } else {//from w  ww .  j a va  2  s.  com
        l.add(program);
    }

    ProcessBuilder pb = new ProcessBuilder(l);
    pb.directory(testOutputDirectory);
    pb.environment().put("JYTHONPATH", ".;" + outputDirectory.getAbsolutePath());
    final Process p;
    getLog().info("starting python tests");
    getLog().info("executing " + pb.command());
    getLog().info("in directory " + testOutputDirectory);
    getLog().info("and also including " + outputDirectory);
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException(
                "Python tests execution failed. Provide the executable '" + program + "' in the path", e);
    }
    copyIO(p.getInputStream(), System.out);
    copyIO(p.getErrorStream(), System.err);
    copyIO(System.in, p.getOutputStream());
    try {
        if (p.waitFor() != 0) {
            throw new MojoExecutionException("Python tests failed with return code: " + p.exitValue());
        } else {
            getLog().info("Python tests (" + program + ") succeeded.");
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }
}

From source file:net.firejack.platform.generate.service.ResourceGeneratorService.java

@ProgressStatus(weight = 2, description = "Copy jars")
public void copyJar(IPackageDescriptor descriptor, InputStream stream, final Structure structure)
        throws Exception {
    ResourceElement[] resources = descriptor.getResources();
    IDomainElement[] domains = descriptor.getConfiguredDomains();

    if (domains == null)
        return;/*from w w  w . j a  v  a  2s  .  c  o  m*/

    final Map<String, String> schemas = new HashMap<String, String>();
    for (IDomainElement domain : domains) {
        if (StringUtils.isNotBlank(domain.getWsdlLocation())) {
            Process exec = Runtime.getRuntime()
                    .exec(new String[] { "wsimport", "-d", structure.getSrc().getPath(), "-p",
                            "wsdl." + StringUtils.normalize(domain.getName()), "-Xnocompile", "-target", "2.1",
                            "-extension", domain.getWsdlLocation() });
            exec.getInputStream().close();
            exec.getErrorStream().close();
            exec.getOutputStream().close();
            exec.waitFor();
        }
    }

    for (ResourceElement resource : resources) {
        if (resource.getName().equals(ReverseEngineeringService.WSDL_SCHEME)) {
            List<FileResourceVersionElement> fileResourceVersionElements = resource
                    .getFileResourceVersionElements();
            FileResourceVersionElement versionElement = fileResourceVersionElements.get(0);
            schemas.put(versionElement.getResourceFilename(), versionElement.getOriginalFilename());
        }
    }

    ArchiveUtils.unzip(stream, new ArchiveUtils.ArchiveCallback() {
        @Override
        public void callback(String dir, String name, InputStream stream) {
            String schemaName = schemas.get(name);
            File file = null;
            if (schemaName != null) {
                file = FileUtils.create(structure.getResource(), "wsdl", schemaName);
            }

            if (file != null) {
                try {
                    FileOutputStream outputStream = FileUtils.openOutputStream(file);
                    IOUtils.copy(stream, outputStream);
                    IOUtils.closeQuietly(outputStream);
                } catch (IOException e) {
                    logger.error(e, e);
                }
            }
        }
    });
}

From source file:org.springframework.integration.gemfire.fork.ForkUtil.java

public static OutputStream cloneJVM(String argument) {
    String cp = System.getProperty("java.class.path");
    String home = System.getProperty("java.home");

    Process proc = null;
    String java = home + "/bin/java".replace("\\", "/");

    String argClass = argument;/*  w  ww.  java2s  .co  m*/

    String[] cmdArray = { java, "-cp", cp, argClass };
    try {
        // ProcessBuilder builder = new ProcessBuilder(cmd, argCp,
        // argClass);
        // builder.redirectErrorStream(true);
        proc = Runtime.getRuntime().exec(cmdArray);
    } catch (IOException ioe) {
        throw new IllegalStateException("Cannot start command " + cmdArray, ioe);
    }

    logger.info("Started fork");
    final Process p = proc;

    final BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    final BufferedReader ebr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    final AtomicBoolean run = new AtomicBoolean(true);

    Thread reader = copyStdXxx(br, run, System.out);
    Thread errReader = copyStdXxx(ebr, run, System.err);

    reader.start();
    errReader.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            logger.info("Stopping fork...");
            run.set(false);
            if (p != null) {
                p.destroy();
            }

            try {
                p.waitFor();
            } catch (InterruptedException e) {
                // ignore
            }
            logger.info("Fork stopped");
        }
    });

    return proc.getOutputStream();
}

From source file:egovframework.com.utl.sys.fsm.service.FileSystemUtils.java

/**
 * Performs the os command./*from w w  w.  jav a  2 s  . c  o m*/
 *
 * @param cmdAttribs  the command line parameters
 * @param max The maximum limit for the lines returned
 * @return the parsed data
 * @throws IOException if an error occurs
 */
List performCommand(String[] cmdAttribs, int max) throws IOException {
    // this method does what it can to avoid the 'Too many open files' error
    // based on trial and error and these links:
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027
    // http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018
    // however, its still not perfect as the JDK support is so poor
    // (see commond-exec or ant for a better multi-threaded multi-os solution)

    List lines = new ArrayList(20);
    Process proc = null;
    InputStream in = null;
    OutputStream out = null;
    InputStream err = null;
    BufferedReader inr = null;
    try {
        proc = openProcess(cmdAttribs);
        in = proc.getInputStream();
        out = proc.getOutputStream();
        err = proc.getErrorStream();
        inr = new BufferedReader(new InputStreamReader(in));
        String line = inr.readLine();
        while (line != null && lines.size() < max) {
            line = line.toLowerCase().trim();
            lines.add(line);
            line = inr.readLine();
        }

        proc.waitFor();
        if (proc.exitValue() != 0) {
            // os command problem, throw exception
            throw new IOException("Command line returned OS error code '" + proc.exitValue() + "' for command "
                    + Arrays.asList(cmdAttribs));
        }
        if (lines.size() == 0) {
            // unknown problem, throw exception
            throw new IOException(
                    "Command line did not return any info " + "for command " + Arrays.asList(cmdAttribs));
        }
        return lines;

    } catch (InterruptedException ex) {
        throw new IOException("Command line threw an InterruptedException '" + ex.getMessage()
                + "' for command " + Arrays.asList(cmdAttribs));
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(err);
        IOUtils.closeQuietly(inr);
        if (proc != null) {
            proc.destroy();
        }
    }
}

From source file:org.scantegrity.scanner.ScannerController.java

private void closeProcess(Process p_process) {
    try {//from   w  ww. j a v  a  2 s .  c o  m
        if (p_process != null) {
            p_process.getErrorStream().close();
            p_process.getInputStream().close();
            p_process.getOutputStream().close();
        }
    } catch (Exception e) {
        //do nothing
    }
}

From source file:com.almunt.jgcaap.systemupdater.MainActivity.java

public String getOS() {
    String outputString = "";
    try {//from   w  w w  . ja va2  s.  c  om
        Process su = Runtime.getRuntime().exec("sh");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
        InputStream inputStream = su.getInputStream();
        outputStream.writeBytes("getprop ro.cm.version" + "\nprint alemun@romania\n");
        outputStream.flush();
        outputString = "";
        while (outputString.endsWith("alemun@romania\n") == false) {
            if (inputStream.available() > 0) {
                byte[] dstInput = new byte[inputStream.available()];
                inputStream.read(dstInput);
                String additionalString = new String(dstInput);
                outputString += additionalString;
            }
        }
        outputString = "Current ROM: " + outputString.substring(0, outputString.length() - 15);
        su.destroy();
    } catch (IOException e) {
        currentRomcardView.setVisibility(CardView.GONE);
    }
    if (outputString.replaceAll("jgcaap", "").length() < outputString.length())
        while (outputString.endsWith("bacon") == false)
            outputString = outputString.substring(0, outputString.length() - 1);
    else
        currentRomcardView.setVisibility(CardView.GONE);
    return outputString;
}

From source file:com.almunt.jgcaap.systemupdater.MainActivity.java

public void FlashFile(final String filename) {
    final boolean[] mayBeContinued = { true };
    AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
    builder1.setTitle("Flashing Confirmation");
    builder1.setMessage(/*from   ww  w.  ja v a  2  s  . co  m*/
            "Are You sure you want to flash this file?\nIt will be added to the OpenRecoveryScript file and TWRP will automatically flash it without a warning!");
    builder1.setCancelable(true);
    builder1.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            try {
                Process su = Runtime.getRuntime().exec("su");
                DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
                outputStream.writeBytes("cd /cache/recovery/\n");
                outputStream.flush();
                outputStream.writeBytes("rm openrecoveryscript\n");
                outputStream.flush();
                outputStream.writeBytes("echo install " + Environment.getExternalStorageDirectory()
                        + "/JgcaapUpdates/" + filename + ">openrecoveryscript\n");
                outputStream.flush();
                outputStream.writeBytes("exit\n");
                outputStream.flush();
                su.waitFor();
            } catch (IOException e) {
                Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show();
                mayBeContinued[0] = false;
            } catch (InterruptedException e) {
                Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show();
                mayBeContinued[0] = false;
            }
            if (mayBeContinued[0]) {
                RebootRecovery(true);
            }
        }
    });
    builder1.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        }
    });
    AlertDialog alert11 = builder1.create();
    alert11.show();
}