Java Code Examples for com.google.common.io.ByteSource#copyTo()

The following examples show how to use com.google.common.io.ByteSource#copyTo() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private static void addFile(JarOutputStream jarFile, JavaFile javaFile) throws IOException {
  initNextEntry(javaFile.getFilePath(), jarFile);
  ByteSource byteSource =
      CharSource.wrap(javaFile.getFileContent()).asByteSource(StandardCharsets.UTF_8);
  byteSource.copyTo(jarFile);
}
 
Example 2
private void copyResource(final ByteSource source, final File target) throws IOException {
    try (final OutputStream out = createFile(target)) {
        source.copyTo(out);
    }
}
 
Example 3
@VisibleForTesting
static byte[] createMetadataHeader(
    ImmutableSet<RuleKey> ruleKeys, ImmutableMap<String, String> metadata, ByteSource data)
    throws IOException {

  ByteArrayOutputStream rawOut = new ByteArrayOutputStream();
  Hasher hasher = HASH_FUNCTION.newHasher();
  try (DataOutputStream out = new DataOutputStream(new HasherOutputStream(hasher, rawOut))) {

    // Write the rule keys to the raw metadata, including them in the end-to-end checksum.
    out.writeInt(ruleKeys.size());
    for (RuleKey ruleKey : ruleKeys) {
      out.writeUTF(ruleKey.toString());
    }

    // Write out the metadata map to the raw metadata, including it in the end-to-end checksum.
    out.writeInt(metadata.size());
    for (Map.Entry<String, String> ent : metadata.entrySet()) {
      out.writeUTF(ent.getKey());
      byte[] val = ent.getValue().getBytes(Charsets.UTF_8);
      out.writeInt(val.length);
      out.write(val);
      if (out.size() > MAX_METADATA_HEADER_SIZE) {
        throw new IOException("Metadata header too big.");
      }
    }
  }

  // Add the file data contents to the end-to-end checksum.
  data.copyTo(new HasherOutputStream(hasher, ByteStreams.nullOutputStream()));

  // Finish the checksum, adding it to the raw metadata
  rawOut.write(hasher.hash().asBytes());

  // Finally, base64 encode the raw bytes to make usable in a HTTP header.
  byte[] bytes = rawOut.toByteArray();
  if (bytes.length > MAX_METADATA_HEADER_SIZE) {
    throw new IOException("Metadata header too big.");
  }
  return bytes;
}