Java Code Examples for com.google.common.io.ByteStreams#nullOutputStream()

The following examples show how to use com.google.common.io.ByteStreams#nullOutputStream() . 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
protected void write(int status, Map<String, String> headers, Object content) throws IOException {
  // write response status code
  servletResponse.setStatus(status);

  // write response headers
  if (headers != null) {
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      servletResponse.addHeader(entry.getKey(), entry.getValue());
    }
  }

  // write response body
  if (content != null) {
    servletResponse.setContentType(SystemService.MIME_JSON);
    if (addContentLength) {
      CountingOutputStream counter = new CountingOutputStream(ByteStreams.nullOutputStream());
      objectWriter.writeValue(counter, content);
      servletResponse.setContentLength((int) counter.getCount());
    }
    objectWriter.writeValue(servletResponse.getOutputStream(), content);
  }
}
 
Example 2
/** Creates the output stream to use for test results. Exposed for mocking. */
OutputStream createOutputResultStream(File reportDir) throws IOException {
  if (!reportDir.exists() && !reportDir.mkdirs()) {
    // TODO: Add Support for directBoot mode for FTL.
    // Right now it returns back a empty OutputStream if the device is in directBootMode.
    if (Build.VERSION.SDK_INT >= 24) {
      if (!((UserManager) getInstrumentation().getContext().getSystemService(UserManager.class))
          .isUserUnlocked()) {
        Log.e(LOG_TAG, "Currently no way to write output streams in direct boot mode.");
        return ByteStreams.nullOutputStream();
      }
    }
    throw new IOException("Failed to prepare report directory.");
  }
  File reportFile = getResultFile(reportDir);
  reportPath = reportFile.getAbsolutePath();
  return new BufferedOutputStream(new FileOutputStream(reportFile));
}
 
Example 3
@Test
public void testThreads() throws Exception {
    LOG.info("AvailableProcessors = " + Runtime.getRuntime().availableProcessors());
    Random r = new Random();
    byte[] data = new byte[10 * 1024 * 1024];
    r.nextBytes(data);
    for (int i = 0; i < data.length; i++)
        data[i] = (byte) (data[i] & 0x7f);  // Strip the top bit to make it amenable to Huffman compression.

    OutputStream out = ByteStreams.nullOutputStream();
    ParallelGZIPOutputStream gzip = new ParallelGZIPOutputStream(out);
    Stopwatch stopwatch = Stopwatch.createStarted();

    for (int i = 0; i < 1024; i++) {
        LOG.debug("Write iteration " + i);
        gzip.write(data);
    }
    gzip.close();

    long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    LOG.info("elapsed=" + elapsed);
}
 
Example 4
Source Project: bazel   File: StreamMultiplexerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testByteEncoding() throws IOException {
  OutputStream devNull = ByteStreams.nullOutputStream();
  StreamDemultiplexer demux = new StreamDemultiplexer((byte) 1, devNull);
  StreamMultiplexer mux = new StreamMultiplexer(demux);
  OutputStream out = mux.createStdout();

  // When we cast 266 to a byte, we get 10. So basically, we ended up
  // comparing 266 with 10 as an integer (because out.write takes an int),
  // and then later cast it to 10. This way we'd end up with a control
  // character \n in the middle of the payload which would then screw things
  // up when the real control character arrived. The fixed version of the
  // StreamMultiplexer avoids this problem by always casting to a byte before
  // carrying out any comparisons.

  out.write(266);
  out.write(10);
}
 
Example 5
Source Project: bundletool   File: GZipUtils.java    License: Apache License 2.0 5 votes vote down vote up
/** Calculates the GZip compressed size in bytes of the target {@code stream}. */
public static long calculateGzipCompressedSize(@WillNotClose InputStream stream)
    throws IOException {
  CountingOutputStream countingOutputStream =
      new CountingOutputStream(ByteStreams.nullOutputStream());
  try (GZIPOutputStream compressedStream = new GZIPOutputStream(countingOutputStream)) {
    ByteStreams.copy(stream, compressedStream);
  }
  return countingOutputStream.getCount();
}
 
