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:com.android.builder.internal.packaging.DexIncrementalRenameManager.java

/**
 * Reads previously saved incremental state.
 *
 * @throws IOException failed to read state; not thrown if no state exists
 *//*from w w w  . j a v  a 2s. c o  m*/
private void readState() throws IOException {
    File stateFile = new File(mIncrementalDir, STATE_FILE);
    if (!stateFile.isFile()) {
        return;
    }

    Properties props = new Properties();
    Closer closer = Closer.create();
    try {
        props.load(closer.register(new FileReader(stateFile)));
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }

    for (int i = 0;; i++) {
        String baseKey = BASE_KEY_PREFIX + i;
        String fileKey = FILE_KEY_PREFIX + i;
        String renamedKey = RENAMED_KEY_PREFIX + i;

        String base = props.getProperty(baseKey);
        String file = props.getProperty(fileKey);
        String rename = props.getProperty(renamedKey);

        if (base == null || file == null || rename == null) {
            break;
        }

        RelativeFile rf = new RelativeFile(new File(base), new File(file));
        mNameMap.put(rf, rename);
    }
}

From source file:alluxio.multi.process.MultiProcessCluster.java

private MultiProcessCluster(Map<PropertyKey, String> properties, int numMasters, int numWorkers,
        String clusterName, DeployMode mode) {
    mProperties = properties;/*  w  ww  .  j a  va 2 s.c om*/
    mNumMasters = numMasters;
    mNumWorkers = numWorkers;
    // Add a unique number so that different runs of the same test use different cluster names.
    mClusterName = clusterName + ThreadLocalRandom.current().nextLong();
    mDeployMode = mode;
    mMasters = new ArrayList<>();
    mWorkers = new ArrayList<>();
    mCloser = Closer.create();
    mState = State.NOT_STARTED;
    mSuccess = false;
}

From source file:gobblin.compaction.hive.AvroExternalTable.java

private Schema getSchemaFromAvroDataFile() throws IOException {
    String firstDataFilePath = HdfsReader.getFirstDataFilePathInDir(dataLocationInHdfs);
    LOG.info("Extracting schema for table " + name + " from avro data file " + firstDataFilePath);
    SeekableInput sin = new HdfsReader(firstDataFilePath).getFsInput();

    Closer closer = Closer.create();
    try {//from w  w w. j  av a 2s .  c o  m
        DataFileReader<Void> dfr = closer
                .register(new DataFileReader<Void>(sin, new GenericDatumReader<Void>()));
        Schema schema = dfr.getSchema();
        return schema;
    } finally {
        closer.close();
    }
}

From source file:org.apache.gobblin.metrics.MetricContext.java

protected MetricContext(String name, MetricContext parent, List<Tag<?>> tags, boolean isRoot)
        throws NameConflictException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(name));

    this.closer = Closer.create();

    try {/*from w w  w .ja va  2s  .  c om*/
        this.innerMetricContext = this.closer.register(new InnerMetricContext(this, name, parent, tags));
    } catch (ExecutionException ee) {
        throw Throwables.propagate(ee);
    }

    this.contextAwareMetricsSet = Sets.newConcurrentHashSet();

    this.notificationTargets = Maps.newConcurrentMap();
    this.executorServiceOptional = Optional.absent();

    this.notificationTimer = new ContextAwareTimer(this, GOBBLIN_METRICS_NOTIFICATIONS_TIMER_NAME);
    register(this.notificationTimer);

    if (!isRoot) {
        RootMetricContext.get().addMetricContext(this);
    }
}

From source file:org.sonatype.nexus.timeline.feeds.sources.ErrorWarningFeedSource.java

/**
 * Extracts ERROR and WARN log lines from given log file. It returns ordered list (newest 1st, oldest last) of
 * found/*  ww  w. j a v  a  2s  . co  m*/
 * log lines, and that list is maximized to have {@code entriesToExtract} entries.
 *
 * @param logFile          the log file to scan.
 * @param entriesToExtract The number how much "newest" entries should be collected.
 */
