当前位置: 首页>>代码示例>>Java>>正文


Java Closer类代码示例

本文整理汇总了Java中com.google.common.io.Closer的典型用法代码示例。如果您正苦于以下问题:Java Closer类的具体用法?Java Closer怎么用?Java Closer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Closer类属于com.google.common.io包,在下文中一共展示了Closer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: writeToZip

import com.google.common.io.Closer; //导入依赖的package包/类
/**
 * Write the dex program resources to @code{archive} and the proguard resource as its sibling.
 */
public void writeToZip(Path archive, OutputMode outputMode) throws IOException {
  OpenOption[] options =
      new OpenOption[] {StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING};
  try (Closer closer = Closer.create()) {
    try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(archive, options))) {
      List<Resource> dexProgramSources = getDexProgramResources();
      for (int i = 0; i < dexProgramSources.size(); i++) {
        ZipEntry zipEntry = new ZipEntry(outputMode.getOutputPath(dexProgramSources.get(i), i));
        byte[] bytes =
            ByteStreams.toByteArray(closer.register(dexProgramSources.get(i).getStream()));
        zipEntry.setSize(bytes.length);
        out.putNextEntry(zipEntry);
        out.write(bytes);
        out.closeEntry();
      }
    }
  }
}
 
开发者ID:inferjay,项目名称:r8,代码行数:22,代码来源:AndroidApp.java

示例2: zipDirectory

import com.google.common.io.Closer; //导入依赖的package包/类
/**
 * Zips an entire directory specified by the path.
 *
 * @param sourceDirectory the directory to read from. This directory and all
 *     subdirectories will be added to the zip-file. The path within the zip
 *     file is relative to the directory given as parameter, not absolute.
 * @param zipFile the zip-file to write to.
 * @throws IOException the zipping failed, e.g. because the input was not
 *     readable.
 */
static void zipDirectory(
    File sourceDirectory,
    File zipFile) throws IOException {
  checkNotNull(sourceDirectory);
  checkNotNull(zipFile);
  checkArgument(
      sourceDirectory.isDirectory(),
      "%s is not a valid directory",
      sourceDirectory.getAbsolutePath());
  checkArgument(
      !zipFile.exists(),
      "%s does already exist, files are not being overwritten",
      zipFile.getAbsolutePath());
  Closer closer = Closer.create();
  try {
    OutputStream outputStream = closer.register(new BufferedOutputStream(
        new FileOutputStream(zipFile)));
    zipDirectory(sourceDirectory, outputStream);
  } catch (Throwable t) {
    throw closer.rethrow(t);
  } finally {
    closer.close();
  }
}
 
开发者ID:spotify,项目名称:hype,代码行数:35,代码来源:ZipFiles.java

示例3: load