Example 6
private static long compress(byte[] data) throws IOException {
  ZipEntry zipEntry = new ZipEntry("entry");
  try (ZipOutputStream zos = new ZipOutputStream(ByteStreams.nullOutputStream())) {
    zipEntry.setMethod(ZipEntry.DEFLATED);
    zos.putNextEntry(zipEntry);
    zos.write(data);
    zos.closeEntry();
  }
  return zipEntry.getCompressedSize();
}
 
Example 7
private static long getOverallRead(final CloseableHttpResponse response, final MessageDigest md)
        throws IOException {

    long overallread;

    try (final OutputStream os = ByteStreams.nullOutputStream();
            final BufferedOutputStream bos = new BufferedOutputStream(new DigestOutputStream(os, md))) {

        try (BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent())) {
            overallread = ByteStreams.copy(bis, bos);
        }
    }

    return overallread;
}
 
Example 8
private static void method() throws Exception {
    ByteStreams.nullOutputStream();
    CharStreams.nullWriter();
    Files.toString((File) null, (Charset) null);
    Files.write("", (File) null, (Charset) null);
    new FileReader((File) null);
    new FileReader((String) null);
    new FileWriter((File) null);
    new FileWriter((File) null, true);
    new FileWriter("");
    new FileWriter("", true);
}
 
Example 9
Source Project: bazel   File: DexFileMerger.java    License: Apache License 2.0 5 votes vote down vote up
private static DexFileAggregator createDexFileAggregator(
    Options options, ListeningExecutorService executor) throws IOException {
  String filePrefix = options.dexPrefix;
  if (options.multidexMode == MultidexStrategy.GIVEN_SHARD) {
    checkArgument(options.inputArchives.size() == 1,
        "--multidex=given_shard requires exactly one --input");
    Pattern namingPattern = Pattern.compile("([0-9]+)\\..*");
    Matcher matcher = namingPattern.matcher(options.inputArchives.get(0).toFile().getName());
    checkArgument(matcher.matches(),
        "expect input named <N>.xxx.zip for --multidex=given_shard but got %s",
        options.inputArchives.get(0).toFile().getName());
    int shard = Integer.parseInt(matcher.group(1));
    checkArgument(shard > 0, "expect positive N in input named <N>.xxx.zip but got %s", shard);
    if (shard > 1) {  // first shard conventionally isn't numbered
      filePrefix += shard;
    }
  }
  return new DexFileAggregator(
      new DxContext(options.verbose ? System.out : ByteStreams.nullOutputStream(), System.err),
      new DexFileArchive(
          new ZipOutputStream(
              new BufferedOutputStream(Files.newOutputStream(options.outputArchive)))),
      executor,
      options.multidexMode,
      options.forceJumbo,
      options.maxNumberOfIdxPerDex,
      options.wasteThresholdPerDex,
      filePrefix);
}
 
Example 10
public void output(Resource resource) throws IOException {
	OutputStream nullo = ByteStreams.nullOutputStream();
	CountingOutputStream co = new CountingOutputStream(nullo);
	StreamCopy.copy(resource.getInputStream(), co);
	long bytes = co.getCount();
	if(bytes > 0) {
		LOG.info(bytes + " unconsumed bytes in Resource InputStream.");
	}
	try {
		out.println(resource.getMetaData().getTopMetaData().toString(1));
	} catch (JSONException e) {
		LOG.warning(e.getMessage());
	}		
}
 
Example 11
@Override
public void run() {

  setStatus(TaskStatus.PROCESSING);

  try {
    // Prevent MZTabFileParser from writing to console
    OutputStream logStream = ByteStreams.nullOutputStream();

    // Load mzTab file
    MZTabFileParser mzTabFileParser = new MZTabFileParser(inputFile, logStream);

    if (!mzTabFileParser.getErrorList().getErrorList().isEmpty()) {
      setStatus(TaskStatus.ERROR);
      setErrorMessage(
          "Error processing " + inputFile + ":\n" + mzTabFileParser.getErrorList().toString());
      return;
    }

    MZTabFile mzTabFile = mzTabFileParser.getMZTabFile();

    // Let's say the initial parsing took 10% of the time
    finishedPercentage = 0.1;

    // Import raw data files
    SortedMap<Integer, RawDataFile> rawDataFiles = importRawDataFiles(mzTabFile);

    // Check if not canceled
    if (isCanceled())
      return;

    // Create a new feature list
    String peakListName = inputFile.getName().replace(".mzTab", "");
    RawDataFile rawDataArray[] = rawDataFiles.values().toArray(new RawDataFile[0]);
    PeakList newPeakList = new SimplePeakList(peakListName, rawDataArray);

    // Check if not canceled
    if (isCanceled())
      return;

    // Import variables
    importVariables(mzTabFile, rawDataFiles);

    // Check if not canceled
    if (isCanceled())
      return;

    // import small molecules (=feature list rows)
    importSmallMolecules(newPeakList, mzTabFile, rawDataFiles);

    // Check if not canceled
    if (isCanceled())
      return;

    // Add the new feature list to the project
    project.addPeakList(newPeakList);

    // Finish
    setStatus(TaskStatus.FINISHED);
    finishedPercentage = 1.0;

  } catch (Exception e) {
    e.printStackTrace();
    setStatus(TaskStatus.ERROR);
    setErrorMessage("Could not import data from " + inputFile + ": " + e.getMessage());
    return;
  }

}
 
