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

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

Introduction

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

Prototype

public RuntimeException rethrow(Throwable e) throws IOException 

Source Link

Document

Stores the given throwable and rethrows it.

Usage

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);/*ww w.j a  va 2 s.  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./*w w w  .  jav a 2  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 w  w.  j av  a 2s.  c o 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:gobblin.example.wikipedia.WikipediaExtractor.java

private JsonElement performHttpQuery(String rootUrl, Map<String, String> query)
        throws URISyntaxException, IOException {
    if (null == this.httpClient) {
        this.httpClient = createHttpClient();
    }/*from   w  ww.  j a va 2  s . com*/
    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.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 .  jav  a2 s.c  om*/

    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: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");
    }/*from   w  w w. j  a v a 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();
    }
}

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

@Override
public Image getImage(String imageName) {
    Closer closer = Closer.create();
    VSphereServiceInstance instance = serviceInstance.get();
    closer.register(instance);/*from  w w  w .  j  a  v  a2 s .  c  om*/
    try {
        try {
            return virtualMachineToImage
                    .apply(getVMwareTemplate(imageName, 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.internal.incremental.DependencyDataStore.java

/**
 * Saves the dependency data to a given file.
 *
 * @param file the file to save the data to.
 * @throws IOException//from   ww w .  ja  v  a 2s  .  c o  m
 */
public void saveTo(@NonNull File file) throws IOException {

    Closer closer = Closer.create();
    try {
        FileOutputStream fos = closer.register(new FileOutputStream(file));
        fos.write(TAG_HEADER);
        writeInt(fos, CURRENT_VERSION);

        for (DependencyData data : getData()) {
            fos.write(TAG_START);
            writePath(fos, data.getMainFile());

            for (String path : data.getSecondaryFiles()) {
                fos.write(TAG_2NDARY_FILE);
                writePath(fos, path);
            }

            for (String path : data.getOutputFiles()) {
                fos.write(TAG_OUTPUT);
                writePath(fos, path);
            }

            for (String path : data.getSecondaryOutputFiles()) {
                fos.write(TAG_2NDARY_OUTPUT);
                writePath(fos, path);
            }

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

From source file:gobblin.metastore.FsStateStore.java

@Override
@SuppressWarnings("unchecked")
public List<T> getAll(String storeName, String tableName) throws IOException {
    List<T> states = Lists.newArrayList();

    Path tablePath = new Path(new Path(this.storeRootDir, storeName), tableName);
    if (!this.fs.exists(tablePath)) {
        return states;
    }//  w  w w. j ava2  s.  co 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);
                states.add(state);
                // We need a new object for each read state
                state = this.stateClass.newInstance();
            }
        } 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 states;
}

From source file:com.tinspx.util.io.ByteUtils.java

/**
 * Copies as many bytes as possible from {@code from} into {@code to},
 * returning the total number of bytes copied.
 * //  www  . j  av  a2s.co m
 * @param from the source to read bytes from
 * @param to the destination to copy bytes read from {@code from} into
 * @return the total number of bytes copied from {@code from} to {@code to}
 * @throws IOException if an IOException occurs
 * @throws NullPointerException if either {@code from} or {@code to} is null
 */
@ThreadLocalArray(8192)
public static int copy(@NonNull ByteSource from, @NonNull ByteBuffer to) throws IOException {
    final Closer closer = Closer.create();
    try {
        return copy(closer.register(from.openStream()), to);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}