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:org.apache.jackrabbit.oak.run.CheckpointsCommand.java

@Override
public void execute(String... args) throws Exception {
    OptionParser parser = new OptionParser();
    OptionSpec segmentTar = parser.accepts("segment-tar", "Use oak-segment-tar instead of oak-segment");
    OptionSet options = parser.parse(args);

    if (options.nonOptionArguments().isEmpty()) {
        System.out.println(//from ww  w. j a  v a 2s  .  c o m
                "usage: checkpoints {<path>|<mongo-uri>} [list|rm-all|rm-unreferenced|rm <checkpoint>] [--segment-tar]");
        System.exit(1);
    }

    boolean success = false;
    Checkpoints cps;
    Closer closer = Closer.create();
    try {
        String op = "list";
        if (options.nonOptionArguments().size() >= 2) {
            op = options.nonOptionArguments().get(1).toString();
            if (!"list".equals(op) && !"rm-all".equals(op) && !"rm-unreferenced".equals(op)
                    && !"rm".equals(op)) {
                failWith("Unknown command.");
            }
        }

        String connection = options.nonOptionArguments().get(0).toString();
        if (connection.startsWith(MongoURI.MONGODB_PREFIX)) {
            MongoClientURI uri = new MongoClientURI(connection);
            MongoClient client = new MongoClient(uri);
            final DocumentNodeStore store = new DocumentMK.Builder().setMongoDB(client.getDB(uri.getDatabase()))
                    .getNodeStore();
            closer.register(Utils.asCloseable(store));
            cps = Checkpoints.onDocumentMK(store);
        } else if (options.has(segmentTar)) {
            cps = Checkpoints.onSegmentTar(new File(connection), closer);
        } else {
            cps = Checkpoints.onSegment(new File(connection), closer);
        }

        System.out.println("Checkpoints " + connection);
        if ("list".equals(op)) {
            int cnt = 0;
            for (Checkpoints.CP cp : cps.list()) {
                System.out.printf("- %s created %s expires %s%n", cp.id, new Timestamp(cp.created),
                        new Timestamp(cp.expires));
                cnt++;
            }
            System.out.println("Found " + cnt + " checkpoints");
        } else if ("rm-all".equals(op)) {
            long time = System.currentTimeMillis();
            long cnt = cps.removeAll();
            time = System.currentTimeMillis() - time;
            if (cnt != -1) {
                System.out.println("Removed " + cnt + " checkpoints in " + time + "ms.");
            } else {
                failWith("Failed to remove all checkpoints.");
            }
        } else if ("rm-unreferenced".equals(op)) {
            long time = System.currentTimeMillis();
            long cnt = cps.removeUnreferenced();
            time = System.currentTimeMillis() - time;
            if (cnt != -1) {
                System.out.println("Removed " + cnt + " checkpoints in " + time + "ms.");
            } else {
                failWith("Failed to remove unreferenced checkpoints.");
            }
        } else if ("rm".equals(op)) {
            if (options.nonOptionArguments().size() < 3) {
                failWith("Missing checkpoint id");
            } else {
                String cp = options.nonOptionArguments().get(2).toString();
                long time = System.currentTimeMillis();
                int cnt = cps.remove(cp);
                time = System.currentTimeMillis() - time;
                if (cnt != 0) {
                    if (cnt == 1) {
                        System.out.println("Removed checkpoint " + cp + " in " + time + "ms.");
                    } else {
                        failWith("Failed to remove checkpoint " + cp);
                    }
                } else {
                    failWith("Checkpoint '" + cp + "' not found.");
                }
            }
        }
        success = true;
    } catch (Throwable t) {
        System.err.println(t.getMessage());
    } finally {
        closer.close();
    }
    if (!success) {
        System.exit(1);
    }
}

From source file:com.google.caliper.config.LoggingConfigLoader.java

