Example usage for com.google.common.io ByteStreams nullOutputStream

List of usage examples for com.google.common.io ByteStreams nullOutputStream

Introduction

In this page you can find the example usage for com.google.common.io ByteStreams nullOutputStream.

Prototype

public static OutputStream nullOutputStream() 

Source Link

Document

Returns an OutputStream that simply discards written bytes.

Usage

From source file:com.facebook.buck.artifact_cache.FullyReadOnCloseInputStream.java

@Override
public void close() throws IOException {
    if (!closed) {
        closed = true;//w  w  w .  j a  v  a  2s. co m
        try {
            ByteStreams.copy(in, ByteStreams.nullOutputStream());
        } catch (IOException e) {
            LOGGER.info(e, "Exception when attempting to fully read the stream.");
        }
    }
    super.close();
}

From source file:org.jpmml.evaluator.IntegrationTestBatch.java

static private void ensureSerializability(Evaluator evaluator) throws IOException {

    try (ObjectOutputStream oos = new ObjectOutputStream(ByteStreams.nullOutputStream())) {
        oos.writeObject(evaluator);//from  w  ww.  j a  v  a  2  s  .  c o  m
    }
}

From source file:com.sonatype.nexus.repository.nuget.internal.odata.NugetPackageUtils.java

/**
 * Determine the metadata for a nuget package.
 * - nuspec data (comes from .nuspec)//w  w  w .  ja va2  s. co  m
 * - size (package size)
 * - hash(es) (package hash sha-512)
 */
public static Map<String, String> packageMetadata(final InputStream inputStream)
        throws IOException, NugetPackageException {
    try (MultiHashingInputStream hashingStream = new MultiHashingInputStream(
            Arrays.asList(HashAlgorithm.SHA512), inputStream)) {
        final byte[] nuspec = extractNuspec(hashingStream);
        Map<String, String> metadata = NuspecSplicer.extractNuspecData(new ByteArrayInputStream(nuspec));

        ByteStreams.copy(hashingStream, ByteStreams.nullOutputStream());

        metadata.put(PACKAGE_SIZE, String.valueOf(hashingStream.count()));
        HashCode code = hashingStream.hashes().get(HashAlgorithm.SHA512);
        metadata.put(PACKAGE_HASH, new String(Base64.encodeBase64(code.asBytes()), Charsets.UTF_8));
        metadata.put(PACKAGE_HASH_ALGORITHM, "SHA512");

        return metadata;
    } catch (XmlPullParserException e) {
        throw new NugetPackageException("Unable to read .nuspec from package stream", e);
    }
}

From source file:com.lithium.flow.util.HashEncoder.java

