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.cesecore.time.providers.NtpClientParser.java

/**
 * Executes a call to an NTP client and parses the output in order to obtain the offset of the selected trusted time source.
 * // w w w .ja v  a  2  s. co  m
 * @return Double containing the offset of the current selected trusted time source
 */
public TrustedTime getTrustedTime() {

    Process proc = null;
    TrustedTime trustedTime = null;
    try {
        Runtime runtime = Runtime.getRuntime();
        proc = runtime.exec(this.ntpClientCommand);

        @SuppressWarnings("unchecked")
        List<String> lines = IOUtils.readLines(proc.getInputStream());

        trustedTime = parseOffset(lines);
    } catch (Exception e) {
        log.error("Error parsing NTP output", e);
        trustedTime = new TrustedTime();
    } finally {
        if (proc != null) {
            IOUtils.closeQuietly(proc.getInputStream());
            IOUtils.closeQuietly(proc.getErrorStream());
            IOUtils.closeQuietly(proc.getOutputStream());
        }
    }

    if (log.isDebugEnabled()) {
        log.debug(trustedTime.toString());
    }

    return trustedTime;
}

From source file:org.trancecode.xproc.step.ExecStepProcessor.java

@Override
protected void execute(final StepInput input, final StepOutput output) throws Exception {
    final String pathSeparator = input.getOptionValue(XProcOptions.PATH_SEPARATOR);
    final String command;
    if (pathSeparator != null) {
        command = input.getOptionValue(XProcOptions.COMMAND).replace(pathSeparator, File.separator);
    } else {//from w w  w  .  j a v a2 s .  c om
        command = input.getOptionValue(XProcOptions.COMMAND);
    }

    final String argSeparator = input.getOptionValue(XProcOptions.ARG_SEPARATOR, " ");
    final Iterable<String> rawArgs = TcStrings.split(input.getOptionValue(XProcOptions.ARGS), argSeparator);
    final Iterable<String> args = Iterables.transform(rawArgs, arg -> {
        if (pathSeparator != null) {
            return arg.replace(pathSeparator, File.separator);
        }

        return arg;
    });
    final String cwd = input.getOptionValue(XProcOptions.CWD);

    final List<XdmNode> inputDocuments = ImmutableList.copyOf(input.readNodes(XProcPorts.SOURCE));
    if (inputDocuments.size() > 1) {
        throw XProcExceptions.xd0006(input.getStep().getLocation(),
                input.getStep().getPortReference(XProcPorts.SOURCE));
    }
    final boolean sourceIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.SOURCE_IS_XML));
    final boolean resultIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.RESULT_IS_XML));
    final boolean wrapResultLines = Boolean.parseBoolean(input.getOptionValue(XProcOptions.WRAP_RESULT_LINES));
    final boolean errorsIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.ERRORS_IS_XML));
    final boolean wrapErrorLines = Boolean.parseBoolean(input.getOptionValue(XProcOptions.WRAP_ERROR_LINES));
    if ((resultIsXml && wrapResultLines) || (errorsIsXml && wrapErrorLines)) {
        throw XProcExceptions.xc0035(input.getStep().getLocation());
    }

    final List<String> commandLine = Lists.newArrayList();
    commandLine.add(command);
    Iterables.addAll(commandLine, Iterables.filter(args, StringPredicates.isNotEmpty()));
    LOG.trace("  commandLine = {}", commandLine);
    final ProcessBuilder processBuilder = new ProcessBuilder(commandLine.toArray(new String[0]));
    processBuilder.redirectErrorStream(false);
    if (cwd != null) {
        final Path newDirectory = Paths.get(cwd);
        if (!Files.isDirectory(newDirectory)) {
            throw XProcExceptions.xc0034(input.getLocation());
        }
        processBuilder.directory(new File(cwd));
    }
    final Process process;
    try {
        process = processBuilder.start();
    } catch (IOException e) {
        throw XProcExceptions.xc0033(input.getLocation());
    }

    if (!inputDocuments.isEmpty()) {
        final String inputContent;
        if (sourceIsXml) {
            inputContent = inputDocuments.get(0).toString();
        } else {
            inputContent = SaxonAxis.childElement(inputDocuments.get(0)).getStringValue();
        }

        new Thread(() -> {
            try {
                IOUtils.write(inputContent, process.getOutputStream());
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            } finally {
                Closeables.closeQuietly(process.getOutputStream());
            }
        }).start();
    }

    final Supplier<File> stdout = TcByteStreams.copyToTempFile(process.getInputStream());
    final Supplier<File> stderr = TcByteStreams.copyToTempFile(process.getErrorStream());

    final int exitCode = process.waitFor();
    LOG.trace("exitCode = {}", exitCode);
    final String failureThreshold = input.getOptionValue(XProcOptions.FAILURE_THRESHOLD);
    if (failureThreshold != null) {
        LOG.trace("failureThreshold  = {}", failureThreshold);
        final int numericFailureThreshold = Integer.parseInt(failureThreshold);
        if (exitCode > numericFailureThreshold) {
            throw XProcExceptions.xc0064(input.getLocation(), exitCode, numericFailureThreshold);
        }
    }

    final File stdoutFile = stdout.get();
    final File stderrFile = stderr.get();
    process.destroy();

    final Processor processor = input.getPipelineContext().getProcessor();
    output.writeNodes(XProcPorts.RESULT,
            parseOutput(stdoutFile, resultIsXml, wrapResultLines, input.getStep().getNode(), processor));
    output.writeNodes(XProcPorts.ERRORS,
            parseOutput(stderrFile, errorsIsXml, wrapErrorLines, input.getStep().getNode(), processor));
    output.writeNodes(XProcPorts.EXIT_STATUS, input.newResultElement(Integer.toString(exitCode)));
}