@Inject
void loadLoggingConfig() {
    File loggingPropertiesFile = new File(caliperDirectory, "logging.properties");
    if (loggingPropertiesFile.isFile()) {
        Closer closer = Closer.create();
        FileInputStream fis = null;
        try {//w  ww. j  a  v a2s  . c o m
            fis = closer.register(new FileInputStream(loggingPropertiesFile));
            logManager.readConfiguration(fis);
        } catch (SecurityException e) {
            logConfigurationException(e);
        } catch (IOException e) {
            logConfigurationException(e);
        } finally {
            try {
                closer.close();
            } catch (IOException e) {
                logger.log(SEVERE, "could not close " + loggingPropertiesFile, e);
            }
        }
        logger.info(String.format("Using logging configuration at %s", loggingPropertiesFile));
    } else {
        try {
            maybeLoadDefaultLogConfiguration(LogManager.getLogManager());
        } catch (SecurityException e) {
            logConfigurationException(e);
        } catch (IOException e) {
            logConfigurationException(e);
        }
    }
}

From source file:gobblin.metrics.MetricReportReporter.java

public MetricReportReporter(Builder<?> builder) {
    super(builder.registry, builder.name, builder.filter, builder.rateUnit, builder.durationUnit);
    this.tags = ImmutableMap.copyOf(builder.tags);
    this.closer = Closer.create();
}

From source file:com.fullcontact.sstable.hadoop.IndexOffsetScanner.java

/**
 * Hadoop fs based version./*from  w w w . ja v a 2  s. com*/
 *
 * @param path File path.
 * @param fileSystem File system.
 */
public IndexOffsetScanner(final Path path, final FileSystem fileSystem) {
    closer = Closer.create();
    try {
        final FSDataInputStream inputStream = fileSystem.open(path);
        this.input = closer.register(new DataInputStream(new FastBufferedInputStream(inputStream)));
    } catch (IOException e) {
        throw new IOError(e);
    }
}

From source file:com.github.fge.jackson.JsonLoader.java

/**
 * Read a {@link JsonNode} from a resource path.
 *
 * <p>This method first tries and loads the resource using {@link
 * Class#getResource(String)}; if not found, is tries and uses the context
 * classloader and if this is not found, this class's classloader.</p>
 *
 * <p>This method throws an {@link IOException} if the resource does not
 * exist.</p>/*from  www . j  ava  2s.  c  o m*/
 *
 * @param resource the path to the resource (<strong>must</strong> begin
 * with a {@code /})
 * @return the JSON document at the resource
 * @throws IllegalArgumentException resource path does not begin with a
 * {@code /}
 * @throws IOException there was a problem loading the resource, or the JSON
 * document is invalid
 */
public static JsonNode fromResource(@Nonnull final String resource) throws IOException {
    Preconditions.checkNotNull(resource);
    Preconditions.checkArgument(resource.startsWith("/"), "resource path does not start with a '/'");
    URL url;
    url = JsonLoader.class.getResource(resource);
    if (url == null) {
        final ClassLoader classLoader = Objects.firstNonNull(Thread.currentThread().getContextClassLoader(),
                JsonLoader.class.getClassLoader());
        final String s = INITIAL_SLASH.matcher(resource).replaceFirst("");
        url = classLoader.getResource(s);
    }
    if (url == null)
        throw new IOException("resource " + resource + " not found");

    final Closer closer = Closer.create();
    final JsonNode ret;
    final InputStream in;

    try {
        in = closer.register(url.openStream());
        ret = READER.fromInputStream(in);
    } finally {
        closer.close();
    }

    return ret;
}

From source file:org.jclouds.vsphere.functions.CreateOrGetTagsId.java