private List<FeedEvent> extractEntriesFromLogfile(final File logFile, final int entriesToExtract)
        throws IOException {
    final List<FeedEvent> entries = Lists.newArrayList();
    Closer closer = Closer.create();
    try {
        final BufferedReader reader = Files.newReader(logFile, Charset.forName("UTF-8"));
        String logLine = reader.readLine();
        while (logLine != null) {
            if (logLine.contains(" WARN ") || logLine.contains(" ERROR ")) {

                // FIXME: Grab following stacktrace if any in log
                // if ( StringUtils.isNotEmpty( item.getStackTrace() ) )
                // {
                // // we need <br/> and &nbsp; to display stack trace on RSS
                // String stackTrace = item.getStackTrace().replace(
                // (String) System.getProperties().get( "line.separator" ),
                // "<br/>" );
                // stackTrace = stackTrace.replace( "\t", "&nbsp;&nbsp;&nbsp;&nbsp;" );
                // contentValue.append( "<br/>" ).append( stackTrace );
                // }

                final FeedEvent entry = new FeedEvent("LOG", // ignored
                        "ERROR_WARNING", // ignored
                        new Date(), // TODO: timestamp from log file?
                        null, // author "system"
                        null, // no link (maybe log config? or support?)
                        Maps.<String, String>newHashMap());
                if (logLine.contains(" ERROR ")) {
                    entry.setTitle("Error");
                } else if (logLine.contains(" WARN ")) {
                    entry.setTitle("Warning");
                }
                entry.setContent(logLine);

                entries.add(entry);
                if (entries.size() > entriesToExtract) {
                    entries.remove(0);
                }
            }
            logLine = reader.readLine();
        }
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
    return Lists.reverse(entries);
}

From source file:org.ow2.proactive_grid_cloud_portal.dataspace.util.VFSZipper.java

public static void unzip(InputStream is, FileObject file) throws IOException {
    Closer closer = Closer.create();
    closer.register(is);/*from   w w w  .  ja  v a  2  s.  c om*/
    try {
        OutputStream os = file.getContent().getOutputStream();
        ZipOutputStream zos = new ZipOutputStream(os);
        closer.register(zos);
        ByteStreams.copy(is, zos);
    } catch (IOException ioe) {
        throw closer.rethrow(ioe);
    } finally {
        closer.close();
    }
}

From source file:io.macgyver.plugin.ci.jenkins.JenkinsApiProxy.java

protected void proxyResponse(Response southResponse, HttpServletRequest northRequest,
        HttpServletResponse northResponse) throws IOException {
    int statusCode = southResponse.code();
    northResponse.setStatus(statusCode);

    Closer closer = Closer.create();
    try {/*from ww  w .j a  v  a  2  s . com*/
        Headers h = southResponse.headers();
        for (String name : h.names()) {
            if (name.toLowerCase().equals("content-encoding")) {
                // do nothing
            } else if (name.toLowerCase().equals("content-length")) {
                // do nothing
            } else {
                logger.info("Add header: {}:{}", name, h.get(name));
                northResponse.addHeader(name, h.get(name));
            }
        }

        ResponseBody body = southResponse.body();

        logger.info("jenkins response: {}", northResponse.getStatus());
        String contentType = southResponse.header("content-type");
        if (contentType.contains("json")) {
            String val = rewriteResponseBody(body.string(), northRequest);
            logger.info("body: {}", val);
            JsonNode n = mapper.readTree(val);

            PrintWriter pw = northResponse.getWriter();
            closer.register(pw);

            pw.print(n.toString());

        } else if (contentType.contains("xml")) {

            PrintWriter pw = northResponse.getWriter();
            closer.register(pw);

            String val = rewriteResponseBody(body.string(), northRequest);

            pw.print(val);

        } else {

            OutputStream os = northResponse.getOutputStream();
            closer.register(os);

            InputStream is = body.byteStream();
            closer.register(is);

            ByteStreams.copy(is, os);

        }

    } finally {
        closer.close();
    }

}

From source file:se.sics.datamodel.util.DMKeyFactory.java

private static Key getIndexKeyByte(ByteId dbId, ByteId typeId, ByteId indexId, byte[] indexValue,
        ByteId objNrId) throws IOException {
    Closer closer = Closer.create();
    try {/*  w  ww .  j a  va  2  s  .  co  m*/
        ByteArrayOutputStream baos = closer.register(new ByteArrayOutputStream());
        DataOutputStream w = closer.register(new DataOutputStream(baos));

        w.write(dbId.getId());
        w.writeByte(indexKF);
        w.write(typeId.getId());
        w.write(indexId.getId());
        w.write(indexValue);
        w.write(objNrId.getId());
        w.flush();

        return new Key(baos.toByteArray());
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:org.apache.jackrabbit.oak.run.SegmentTarUtils.java

static void backup(File source, File target) throws IOException {
    Closer closer = Closer.create();
    try {/*from  w w  w.j a v a2  s .c  om*/
        FileStore fs;
        if (FileStoreBackup.USE_FAKE_BLOBSTORE) {
            fs = openReadOnlyFileStore(source, newBasicReadOnlyBlobStore());
        } else {
            fs = openReadOnlyFileStore(source);
        }
        closer.register(fs);
        FileStoreBackup.backup(fs.getReader(), fs.getRevisions(), target);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:feign.TrustingSSLSocketFactory.java

private static KeyStore loadKeyStore(InputSupplier<InputStream> inputStreamSupplier) throws IOException {
    Closer closer = Closer.create();
    try {/*from   w  ww. j  a  va2s  .  co m*/
        InputStream inputStream = closer.register(inputStreamSupplier.getInput());
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(inputStream, KEYSTORE_PASSWORD);
        return keyStore;
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}