@Nonnull
public String process(@Nonnull InputStream in) throws IOException {
    checkNotNull(in);//from   ww w. j  a  va2s  . c  om
    try {
        HashingInputStream hashIn = new HashingInputStream(function, in);
        IOUtils.copy(hashIn, ByteStreams.nullOutputStream());
        return encoding.encode(hashIn.hash().asBytes());
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:com.indeed.lsmtree.core.tools.StoreCat.java

public static <K, V> String md5(final Store<K, V> store, K start, boolean startInclusive, final K end,
        final boolean endInclusive) throws IOException {
    MD5OutputStream md5 = new MD5OutputStream(ByteStreams.nullOutputStream());
    DataOutputStream out = new DataOutputStream(md5);
    final Serializer<K> keySerializer = store.getKeySerializer();
    final Serializer<V> valueSerializer = store.getValueSerializer();
    Iterator<Store.Entry<K, V>> it = store.iterator(start, startInclusive);
    Iterator<Store.Entry<K, V>> iterator = end == null ? it : ItUtil.span(new F<Store.Entry<K, V>, Boolean>() {
        public Boolean f(final Store.Entry<K, V> kvEntry) {
            final int cmp = store.getComparator().compare(kvEntry.getKey(), end);
            return cmp < 0 || cmp == 0 && endInclusive;
        }//from   ww w.ja  va2  s  .  c o m
    }, it)._1();
    while (iterator.hasNext()) {
        Store.Entry<K, V> next = iterator.next();
        keySerializer.write(next.getKey(), out);
        valueSerializer.write(next.getValue(), out);
    }
    return md5.getHashString();
}

From source file:com.palantir.util.crypto.Sha256Hash.java

/**
 * This method will read all the bytes in the stream and digest them.
 * It will attempt to close the stream as well.
 *///from w w  w.  j  av a  2 s  .c  om
public static Sha256Hash createFrom(InputStream is) throws IOException {
    try {
        MessageDigest digest = getMessageDigest();
        DigestInputStream digestInputStream = new DigestInputStream(is, digest);
        ByteStreams.copy(digestInputStream, ByteStreams.nullOutputStream());
        digestInputStream.close();
        return createFrom(digest);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            /* don't throw from finally*/}
    }
}

From source file:com.github.benmanes.caffeine.cache.simulator.policy.product.Cache2kPolicy.java

@SuppressWarnings("deprecation")
public Cache2kPolicy(Config config) {
    Logger logger = LogManager.getLogManager().getLogger("");
    Level level = logger.getLevel();
    logger.setLevel(Level.OFF);/*from  w  w w. ja  v  a  2s .  c  om*/
    PrintStream err = System.err;
    System.setErr(new PrintStream(ByteStreams.nullOutputStream()));
    try {
        this.policyStats = new PolicyStats("product.Cache2k");
        BasicSettings settings = new BasicSettings(config);
        cache = Cache2kBuilder.of(Object.class, Object.class).entryCapacity(settings.maximumSize())
                .eternal(true).build();
        maximumSize = settings.maximumSize();
    } finally {
        System.setErr(err);
        LogManager.getLogManager().getLogger("").setLevel(level);
    }
}

From source file:com.google.devtools.build.lib.sandbox.LinuxSandboxedSpawnRunner.java

public static boolean isSupported(CommandEnvironment cmdEnv) {
    if (OS.getCurrent() != OS.LINUX) {
        return false;
    }//from w  w w  .  jav  a 2s .c o m
    Path embeddedTool = getLinuxSandbox(cmdEnv);
    if (embeddedTool == null) {
        // The embedded tool does not exist, meaning that we don't support sandboxing (e.g., while
        // bootstrapping).
        return false;
    }

    Path execRoot = cmdEnv.getExecRoot();

    List<String> args = new ArrayList<>();
    args.add(embeddedTool.getPathString());
    args.add("--");
    args.add("/bin/true");

    ImmutableMap<String, String> env = ImmutableMap.of();
    File cwd = execRoot.getPathFile();

    Command cmd = new Command(args.toArray(new String[0]), env, cwd);
    try {
        cmd.execute(ByteStreams.nullOutputStream(), ByteStreams.nullOutputStream());
    } catch (CommandException e) {
        return false;
    }

    return true;
}

From source file:com.bouncestorage.chaoshttpproxy.HttpBinHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse servletResponse) throws IOException {
    logger.trace("request: {}", request);
    for (String headerName : Collections.list(request.getHeaderNames())) {
        logger.trace("header: {}: {}", headerName, request.getHeader(headerName));
    }/*w w  w  . j a v  a  2 s  . c o  m*/
    String method = request.getMethod();
    String uri = request.getRequestURI();
    try (InputStream is = request.getInputStream(); OutputStream os = servletResponse.getOutputStream()) {
        Writer writer = new OutputStreamWriter(os, StandardCharsets.UTF_8);
        if (method.equals("GET") && uri.startsWith("/status/")) {
            ByteStreams.copy(is, ByteStreams.nullOutputStream());
            int status = Integer.parseInt(uri.substring("/status/".length()));
            servletResponse.setStatus(status);
            baseRequest.setHandled(true);
            return;
        } else if (method.equals("GET") && uri.equals("/get")) {
            ByteStreams.copy(is, ByteStreams.nullOutputStream());
            // TODO: return JSON blob of request
            String content = "Hello, world!";
            servletResponse.setContentLength(content.length());
            servletResponse.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            writer.write(content);
            writer.flush();
            return;
        } else if (method.equals("POST") && uri.equals("/post")) {
            ByteStreams.copy(is, os);
            servletResponse.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            return;
        } else if (method.equals("PUT") && uri.equals("/put")) {
            ByteStreams.copy(is, os);
            servletResponse.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            return;
        } else if (method.equals("GET") && uri.equals("/response-headers")) {
            ByteStreams.copy(is, ByteStreams.nullOutputStream());
            for (String paramName : Collections.list(request.getParameterNames())) {
                servletResponse.addHeader(paramName, request.getParameter(paramName));
            }
            servletResponse.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            return;
        }
        servletResponse.setStatus(501);
        baseRequest.setHandled(true);
    }
}

From source file:com.google.devtools.build.lib.sandbox.DarwinSandboxedSpawnRunner.java

public static boolean isSupported(CommandEnvironment cmdEnv) {
    if (OS.getCurrent() != OS.DARWIN) {
        return false;
    }/*w w  w.j  a va 2 s .  c  om*/
    if (!ProcessWrapperRunner.isSupported(cmdEnv)) {
        return false;
    }

    List<String> args = new ArrayList<>();
    args.add(SANDBOX_EXEC);
    args.add("-p");
    args.add("(version 1) (allow default)");
    args.add("/usr/bin/true");

    ImmutableMap<String, String> env = ImmutableMap.of();
    File cwd = new File("/usr/bin");

    Command cmd = new Command(args.toArray(new String[0]), env, cwd);
    try {
        cmd.execute(ByteStreams.nullOutputStream(), ByteStreams.nullOutputStream());
    } catch (CommandException e) {
        return false;
    }

    return true;
}