Java com.google.common.io.Closer 代码实例

・16 分钟阅读

以下是展示如何使用com.google.common.io.Closer的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Test(groups = {"live", "livelong", "longtest"}, dependsOnMethods = {"testWaitForSucceed"})
public void testGetJobOutput() throws IOException {
   Closer closer = Closer.create();
   try {
      InputStream inputStream = closer.register(api.getJobOutput(VAULT_NAME, archiveRetrievalJob).openStream());
      InputStream expectedInputStream = closer.register(buildData(PART_SIZE * 2 * MiB).openStream());
      assertThat(inputStream).hasContentEqualTo(expectedInputStream);
   } finally {
      closer.close();
   }
}
 

实例 2


protected void copy(InputStream is, OutputStream os) throws IOException {
  TransferEvent transferEvent =
      new TransferEvent(OkHttpWagon.this, resource, TransferEvent.TRANSFER_PROGRESS,
          TransferEvent.REQUEST_PUT);
  transferEvent.setTimestamp(System.currentTimeMillis());
  Closer closer = Closer.create();
  try {
    closer.register(is);
    closer.register(os);
    int n = 0;
    final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    while (-1 != (n = is.read(buffer))) {
      write(os, n, buffer);
      fireTransferProgress(transferEvent, buffer, n);
    }
  } finally {
    closer.close();
  }
}
 

实例 3


public static Manifest getManifest( File file )
    throws IOException
{
    Closer closer = Closer.create();
    try
    {
        final JarInputStream jis =
                closer.register(
                    new JarInputStream( new BufferedInputStream( new FileInputStream( file ) ) ) );
        final Manifest manifest = jis.getManifest();
        if ( manifest != null )
        {
            return new Manifest( manifest );
        }
        for ( JarEntry je = jis.getNextJarEntry(); je != null; je = jis.getNextJarEntry() )
        {
            if ( je.getName().equals( MANIFEST_JAR_ENTRY ) )
            {
                return new Manifest( jis );
            }
        }
    }
    finally
    {
        closer.close();
    }
    return new Manifest();
}
 

实例 4


public static void defineClassesInBootstrapClassLoader(
        Collection<LazyDefinedClass> lazyDefinedClasses, Instrumentation instrumentation,
        File generatedJarFile) throws IOException {
    Closer closer = Closer.create();
    try {
        FileOutputStream out = closer.register(new FileOutputStream(generatedJarFile));
        JarOutputStream jarOut = closer.register(new JarOutputStream(out));
        generate(lazyDefinedClasses, jarOut);
    } catch (Throwable t) {
        closer.rethrow(t);
    } finally {
        closer.close();
    }
    instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(generatedJarFile));
}
 

实例 5


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();
  }
}
 

实例 6


public void file(Filer filer, CharSequence name,  Iterable<? extends Element> originatingElements)
    throws IOException {
  JavaFileObject sourceFile = filer.createSourceFile(name,
      Iterables.toArray(originatingElements, Element.class));
  Closer closer = Closer.create();
  try {
    write(closer.register(sourceFile.openWriter()));
  } catch (Exception e) {
    try {
      sourceFile.delete();
    } catch (Exception e2) {
      // couldn't delete the file
    }
    throw closer.rethrow(e);
  } finally {
    closer.close();
  }
}
 

实例 7


@Test
public void t_01() throws IOException {
    GridFS gf = new GridFS(mongoClient.getDB("test"), "glados-wiki");
    Resource r = resourceLoader.getResource("classpath:com/aperture_software/glados_wiki/tests/GridFsTests/test.jpg");
    assertNotNull(r);
    File f = r.getFile();
    assertNotNull(f);
    assertTrue(f.exists());
    GridFSInputFile gif = gf.createFile(f);
    gif.setFilename(f.getName());
    //gif.setContentType();
    gif.save();
    GridFSDBFile gif2 = gf.find((ObjectId) gif.getId());
    assertNotNull(gif2);
    Closer closer = Closer.create();
    try {
        InputStream fileIn = new FileInputStream(f);
        assertNotNull(fileIn);
        closer.register(fileIn);
        InputStream gif2_in = gif2.getInputStream();
        assertNotNull(gif2_in);
        closer.register(gif2_in);
        assertTrue(IOUtils.contentEquals(fileIn, gif2_in));
    } finally {
        closer.close();
    }
    gf.remove((ObjectId) gif.getId());
}
 

实例 8


/**
 * Check if an object is serializable, emit a warning log if it is not.
 *
 * @param attribute
 *            the attribute to check
 * @throws IOException
 */
private void checkSerializable(final Object attribute) throws IOException {
    if (!Serializable.class.isAssignableFrom(attribute.getClass())) {
        log.warn(format("Session attribute [%s] of class [%s] is not "
                + "serializable.", attribute, attribute.getClass()));
    }
    final Closer closer = Closer.create();
    try {
        final ObjectOutputStream out = closer.register(new ObjectOutputStream(
                ByteStreams.nullOutputStream()));
        out.writeObject(attribute);
    } catch (Throwable t) {
        closer.rethrow(t);
    } finally {
        closer.close();
    }
}
 

实例 9


/** Returns a URL to a local copy of the given resource, or null. There is
 * no filename conflict resolution. */
