Example usage for com.google.common.io Closeables close

List of usage examples for com.google.common.io Closeables close

Introduction

In this page you can find the example usage for com.google.common.io Closeables close.

Prototype

public static void close(@Nullable Closeable closeable, boolean swallowIOException) throws IOException 

Source Link

Document

Closes a Closeable , with control over whether an IOException may be thrown.

Usage

From source file:eu.interedition.text.Text.java

public Text write(Session session, Reader content) throws IOException {
    final FileBackedOutputStream buf = createBuffer();
    CountingWriter tempWriter = null;// w ww .j av  a2  s .com
    try {
        CharStreams.copy(content, tempWriter = new CountingWriter(new OutputStreamWriter(buf, Text.CHARSET)));
    } finally {
        Closeables.close(tempWriter, false);
    }

    Reader bufReader = null;
    try {
        return write(session, bufReader = new InputStreamReader(buf.getSupplier().getInput(), Text.CHARSET),
                tempWriter.length);
    } finally {
        Closeables.close(bufReader, false);
    }
}

From source file:org.apache.mahout.cf.taste.hadoop.item.IDReader.java

private Map<Long, FastIDSet> readUserItemFilter(String pathString) throws IOException {
    Map<Long, FastIDSet> result = Maps.newHashMap();
    InputStream in = openFile(pathString);

    try {/* w  ww .  j  a  va 2s.co m*/
        for (String line : new FileLineIterable(in)) {
            try {
                String[] tokens = SEPARATOR.split(line.toString());
                Long userId = Long.parseLong(tokens[0]);
                Long itemId = Long.parseLong(tokens[1]);

                addUserAndItemIdToUserItemFilter(result, userId, itemId);
            } catch (NumberFormatException nfe) {
                log.warn("userItemFile line ignored: {}", line);
            }
        }
    } finally {
        Closeables.close(in, true);
    }

    return result;
}

From source file:com.comphenix.protocol.wrappers.nbt.NbtFactory.java

/**
 * Load a NBT compound from a GZIP compressed file.
 * @param file - the source file.//  www . j  a va2  s.co  m
 * @return The compound.
 * @throws IOException Unable to load file.
 */
public static NbtCompound fromFile(String file) throws IOException {
    Preconditions.checkNotNull(file, "file cannot be NULL");
    FileInputStream stream = null;
    DataInputStream input = null;
    boolean swallow = true;

    try {
        stream = new FileInputStream(file);
        NbtCompound result = NbtBinarySerializer.DEFAULT
                .deserializeCompound(input = new DataInputStream(new GZIPInputStream(stream)));
        swallow = false;
        return result;
    } finally {
        // Would be nice to avoid this, but alas - we have to use Java 6
        if (input != null)
            Closeables.close(input, swallow);
        else if (stream != null)
            Closeables.close(stream, swallow);
    }
}

From source file:hudson.plugins.timestamper.io.TimestampsWriter.java

/**
 * {@inheritDoc}
 */
@Override
public void close() throws IOException {
    Closeables.close(timestampsOutput, false);
}

From source file:com.vilt.minium.impl.JQueryInvoker.java

protected static String getFileContent(String filename) {
    InputStream in = null;//from w ww  .ja  va  2s.  co  m
    try {
        in = getClasspathFileInputStream(filename);
        return CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8));
    } catch (IOException e) {
        throw new WebElementsException(format("Could not load %s from classpath", filename), e);
    } finally {
        try {
            Closeables.close(in, true);
        } catch (IOException e) {
        }
    }
}

From source file:org.apache.mahout.utils.vectors.arff.Driver.java

protected static void writeLabelBindings(File dictOut, ARFFModel arffModel, String delimiter,
        boolean jsonDictonary) throws IOException {
    Writer writer = Files.newWriterSupplier(dictOut, Charsets.UTF_8, true).getOutput();
    try {/* www  .  j a  v  a  2s.c om*/
        if (jsonDictonary) {
            writeLabelBindingsJSON(writer, arffModel);
        } else {
            writeLabelBindings(writer, arffModel, delimiter);
        }
    } finally {
        Closeables.close(writer, false);
    }
}

From source file:com.kixeye.chassis.bootstrap.configuration.zookeeper.ZookeeperConfigurationProvider.java

@Override
public void close() throws IOException {
    Closeables.close(curatorFramework, false);
}

From source file:io.smartspaces.master.api.master.internal.StandardMasterApiActivityManager.java

@Override
public Map<String, Object> saveActivity(SimpleActivity activityDescription, InputStream activityContentStream) {
    try {//from  www  .  ja v a 2s. c  om
        Activity finalActivity = resourceRepositoryManager.addActivity(activityContentStream);

        return SmartSpacesMessagesSupport.getSuccessResponse(extractBasicActivityApiData(finalActivity));
    } catch (Throwable e) {
        Map<String, Object> response = SmartSpacesMessagesSupport
                .getFailureResponse(MasterApiMessages.MESSAGE_API_CALL_FAILURE, e);

        logResponseError("Attempt to import activity data failed", response);

        return response;
    } finally {
        try {
            Closeables.close(activityContentStream, true);
        } catch (IOException e) {
            // Won't ever be thrown.
        }
    }
}

From source file:org.apache.mahout.clustering.evaluation.RepresentativePointsDriver.java

private static void writeInitialState(Path output, Path clustersIn) throws IOException {
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(output.toUri(), conf);
    for (FileStatus dir : fs.globStatus(clustersIn)) {
        Path inPath = dir.getPath();
        for (FileStatus part : fs.listStatus(inPath, PathFilters.logsCRCFilter())) {
            Path inPart = part.getPath();
            Path path = new Path(output, inPart.getName());
            SequenceFile.Writer writer = new SequenceFile.Writer(fs, conf, path, IntWritable.class,
                    VectorWritable.class);
            try {
                for (ClusterWritable clusterWritable : new SequenceFileValueIterable<ClusterWritable>(inPart,
                        true, conf)) {//  w w  w .j a  v a 2 s  .  c  om
                    Cluster cluster = clusterWritable.getValue();
                    if (log.isDebugEnabled()) {
                        log.debug("C-{}: {}", cluster.getId(),
                                AbstractCluster.formatVector(cluster.getCenter(), null));
                    }
                    writer.append(new IntWritable(cluster.getId()), new VectorWritable(cluster.getCenter()));
                }
            } finally {
                Closeables.close(writer, false);
            }
        }
    }
}

From source file:com.metamx.common.io.smoosh.FileSmoosher.java

@Override
public void close() throws IOException {
    Closeables.close(currOut, false);

    File metaFile = metaFile(baseDir);

    Writer out = null;/* ww  w  . j  ava 2 s .  c  o  m*/
    try {
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(metaFile), Charsets.UTF_8));
        out.write(String.format("v1,%d,%d", maxChunkSize, outFiles.size()));
        out.write("\n");

        for (Map.Entry<String, Metadata> entry : internalFiles.entrySet()) {
            final Metadata metadata = entry.getValue();
            out.write(joiner.join(entry.getKey(), metadata.getFileNum(), metadata.getStartOffset(),
                    metadata.getEndOffset()));
            out.write("\n");
        }
    } finally {
        Closeables.close(out, false);
    }
}