Example 12
Source Project: copybara   File: GithubArchive.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public OutputStream openStream() {
  return ByteStreams.nullOutputStream();
}
 
Example 13
public static OutputStream silentOut() {
	return ByteStreams.nullOutputStream();
}
 
Example 14
Source Project: buck   File: XctoolRunTestsStepTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void xctoolCommandWithTestSelectorMatchingNothingDoesNotFail() throws Exception {
  FakeProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
  XctoolRunTestsStep step =
      new XctoolRunTestsStep(
          projectFilesystem,
          Paths.get("/path/to/xctool"),
          ImmutableMap.of(),
          Optional.empty(),
          "iphonesimulator",
          Optional.empty(),
          ImmutableSet.of(
              Paths.get("/path/to/FooTest.xctest"), Paths.get("/path/to/BarTest.xctest")),
          ImmutableMap.of(),
          ImmutableMap.of(),
          Paths.get("/path/to/output.json"),
          Optional.empty(),
          AppleDeveloperDirectoryForTestsProvider.of(Paths.get("/path/to/developer/dir")),
          TestSelectorList.builder().addRawSelectors("Blargh#Xyzzy").build(),
          false,
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty());
  ProcessExecutorParams xctoolListOnlyParams =
      ProcessExecutorParams.builder()
          .setCommand(
              ImmutableList.of(
                  "/path/to/xctool",
                  "-reporter",
                  "json-stream",
                  "-sdk",
                  "iphonesimulator",
                  "run-tests",
                  "-logicTest",
                  "/path/to/FooTest.xctest",
                  "-logicTest",
                  "/path/to/BarTest.xctest",
                  "-listTestsOnly"))
          .setEnvironment(ImmutableMap.of("DEVELOPER_DIR", "/path/to/developer/dir"))
          .setDirectory(projectFilesystem.getRootPath().getPath())
          .setRedirectOutput(ProcessBuilder.Redirect.PIPE)
          .build();
  try (InputStream stdout =
          getClass().getResourceAsStream("testdata/xctool-output/list-tests-only.json");
      InputStream stderr = new ByteArrayInputStream(new byte[0])) {
    assertThat(stdout, not(nullValue()));
    FakeProcess fakeXctoolListTestsProcess =
        new FakeProcess(0, ByteStreams.nullOutputStream(), stdout, stderr);
    FakeProcessExecutor processExecutor =
        new FakeProcessExecutor(
            ImmutableMap.of(xctoolListOnlyParams, fakeXctoolListTestsProcess));
    ExecutionContext executionContext =
        TestExecutionContext.newBuilder()
            .setProcessExecutor(processExecutor)
            .setEnvironment(ImmutableMap.of())
            .build();
    assertThat(step.execute(executionContext).getExitCode(), equalTo(0));
  }
}
 
Example 15
Source Project: batfish   File: CompositePrintStream.java    License: Apache License 2.0 4 votes vote down vote up
public CompositePrintStream(PrintStream ps1, PrintStream ps2) {
  super(ByteStreams.nullOutputStream());
  _ps1 = ps1;
  _ps2 = ps2;
}
 
Example 16
@Override
public OutputStream getOutputStream() {
  return ByteStreams.nullOutputStream();
}
 
Example 17
Source Project: bazel   File: JUnit4RunnerTest.java    License: Apache License 2.0 4 votes vote down vote up
OutputStream xmlOutputStream() {
  return ByteStreams.nullOutputStream();
}
 