From source file:org.codelibs.fess.helper.JobHelper.java

protected void destroyCrawlerProcess(final JobProcess jobProcess) {
    if (jobProcess != null) {
        final InputStreamThread ist = jobProcess.getInputStreamThread();
        try {/*  w  w w  .  ja v  a  2s .  c o m*/
            ist.interrupt();
        } catch (final Exception e) {
            logger.warn("Could not interrupt a thread of an input stream.", e);
        }

        final CountDownLatch latch = new CountDownLatch(1);
        final Process process = jobProcess.getProcess();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    IOUtils.closeQuietly(process.getInputStream());
                } catch (final Exception e) {
                    logger.warn("Could not close a process input stream.", e);
                }
                try {
                    IOUtils.closeQuietly(process.getErrorStream());
                } catch (final Exception e) {
                    logger.warn("Could not close a process error stream.", e);
                }
                try {
                    IOUtils.closeQuietly(process.getOutputStream());
                } catch (final Exception e) {
                    logger.warn("Could not close a process output stream.", e);
                }
                latch.countDown();
            }
        }, "ProcessCloser").start();

        try {
            latch.await(10, TimeUnit.SECONDS);
        } catch (final InterruptedException e) {
            logger.warn("Interrupted to wait a process.", e);
        }
        try {
            process.destroy();
        } catch (final Exception e) {
            logger.error("Could not destroy a process correctly.", e);
        }
    }
}

From source file:org.apache.nifi.processors.standard.ExecuteStreamCommand.java

