Example usage for com.google.common.io Closer create

List of usage examples for com.google.common.io Closer create

Introduction

In this page you can find the example usage for com.google.common.io Closer create.

Prototype

public static Closer create() 

Source Link

Document

Creates a new Closer .

Usage

From source file:tachyon.client.block.LocalBlockInStream.java

/**
 * Creates a new local block input stream.
 *
 * @param blockId the block id//from w w  w  .j  av a2 s  . c om
 * @throws IOException if I/O error occurs
 */
public LocalBlockInStream(long blockId, long blockSize) throws IOException {
    super(blockId, blockSize);
    mContext = BlockStoreContext.INSTANCE;

    mCloser = Closer.create();
    mWorkerClient = mContext.acquireWorkerClient(NetworkAddressUtils.getLocalHostName(ClientContext.getConf()));
    FileChannel localFileChannel = null;

    try {
        String blockPath = mWorkerClient.lockBlock(blockId);
        if (blockPath == null) {
            throw new IOException(ExceptionMessage.BLOCK_NOT_LOCALLY_AVAILABLE.getMessage(mBlockId));
        }
        RandomAccessFile localFile = mCloser.register(new RandomAccessFile(blockPath, "r"));
        localFileChannel = mCloser.register(localFile.getChannel());
    } catch (IOException e) {
        mContext.releaseWorkerClient(mWorkerClient);
        throw e;
    }

    mLocalFileChannel = localFileChannel;
}

From source file:com.pants.examples.annotation.processor.ExampleProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        return false;
    }//from   w  w w  .j av  a  2  s .com

    FileObject outputFile = createResource("" /* no package */, EXAMPLES_FILE_NAME);
    if (outputFile != null) {
        Closer closer = Closer.create();
        try {
            PrintWriter writer = closer.register(new PrintWriter(outputFile.openWriter()));
            writer.println("{");
            for (TypeElement appAnnotation : annotations) {
                Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(appAnnotation);
                Set<TypeElement> exampleElements = ElementFilter.typesIn(annotatedElements);
                for (Element elem : exampleElements) {
                    String typeName = elem.getSimpleName().toString();
                    for (AnnotationMirror mirror : elem.getAnnotationMirrors()) {
                        String n = ((TypeElement) mirror.getAnnotationType().asElement()).getQualifiedName()
                                .toString();
                        if (Example.class.getCanonicalName().equals(n)) {
                            Map<? extends ExecutableElement, ? extends AnnotationValue> values = mirror
                                    .getElementValues();
                            for (ExecutableElement key : values.keySet()) {
                                if ("value".equals(key.getSimpleName().toString())) {
                                    String exampleValue = (String) values.get(key).getValue();
                                    if (exampleValue != null) {
                                        writer.println("  {'type' : '" + typeName + "', 'value': '"
                                                + exampleValue + "'},");
                                    }
                                }
                            }
                        }
                    }
                }
                writer.println("}\n");
            }
            closer.close();
            log(Diagnostic.Kind.NOTE, "Generated resource '%s'", outputFile.toUri());
        } catch (IOException e) {
            error("Couldn't write to '%s': %s", outputFile.toUri(), e);
        }
    }
    return true;
}

From source file:fr.techcode.downloadix.validation.FileValidator.java

/**
 * Validate if the file isn't corrupt//from   w w w . ja  va  2 s.  c om
 *
 * @param file File to check
 * @return Valid or Corrupt
 */
