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

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

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes all Closeable instances that have been added to this Closer .

Usage

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  w  w  . j  a v  a2s  . com
    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:tachyon.command.TFsShell.java

/**
 * Copies a file specified by argv from the filesystem to the local filesystem.
 * /*from   w  w  w .  j a  v a2 s  .  co  m*/
 * @param argv [] Array of arguments given by the user's input from the terminal
 * @return 0 if command is successful, -1 if an error occurred.
 * @throws IOException
 */
public int copyToLocal(String[] argv) throws IOException {
    if (argv.length != 3) {
        System.out.println("Usage: tfs copyToLocal <src> <localdst>");
        return -1;
    }

    TachyonURI srcPath = new TachyonURI(argv[1]);
    String dstPath = argv[2];
    File dst = new File(dstPath);
    TachyonFS tachyonClient = createFS(srcPath);
    TachyonFile tFile = tachyonClient.getFile(srcPath);

    // tachyonClient.getFile() catches FileDoesNotExist exceptions and returns null
    if (tFile == null) {
        throw new IOException(srcPath.toString());
    }

    Closer closer = Closer.create();
    try {
        InStream is = closer.register(tFile.getInStream(ReadType.NO_CACHE));
        FileOutputStream out = closer.register(new FileOutputStream(dst));
        byte[] buf = new byte[512];
        int t = is.read(buf);
        while (t != -1) {
            out.write(buf, 0, t);
            t = is.read(buf);
        }
        System.out.println("Copied " + srcPath + " to " + dstPath);
        return 0;
    } finally {
        closer.close();
    }
}

From source file:org.jclouds.vsphere.compute.config.VSphereComputeServiceAdapter.java