Example 18
Source Project: bazel   File: JUnit4RunnerTest.java    License: Apache License 2.0 4 votes vote down vote up
PrintStream provideStderrStream() {
  return new PrintStream(ByteStreams.nullOutputStream());
}
 
Example 19
Source Project: bazel   File: LocalSpawnRunnerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public OutputStream getOutputStream() {
  return ByteStreams.nullOutputStream();
}
 
Example 20
Source Project: buck   File: XctoolRunTestsStepTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void xctoolCommandWithTestSelectorFiltersTests() throws Exception {
  FakeProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
  XctoolRunTestsStep step =
      new XctoolRunTestsStep(
          projectFilesystem,
          Paths.get("/path/to/xctool"),
          ImmutableMap.of(),
          Optional.empty(),
          "iphonesimulator",
          Optional.empty(),
          ImmutableSet.of(
              Paths.get("/path/to/FooTest.xctest"), Paths.get("/path/to/BarTest.xctest")),
          ImmutableMap.of(),
          ImmutableMap.of(),
          Paths.get("/path/to/output.json"),
          Optional.empty(),
          AppleDeveloperDirectoryForTestsProvider.of(Paths.get("/path/to/developer/dir")),
          TestSelectorList.builder().addRawSelectors("#.*Magic.*").build(),
          false,
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          Optional.empty());

  ProcessExecutorParams xctoolListOnlyParams =
      ProcessExecutorParams.builder()
          .setCommand(
              ImmutableList.of(
                  "/path/to/xctool",
                  "-reporter",
                  "json-stream",
                  "-sdk",
                  "iphonesimulator",
                  "run-tests",
                  "-logicTest",
                  "/path/to/FooTest.xctest",
                  "-logicTest",
                  "/path/to/BarTest.xctest",
                  "-listTestsOnly"))
          .setEnvironment(ImmutableMap.of("DEVELOPER_DIR", "/path/to/developer/dir"))
          .setDirectory(projectFilesystem.getRootPath().getPath())
          .setRedirectOutput(ProcessBuilder.Redirect.PIPE)
          .build();
  try (InputStream stdout =
          getClass().getResourceAsStream("testdata/xctool-output/list-tests-only.json");
      InputStream stderr = new ByteArrayInputStream(new byte[0])) {
    assertThat(stdout, not(nullValue()));
    FakeProcess fakeXctoolListTestsProcess =
        new FakeProcess(0, ByteStreams.nullOutputStream(), stdout, stderr);
    ProcessExecutorParams xctoolRunTestsParamsWithOnlyFilters =
        ProcessExecutorParams.builder()
            .addCommand(
                "/path/to/xctool",
                "-reporter",
                "json-stream",
                "-sdk",
                "iphonesimulator",
                "run-tests",
                "-logicTest",
                "/path/to/FooTest.xctest",
                "-logicTest",
                "/path/to/BarTest.xctest",
                "-only",
                "/path/to/FooTest.xctest:FooTest/testMagicValue,FooTest/testAnotherMagicValue",
                "-only",
                "/path/to/BarTest.xctest:BarTest/testYetAnotherMagicValue")
            .setEnvironment(ImmutableMap.of("DEVELOPER_DIR", "/path/to/developer/dir"))
            .setDirectory(projectFilesystem.getRootPath().getPath())
            .setRedirectOutput(ProcessBuilder.Redirect.PIPE)
            .build();
    FakeProcess fakeXctoolSuccess = new FakeProcess(0, "", "");
    FakeProcessExecutor processExecutor =
        new FakeProcessExecutor(
            ImmutableMap.of(
                xctoolListOnlyParams, fakeXctoolListTestsProcess,
                // The important part of this test is that we want to make sure xctool
                // is run with the correct -only parameters. (We don't really care what
                // the return value of this xctool is, so we make it always succeed.)
                xctoolRunTestsParamsWithOnlyFilters, fakeXctoolSuccess));
    ExecutionContext executionContext =
        TestExecutionContext.newBuilder()
            .setProcessExecutor(processExecutor)
            .setEnvironment(ImmutableMap.of())
            .build();
    assertThat(step.execute(executionContext).getExitCode(), equalTo(0));
  }
}