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:de.phoenix.submission.SubmissionCompilerAndTest.java

@Override
public PhoenixSubmissionResult controlSubmission(TaskSubmission submission) {

    SubmissionTask task = new SubmissionTask();

    File dir = PhoenixApplication.submissionPipelineDir;
    List<String> commands = getCommands();

    // Check, if all necessary classes are submitted
    Set<String> classes = new HashSet<String>();
    for (Text text : submission.getTask().getTexts()) {
        classes.add(text.getTitle());/*from   w ww  .j  a v a 2s  . c om*/
    }

    for (Text clazz : submission.getTexts()) {
        task.addClass(clazz.convert());
        classes.remove(clazz.getTitle());
    }

    // Some to implement classes are missing -> error
    if (!classes.isEmpty()) {
        return new PhoenixSubmissionResult(SubmissionStatus.MISSING_FILES,
                "Missing classes to implement/submit. Maybe you wrote the name of the class wrong? Missing Classes:\r\n"
                        + classes.toString());
    }

    if (submission.getTask().isAutomaticTest()) {
        for (TaskTest test : submission.getTask().getTaskTests()) {
            addTest(task, test);
        }
    }

    // TODO: Add libraries
    ProcessBuilder builder = new ProcessBuilder(commands);
    builder.directory(dir);

    File errorLog = new File(dir, "error.log");
    errorLog.delete();
    builder.redirectError(errorLog);

    try {
        Process process = builder.start();
        JSON_MAPPER.writeValue(process.getOutputStream(), task);
        process.getOutputStream().close();

        PhoenixSubmissionResult result = JSON_MAPPER.readValue(process.getInputStream(),
                PhoenixSubmissionResult.class);

        return result;
    } catch (Exception e) {
        DebugLog.log(e);
    }

    return new PhoenixSubmissionResult(SubmissionStatus.OK, "Fine");
}

From source file:org.globusonline.transfer.DelegateProxyActivation.java

/**
 * Create a proxy certificate using the provided public key and signed
 * by the provided credential./*w  w w . j ava2s. co  m*/
 *
 * Appends the certificate chain to proxy certificate, and returns as PEM.
 * Uses an external program to construct the certificate; see
 *   https://github.com/globusonline/transfer-api-client-python/tree/master/mkproxy
 * @param publicKeyPem  String containing a PEM encoded RSA public key
 * @param credentialPem String containing a PEM encoded credential, with
 *                      certificate, private key, and trust chain.
 * @param hours         Hours the certificate will be valid for.
 */
public String createProxyCertificate(String publicKeyPem, String credentialPem, int hours)
        throws IOException, InterruptedException {
    Process p = new ProcessBuilder(mkproxyPath, "" + hours).start();

    DataOutputStream out = new DataOutputStream(p.getOutputStream());
    out.writeBytes(publicKeyPem);
    out.writeBytes(credentialPem);
    out.close();

    p.waitFor();

    if (p.exitValue() != 0) {
        InputStreamReader in = new InputStreamReader(p.getErrorStream());
        String err = readEntireStream(in);
        throw new IOException("Returned with code " + p.exitValue() + ": " + err);
    }

    InputStreamReader in = new InputStreamReader(p.getInputStream());
    String certChain = readEntireStream(in);
    return certChain;
}

From source file:es.ua.dlsi.patch.translation.LocalApertiumTranslator.java