@Override
public VirtualMachine getNode(String vmName) {
    Closer closer = Closer.create();
    VSphereServiceInstance instance = serviceInstance.get();
    closer.register(instance);// w w  w  . j  a v a  2s.  c o m
    try {
        try {
            return getVM(vmName, instance.getInstance().getRootFolder());
        } catch (Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    } catch (IOException e) {
        Throwables.propagateIfPossible(e);
    }
    return null;
}

From source file:com.android.builder.compiling.BuildConfigGenerator.java

/**
 * Generates the BuildConfig class./*ww  w .ja va2 s  .c  o  m*/
 */
public void generate() throws IOException {
    File pkgFolder = getFolderPath();
    if (!pkgFolder.isDirectory()) {
        if (!pkgFolder.mkdirs()) {
            throw new RuntimeException("Failed to create " + pkgFolder.getAbsolutePath());
        }
    }

    File buildConfigJava = new File(pkgFolder, BUILD_CONFIG_NAME);

    Closer closer = Closer.create();
    try {
        FileOutputStream fos = closer.register(new FileOutputStream(buildConfigJava));
        OutputStreamWriter out = closer.register(new OutputStreamWriter(fos, Charsets.UTF_8));
        JavaWriter writer = closer.register(new JavaWriter(out));

        writer.emitJavadoc("Automatically generated file. DO NOT MODIFY").emitPackage(mBuildConfigPackageName)
                .beginType("BuildConfig", "class", PUBLIC_FINAL);

        for (ClassField field : mFields) {
            emitClassField(writer, field);
        }

        for (Object item : mItems) {
            if (item instanceof ClassField) {
                emitClassField(writer, (ClassField) item);
            } else if (item instanceof String) {
                writer.emitSingleLineComment((String) item);
            }
        }

        writer.endType();
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:org.jclouds.vsphere.compute.config.VSphereComputeServiceAdapter.java

@Override
public Iterable<VirtualMachine> listNodes() {
    Closer closer = Closer.create();
    VSphereServiceInstance instance = serviceInstance.get();
    closer.register(instance);//  w  ww .j a va 2  s  .  co  m

    try {
        try {
            return listNodes(instance);
        } catch (Throwable e) {
            logger.error("Can't find vm", e);
            throw closer.rethrow(e);
        } finally {
            closer.close();
        }
    } catch (Throwable t) {
        return ImmutableSet.of();
    }
}

From source file:tachyon.worker.tiered.StorageDir.java

/**
 * Copy block file from this StorageDir to another StorageDir, the caller must ensure that this
 * block is locked during copying/*from ww w.java  2s .  com*/
 *
 * @param blockId Id of the block
 * @param dstDir destination StorageDir
 * @return true if success, false otherwise
 * @throws IOException
 */
public boolean copyBlock(long blockId, StorageDir dstDir) throws IOException {
    long size = getBlockSize(blockId);
    if (size == -1) {
        LOG.error("Block file doesn't exist! blockId:{}", blockId);
        return false;
    }
    boolean copySuccess = false;
    Closer closer = Closer.create();
    ByteBuffer buffer = null;
    BlockHandler bhDst = null;
    try {
        BlockHandler bhSrc = closer.register(getBlockHandler(blockId));
        bhDst = closer.register(dstDir.getBlockHandler(blockId));
        buffer = bhSrc.read(0, (int) size);
        copySuccess = (bhDst.append(0, buffer) == size);
    } finally {
        closer.close();
        CommonUtils.cleanDirectBuffer(buffer);
    }
    if (copySuccess) {
        Long accessTimeMs = mLastBlockAccessTimeMs.get(blockId);
        if (accessTimeMs != null) {
            dstDir.addBlockId(blockId, size, accessTimeMs, true);
        } else {
            // The block had been freed during our copy. Because we lock the block before copy, the
            // actual block file is not deleted but the blockId is deleted from mLastBlockAccessTimeMs.
            // So we delete the copied block and return the space. We still think copyBlock is
            // successful and return true as nothing needed to be copied.
            bhDst.delete();
            dstDir.returnSpace(Users.MIGRATE_DATA_USER_ID, size);
        }
    }
    return copySuccess;
}

From source file:gobblin.metastore.FsStateStore.java

@Override
@SuppressWarnings("unchecked")
public T get(String storeName, String tableName, String stateId) throws IOException {
    Path tablePath = new Path(new Path(this.storeRootDir, storeName), tableName);
    if (!this.fs.exists(tablePath)) {
        return null;
    }//from   w  w w.j  a v a  2 s . c  o m

    Closer closer = Closer.create();
    try {
        @SuppressWarnings("deprecation")
        SequenceFile.Reader reader = closer.register(new SequenceFile.Reader(this.fs, tablePath, this.conf));
        try {
            Text key = new Text();
            T state = this.stateClass.newInstance();
            while (reader.next(key)) {
                state = (T) reader.getCurrentValue(state);
                if (key.toString().equals(stateId)) {
                    return state;
                }
            }
        } catch (Exception e) {
            throw new IOException(
                    "failure retrieving state from storeName " + storeName + " tableName " + tableName, e);
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }

    return null;
}

From source file:tachyon.command.TFsShell.java

private int copyPath(File src, TachyonFS tachyonClient, TachyonURI dstPath) throws IOException {
    if (!src.isDirectory()) {
        int fileId = tachyonClient.createFile(dstPath);
        if (fileId == -1) {
            return -1;
        }//from  ww w  .  j  a va2  s  .c o  m
        TachyonFile tFile = tachyonClient.getFile(fileId);
        Closer closer = Closer.create();
        try {
            OutStream os = closer.register(tFile.getOutStream(UserConf.get().DEFAULT_WRITE_TYPE));
            FileInputStream in = closer.register(new FileInputStream(src));
            FileChannel channel = closer.register(in.getChannel());
            ByteBuffer buf = ByteBuffer.allocate(Constants.KB);
            while (channel.read(buf) != -1) {
                buf.flip();
                os.write(buf.array(), 0, buf.limit());
            }
        } finally {
            closer.close();
        }
        return 0;
    } else {
        tachyonClient.mkdir(dstPath);
        for (String file : src.list()) {
            TachyonURI newPath = new TachyonURI(dstPath, new TachyonURI(file));
            File srcFile = new File(src, file);
            if (copyPath(srcFile, tachyonClient, newPath) == -1) {
                return -1;
            }
        }
    }
    return 0;
}

From source file:gobblin.example.wikipedia.WikipediaExtractor.java

private JsonElement performHttpQuery(String rootUrl, Map<String, String> query)
        throws URISyntaxException, IOException {
    if (null == this.httpClient) {
        this.httpClient = createHttpClient();
    }/*w  w w  . j av  a 2 s . co m*/
    HttpUriRequest req = createHttpRequest(rootUrl, query);

    Closer closer = Closer.create();

    StringBuilder sb = new StringBuilder();
    try {
        HttpResponse response = sendHttpRequest(req, this.httpClient);
        if (response instanceof CloseableHttpResponse) {
            closer.register((CloseableHttpResponse) response);
        }
        BufferedReader br = closer
                .register(new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
                        ConfigurationKeys.DEFAULT_CHARSET_ENCODING)));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            LOG.error("IOException in Closer.close() while performing query " + req + ": " + e, e);
        }
    }

    if (Strings.isNullOrEmpty(sb.toString())) {
        LOG.warn("Received empty response for query: " + req);
        return new JsonObject();
    }

    JsonElement jsonElement = GSON.fromJson(sb.toString(), JsonElement.class);
    return jsonElement;

}

From source file:gobblin.yarn.GobblinYarnAppLauncher.java

private void setupSecurityTokens(ContainerLaunchContext containerLaunchContext) throws IOException {
    Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials();
    String tokenRenewer = this.yarnConfiguration.get(YarnConfiguration.RM_PRINCIPAL);
    if (tokenRenewer == null || tokenRenewer.length() == 0) {
        throw new IOException("Failed to get master Kerberos principal for the RM to use as renewer");
    }/*w  w w.  j  a  va 2  s .c  o  m*/

    // For now, only getting tokens for the default file-system.
    Token<?> tokens[] = this.fs.addDelegationTokens(tokenRenewer, credentials);
    if (tokens != null) {
        for (Token<?> token : tokens) {
            LOGGER.info("Got delegation token for " + this.fs.getUri() + "; " + token);
        }
    }

    Closer closer = Closer.create();
    try {
        DataOutputBuffer dataOutputBuffer = closer.register(new DataOutputBuffer());
        credentials.writeTokenStorageToStream(dataOutputBuffer);
        ByteBuffer fsTokens = ByteBuffer.wrap(dataOutputBuffer.getData(), 0, dataOutputBuffer.getLength());
        containerLaunchContext.setTokens(fsTokens);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}