@Override
public void onTrigger(ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile inputFlowFile = session.get();
    if (null == inputFlowFile) {
        return;/*from w  ww  .  jav  a  2  s.c om*/
    }

    final ArrayList<String> args = new ArrayList<>();
    final boolean putToAttribute = context.getProperty(PUT_OUTPUT_IN_ATTRIBUTE).isSet();
    final Integer attributeSize = context.getProperty(PUT_ATTRIBUTE_MAX_LENGTH).asInteger();
    final String attributeName = context.getProperty(PUT_OUTPUT_IN_ATTRIBUTE).getValue();

    final String executeCommand = context.getProperty(EXECUTION_COMMAND)
            .evaluateAttributeExpressions(inputFlowFile).getValue();
    args.add(executeCommand);
    final String commandArguments = context.getProperty(EXECUTION_ARGUMENTS)
            .evaluateAttributeExpressions(inputFlowFile).getValue();
    final boolean ignoreStdin = Boolean.parseBoolean(context.getProperty(IGNORE_STDIN).getValue());
    if (!StringUtils.isBlank(commandArguments)) {
        for (String arg : ArgumentUtils.splitArgs(commandArguments,
                context.getProperty(ARG_DELIMITER).getValue().charAt(0))) {
            args.add(arg);
        }
    }
    final String workingDir = context.getProperty(WORKING_DIR).evaluateAttributeExpressions(inputFlowFile)
            .getValue();

    final ProcessBuilder builder = new ProcessBuilder();

    logger.debug("Executing and waiting for command {} with arguments {}",
            new Object[] { executeCommand, commandArguments });
    File dir = null;
    if (!StringUtils.isBlank(workingDir)) {
        dir = new File(workingDir);
        if (!dir.exists() && !dir.mkdirs()) {
            logger.warn("Failed to create working directory {}, using current working directory {}",
                    new Object[] { workingDir, System.getProperty("user.dir") });
        }
    }
    final Map<String, String> environment = new HashMap<>();
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        if (entry.getKey().isDynamic()) {
            environment.put(entry.getKey().getName(), entry.getValue());
        }
    }
    builder.environment().putAll(environment);
    builder.command(args);
    builder.directory(dir);
    builder.redirectInput(Redirect.PIPE);
    builder.redirectOutput(Redirect.PIPE);
    final Process process;
    try {
        process = builder.start();
    } catch (IOException e) {
        logger.error("Could not create external process to run command", e);
        throw new ProcessException(e);
    }
    try (final OutputStream pos = process.getOutputStream();
            final InputStream pis = process.getInputStream();
            final InputStream pes = process.getErrorStream();
            final BufferedInputStream bis = new BufferedInputStream(pis);
            final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pes))) {
        int exitCode = -1;
        final BufferedOutputStream bos = new BufferedOutputStream(pos);
        FlowFile outputFlowFile = putToAttribute ? inputFlowFile : session.create(inputFlowFile);

        ProcessStreamWriterCallback callback = new ProcessStreamWriterCallback(ignoreStdin, bos, bis, logger,
                attributeName, session, outputFlowFile, process, putToAttribute, attributeSize);
        session.read(inputFlowFile, callback);

        outputFlowFile = callback.outputFlowFile;
        if (putToAttribute) {
            outputFlowFile = session.putAttribute(outputFlowFile, attributeName,
                    new String(callback.outputBuffer, 0, callback.size));
        }

        exitCode = callback.exitCode;
        logger.debug("Execution complete for command: {}.  Exited with code: {}",
                new Object[] { executeCommand, exitCode });

        Map<String, String> attributes = new HashMap<>();

        final StringBuilder strBldr = new StringBuilder();
        try {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                strBldr.append(line).append("\n");
            }
        } catch (IOException e) {
            strBldr.append("Unknown...could not read Process's Std Error");
        }
        int length = strBldr.length() > 4000 ? 4000 : strBldr.length();
        attributes.put("execution.error", strBldr.substring(0, length));

        final Relationship outputFlowFileRelationship = putToAttribute ? ORIGINAL_RELATIONSHIP
                : OUTPUT_STREAM_RELATIONSHIP;
        if (exitCode == 0) {
            logger.info("Transferring flow file {} to {}",
                    new Object[] { outputFlowFile, outputFlowFileRelationship.getName() });
        } else {
            logger.error("Transferring flow file {} to {}. Executable command {} ended in an error: {}",
                    new Object[] { outputFlowFile, outputFlowFileRelationship.getName(), executeCommand,
                            strBldr.toString() });
        }

        attributes.put("execution.status", Integer.toString(exitCode));
        attributes.put("execution.command", executeCommand);
        attributes.put("execution.command.args", commandArguments);
        outputFlowFile = session.putAllAttributes(outputFlowFile, attributes);

        // This transfer will transfer the FlowFile that received the stream out put to it's destined relationship.
        // In the event the stream is put to the an attribute of the original, it will be transferred here.
        session.transfer(outputFlowFile, outputFlowFileRelationship);

        if (!putToAttribute) {
            logger.info("Transferring flow file {} to original", new Object[] { inputFlowFile });
            inputFlowFile = session.putAllAttributes(inputFlowFile, attributes);
            session.transfer(inputFlowFile, ORIGINAL_RELATIONSHIP);
        }

    } catch (final IOException ex) {
        // could not close Process related streams
        logger.warn("Problem terminating Process {}", new Object[] { process }, ex);
    } finally {
        process.destroy(); // last ditch effort to clean up that process.
    }
}