@Inject
public synchronized void start() {
    Closer closer = Closer.create();
    VSphereServiceInstance client = serviceInstance.get();
    closer.register(client);//from  w  w w  . j  a  v  a 2  s  .com
    try {
        try {

            CustomFieldDef[] customFieldDefs = client.getInstance().getCustomFieldsManager().getField();
            if (null != customFieldDefs) {
                for (CustomFieldDef field : customFieldDefs) {
                    if (field.getName().equalsIgnoreCase(VSphereConstants.JCLOUDS_TAGS)) {
                        customFieldDefMap.put(VSphereConstants.JCLOUDS_TAGS, field);
                    } else if (field.getName().equalsIgnoreCase(VSphereConstants.JCLOUDS_GROUP)) {
                        customFieldDefMap.put(VSphereConstants.JCLOUDS_GROUP, field);
                    }
                }
            }
            if (!customFieldDefMap.containsKey(VSphereConstants.JCLOUDS_TAGS))
                customFieldDefMap.put(VSphereConstants.JCLOUDS_TAGS,
                        client.getInstance().getCustomFieldsManager()
                                .addCustomFieldDef(VSphereConstants.JCLOUDS_TAGS, null, null, null));
            if (!customFieldDefMap.containsKey(VSphereConstants.JCLOUDS_GROUP))
                customFieldDefMap.put(VSphereConstants.JCLOUDS_GROUP,
                        client.getInstance().getCustomFieldsManager()
                                .addCustomFieldDef(VSphereConstants.JCLOUDS_GROUP, null, null, null));
        } catch (Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    } catch (IOException e) {
        Throwables.propagate(e);
    }
}

From source file:gobblin.source.extractor.extract.google.GoogleDriveFsHelper.java

public GoogleDriveFsHelper(State state, Drive client) {
    this(state, client, Closer.create());
}

From source file:com.googlecode.jmxtrans.model.output.SensuWriter2.java

@Override
public void write(@Nonnull Writer writer, @Nonnull Server server, @Nonnull Query query,
        @Nonnull Iterable<Result> results) throws IOException {
    Closer closer = Closer.create();
    try {/*from  w w w  .  j ava2s.  c o  m*/
        JsonGenerator g = closer.register(jsonFactory.createGenerator(writer));
        g.useDefaultPrettyPrinter();
        g.writeStartObject();
        g.writeStringField("name", "jmxtrans");
        g.writeStringField("type", "metric");
        g.writeStringField("handler", "graphite");

        StringWriter temporaryWriter = closer.register(new StringWriter());
        graphiteWriter.write(temporaryWriter, server, query, results);

        g.writeStringField("output", temporaryWriter.toString());
        g.writeEndObject();
        g.flush();
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

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

/**
 * Creates a new local block output stream.
 *
 * @param blockId the block id//from w ww  .  ja  v  a 2  s .c  om
 * @param blockSize the block size
 * @throws IOException if an I/O error occurs
 */
public LocalBlockOutStream(long blockId, long blockSize) throws IOException {
    super(blockId, blockSize);
    mCloser = Closer.create();
    mWorkerClient = mContext.acquireWorkerClient(NetworkAddressUtils.getLocalHostName(ClientContext.getConf()));

    try {
        long initialSize = ClientContext.getConf().getBytes(Constants.USER_FILE_BUFFER_BYTES);
        String blockPath = mWorkerClient.requestBlockLocation(mBlockId, initialSize);
        mReservedBytes += initialSize;
        FileUtils.createBlockPath(blockPath);
        RandomAccessFile localFile = mCloser.register(new RandomAccessFile(blockPath, "rw"));
        mLocalFileChannel = mCloser.register(localFile.getChannel());
        // Change the permission of the temporary file in order that the worker can move it.
        LOG.info("LocalBlockOutStream created new file block, block path: {}", blockPath);
    } catch (IOException ioe) {
        mContext.releaseWorkerClient(mWorkerClient);
        throw ioe;
    }
}

From source file:com.moz.fiji.commons.monitoring.CompoundNotifier.java

/** {@inheritDoc} */
@Override//from w  w  w . j a  va 2s  . c  om
public void close() throws IOException {
    final Closer closer = Closer.create();
    for (final Notifier notifier : mNotifiers) {
        closer.register(notifier);
    }
    closer.close();
}