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:net.derquinse.common.io.BytesTransformer.java

/** Transforms a byte source. */
public void transform(ByteSource input, ByteSink output) throws IOException {
    checkInput(input);// ww w  .j  av a2 s.c om
    checkOutput(output);
    final Closer closer = Closer.create();
    try {
        transform(closer.register(input.openStream()), closer.register(output.openStream()));
    } finally {
        closer.close();
    }
}

From source file:se.sics.caracaldb.store.RangeReq.java

@Override
public StorageResponse execute(Persistence store) throws IOException {
    TreeMap<Key, byte[]> results = new TreeMap<Key, byte[]>();

    long lengthDiff = 0;
    long keyNumDiff = 0;
    Diff diff = null;//from w  ww. j  a  va2  s. c om

    Closer closer = Closer.create();
    try {
        action.prepare(store);
        byte[] begin = range.begin.getArray();
        for (StoreIterator it = closer.register(store.iterator(begin)); it.hasNext(); it.next()) {
            byte[] key = it.peekKey();
            SortedMap<Integer, ByteArrayRef> oldVals = it.peekAllValues();
            ByteArrayRef oldVal = null;
            for (Entry<Integer, ByteArrayRef> e : oldVals.entrySet()) {
                if (e.getKey() <= maxVersionId) {
                    oldVal = e.getValue();
                    break;
                }
            }
            if (range.contains(key)) {
                Pair<Boolean, ByteArrayRef> res = transFilter.execute(oldVal);
                if (res.getValue0()) {
                    if (limit.read(res.getValue1())) {
                        results.put(new Key(key), res.getValue1().dereference());
                        long newSize = action.process(key, res.getValue1(), actionVersionId);
                        if (oldVal != null) {
                            if (newSize == 0) {
                                lengthDiff -= oldVal.length;
                                keyNumDiff--;
                            } else if (newSize > 0) {
                                lengthDiff -= oldVal.length - newSize;
                            }
                        }
                        if (!limit.canRead()) {
                            break;
                        }
                    } else {
                        break;
                    }
                }
            } else {
                //special case (a,b) and key is a
                if (Key.compare(begin, key) != 0) {
                    break; // reached end of range
                }
            }
        }
        action.commit();
        diff = new Diff(lengthDiff, keyNumDiff);
    } catch (Throwable e) {
        action.abort();
        closer.rethrow(e);
    } finally {
        closer.close();
    }
    return new RangeResp(this, results, !limit.canRead(), diff);
}

From source file:zotmc.collect.forge.McCollectInit.java