@Override
public boolean isValid(File file) {
    // Check if the file exist
    if (!file.exists())
        return false;

    // Get bytes from a file
    byte[] datas = null;
    Closer closer = Closer.create();
    try {
        try {
            FileInputStream stream = closer.register(new FileInputStream(file));
            datas = ByteStreams.toByteArray(stream);
        } catch (Throwable throwable) {
            throw closer.rethrow(throwable);
        } finally {
            closer.close();
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return datas != null && algorithm.hashBytes(datas).toString().equalsIgnoreCase(hash);
}

From source file:alluxio.client.block.stream.BlockInStream.java

/**
 * Creates an instance of local {@link BlockInStream} that reads from local worker.
 *
 * @param blockId the block ID/*  ww  w  .  ja  va  2  s.  com*/
 * @param blockSize the block size
 * @param workerNetAddress the worker network address
 * @param context the file system context
 * @param options the options
 * @throws IOException if it fails to create an instance
 * @return the {@link BlockInStream} created
 */
// TODO(peis): Use options idiom (ALLUXIO-2579).
public static BlockInStream createLocalBlockInStream(long blockId, long blockSize,
        WorkerNetAddress workerNetAddress, FileSystemContext context, InStreamOptions options)
        throws IOException {
    Closer closer = Closer.create();
    try {
        BlockWorkerClient blockWorkerClient = closer
                .register(context.createBlockWorkerClient(workerNetAddress));
        LockBlockResource lockBlockResource = closer
                .register(blockWorkerClient.lockBlock(blockId, LockBlockOptions.defaults()));
        PacketInStream inStream = closer.register(PacketInStream
                .createLocalPacketInStream(lockBlockResource.getResult().getBlockPath(), blockId, blockSize));
        blockWorkerClient.accessBlock(blockId);
        return new BlockInStream(inStream, blockWorkerClient, closer, options);
    } catch (AlluxioException | IOException e) {
        CommonUtils.closeQuietly(closer);
        throw CommonUtils.castToIOException(e);
    }
}

From source file:com.facebook.buck.remoteexecution.grpc.server.GrpcServer.java

@Override
public void close() throws IOException {
    try (Closer closer = Closer.create()) {
        closer.register(server::shutdown);
        closer.register(workDir);/*from w w w .ja va2 s .c o  m*/
    }
    try {
        server.awaitTermination(3, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jclouds.vsphere.suppliers.VSphereLocationSupplier.java

private Set<? extends Location> getClusters() {
    Set<Location> hosts = Sets.newHashSet();
    Closer closer = Closer.create();
    VSphereServiceInstance instance = serviceInstance.get();
    closer.register(instance);/*from  w  ww.  j a v  a2 s  . c  o  m*/
    try {
        try {

            ManagedEntity[] clusterEntities = new InventoryNavigator(instance.getInstance().getRootFolder())
                    .searchManagedEntities("ClusterComputeResource");

            for (ManagedEntity cluster : clusterEntities) {
                Location location = new LocationImpl(LocationScope.ZONE, cluster.getName(), cluster.getName(),
                        null, ImmutableSet.of(""), Maps.<String, Object>newHashMap());
                hosts.add(location);
            }

            hosts.add(new LocationImpl(LocationScope.ZONE, "default", "default", null, ImmutableSet.of(""),
                    Maps.<String, Object>newHashMap()));

            return hosts;
        } catch (Exception e) {
            logger.error("Problem in finding a valid cluster", e);
            closer.rethrow(e);
        } finally {
            closer.close();
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

    return hosts;
}

From source file:com.android.build.gradle.internal.tasks.FilteredJarCopyTask.java

@TaskAction
@Override/*from ww  w .jav  a  2s. c om*/
public void copy() throws IOException {
    if (excludes.isEmpty()) {
        super.copy();
    }

    // create Pattern Objects.
    List<Pattern> patterns = excludes.stream().map(Pattern::compile).collect(Collectors.toList());

    byte[] buffer = new byte[4096];

    try (Closer closer = Closer.create()) {
        FileOutputStream fos = closer.register(new FileOutputStream(outputFile));
        BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos));
        ZipOutputStream zos = closer.register(new ZipOutputStream(bos));

        FileInputStream fis = closer.register(new FileInputStream(inputFile));
        BufferedInputStream bis = closer.register(new BufferedInputStream(fis));
        ZipInputStream zis = closer.register(new ZipInputStream(bis));

        // loop on the entries of the intermediary package and put them in the final package.
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            String name = entry.getName();

            if (!checkEntry(patterns, name)) {
                continue;
            }

            JarEntry newEntry;

            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }

            // add the entry to the jar archive
            zos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                zos.write(buffer, 0, count);
            }

            zos.closeEntry();
            zis.closeEntry();
        }
    }
}

From source file:zipkin.storage.cassandra3.DefaultSessionFactory.java

/**
 * Creates a session and ensures schema if configured. Closes the cluster and session if any
 * exception occurred./*from www  .  j a  v a  2s . c om*/
 */
@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;
    }
}

From source file:zipkin2.storage.cassandra.DefaultSessionFactory.java

/**
 * Creates a session and ensures schema if configured. Closes the cluster and session if any
 * exception occurred./*from   ww w  .j  a v  a2 s  . co  m*/
 */
@Override
public Session create(CassandraStorage cassandra) {
    Closer closer = Closer.create();
    try {
        Cluster cluster = closer.register(buildCluster(cassandra));
        cluster.register(new QueryLogger.Builder().build());
        Session session;
        String keyspace = cassandra.keyspace();
        if (cassandra.ensureSchema()) {
            session = closer.register(cluster.connect());
            Schema.ensureExists(keyspace, cassandra.searchEnabled(), session);
            session.execute("USE " + keyspace);
        } else {
            LOG.debug("Skipping schema check on keyspace {} as ensureSchema was false", keyspace);
            session = cluster.connect(keyspace);
        }

        initializeUDTs(session);

        return session;
    } catch (RuntimeException e) {
        try {
            closer.close();
        } catch (IOException ignored) {
        }
        throw e;
    }
}

From source file:org.ow2.proactive.scheduler.rest.readers.TaskResultReader.java

@Override
public Serializable readFrom(Class<Serializable> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    Closer closer = Closer.create();
    try {//from   w  ww. ja  v a 2 s. c  o m
        entityStream = closer.register(entityStream);
        return CharStreams.toString(new InputStreamReader(entityStream));
    } catch (IOException ioe) {
        throw closer.rethrow(ioe);
    } finally {
        closer.close();
    }
}