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.collatex.cli.URLWitness.java

public URLWitness read(Function<String, Iterable<String>> tokenizer, Function<String, String> normalizer,
        Charset charset, XPathExpression tokenXPath)
        throws IOException, XPathExpressionException, SAXException {
    InputStream stream = null;/* w  w w  .  j av  a2 s. c om*/
    try {
        stream = url.openStream();
        if (tokenXPath != null) {
            final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            final Document document = documentBuilder.parse(stream);
            document.normalizeDocument();

            final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document, XPathConstants.NODESET);
            final List<Token> tokens = Lists.newArrayListWithExpectedSize(tokenNodes.getLength());
            for (int nc = 0; nc < tokenNodes.getLength(); nc++) {
                final Node tokenNode = tokenNodes.item(nc);
                final String tokenText = tokenNode.getTextContent();
                tokens.add(new NodeToken(this, tokenText, normalizer.apply(tokenText), tokenNode));
            }
            setTokens(tokens);
        } else {
            final List<Token> tokens = Lists.newLinkedList();
            for (String tokenText : tokenizer
                    .apply(CharStreams.toString(new InputStreamReader(stream, charset)))) {
                tokens.add(new SimpleToken(this, tokenText, normalizer.apply(tokenText)));
            }
            setTokens(tokens);
        }
    } catch (ParserConfigurationException e) {
        throw new SAXException(e);
    } finally {
        Closeables.close(stream, false);
    }
    return this;
}

From source file:org.apache.giraph.graph.RetryableJobProgressTrackerClient.java

@Override
public synchronized void cleanup() throws IOException {
    Closeables.close(clientManager, true);
    try {//from   w  w  w  .j  a  v  a  2s.co  m
        clientManager.close();
        // CHECKSTYLE: stop IllegalCatch
    } catch (Exception e) {
        // CHECKSTYLE: resume IllegalCatch
        if (LOG.isDebugEnabled()) {
            LOG.debug("Exception occurred while trying to close JobProgressTracker", e);
        }
    }
}

From source file:io.gearpump.transport.netty.MessageBatch.java

/**
 * create a buffer containing the encoding of this batch
 *///from  ww  w  . java2 s  .c  o  m
ChannelBuffer buffer() throws IOException {
    ChannelBufferOutputStream bout = new ChannelBufferOutputStream(ChannelBuffers.directBuffer(encoded_length));

    try {
        for (TaskMessage msg : messages) {
            writeTaskMessage(bout, msg);
        }
        return bout.buffer();
    } catch (IOException e) {
        log.error("Error while writing Tasks to Channel Buffer - {}", e.getMessage());
    } finally {
        Closeables.close(bout, false);
    }
    return null;
}

From source file:org.apache.mahout.common.distance.MahalanobisDistanceMeasure.java