@EventHandler
public void preInit(FMLPreInitializationEvent event) {
    try {/*from w  w  w  .  jav a  2  s  .  co m*/
        File dir = new File(event.getModConfigurationDirectory(), MODID);

        if (dir.exists() && !dir.isDirectory())
            dir.delete();
        dir.mkdirs();

        Joiner slash = Joiner.on('/');

        for (File f : dir.listFiles())
            try {
                String fn = f.getName();

                if (fn.toLowerCase(ENGLISH).endsWith(".js"))
                    scripts.put(fn, Files.toString(f, Charsets.UTF_8));

                else if (fn.toLowerCase(ENGLISH).endsWith(".zip")) {
                    Closer closer = Closer.create();

                    try {
                        ZipFile zf = new ZipFile(f);
                        closer.register(zf);

                        for (ZipEntry ze : Enumerable.forZipFile(zf))
                            if (ze.getName().toLowerCase(ENGLISH).endsWith(".js")) {
                                String zen = slash.join(fn, ze.getName());

                                try {
                                    scripts.put(zen, CharStreams.toString(
                                            new InputStreamReader(zf.getInputStream(ze), Charsets.UTF_8)));

                                } catch (Exception e) {
                                    FMLLog.log(ERROR, e, "[%s] An error occurred while reading a file: %s",
                                            NAME, zen);
                                }
                            }

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

            } catch (Exception e) {
                FMLLog.log(ERROR, e, "[%s] An error occurred while reading a file: %s", NAME, f.getName());
            }

    } catch (Exception e) {
        FMLLog.log(ERROR, e, "[%s] An error occurred while trying to access the setting files!", NAME);
    }

}

From source file:gobblin.metrics.reporter.ConfiguredScheduledReporter.java

public ConfiguredScheduledReporter(Builder<?> builder, Config config) {
    super(builder.name, config);
    this.rateUnit = builder.rateUnit;
    this.durationUnit = builder.durationUnit;
    this.rateFactor = builder.rateUnit.toSeconds(1);
    this.durationFactor = 1.0 / builder.durationUnit.toNanos(1);
    this.tags = ImmutableMap.copyOf(builder.tags);
    this.closer = Closer.create();
    this.metricContextName = builder.metricContextName;
}

From source file:com.complexible.common.io.ByteStreams2.java

public static byte[] gzip(final byte[] theBytes) throws IOException {
    final ByteArrayOutputStream aOut = new ByteArrayOutputStream(theBytes.length);

    final GZIPOutputStream aZipped = new GZIPOutputStream(aOut);
    final ByteArrayInputStream aIn = new ByteArrayInputStream(theBytes);

    Closer aCloser = Closer.create();
    aCloser.register(aZipped);/*w w  w .jav  a  2  s. com*/
    aCloser.register(aIn);

    try {
        ByteStreams.copy(aIn, aZipped);
    } finally {
        aCloser.close();
    }

    return aOut.toByteArray();
}

From source file:org.apache.gobblin.compliance.ComplianceJob.java

public ComplianceJob(Properties properties) {
    this.properties = properties;
    ExecutorService executor = ScalingThreadPoolExecutor.newScalingThreadPool(0,
            Integer.parseInt(properties.getProperty(ComplianceConfigurationKeys.MAX_CONCURRENT_DATASETS,
                    ComplianceConfigurationKeys.DEFAULT_MAX_CONCURRENT_DATASETS)),
            100,/*  w w w .  j  av  a 2 s . c  o  m*/
            ExecutorsUtils.newThreadFactory(Optional.<Logger>absent(), Optional.of("complaince-job-pool-%d")));
    this.service = MoreExecutors.listeningDecorator(executor);
    this.closer = Closer.create();
    List<Tag<?>> tags = Lists.newArrayList();
    tags.addAll(Tag.fromMap(AzkabanTags.getAzkabanTags()));
    this.metricContext = this.closer
            .register(Instrumented.getMetricContext(new State(properties), ComplianceJob.class, tags));
    this.isMetricEnabled = GobblinMetrics.isEnabled(properties);
    this.eventSubmitter = new EventSubmitter.Builder(this.metricContext, ComplianceEvents.NAMESPACE).build();
    this.throwables = Lists.newArrayList();
}

From source file:org.apache.gobblin.runtime.JobLauncherTestHelper.java

public void runTest(Properties jobProps) throws Exception {
    String jobName = jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY);
    String jobId = JobLauncherUtils.newJobId(jobName);
    jobProps.setProperty(ConfigurationKeys.JOB_ID_KEY, jobId);

    JobContext jobContext = null;/*from  w ww .ja  v a 2s .c  o m*/
    Closer closer = Closer.create();
    try {
        JobLauncher jobLauncher = closer
                .register(JobLauncherFactory.newJobLauncher(this.launcherProps, jobProps));
        jobLauncher.launchJob(null);
        jobContext = ((AbstractJobLauncher) jobLauncher).getJobContext();
    } finally {
        closer.close();
    }

    Assert.assertTrue(jobContext.getJobMetricsOptional().isPresent());
    String jobMetricContextTags = jobContext.getJobMetricsOptional().get().getMetricContext().getTags()
            .toString();
    Assert.assertTrue(jobMetricContextTags.contains(ClusterNameTags.CLUSTER_IDENTIFIER_TAG_NAME),
            ClusterNameTags.CLUSTER_IDENTIFIER_TAG_NAME + " tag missing in job metric context tags.");

    List<JobState.DatasetState> datasetStateList = this.datasetStateStore.getAll(jobName,
            sanitizeJobNameForDatasetStore(jobId) + ".jst");
    DatasetState datasetState = datasetStateList.get(0);

    Assert.assertEquals(datasetState.getState(), JobState.RunningState.COMMITTED);
    Assert.assertEquals(datasetState.getCompletedTasks(), 4);
    Assert.assertEquals(datasetState.getJobFailures(), 0);

    for (TaskState taskState : datasetState.getTaskStates()) {
        Assert.assertEquals(taskState.getWorkingState(), WorkUnitState.WorkingState.COMMITTED);
        Assert.assertEquals(taskState.getPropAsLong(ConfigurationKeys.WRITER_RECORDS_WRITTEN),
                TestExtractor.TOTAL_RECORDS);
    }
}

From source file:org.fao.geonet.api.records.formatters.groovy.Functions.java

/**
 * Creates a groovy.xml.MarkupBuilder object and executes the closure with the MarkupBuilder as
 * its parameter./*from  w w w .ja va  2 s. c  o m*/
 *
 * The xml created with the MarkupBuilder is returned as a string.
 *
 * @param htmlFunction function that uses the MarkupBuilder to create xml or html
 */
public String html(Closure htmlFunction) {
    Closer closer = Closer.create();
    try {
        final StringWriter writer = closer.register(new StringWriter());
        final IndentPrinter indentPrinter = new IndentPrinter(writer, " ", true, false);
        MarkupBuilder html = new MarkupBuilder(indentPrinter);
        htmlFunction.call(html);
        return writer.toString();
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            throw new Error(e);
        }
    }
}

From source file:org.apache.jackrabbit.oak.upgrade.cli.container.MongoNodeStoreContainer.java

@Override
public NodeStore open() throws IOException {
    this.closer = Closer.create();
    return mongoFactory.create(blob.open(), closer);
}

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

/**
 * Read a JSON value from an {@link InputStream}
 *
 * @param in the input stream/* w  w  w . j ava2  s. c  o m*/
 * @return the value
 * @throws IOException malformed input, or problem encountered when reading
 * from the stream
 */
public JsonNode fromInputStream(final InputStream in) throws IOException {
    final Closer closer = Closer.create();
    final JsonParser parser;
    final MappingIterator<JsonNode> iterator;

    try {
        parser = closer.register(reader.getFactory().createParser(in));
        iterator = reader.readValues(parser);
        return readNode(closer.register(iterator));
    } finally {
        closer.close();
    }
}