protected String addLocalResources(URL url) throws IOException {
    // Attempt to make local copy
    File resourceDir = computeResourceDir();
    if (resourceDir != null) {
        String base = url.getFile();
        base = base.substring(base.lastIndexOf('/') + 1);
        mNameToFile.put(base, new File(url.toExternalForm()));
        File target = new File(resourceDir, base);
        Closer closer = Closer.create();
        try {
            FileOutputStream output = closer.register(new FileOutputStream(target));
            InputStream input = closer.register(url.openStream());
            ByteStreams.copy(input, output);
        } catch (Throwable e) {
            closer.rethrow(e);
        } finally {
            closer.close();
        }
        return resourceDir.getName() + '/' + encodeUrl(base);
    }
    return null;
}
 

实例 10


private static void loadClassNamesFromJarFile(File jarFile,
        Multimap<String, File> newClassNameLocations) throws IOException {
    Closer closer = Closer.create();
    InputStream s = new FileInputStream(jarFile);
    JarInputStream jarIn = closer.register(new JarInputStream(s));
    try {
        loadClassNamesFromManifestClassPath(jarIn, jarFile, newClassNameLocations);
        loadClassNamesFromJarInputStream(jarIn, jarFile, newClassNameLocations);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}
 

实例 11


private void readFromUrl(String url, final HttpOutputMessage output) throws IOException {
    final HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
    conn.setConnectTimeout(60 * 1000);
    conn.setReadTimeout(60 * 1000);
    conn.setRequestMethod("GET");
    try {
        output.setStatus(conn.getResponseCode());
        final String contentType = conn.getContentType();
        if (contentType != null) {
            output.setContentType(contentType);
        }
        // for download files
        final String contentDisposition = conn.getHeaderField("Content-Disposition");
        if (contentDisposition != null) {
            output.addHttpHeader("Content-Disposition", contentDisposition);
        }
        Closer closer = Closer.create();
        try {
            InputStream errorStream = closer.register(conn.getErrorStream());
            InputStream in = errorStream != null ? errorStream : closer.register(conn.getInputStream());
            ByteStreams.copy(in, closer.register(output.getOutputStream()));
        } catch (Throwable e) {
            throw closer.rethrow(e);
        } finally {
            closer.close();
        }
    } finally {
        conn.disconnect();
    }
}
 

实例 12


private void doRequest(String url, String method, final OutputProvider output) throws IOException {
    final HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
    conn.setConnectTimeout(60 * 1000);
    conn.setReadTimeout(60 * 1000);
    conn.setRequestMethod(method);
    try {
        if (output instanceof HttpOutputMessage) {
            HttpOutputMessage httpOutput = (HttpOutputMessage)output;
            httpOutput.setStatus(conn.getResponseCode());
            final String contentType = conn.getContentType();
            if (contentType != null) {
                httpOutput.addHttpHeader("Content-Type", contentType);
            }
            // for download files
            final String contentDisposition = conn.getHeaderField("Content-Disposition");
            if (contentDisposition != null) {
                httpOutput.addHttpHeader("Content-Disposition", contentDisposition);
            }
        }
        Closer closer = Closer.create();
        try {
            ByteStreams.copy(closer.register(conn.getInputStream()), closer.register(output.getOutputStream()));
        } catch (Throwable e) {
            throw closer.rethrow(e);
        } finally {
            closer.close();
        }
    } finally {
        conn.disconnect();
    }
}
 

实例 13


/**
 * Check to see if there was an error processing an rrdtool command
 */
private void checkErrorStream(Process process) throws Exception {
        Closer closer = Closer.create();
        try {
                InputStream is = closer.register(process.getErrorStream());
                // rrdtool should use platform encoding (unless you did something
                // very strange with your installation of rrdtool). So let's be
                // explicit and use the presumed correct encoding to read errors.
                InputStreamReader isr = closer.register(new InputStreamReader(is, Charset.defaultCharset()));
                BufferedReader br = closer.register(new BufferedReader(isr));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                        sb.append(line);
                }
                if (sb.length() > 0) {
                        throw new RuntimeException(sb.toString());
                }
        } catch (Throwable t) {
                throw closer.rethrow(t);
        } finally {
                closer.close();
        }
}
 

实例 14


private void logValue(Server server, Query query, List<String> typeNames, Result result, Map.Entry<String, Object> values) throws IOException {
        Object value = values.getValue();
        if (value != null && isNumeric(value)) {
                Closer closer = Closer.create();
                try {
                        closer.register(MDC.putCloseable("server", computeAlias(server)));
                        closer.register(MDC.putCloseable("metric", KeyUtils.getKeyString(server, query, result, values, typeNames, null)));
                        closer.register(MDC.putCloseable("value", value.toString()));
                        if (result.getKeyAlias() != null) {
                                closer.register(MDC.putCloseable("resultAlias", result.getKeyAlias()));
                        }
                        closer.register(MDC.putCloseable("attributeName", result.getAttributeName()));
                        closer.register(MDC.putCloseable("key", values.getKey()));
                        closer.register(MDC.putCloseable("epoch", valueOf(result.getEpoch())));
                        logger.info("");
                } catch (Throwable t) {
                        closer.rethrow(t);
                } finally {
                        closer.close();
                }
        }
}
 
讨论
淘淘あ西西 profile image