From source file:com.chummy.jezebel.material.dark.activities.Main.java

public void RunAsRoot(String[] cmds) {
    try {//from   w w  w. j  ava  2  s  .co m
        Process p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        for (String tmpCmd : cmds) {
            os.writeBytes(tmpCmd + "\n");
        }
        os.writeBytes("exit\n");
        os.flush();
    } catch (IOException e) {
        e.printStackTrace();
        Toast toast = Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG);
        toast.show();
    }
}

From source file:de.uni_koblenz.jgralab.utilities.tg2dot.Tg2Dot.java

public InputStream convertToGraphVizStream(GraphVizProgram prog) throws IOException {
    String executionString = String.format("%s%s -T%s", prog.path, prog.layouter, prog.outputFormat);
    final Process process = Runtime.getRuntime().exec(executionString);
    InputStream inputStream = new BufferedInputStream(process.getInputStream());
    new Thread() {
        @Override//from www . j  a va2s .c om
        public void run() {
            PrintStream ps = new PrintStream(process.getOutputStream());
            convert(ps);
            ps.flush();
            ps.close();
        };
    }.start();
    return inputStream;
}

From source file:com.adito.community.unix.UNIXUserDatabase.java

public void changePassword(String username, String oldPassword, String password,
        boolean forcePasswordChangeAtLogon) throws UserDatabaseException, InvalidLoginCredentialsException {
    if (!supportsPasswordChange()) {
        throw new InvalidLoginCredentialsException("Database doesn't support password change.");
    }/* w w w.  j av  a  2 s .  co  m*/
    if (forcePasswordChangeAtLogon) {
        LOG.warn(
                "Password change function of UNIX user database does not support forcePassswordChangeAtLogon.");
    }
    Process p = null;
    try {
        p = Runtime.getRuntime()
                .exec("true".equals(SystemProperties.get("adito.useDevConfig", "false"))
                        ? "sudo /usr/sbin/chpasswd"
                        : "/usr/sbin/chpasswd");
        new StreamReaderThread(p.getInputStream());
        new StreamReaderThread(p.getErrorStream());
        OutputStream out = p.getOutputStream();
        PrintWriter pw = new PrintWriter(out);
        pw.println(username + ":" + password);
        pw.flush();
        out.close();
        try {
            p.waitFor();
        } catch (InterruptedException ie) {

        }
        int ret = p.exitValue();
        if (ret != 0) {
            throw new UserDatabaseException(
                    "Failed to change password. chpasswd returned exit code " + ret + ".");
        }

    } catch (IOException e) {
        throw new UserDatabaseException("Failed to change password.", e);
    } finally {
        if (p != null) {
            Util.closeStream(p.getOutputStream());
            Util.closeStream(p.getInputStream());
            Util.closeStream(p.getErrorStream());
        }
    }
}

From source file:ixa.pipe.ned_ukb.Annotate.java