import com.google.common.io.Closer; //导入依赖的package包/类
@Override
public boolean load(final BuildCacheKey key, final BuildCacheEntryReader reader) throws BuildCacheException {
    return persistentCache.useCache("load build cache entry", new Factory<Boolean>() {
        @Override
        public Boolean create() {
            File file = getFile(key.getHashCode());
            if (file.isFile()) {
                try {
                    Closer closer = Closer.create();
                    FileInputStream stream = closer.register(new FileInputStream(file));
                    try {
                        reader.readFrom(stream);
                        return true;
                    } finally {
                        closer.close();
                    }
                } catch (IOException ex) {
                    throw new UncheckedIOException(ex);
                }
            }
            return false;
        }
    });
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:25,代码来源:LocalDirectoryBuildCache.java

示例4: store

import com.google.common.io.Closer; //导入依赖的package包/类
@Override
public void store(final BuildCacheKey key, final BuildCacheEntryWriter result) throws BuildCacheException {
    persistentCache.useCache("store build cache entry", new Runnable() {
        @Override
        public void run() {
            File file = getFile(key.getHashCode());
            try {
                Closer closer = Closer.create();
                OutputStream output = closer.register(new FileOutputStream(file));
                try {
                    result.writeTo(output);
                } finally {
                    closer.close();
                }
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }
    });
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:21,代码来源:LocalDirectoryBuildCache.java

示例5: main

import com.google.common.io.Closer; //导入依赖的package包/类
public static void main(String[] args)
    throws IOException, ProguardRuleParserException, CompilationException, ExecutionException {
  Command.Builder builder = Command.parse(args);
  Command command = builder.build();
  if (command.isPrintHelp()) {
    System.out.println(Command.USAGE_MESSAGE);
    return;
  }
  AndroidApp app = command.getInputApp();
  Map<String, Integer> result = new HashMap<>();
  try (Closer closer = Closer.create()) {
    for (Resource resource : app.getDexProgramResources()) {
      for (Segment segment: DexFileReader.parseMapFrom(closer.register(resource.getStream()))) {
        int value = result.computeIfAbsent(segment.typeName(), (key) -> 0);
        result.put(segment.typeName(), value + segment.size());
      }
    }
  }
  System.out.println("Segments in dex application (name: size):");
  result.forEach( (key, value) -> System.out.println(" - " + key + ": " + value));
}
 
开发者ID:inferjay,项目名称:r8,代码行数:22,代码来源:DexSegments.java

示例6: buildAndTreeShakeFromDeployJar

import com.google.common.io.Closer; //导入依赖的package包/类
@Test
public void buildAndTreeShakeFromDeployJar()
    throws ExecutionException, IOException, ProguardRuleParserException, CompilationException {
  int maxSize = 20000000;
  AndroidApp app = runAndCheckVerification(
      CompilerUnderTest.R8,
      CompilationMode.RELEASE,
      BASE + APK,
      null,
      BASE + PG_CONF,
      null,
      // Don't pass any inputs. The input will be read from the -injars in the Proguard
      // configuration file.
      ImmutableList.of());
  int bytes = 0;
  try (Closer closer = Closer.create()) {
    for (Resource dex : app.getDexProgramResources()) {
      bytes += ByteStreams.toByteArray(closer.register(dex.getStream())).length;
    }
  }
  assertTrue("Expected max size of " + maxSize + ", got " + bytes, bytes < maxSize);
}
 
开发者ID:inferjay,项目名称:r8,代码行数:23,代码来源:YouTubeTreeShakeJarVerificationTest.java

示例7: assertIdenticalApplications

import com.google.common.io.Closer; //导入依赖的package包/类
public void assertIdenticalApplications(AndroidApp app1, AndroidApp app2, boolean write)
    throws IOException {
  try (Closer closer = Closer.create()) {
    if (write) {
      app1.writeToDirectory(temp.newFolder("app1").toPath(), OutputMode.Indexed);
      app2.writeToDirectory(temp.newFolder("app2").toPath(), OutputMode.Indexed);
    }
    List<Resource> files1 = app1.getDexProgramResources();
    List<Resource> files2 = app2.getDexProgramResources();
    assertEquals(files1.size(), files2.size());
    for (int index = 0; index < files1.size(); index++) {
      InputStream file1 = closer.register(files1.get(index).getStream());
      InputStream file2 = closer.register(files2.get(index).getStream());
      byte[] bytes1 = ByteStreams.toByteArray(file1);
      byte[] bytes2 = ByteStreams.toByteArray(file2);
      assertArrayEquals("File index " + index, bytes1, bytes2);
    }
  }
}
 
开发者ID:inferjay,项目名称:r8,代码行数:20,代码来源:CompilationTestBase.java

示例8: writeSelfReferencingJarFile

import com.google.common.io.Closer; //导入依赖的package包/类
private static void writeSelfReferencingJarFile(File jarFile, String... entries)
    throws IOException {
  Manifest manifest = new Manifest();
  // Without version, the manifest is silently ignored. Ugh!
  manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
  manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, jarFile.getName());

  Closer closer = Closer.create();
  try {
    FileOutputStream fileOut = closer.register(new FileOutputStream(jarFile));
    JarOutputStream jarOut = closer.register(new JarOutputStream(fileOut));
    for (String entry : entries) {
      jarOut.putNextEntry(new ZipEntry(entry));
      Resources.copy(ClassPathTest.class.getResource(entry), jarOut);
      jarOut.closeEntry();
    }
  } catch (Throwable e) {
    throw closer.rethrow(e);
  } finally {
    closer.close();
  }
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:23,代码来源:ClassPathTest.java

示例9: loadProperties

import com.google.common.io.Closer; //导入依赖的package包/类
@Override
@NonNull
public Properties loadProperties(@NonNull File file) {
    Properties props = new Properties();
    Closer closer = Closer.create();
    try {
        FileInputStream fis = closer.register(new FileInputStream(file));
        props.load(fis);
    } catch (IOException ignore) {
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
        }
    }
    return props;
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:18,代码来源:FileOp.java

示例10: setUp

import com.google.common.io.Closer; //导入依赖的package包/类
@Before
public void setUp() {
  executor = createMock(DelayExecutor.class);
  clock = new FakeClock();
  stateManager = createMock(StateManager.class);
  storageUtil = new StorageTestUtil(this);
  storageUtil.expectOperations();
  shutdownCommand = createMock(Command.class);
  pruner = new TaskHistoryPruner(
      executor,
      stateManager,
      clock,
      new HistoryPrunnerSettings(ONE_DAY, ONE_MINUTE, PER_JOB_HISTORY),
      storageUtil.storage,
      new Lifecycle(shutdownCommand));
  closer = Closer.create();
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Mesos,代码行数:18,代码来源:TaskHistoryPrunerTest.java

示例11: createDockerRunner

import com.google.common.io.Closer; //导入依赖的package包/类
private static DockerRunner createDockerRunner(
    String id,
    Environment environment,
    StateManager stateManager,
    ScheduledExecutorService scheduler,
    Stats stats,
    Debug debug) {
  final Config config = environment.config();
  final Closer closer = environment.closer();

  if (isDevMode(config)) {
    LOG.info("Creating LocalDockerRunner");
    return closer.register(DockerRunner.local(scheduler, stateManager));
  } else {
    final NamespacedKubernetesClient kubernetes = closer.register(getKubernetesClient(
        config, id, createGkeClient(), DefaultKubernetesClient::new));
    final ServiceAccountKeyManager serviceAccountKeyManager = createServiceAccountKeyManager();
    return closer.register(DockerRunner.kubernetes(kubernetes, stateManager, stats,
        serviceAccountKeyManager, debug));
  }
}
 
开发者ID:spotify,项目名称:styx,代码行数:22,代码来源:StyxScheduler.java

示例12: create

import com.google.common.io.Closer; //导入依赖的package包/类
/**
 * Creates a session and ensures schema if configured. Closes the cluster and session if any
 * exception occurred.
 */
@Override public Session create(Cassandra3Storage cassandra) {
  Closer closer = Closer.create();
  try {
    Cluster cluster = closer.register(buildCluster(cassandra));
    cluster.register(new QueryLogger.Builder().build());
    Session session;
    if (cassandra.ensureSchema) {
      session = closer.register(cluster.connect());
      Schema.ensureExists(cassandra.keyspace, session);
      session.execute("USE " + cassandra.keyspace);
    } else {
      session = cluster.connect(cassandra.keyspace);
    }

    initializeUDTs(session);

    return session;
  } catch (RuntimeException e) {
    try {
      closer.close();
    } catch (IOException ignored) {
    }
    throw e;
  }
}
 
开发者ID:liaominghua,项目名称:zipkin,代码行数:30,代码来源:DefaultSessionFactory.java

示例13: create

import com.google.common.io.Closer; //导入依赖的package包/类
/**
 * Creates a session and ensures schema if configured. Closes the cluster and session if any
 * exception occurred.
 */
@Override public Session create(CassandraStorage cassandra) {
  Closer closer = Closer.create();
  try {
    Cluster cluster = closer.register(buildCluster(cassandra));
    cluster.register(new QueryLogger.Builder().build());
    if (cassandra.ensureSchema) {
      Session session = closer.register(cluster.connect());
      Schema.ensureExists(cassandra.keyspace, session);
      session.execute("USE " + cassandra.keyspace);
      return session;
    } else {
      return cluster.connect(cassandra.keyspace);
    }
  } catch (RuntimeException e) {
    try {
      closer.close();
    } catch (IOException ignored) {
    }
    throw e;
  }
}
 
开发者ID:liaominghua,项目名称:zipkin,代码行数:26,代码来源:SessionFactory.java

示例14: compress

import com.google.common.io.Closer; //导入依赖的package包/类
/**
 * Deflater 压缩
 *
 * @param content
 * @return
 */
public static byte[] compress(String content) {
    Closer closer = Closer.create();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, true);
    try {
        DeflaterOutputStream out = closer.register(new DeflaterOutputStream(byteArrayOutputStream, deflater));
        out.write(content.getBytes(Charsets.UTF_8.name()));
    } catch (Exception e) {
        logger.error(String.format("compress error:"), e);
    } finally {
        if (closer != null)
            try {
                closer.close();
            } catch (Exception ex) {
                logger.info(String.format("compress error,close the stream error:"), ex);
            }
    }
    deflater.end();
    return byteArrayOutputStream.toByteArray();
}
 
开发者ID:glameyzhou,项目名称:scaffold,代码行数:27,代码来源:CompressHandler.java

示例15: decompress

import com.google.common.io.Closer; //导入依赖的package包/类
/**
     * inflater 解压
     *
     * @param inputStream
     * @return
     */
    public static byte[] decompress(InputStream inputStream) {
        Closer closer = Closer.create();
        try {
            BufferedInputStream bufferInputStream = closer.register(new BufferedInputStream(new InflaterInputStream(inputStream, new Inflater(true))));
//			bufferInputStream = closer.register(new BufferedInputStream(new GZIPInputStream(inputStream)));
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ByteStreams.copy(bufferInputStream, byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            logger.error(String.format("decompress error:"), e);
        } finally {
            try {
                if (closer != null) {
                    closer.close();
                }
            } catch (Exception e1) {
                logger.error(String.format("decompress error,close the stream error"), e1);
            }
        }
        return null;
    }
 
开发者ID:glameyzhou,项目名称:scaffold,代码行数:28,代码来源:CompressHandler.java


注:本文中的com.google.common.io.Closer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。