@Override
public void configure(Configuration jobConf) {
    if (parameters == null) {
        ParameteredGeneralizations.configureParameters(this, jobConf);
    }//from   ww  w  .j a va2 s  . c o  m
    try {
        if (inverseCovarianceFile.get() != null) {
            FileSystem fs = FileSystem.get(inverseCovarianceFile.get().toUri(), jobConf);
            MatrixWritable inverseCovarianceMatrix = ClassUtils
                    .instantiateAs((Class<? extends MatrixWritable>) matrixClass.get(), MatrixWritable.class);
            if (!fs.exists(inverseCovarianceFile.get())) {
                throw new FileNotFoundException(inverseCovarianceFile.get().toString());
            }
            DataInputStream in = fs.open(inverseCovarianceFile.get());
            try {
                inverseCovarianceMatrix.readFields(in);
            } finally {
                Closeables.close(in, true);
            }
            this.inverseCovarianceMatrix = inverseCovarianceMatrix.get();
            Preconditions.checkArgument(this.inverseCovarianceMatrix != null,
                    "inverseCovarianceMatrix not initialized");
        }

        if (meanVectorFile.get() != null) {
            FileSystem fs = FileSystem.get(meanVectorFile.get().toUri(), jobConf);
            VectorWritable meanVector = ClassUtils
                    .instantiateAs((Class<? extends VectorWritable>) vectorClass.get(), VectorWritable.class);
            if (!fs.exists(meanVectorFile.get())) {
                throw new FileNotFoundException(meanVectorFile.get().toString());
            }
            DataInputStream in = fs.open(meanVectorFile.get());
            try {
                meanVector.readFields(in);
            } finally {
                Closeables.close(in, true);
            }
            this.meanVector = meanVector.get();
            Preconditions.checkArgument(this.meanVector != null, "meanVector not initialized");
        }

    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.netflix.suro.SuroControl.java

/**
 * Processes user command. For now it supports only "exit", case insensitive.
 * @param clientSocket The client socket after connection is established between a client and this server
 *
 * @return the last processed command/*from www .java2s .c  o  m*/
 */
private Command processCommand(Socket clientSocket) {
    BufferedReader in = null;
    BufferedWriter out = null;
    try {
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
        String s;
        while ((s = in.readLine()) != null) {
            if ("exit".equalsIgnoreCase(s.trim())) {
                respond(out, "ok");

                return Command.EXIT;
            } else {
                respond(out, String.format("Unknown command '%s'", s));
            }
        }
    } catch (IOException e) {
        log.warn(String.format("Failed to accept user command at port %d: %s", clientSocket.getPort(),
                e.getMessage()), e);
    } finally {
        try {
            Closeables.close(in, true);
            Closeables.close(out, true);
        } catch (IOException ignored) {

        }

    }

    return null;
}

From source file:com.ml.ira.algos.LogisticModelParameters.java

/**
 * Saves a model to an output stream./*from   w w w.  ja  v  a2s  .  co  m*/
 */
public void saveTo(OutputStream out) throws IOException {
    Closeables.close(lr, false);
    targetCategories = getCsvRecordFactory().getTargetCategories();
    write(new DataOutputStream(out));
}

From source file:org.jclouds.examples.rackspace.cloudblockstorage.DeleteSnapshot.java

/**
 * Always close your service when you're done with it.
 *
 * Note that closing quietly like this is not necessary in Java 7.
 * You would use try-with-resources in the main method instead.
 *///  w ww.  j  av  a  2 s.  co m
public void close() throws IOException {
    Closeables.close(cinderApi, true);
}

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

private Map<Long, Long> readTimeShifts() throws IOException {
    if (!timeShiftsFile.isFile()) {
        return Collections.emptyMap();
    }/*from   w  w  w  . j a  va2s.co m*/
    Map<Long, Long> timeShifts = new HashMap<Long, Long>();
    CountingInputStream inputStream = new CountingInputStream(
            new BufferedInputStream(new FileInputStream(timeShiftsFile)));
    boolean threw = true;
    try {
        while (inputStream.getCount() < timeShiftsFile.length()) {
            long entry = Varint.read(inputStream);
            long shift = Varint.read(inputStream);
            timeShifts.put(entry, shift);
        }
        threw = false;
    } finally {
        Closeables.close(inputStream, threw);
    }
    return timeShifts;
}

From source file:org.apache.mahout.classifier.naivebayes.NaiveBayesModel.java

public static NaiveBayesModel materialize(Path output, Configuration conf) throws IOException {
    FileSystem fs = output.getFileSystem(conf);

    Vector weightsPerLabel = null;
    Vector perLabelThetaNormalizer = null;
    Vector weightsPerFeature = null;
    Matrix weightsPerLabelAndFeature;/*  w ww  .j  a v a  2  s.  co m*/
    float alphaI;
    boolean isComplementary;

    FSDataInputStream in = fs.open(new Path(output, "naiveBayesModel.bin"));
    try {
        alphaI = in.readFloat();
        isComplementary = in.readBoolean();
        weightsPerFeature = VectorWritable.readVector(in);
        weightsPerLabel = new DenseVector(VectorWritable.readVector(in));
        if (isComplementary) {
            perLabelThetaNormalizer = new DenseVector(VectorWritable.readVector(in));
        }
        weightsPerLabelAndFeature = new SparseRowMatrix(weightsPerLabel.size(), weightsPerFeature.size());
        for (int label = 0; label < weightsPerLabelAndFeature.numRows(); label++) {
            weightsPerLabelAndFeature.assignRow(label, VectorWritable.readVector(in));
        }
    } finally {
        Closeables.close(in, true);
    }
    NaiveBayesModel model = new NaiveBayesModel(weightsPerLabelAndFeature, weightsPerFeature, weightsPerLabel,
            perLabelThetaNormalizer, alphaI, isComplementary);
    model.validate();
    return model;
}

From source file:edu.msoe.se2800.h4.Logger.java

/**
 * Example usage:/*from www. ja  va  2s . c om*/
 * <p/>
 * <code>
 * public class PerfectPerson {<br/>
 * public static final String TAG = "Logger";<br/>
 * public PerfectPerson() {<br/>
 * Logger.INSTANCE.log(TAG, "My eyes are %s and my hair is %s", new String[]{"Green", "Blonde"});<br/> 
 * }<br/>
 * }<br/>
 * </code><br/>
 * will produce (PerfectPerson, My eyes are Green and my hair is Blonde).
 * 
 * @param tag of the class making the call.
 * @param message to be logged. Use %s to indicate fields.
 * @param args Strings to populate fields with. These need to be in the order they are found in
 *            the message
 */
public void log(String tag, String message, String[] args) {
    synchronized (this) {
        OutputStreamWriter writer = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(FILE_NAME, true));
            DateFormat format = DateFormat.getInstance();

            // Print the date/timestamp
            writer.write(format.format(new Date()));
            writer.write(" | ");

            // Print the tag
            writer.write(tag);
            writer.write(" | ");

            if (StringUtils.countMatches(message, "%s") != args.length) {
                throw new IllegalArgumentException("The number of placeholders in (" + message
                        + ") was not the same as the number of args (" + args.length + ").");
            }
            for (String s : args) {
                message = StringUtils.replaceOnce(message, "%s", s);
            }

            // Print the message
            writer.write(message);
            writer.write("\n");
        } catch (FileNotFoundException e1) {
            System.out.println("The specified file could not be found.");
        } catch (IOException e) {
            System.out.println("Unable to connect to the logger. This call to log() will be ignored.");
        } finally {
            if (writer != null) {
                try {
                    Closeables.close(writer, true);
                } catch (IOException e) {
                }
            }
        }
    }

}