public void disambiguateNEsToKAF(KAFDocument kaf, String scripts, String ukbExec, String ukbKb, String ukbDict,
        String wikiDb) throws Exception {

    String resourceExternalRef = ukbKb.substring(ukbKb.lastIndexOf("/") + 1);

    List<String> neIds = new ArrayList<String>();
    String ukbContext = "naf\n";

    List<Entity> entities = kaf.getEntities();
    for (Entity entity : entities) {
        String entityId = entity.getId();
        String entityLemma = "";
        List<Term> entityTerms = entity.getTerms();
        for (Term term : entityTerms) {
            String tId = term.getId();
            neIds.add(tId);/*from   ww  w .  j  a  v a  2  s .c om*/
            if (!entityLemma.equals("")) {
                entityLemma += "_";
            }
            entityLemma += term.getLemma().toLowerCase();
        }
        ukbContext += entityLemma + "##" + entityId + "#1 ";
    }

    String formsContext2Match = "";
    String lemmasContext2Match = "";

    List<Term> terms = kaf.getTerms();
    for (Term term : terms) {
        if (!neIds.contains(term.getId())) {
            if (!(term.getForm().contains("@@")) && !(term.getForm().contains(" "))) {
                formsContext2Match += term.getForm().toLowerCase() + "@@" + term.getWFs().get(0).getOffset()
                        + " ";
                lemmasContext2Match += term.getLemma().toLowerCase() + "@@" + term.getWFs().get(0).getOffset()
                        + " ";
            }
        }
    }

    // create UKB context
    String[] cmdMatch = { "perl", scripts + "/merge_match.pl", "-d", wikiDb, "--t1", formsContext2Match, "--t2",
            lemmasContext2Match };

    Process pMatch = Runtime.getRuntime().exec(cmdMatch);

    String matchedContext = "";
    String outputLineContext = "";
    BufferedReader outputContextStream = new BufferedReader(
            new InputStreamReader(pMatch.getInputStream(), "UTF-8"));
    while ((outputLineContext = outputContextStream.readLine()) != null) {
        matchedContext += outputLineContext + "\n";
    }
    outputContextStream.close();

    String errorContext = "";
    BufferedReader errorContextStream = new BufferedReader(new InputStreamReader(pMatch.getErrorStream()));
    while ((errorContext = errorContextStream.readLine()) != null) {
        System.err.println("MERGE_MATCH ERROR: " + errorContext);
    }
    errorContextStream.close();

    pMatch.waitFor();

    String[] contextStrings = matchedContext.split(" ");
    for (String contextString : contextStrings) {
        if (contextString.equals(""))
            continue;
        contextString = contextString.trim();

        //ContextString = spot_string@@spot_offset
        String[] contextWordOffset = contextString.split("@@");
        ukbContext += contextWordOffset[0] + "##" + contextWordOffset[1] + "#1 ";
    }

    File contextTmpFile = File.createTempFile("context", ".tmp");
    contextTmpFile.deleteOnExit();
    String contextTmpFileName = contextTmpFile.getAbsolutePath();

    Writer contextFile = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(contextTmpFile), "UTF-8"));
    try {
        contextFile.write(ukbContext);
    } finally {
        contextFile.close();
    }

    // run UKB
    String cmdUkb = ukbExec
            + " --prank_damping 0.90 --prank_iter 15 --allranks --minput --nopos --ppr_w2w --dict_weight -K "
            + ukbKb + " -D " + ukbDict + " " + contextTmpFileName;

    Process pUkb = Runtime.getRuntime().exec(cmdUkb);

    String outputUkb = "";
    String outputLineUkb = "";
    BufferedReader outputUkbStream = new BufferedReader(new InputStreamReader(pUkb.getInputStream(), "UTF-8"));
    while ((outputLineUkb = outputUkbStream.readLine()) != null) {
        outputUkb += outputLineUkb + "\n";
    }
    outputUkbStream.close();

    String errorUkb = "";
    BufferedReader errorUkbStream = new BufferedReader(new InputStreamReader(pUkb.getErrorStream()));
    while ((errorUkb = errorUkbStream.readLine()) != null) {
        System.err.println("UKB ERROR: " + errorUkb);
    }
    errorUkbStream.close();

    pUkb.waitFor();

    // UKB output (one line): context_id word_id (concept_id(/weight)?)+ !! lemma   (there are 2 spaces after word_id)
    // UKB output example:    naf e12  Norvegia/0.999998 Norvegiako_bandera/2.25207e-06 !! norvegia
    Map<String, String> entityLinks = new HashMap<String, String>(); // e12 --> Norvegia/0.999998
    String ukbDisambiguations[] = outputUkb.split("\n");
    for (String ukbDisambiguation : ukbDisambiguations) {
        if (ukbDisambiguation.startsWith("!! -v"))
            continue;
        String ukbLine[] = ukbDisambiguation.split(" ");
        entityLinks.put(ukbLine[1], ukbLine[3]);
    }

    // UKB links to KAF
    for (Entity entity : entities) {
        String entityId = entity.getId();
        if (entityLinks.containsKey(entityId)) {
            String reference = entityLinks.get(entityId).split("/")[0];
            String confidence = entityLinks.get(entityId).split("/")[1];
            String ref2 = reference;
            reference = "http://" + language + ".wikipedia.org/wiki/" + reference;
            ExternalRef externalRef = kaf.newExternalRef(resourceExternalRef, reference);
            externalRef.setConfidence(Float.parseFloat(confidence));
            externalRef.setSource(language);
            externalRef.setReftype(language);
            entity.addExternalRef(externalRef);
            if (cross) {
                String mappingRef = getMappingRef(reference);
                if (mappingRef != null) {
                    ExternalRef enRef = kaf.newExternalRef(this.resourceMapping, mappingRef);
                    enRef.setConfidence(Float.parseFloat(confidence));
                    enRef.setSource(language);
                    enRef.setReftype("en");
                    entity.addExternalRef(enRef);
                }
            }
        } else { // UKB didn't assign any link to this entity. Try with MFS
            String cmdMfs = "perl " + scripts + "/mfs.pl -d " + wikiDb;
            Process pMfs = Runtime.getRuntime().exec(cmdMfs);

            String entityLemma = "";
            List<Term> entityTerms = entity.getTerms();
            for (Term term : entityTerms) {
                if (!entityLemma.equals("")) {
                    entityLemma += "_";
                }
                entityLemma += term.getLemma().toLowerCase();
            }

            OutputStream stdinMfs = pMfs.getOutputStream();
            stdinMfs.write(entityLemma.getBytes());
            stdinMfs.flush();
            stdinMfs.close();

            String outputMfs = "";
            BufferedReader outputMfsStream = new BufferedReader(
                    new InputStreamReader(pMfs.getInputStream(), "UTF-8"));
            outputMfs = outputMfsStream.readLine();
            outputMfsStream.close();

            String errorMfs = "";
            BufferedReader errorMfsStream = new BufferedReader(new InputStreamReader(pMfs.getErrorStream()));
            while ((errorMfs = errorMfsStream.readLine()) != null) {
                System.err.println("MFS ERROR: " + errorMfs);
            }
            errorMfsStream.close();

            pMfs.waitFor();
            if (!outputMfs.equals("NILL")) {
                String reference = outputMfs;
                String confidence = "1";
                reference = "http://" + language + ".wikipedia.org/wiki/" + reference;
                ExternalRef externalRef = kaf.newExternalRef("MFS_" + resourceExternalRef, reference);
                externalRef.setConfidence(Float.parseFloat(confidence));
                externalRef.setSource(language);
                externalRef.setReftype(language);
                entity.addExternalRef(externalRef);
                if (cross) {
                    String mappingRef = getMappingRef(reference);
                    if (mappingRef != null) {
                        ExternalRef enRef = kaf.newExternalRef(this.resourceMapping, mappingRef);
                        enRef.setConfidence(Float.parseFloat(confidence));
                        enRef.setSource(language);
                        enRef.setReftype("en");
                        entity.addExternalRef(enRef);
                    }
                }

            }
        }
    }

}

