Example usage for org.apache.commons.io.output NullOutputStream NULL_OUTPUT_STREAM

List of usage examples for org.apache.commons.io.output NullOutputStream NULL_OUTPUT_STREAM

Introduction

In this page you can find the example usage for org.apache.commons.io.output NullOutputStream NULL_OUTPUT_STREAM.

Prototype

NullOutputStream NULL_OUTPUT_STREAM

To view the source code for org.apache.commons.io.output NullOutputStream NULL_OUTPUT_STREAM.

Click Source Link

Document

A singleton.

Usage

From source file:org.jenkinsci.plugins.drupal.beans.DrushInvocation.java

/**
 * Execute a Drush command.//from   w w w  . ja v  a2s . c o m
 */
protected boolean execute(ArgumentListBuilder args, TaskListener out) throws IOException, InterruptedException {
    ProcStarter starter = launcher.launch().pwd(workspace).cmds(args);
    if (out == null) {
        // Output stdout/stderr into listener.
        starter.stdout(listener);
    } else {
        // Output stdout into out.
        // Do not output stderr since this breaks the XML formatting on stdout.
        starter.stdout(out).stderr(NullOutputStream.NULL_OUTPUT_STREAM);
    }
    starter.join();
    return true;
}

From source file:org.kalypso.ogc.sensor.diagview.grafik.GrafikLauncher.java

/**
 * Starts the grafik with a java.lang.File tpl-File.
 */// w  w w  .  j  a v  a  2  s . c  o m
private static IStatus startGrafikTPL(final File tplFile, final RememberForSync[] syncs,
        final IProgressMonitor monitor) throws SensorException {
    try {
        final File grafikExe = getGrafikProgramPath();

        final String[] commands = new String[] { //
                grafikExe.getAbsolutePath(), "/V", tplFile.getAbsolutePath() }; //$NON-NLS-1$

        final ICancelable cancelable = new ProgressCancelable(monitor);

        final ProcessHelper helper = new ProcessHelper(commands, null, grafikExe.getParentFile(), cancelable, 0,
                NullOutputStream.NULL_OUTPUT_STREAM, NullOutputStream.NULL_OUTPUT_STREAM,
                new NullInputStream(0));
        helper.setKillOnCancel(false);
        helper.start();

        if (monitor.isCanceled())
            return new Status(IStatus.CANCEL, KalypsoGisPlugin.PLUGIN_ID,
                    Messages.getString("GrafikLauncher.3")); //$NON-NLS-1$

        return syncBack(syncs);
    } catch (final Exception e) {
        throw new SensorException(e);
    }
}

From source file:org.nuxeo.ecm.core.blob.binary.DefaultBinaryManager.java

/**
 * Stores and digests a temporary FileBlob.
 */// w w  w.  j  a v a2s.  c om
protected String storeAndDigest(FileBlob blob) throws IOException {
    String digest;
    try (InputStream in = blob.getStream()) {
        digest = storeAndDigest(in, NullOutputStream.NULL_OUTPUT_STREAM);
    }
    File digestFile = getFileForDigest(digest, true);
    if (digestFile.exists()) {
        // The file with the proper digest is already there so don't do anything. This is to avoid
        // "Stale NFS File Handle" problems which would occur if we tried to overwrite it anyway.
        // Note that this doesn't try to protect from the case where two identical files are uploaded
        // at the same time.
        // Update date for the GC.
        digestFile.setLastModified(blob.getFile().lastModified());
    } else {
        blob.moveTo(digestFile);
    }
    return digest;
}

From source file:org.owasp.dependencycheck.analyzer.AssemblyAnalyzer.java

/**
 * Initialize the analyzer. In this case, extract GrokAssembly.exe to a temporary location.
 *
 * @throws Exception if anything goes wrong
 *///  w w w .  j  a  v  a2s .  com
