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.upgrade.cli.OakUpgrade.java

public static void migrate(MigrationCliArguments argumentParser) throws IOException {
    MigrationOptions options = argumentParser.getOptions();
    StoreArguments stores = argumentParser.getStoreArguments();
    Closer closer = Closer.create();
    CliUtils.handleSigInt(closer);/* w  ww  .  j a  va  2 s . c o  m*/
    MigrationFactory factory = new MigrationFactory(options, stores, closer);
    try {
        if (stores.getSrcStore().isJcr2()) {
            upgrade(factory);
        } else {
            sidegrade(factory);
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.skcraft.launcher.install.ZipExtract.java

@Override
public void run() {
    Closer closer = Closer.create();

    try {//w  w w  .j a v a2  s  . co  m
        InputStream is = closer.register(source.openBufferedStream());
        ZipInputStream zis = closer.register(new ZipInputStream(is));
        ZipEntry entry;

        destination.getParentFile().mkdirs();

        while ((entry = zis.getNextEntry()) != null) {
            if (matches(entry)) {
                File file = new File(getDestination(), entry.getName());
                writeEntry(zis, file);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
        }
    }
}

From source file:gobblin.metrics.reporter.util.EventUtils.java

/**
 * Parses a {@link gobblin.metrics.MetricReport} from a byte array representing a json input.
 * @param reuse MetricReport to reuse.//from w  w  w. j a va2 s.com
 * @param bytes Input bytes.
 * @return MetricReport.
 * @throws java.io.IOException
 */
public synchronized static GobblinTrackingEvent deserializeReportFromJson(GobblinTrackingEvent reuse,
        byte[] bytes) throws IOException {
    if (!reader.isPresent()) {
        reader = Optional.of(new SpecificDatumReader<>(GobblinTrackingEvent.class));
    }

    Closer closer = Closer.create();

    try {
        DataInputStream inputStream = closer.register(new DataInputStream(new ByteArrayInputStream(bytes)));

        // Check version byte
        int versionNumber = inputStream.readInt();
        if (versionNumber != SCHEMA_VERSION) {
            throw new IOException(
                    String.format("MetricReport schema version not recognized. Found version %d, expected %d.",
                            versionNumber, SCHEMA_VERSION));
        }

        // Decode the rest
        Decoder decoder = DecoderFactory.get().jsonDecoder(GobblinTrackingEvent.SCHEMA$, inputStream);
        return reader.get().read(reuse, decoder);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:org.apache.gobblin.metrics.reporter.util.MetricReportUtils.java

/**
 * Parses a {@link org.apache.gobblin.metrics.MetricReport} from a byte array representing a json input.
 * @param reuse MetricReport to reuse.//from w  w  w  . j  a  v  a2  s  .com
 * @param bytes Input bytes.
 * @return MetricReport.
 * @throws java.io.IOException
 */
public synchronized static MetricReport deserializeReportFromJson(MetricReport reuse, byte[] bytes)
        throws IOException {
    if (!READER.isPresent()) {
        READER = Optional.of(new SpecificDatumReader<>(MetricReport.class));
    }

    Closer closer = Closer.create();

    try {
        DataInputStream inputStream = closer.register(new DataInputStream(new ByteArrayInputStream(bytes)));

        // Check version byte
        int versionNumber = inputStream.readInt();
        if (versionNumber != SCHEMA_VERSION) {
            throw new IOException(
                    String.format("MetricReport schema version not recognized. Found version %d, expected %d.",
                            versionNumber, SCHEMA_VERSION));
        }

        // Decode the rest
        Decoder decoder = DecoderFactory.get().jsonDecoder(MetricReport.SCHEMA$, inputStream);
        return READER.get().read(reuse, decoder);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.skcraft.launcher.persistence.Persistence.java

/**
 * Save an object to file.//from w ww  .ja  v a 2  s  . c  o  m
 *
 * @param object the object
 * @throws java.io.IOException on save error
 */
public static void commit(@NonNull Object object) throws IOException {
    ByteSink sink;
    synchronized (bound) {
        sink = bound.get(object);
        if (sink == null) {
            throw new IOException("Cannot persist unbound object: " + object);
        }
    }

    Closer closer = Closer.create();
    try {
        OutputStream os = closer.register(sink.openBufferedStream());
        mapper.writeValue(os, object);
    } finally {
        closer.close();
    }
}

From source file:alluxio.cli.ConfigurationDocGenerator.java

/**
 * Writes property key to csv files.//  w  ww . j  a  va2  s .  c  om
 *
 * @param defaultKeys Collection which is from PropertyKey DEFAULT_KEYS_MAP.values()
 * @param filePath    path for csv files
 */
static void writeCSVFile(Collection<? extends PropertyKey> defaultKeys, String filePath) throws IOException {
    if (defaultKeys.size() == 0) {
        return;
    }

    FileWriter fileWriter;
    Closer closer = Closer.create();
    String[] fileNames = { "user-configuration.csv", "master-configuration.csv", "worker-configuration.csv",
            "security-configuration.csv", "key-value-configuration.csv", "common-configuration.csv",
            "cluster-management-configuration.csv" };

    try {
        // HashMap for FileWriter per each category
        Map<String, FileWriter> fileWriterMap = new HashMap<>();
        for (String fileName : fileNames) {
            fileWriter = new FileWriter(PathUtils.concatPath(filePath, fileName));
            // Write the CSV file header and line separator after the header
            fileWriter.append(CSV_FILE_HEADER + "\n");
            //put fileWriter
            String key = fileName.substring(0, fileName.indexOf("configuration") - 1);
            fileWriterMap.put(key, fileWriter);
            //register file writer
            closer.register(fileWriter);
        }

        // Sort defaultKeys
        List<PropertyKey> dfkeys = new ArrayList<>(defaultKeys);
        Collections.sort(dfkeys);

        for (PropertyKey propertyKey : dfkeys) {
            String pKey = propertyKey.toString();
            String defaultDescription;
            if (propertyKey.getDefaultSupplier().get() == null) {
                defaultDescription = "";
            } else {
                defaultDescription = propertyKey.getDefaultSupplier().getDescription();
            }
            // Quote the whole description to escape characters such as commas.
            defaultDescription = String.format("\"%s\"", defaultDescription);

            // Write property key and default value to CSV
            String keyValueStr = pKey + "," + defaultDescription + "\n";
            if (pKey.startsWith("alluxio.user.")) {
                fileWriter = fileWriterMap.get("user");
            } else if (pKey.startsWith("alluxio.master.")) {
                fileWriter = fileWriterMap.get("master");
            } else if (pKey.startsWith("alluxio.worker.")) {
                fileWriter = fileWriterMap.get("worker");
            } else if (pKey.startsWith("alluxio.security.")) {
                fileWriter = fileWriterMap.get("security");
            } else if (pKey.startsWith("alluxio.keyvalue.")) {
                fileWriter = fileWriterMap.get("key-value");
            } else if (pKey.startsWith("alluxio.integration")) {
                fileWriter = fileWriterMap.get("cluster-management");
            } else {
                fileWriter = fileWriterMap.get("common");
            }
            fileWriter.append(keyValueStr);
        }

        LOG.info("Property Key CSV files were created successfully.");
    } catch (Exception e) {
        throw closer.rethrow(e);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            LOG.error("Error while flushing/closing Property Key CSV FileWriter", e);
        }
    }
}

From source file:ru.runa.af.web.system.TaskHandlerClassesInformation.java

private static void init() {
    String deploymentDirPath = IoCommons.getDeploymentDirPath();
    String earFilePath = deploymentDirPath + "/" + SystemProperties.getEARFileName();
    Closer closer = Closer.create();
    try {/*from ww  w  . j a v a2 s .  c o m*/
        ZipInputStream earInputStream = closer.register(new ZipInputStream(new FileInputStream(earFilePath)));
        ZipEntry entry;
        while ((entry = earInputStream.getNextEntry()) != null) {
            if (entry.getName().endsWith(".jar")) {
                searchInJar(entry.getName(), new JarInputStream(earInputStream));
            }
        }
        if (IoCommons.getAppServer() == AppServer.JBOSS4) {
            File deploymentDirectory = new File(deploymentDirPath);
            log.debug("Searching in deployment directory: " + deploymentDirectory);
            for (File file : IoCommons.getJarFiles(deploymentDirectory)) {
                JarInputStream jarInputStream = closer.register(new JarInputStream(new FileInputStream(file)));
                searchInJar(file.getName(), jarInputStream);
            }
        }
        File extensionDirectory = new File(IoCommons.getExtensionDirPath());
        if (extensionDirectory.exists() && extensionDirectory.isDirectory()) {
            log.debug("Searching in extension directory: " + extensionDirectory);
            for (File file : IoCommons.getJarFiles(extensionDirectory)) {
                JarInputStream jarInputStream = closer.register(new JarInputStream(new FileInputStream(file)));
                searchInJar(file.getName(), jarInputStream);
            }
        } else {
            log.debug("No extension directory found: " + extensionDirectory);
        }
    } catch (Throwable e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            log.warn(e);
        }
    }
}

From source file:org.gradle.caching.internal.controller.service.LoadTarget.java

@Override
public void readFrom(InputStream input) throws IOException {
    Closer closer = Closer.create();
    closer.register(input);//from  ww  w  .  j  av  a 2  s  .co m
    try {
        if (loaded) {
            throw new IllegalStateException("Build cache entry has already been read");
        }
        Files.asByteSink(file).writeFrom(input);
        loaded = true;
    } catch (Exception e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:org.gradle.caching.internal.controller.service.StoreTarget.java

@Override
public void writeTo(OutputStream output) throws IOException {
    Closer closer = Closer.create();
    closer.register(output);//  w  w w .  j  a v a  2s .c o  m
    try {
        if (stored) {
            throw new IllegalStateException("Build cache entry has already been stored");
        }
        stored = true;
        Files.asByteSource(file).copyTo(output);
    } catch (Exception e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:gobblin.compaction.HdfsWriter.java

public void write(String text) throws IOException {
    String dirInHdfs = getDirInHdfs();
    this.fileSystem.mkdirs(new Path(dirInHdfs));

    Closer closer = Closer.create();
    try {/*ww  w.j a v  a 2  s .  c om*/
        FSDataOutputStream fout = closer.register(this.fileSystem.create(new Path(filePathInHdfs)));
        fout.writeChars(text);
    } finally {
        closer.close();
    }
}