From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java

private void install(String downloadUrl) {
    Double vNum = 0.0;// w w  w  .ja  v  a2 s  . c  om
    if (appVersion != null) {
        vNum = Double.parseDouble(appVersion);
    }
    String installerPath = getInstallerName(downloadUrl);
    if (os.contains("windows")) {
        try {
            Runtime.getRuntime().exec("msiexec /i \"" + installerPath + "\"");
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (os.startsWith("mac")) {
        try {
            Runtime.getRuntime().exec(new String[] { "/usr/bin/open", installerPath });
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        JLabel pwLabel = new JLabel("Sudo Password");
        JTextField password = new JPasswordField();
        Object[] objs = { pwLabel, password };
        int result = JOptionPane.showConfirmDialog(null, objs, "Please enter a sudo password",
                JOptionPane.OK_CANCEL_OPTION);
        String pas = null;
        if (result == JOptionPane.OK_OPTION) {
            pas = password.getText();
        }

        if (pas != null) {
            if (os.equals("CentOS")) {
                // sudo yum install TCIADownloader-1.0-1.x86_64.rpm
                try {
                    String upgradCmd = "/usr/bin/sudo -S yum -q -y remove TCIADownloader.x86_64;/usr/bin/sudo -S yum -y -q install ";
                    if (vNum >= 3.2)
                        upgradCmd = "/usr/bin/sudo -S yum -q -y remove NBIADataRetriever.x86_64;/usr/bin/sudo -S yum -y -q install ";

                    String[] cmd = { "/bin/bash", "-c", upgradCmd + installerPath };

                    Process pb = Runtime.getRuntime().exec(cmd);
                    BufferedWriter writer = null;
                    writer = new BufferedWriter(new OutputStreamWriter(pb.getOutputStream()));
                    writer.write(pas);
                    writer.write('\n');
                    writer.flush();

                    String status = null;

                    if (pb.waitFor() == 0) {
                        status = "successfully";
                    } else {
                        status = "unsuccessfully";
                    }

                    JOptionPane.showMessageDialog(null,
                            "Installation of new version of NBIA Data Retriever is completed " + status + ".");
                } catch (IOException | InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else if (os.equals("Ubuntu")) {
                // sudo dpkg -i tciadownloader_1.0-2_amd64.deb
                String upgradCmd = "/usr/bin/sudo -S dpkg -i ";
                if (vNum >= 3.2)
                    upgradCmd = "/usr/bin/sudo -S dpkg -i nbia-data-retriever; /usr/bin/sudo -S dpkg -i ";
                try {
                    String[] cmd = { "/bin/bash", "-c", upgradCmd + installerPath };

                    Process pb = Runtime.getRuntime().exec(cmd);
                    BufferedWriter writer = null;
                    writer = new BufferedWriter(new OutputStreamWriter(pb.getOutputStream()));
                    writer.write(pas);
                    writer.write('\n');
                    writer.flush();

                    String status = null;

                    if (pb.waitFor() == 0) {
                        status = "successfully";
                    } else {
                        status = "unsuccessfully";
                    }

                    JOptionPane.showMessageDialog(null,
                            "Installation of new version of NBIA Data Retriever is completed " + status + ".");
                } catch (IOException | InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:com.orange.clara.cloud.servicedbdumper.integrations.AbstractIntegrationTest.java

public void populateDataToDatabaseRefFromFile(File fakeData, DatabaseRef databaseServer)
        throws CannotFindDatabaseDumperException, IOException, InterruptedException {
    this.reportIntegration.setFakeDataFileSize(fakeData.length());
    long currentTime = System.currentTimeMillis();
    logger.info(/* ww w.  java2s .  c om*/
            "Populating fake data on server: {} - database {} will be created with data from file {} which has size of {}",
            databaseServer.getHost(), DATABASE_SOURCE_NAME, fakeData.getAbsolutePath(),
            humanize.Humanize.binaryPrefix(fakeData.length()));
    DatabaseDriver databaseDriver = dbDumpersFactory.getDatabaseDumper(databaseServer);
    String[] restoreCommandLine = databaseDriver.getRestoreCommandLine();
    int i = 1;
    while (true) {
        Process process = this.runCommandLine(restoreCommandLine);
        OutputStream outputStream = process.getOutputStream();
        InputStream dumpFileInputStream = Files.asByteSource(fakeData).openStream();
        try {
            ByteStreams.copy(dumpFileInputStream, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {

        } finally {
            dumpFileInputStream.close();
        }
        process.waitFor();
        if (process.exitValue() == 0) {
            break;
        }
        dumpFileInputStream.close();
        outputStream.close();
        if (i >= populateDataRetry) {
            throw this.generateInterruptedExceptionFromProcess(process);
        }
        logger.warn("Retry {}/{}: fail to populate data.", i, populateDataRetry);
        i++;
    }
    this.reportIntegration.setPopulateToDatabaseTime((System.currentTimeMillis() - currentTime) / 1000);
    logger.info("Finished to populate fake data on server: {} \n Duration: {}", databaseServer.getHost(),
            humanize.Humanize.duration(this.reportIntegration.getPopulateToDatabaseTime()));
}