@Override
public void initializeFileTypeAnalyzer() throws Exception {
    final File tempFile = File.createTempFile("GKA", ".exe", Settings.getTempDirectory());
    FileOutputStream fos = null;
    InputStream is = null;
    try {
        fos = new FileOutputStream(tempFile);
        is = AssemblyAnalyzer.class.getClassLoader().getResourceAsStream("GrokAssembly.exe");
        IOUtils.copy(is, fos);

        grokAssemblyExe = tempFile;
        // Set the temp file to get deleted when we're done
        grokAssemblyExe.deleteOnExit();
        LOGGER.debug("Extracted GrokAssembly.exe to {}", grokAssemblyExe.getPath());
    } catch (IOException ioe) {
        this.setEnabled(false);
        LOGGER.warn("Could not extract GrokAssembly.exe: {}", ioe.getMessage());
        throw new AnalysisException("Could not extract GrokAssembly.exe", ioe);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (Throwable e) {
                LOGGER.debug("Error closing output stream");
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (Throwable e) {
                LOGGER.debug("Error closing input stream");
            }
        }
    }

    // Now, need to see if GrokAssembly actually runs from this location.
    final List<String> args = buildArgumentList();
    try {
        final ProcessBuilder pb = new ProcessBuilder(args);
        final Process p = pb.start();
        // Try evacuating the error stream
        IOUtils.copy(p.getErrorStream(), NullOutputStream.NULL_OUTPUT_STREAM);

        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(p.getInputStream());
        final XPath xpath = XPathFactory.newInstance().newXPath();
        final String error = xpath.evaluate("/assembly/error", doc);
        if (p.waitFor() != 1 || error == null || error.isEmpty()) {
            LOGGER.warn(
                    "An error occurred with the .NET AssemblyAnalyzer, please see the log for more details.");
            LOGGER.debug("GrokAssembly.exe is not working properly");
            grokAssemblyExe = null;
            this.setEnabled(false);
            throw new AnalysisException("Could not execute .NET AssemblyAnalyzer");
        }
    } catch (AnalysisException e) {
        throw e;
    } catch (Throwable e) {
        LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer;\n"
                + "this can be ignored unless you are scanning .NET DLLs. Please see the log for more details.");
        LOGGER.debug("Could not execute GrokAssembly {}", e.getMessage());
        this.setEnabled(false);
        throw new AnalysisException("An error occurred with the .NET AssemblyAnalyzer", e);
    }
    builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
}

From source file:org.uimafit.testing.util.HideOutput.java

/**
 * calling this constructor will silence System.out and System.err until
 * {@link #restoreOutput()} is called by setting them to this OutputStream
 *//*from w  ww. j ava  2 s.c  o  m*/
public HideOutput() {
    this.out = System.out;
    this.err = System.err;
    System.setOut(new PrintStream(NullOutputStream.NULL_OUTPUT_STREAM));
    System.setErr(new PrintStream(NullOutputStream.NULL_OUTPUT_STREAM));
}

From source file:org.vafer.jdeb.ControlBuilder.java

/**
 * Build control archive of the deb//from   w  w w.  j  av  a 2s. c  o m
 *
 * @param packageControlFile the package control file
 * @param controlFiles the other control information files (maintainer scripts, etc)
 * @param dataSize  the size of the installed package
 * @param checksums the md5 checksums of the files in the data archive
 * @param output
 * @return
 * @throws java.io.FileNotFoundException
 * @throws java.io.IOException
 * @throws java.text.ParseException
 */
void buildControl(BinaryPackageControlFile packageControlFile, File[] controlFiles, StringBuilder checksums,
        File output) throws IOException, ParseException {
    final File dir = output.getParentFile();
    if (dir != null && (!dir.exists() || !dir.isDirectory())) {
        throw new IOException("Cannot write control file at '" + output.getAbsolutePath() + "'");
    }

    final TarArchiveOutputStream outputStream = new TarArchiveOutputStream(
            new GZIPOutputStream(new FileOutputStream(output)));
    outputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

    // create the final package control file out of the "control" file, copy all other files, ignore the directories
    for (File file : controlFiles) {
        if (file.isDirectory()) {
            // warn about the misplaced directory, except for directories ignored by default (.svn, cvs, etc)
            if (!isDefaultExcludes(file)) {
                console.info("Found directory '" + file
                        + "' in the control directory. Maybe you are pointing to wrong dir?");
            }
            continue;
        }

        if (CONFIGURATION_FILENAMES.contains(file.getName()) || MAINTAINER_SCRIPTS.contains(file.getName())) {
            FilteredFile configurationFile = new FilteredFile(new FileInputStream(file), resolver);
            addControlEntry(file.getName(), configurationFile.toString(), outputStream);

        } else if (!"control".equals(file.getName())) {
            // initialize the information stream to guess the type of the file
            InformationInputStream infoStream = new InformationInputStream(new FileInputStream(file));
            Utils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM);
            infoStream.close();

            // fix line endings for shell scripts
            InputStream in = new FileInputStream(file);
            if (infoStream.isShell() && !infoStream.hasUnixLineEndings()) {
                byte[] buf = Utils.toUnixLineEndings(in);
                in = new ByteArrayInputStream(buf);
            }

            addControlEntry(file.getName(), IOUtils.toString(in), outputStream);

            in.close();
        }
    }

    if (packageControlFile == null) {
        throw new FileNotFoundException("No 'control' file found in " + Arrays.toString(controlFiles));
    }

    addControlEntry("control", packageControlFile.toString(), outputStream);
    addControlEntry("md5sums", checksums.toString(), outputStream);

    outputStream.close();
}