public Map<String, Set<String>> getTranslation(final Set<String> inputset) {
    Map<String, Set<String>> dictionary = new HashMap<>();
    if (!inputset.isEmpty()) {
        try {//from w  w w.  j av a  2s  .c  o m
            StringBuilder sb = new StringBuilder();
            List<String> input = new LinkedList<>(inputset);
            for (String s : input) {
                sb.append("<p>");
                sb.append(s);
                sb.append("</p>");
            }

            //String[] command = {"apertium", "-u", "-f html", langCmd};

            ProcessBuilder probuilder = new ProcessBuilder("apertium", "-u", "-fhtml", langCmd);

            Process process = probuilder.start();
            OutputStream stdin = process.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
            writer.write(sb.toString());
            writer.flush();
            writer.close();

            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuilder finalline = new StringBuilder();

            while ((line = br.readLine()) != null) {
                finalline.append(line);
            }
            br.close();
            String finaltranslation = StringEscapeUtils
                    .unescapeHtml3(finalline.toString().replaceAll("\\s<", "<").replaceAll(">\\s", ">")
                            .replaceAll("^<p>", "").replace("</p>", ""));
            List<String> translations = new LinkedList<>(Arrays.asList(finaltranslation.split("<p>")));
            for (int i = 0; i < translations.size(); i++) {
                if (dictionary.containsKey(input.get(i))) {
                    dictionary.get(input.get(i)).add(translations.get(i));
                } else {
                    Set<String> trans_set = new HashSet<>();
                    trans_set.add(translations.get(i));
                    dictionary.put(input.get(i), trans_set);
                }
            }

        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }
    return dictionary;
}

From source file:logicProteinHypernetwork.analysis.complexes.offline.ComplexPredictionCommand.java

/**
 * Returns predicted complexes for a given undirected graph of proteins.
 *
 * @param g the graph//from  w  w  w .  ja  v a  2 s .co  m
 * @return the predicted complexes
 */
public Collection<Complex> transform(UndirectedGraph<Protein, Interaction> g) {
    try {
        Process p = Runtime.getRuntime().exec(command);
        BufferedOutputStream outputStream = new BufferedOutputStream(p.getOutputStream());
        BufferedInputStream inputStream = new BufferedInputStream(p.getInputStream());

        for (Interaction i : g.getEdges()) {
            String out = i.first() + " pp " + i.second();
            outputStream.write(out.getBytes());
        }
        outputStream.close();
        p.waitFor();

        if (!hypernetwork.getProteins().hasIndex()) {
            hypernetwork.getProteins().buildIndex();
        }

        Collection<Complex> complexes = new ArrayList<Complex>();
        Scanner s = new Scanner(inputStream);
        Pattern rowPattern = Pattern.compile(".*?\\n");
        Pattern proteinPattern = Pattern.compile(".*?\\s");
        while (s.hasNext(rowPattern)) {
            Complex c = new Complex();
            while (s.hasNext(proteinPattern)) {
                c.add(hypernetwork.getProteins().getProteinById(s.next(proteinPattern).trim()));
            }
            complexes.add(c);
        }
        inputStream.close();

        return complexes;

    } catch (InterruptedException ex) {
        Logger.getLogger(ComplexPredictionCommand.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ComplexPredictionCommand.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.casbah.provider.openssl.OpenSslWrapper.java

public int executeCommand(InputStream input, OutputStream output, OutputStream error,
        final List<String> parameters) throws IOException, InterruptedException {
    List<String> fullParams = new ArrayList<String>(parameters);
    fullParams.add(0, opensslExecutable);
    ProcessBuilder processBuilder = new ProcessBuilder(fullParams);
    CyclicBarrier barrier = new CyclicBarrier(3);
    Map<String, String> env = processBuilder.environment();
    env.put(CASBAH_SSL_CA_ROOT, caRootDir.getAbsolutePath());
    Process proc = processBuilder.start();
    if (input != null) {
        BufferedOutputStream stdin = new BufferedOutputStream(proc.getOutputStream());
        IOUtils.copy(input, stdin);//from w  ww . j  av a 2  s  .  c  o  m
        stdin.flush();
    }
    StreamConsumer outputConsumer = new StreamConsumer(output, proc.getInputStream(), barrier, TIMEOUT);
    StreamConsumer errorConsumer = new StreamConsumer(error, proc.getErrorStream(), barrier, TIMEOUT);
    outputConsumer.start();
    errorConsumer.start();
    int returnValue = proc.waitFor();
    try {
        barrier.await(TIMEOUT, TimeUnit.SECONDS);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return returnValue;
}

From source file:org.kontalk.xmppserver.pgp.GnuPGInterface.java

private int invoke(byte[] standardInput, OutputStream output, String... args) throws IOException {
    try {//from  w  w  w .  ja va  2s  . co  m
        String[] procArgs = new String[args.length + 1];
        procArgs[0] = GPG_EXEC;
        System.arraycopy(args, 0, procArgs, 1, args.length);
        Process p = new ProcessBuilder(procArgs).start();
        if (standardInput != null) {
            p.getOutputStream().write(standardInput);
            p.getOutputStream().close();
        }
        if (output != null)
            IOUtils.copy(p.getInputStream(), output);

        return p.waitFor();
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:com.lithium.flow.vault.AgentVault.java

private void startAgent(@Nonnull String password) {
    try {/*from   w  ww.jav  a  2 s . co m*/
        int port = findFreePort();
        String agentPassword = Vaults.securePassword();

        Map<String, String> map = new HashMap<>();
        Store agentStore = new MemoryStore(map);
        Vault agentVault = new SecureVault(Configs.empty(), agentStore);
        agentVault.setup(agentPassword);
        agentVault.putValue("password", password);

        ProcessBuilder builder = new ProcessBuilder();
        builder.command(System.getProperty("java.home") + "/bin/java", "-Dagent.port=" + port,
                AgentServer.class.getName());
        builder.environment().put("CLASSPATH", System.getProperty("java.class.path"));
        Process process = builder.start();

        OutputStream out = process.getOutputStream();
        mapper.writeValue(out, map);
        out.close();

        store.putValue("vault.agent.port", String.valueOf(port));
        store.putValue("vault.agent.password", agentPassword);
    } catch (IOException e) {
        throw new VaultException("failed to start agent", e);
    }
}

From source file:org.globus.workspace.accounting.impls.dbdefault.DelayedAccountingFileLogger.java

private static boolean setFilePermissions(String file, int mode) {

    final Runtime runtime = Runtime.getRuntime();
    final String[] cmd = new String[] { "chmod", String.valueOf(mode), file };
    Process process = null;
    try {//from ww  w  .j  a va 2 s.c om
        process = runtime.exec(cmd, null);
        return process.waitFor() == 0 ? true : false;
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
        } else {
            logger.error(e.getMessage());
        }
        return false;
    } finally {
        if (process != null) {
            try {
                process.getErrorStream().close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
            try {
                process.getInputStream().close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
            try {
                process.getOutputStream().close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

From source file:de.rinderle.softvis3d.layout.dot.ExecuteCommand.java

private void writeStringToOutput(final String inputGraph, final Process process) throws IOException {
    final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
    out.write(inputGraph);/*w ww. j  a  v a  2s.  co  m*/
    out.close();
}

From source file:com.apress.prospringintegration.customadapters.outbound.ShellMessageWritingMessageEndpoint.java

protected int writeToShellCommand(String[] cmds, String msg) {
    try {/*  ww w .j  ava 2  s  .c  o  m*/
        ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(cmds));
        Process proc = processBuilder.start();

        Writer streamWriter = null;

        try {
            streamWriter = new OutputStreamWriter(proc.getOutputStream());
            streamWriter.write(msg);
        } finally {
            IOUtils.closeQuietly(streamWriter);
        }

        int retVal = proc.waitFor();

        if (retVal != 0) {
            throw new RuntimeException("couldn't write message to 'write'");
        }

        return retVal;
    } catch (Throwable th) {
        throw new RuntimeException(th);
    }
}