From source file:org.vafer.jdeb.DebMakerTestCase.java

public void testControlFilesPermissions() throws Exception {
    File deb = new File("target/test-classes/test-control.deb");
    if (deb.exists() && !deb.delete()) {
        fail("Couldn't delete " + deb);
    }/*from  ww w  .  j a  v a 2 s  . co  m*/

    Collection<DataProducer> producers = Arrays.asList(new DataProducer[] { new EmptyDataProducer() });
    DebMaker maker = new DebMaker(new NullConsole(), producers);
    maker.setDeb(deb);
    maker.setControl(new File("target/test-classes/org/vafer/jdeb/deb/control"));

    maker.createDeb(Compression.NONE);

    // now reopen the package and check the control files
    assertTrue("package not build", deb.exists());

    boolean found = ArchiveWalker.walkControl(deb, new ArchiveVisitor<TarArchiveEntry>() {
        public void visit(TarArchiveEntry entry, byte[] content) throws IOException {
            assertFalse("directory found in the control archive", entry.isDirectory());
            assertTrue("prefix", entry.getName().startsWith("./"));

            InformationInputStream infoStream = new InformationInputStream(new ByteArrayInputStream(content));
            IOUtils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM);

            if (infoStream.isShell()) {
                assertTrue("Permissions on " + entry.getName() + " should be 755", entry.getMode() == 0755);
            } else {
                assertTrue("Permissions on " + entry.getName() + " should be 644", entry.getMode() == 0644);
            }

            assertTrue(entry.getName() + " doesn't have Unix line endings", infoStream.hasUnixLineEndings());

            assertEquals("user", "root", entry.getUserName());
            assertEquals("group", "root", entry.getGroupName());
        }
    });

    assertTrue("Control files not found in the package", found);
}

From source file:org.zeroturnaround.exec.ProcessExecutor.java

/**
 * Redirects the process' output stream to given output stream.
 * If this method is invoked multiple times each call overwrites the previous.
 * Use {@link #redirectOutputAlsoTo(OutputStream)} if you want to redirect the output to multiple streams.
 *
 * @param output output stream where the process output is redirected to (<code>null</code> means {@link NullOutputStream} which acts like a <code>/dev/null</code>).
 * @return This process executor./*  w  w  w. j  a v  a 2  s . c om*/
 */
public ProcessExecutor redirectOutput(OutputStream output) {
    if (output == null)
        output = NullOutputStream.NULL_OUTPUT_STREAM;
    PumpStreamHandler pumps = pumps();
    // Only set the output stream handler, preserve the same error stream handler
    return streams(new PumpStreamHandler(output, pumps == null ? null : pumps.getErr(),
            pumps == null ? null : pumps.getInput()));
}

From source file:org.zeroturnaround.exec.ProcessExecutor.java

/**
 * Redirects the process' error stream to given output stream.
 * If this method is invoked multiple times each call overwrites the previous.
 * Use {@link #redirectErrorAlsoTo(OutputStream)} if you want to redirect the error to multiple streams.
 * <p>//w  w  w  .  jav  a 2 s.co  m
 * Calling this method automatically disables merging the process error stream to its output stream.
 * </p>
 *
 * @param output output stream where the process error is redirected to (<code>null</code> means {@link NullOutputStream} which acts like a <code>/dev/null</code>).
 * @return This process executor.
 */
public ProcessExecutor redirectError(OutputStream output) {
    if (output == null)
        output = NullOutputStream.NULL_OUTPUT_STREAM;
    PumpStreamHandler pumps = pumps();
    // Only set the error stream handler, preserve the same output stream handler
    streams(new PumpStreamHandler(pumps == null ? null : pumps.getOut(), output,
            pumps == null ? null : pumps.getInput()));
    redirectErrorStream(false);
    return this;
}

From source file:pt.webdetails.cpf.Util.java

public static String getMd5Digest(InputStream input) throws IOException {
    try {//w w w  . ja  v a 2  s  . c o  m
        MessageDigest digest = MessageDigest.getInstance("MD5");
        DigestInputStream digestStream = new DigestInputStream(input, digest);
        IOUtils.copy(digestStream, NullOutputStream.NULL_OUTPUT_STREAM);
        return bytesToHex(digest.digest());
    } catch (NoSuchAlgorithmException e) {
        logger.fatal("No MD5!", e);
        return null;
    }
}