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:org.apache.mahout.text.PrefixAdditionFilter.java

@Override
protected void process(FileStatus fst, Path current) throws IOException {
    FileSystem fs = getFs();//  www. j  a v a2  s. c  om
    ChunkedWriter writer = getWriter();
    if (fst.isDir()) {
        String dirPath = getPrefix() + Path.SEPARATOR + current.getName() + Path.SEPARATOR
                + fst.getPath().getName();
        fs.listStatus(fst.getPath(),
                new PrefixAdditionFilter(getConf(), dirPath, getOptions(), writer, getCharset(), fs));
    } else {
        InputStream in = null;
        try {
            in = fs.open(fst.getPath());

            StringBuilder file = new StringBuilder();
            for (String aFit : new FileLineIterable(in, getCharset(), false)) {
                file.append(aFit).append('\n');
            }
            String name = current.getName().equals(fst.getPath().getName()) ? current.getName()
                    : current.getName() + Path.SEPARATOR + fst.getPath().getName();
            writer.write(getPrefix() + Path.SEPARATOR + name, file.toString());
        } finally {
            Closeables.close(in, false);
        }
    }
}

From source file:org.eclipse.epp.internal.logging.aeri.ui.utils.Zips.java

public static void zip(File directory, File out) throws IOException {
    ZipOutputStream zos = null;/*ww  w . j  av a 2 s . com*/
    try {
        OutputSupplier<FileOutputStream> s = Files.newOutputStreamSupplier(out);
        zos = new ZipOutputStream(s.getOutput());
        for (File f : FileUtils.listFiles(directory, FILE, DIRECTORY)) {
            String path = removeStart(f.getPath(), directory.getAbsolutePath() + File.separator);
            path = path.replace(File.separatorChar, '/');
            ZipEntry e = new ZipEntry(path);
            zos.putNextEntry(e);
            Files.asByteSource(f).copyTo(zos);
            zos.closeEntry();
        }
    } finally {
        Closeables.close(zos, false);
    }
}

From source file:org.sonatype.nexus.apachehttpclient.NexusSSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {/*  ww w.  j a v a 2 s .  c  o  m*/
        hostnameVerifier.verify(hostname, sslsock);
    } catch (final IOException e) {
        Closeables.close(sslsock, true);
        throw e;
    }
}

From source file:org.jclouds.examples.rackspace.cloudfiles.CreateContainer.java

/**
 * Always close your service when you're done with it.
 */
public void close() throws IOException {
    Closeables.close(cloudFiles, true);
}

From source file:org.apache.mahout.utils.io.ChunkedWriter.java

/** Writes a new key-value pair, creating a new sequence file if necessary.*/
public void write(String key, String value) throws IOException {
    if (currentChunkSize > maxChunkSizeInBytes) {
        Closeables.close(writer, false);
        currentChunkID++;/*  www  . j a  v a2s .c  om*/
        writer = new SequenceFile.Writer(fs, conf, getPath(currentChunkID), Text.class, Text.class);
        currentChunkSize = 0;
    }

    Text keyT = new Text(key);
    Text valueT = new Text(value);
    currentChunkSize += keyT.getBytes().length + valueT.getBytes().length; // Overhead
    writer.append(keyT, valueT);
}

From source file:eu.interedition.text.util.AbstractTextRepository.java

public Text create(XMLStreamReader xml) throws IOException, XMLStreamException {
    final File xmlSource = File.createTempFile(getClass().getName(), ".xml");

    final FileBackedOutputStream xmlBuf = createBuffer();
    XMLEventReader xmlEventReader = null;
    XMLEventWriter xmlEventWriter = null;
    try {//from ww  w .j  a v a2 s.co m
        xmlEventReader = xmlInputFactory.createXMLEventReader(xml);
        xmlEventWriter = xmlOutputFactory.createXMLEventWriter(new OutputStreamWriter(xmlBuf, Text.CHARSET));
        xmlEventWriter.add(xmlEventReader);
    } finally {
        XML.closeQuietly(xmlEventWriter);
        XML.closeQuietly(xmlEventReader);
        Closeables.close(xmlBuf, false);
    }

    Reader xmlBufReader = null;
    try {
        xmlBufReader = new InputStreamReader(xmlBuf.getSupplier().getInput(), Text.CHARSET);
        return write(create(Text.Type.XML), xmlBufReader);
    } finally {
        Closeables.close(xmlBufReader, false);
        xmlSource.delete();
    }
}

From source file:io.druid.segment.data.VSizeIndexedWriter.java

@Override
public void close() throws IOException {
    final byte numBytesForMax = VSizeIndexedInts.getNumBytesForMax(maxId);

    valuesOut.write(new byte[4 - numBytesForMax]);

    Closeables.close(headerOut, false);
    Closeables.close(valuesOut, false);//www.java2s . c om

    final long numBytesWritten = headerOut.getCount() + valuesOut.getCount();

    Preconditions.checkState(headerOut.getCount() == (numWritten * 4),
            "numWritten[%s] number of rows should have [%s] bytes written to headerOut, had[%s]", numWritten,
            numWritten * 4, headerOut.getCount());
    Preconditions.checkState(numBytesWritten < Integer.MAX_VALUE, "Wrote[%s] bytes, which is too many.",
            numBytesWritten);

    OutputStream metaOut = ioPeon.makeOutputStream(makeFilename("meta"));

    try {
        metaOut.write(new byte[] { version, numBytesForMax });
        metaOut.write(Ints.toByteArray((int) numBytesWritten + 4));
        metaOut.write(Ints.toByteArray(numWritten));
    } finally {
        metaOut.close();
    }
}

From source file:org.dyndns.jkiddo.service.daap.client.RequestHelper.java

@SuppressWarnings("unchecked")
public static <T extends Chunk> T requestParsed(final String url, final boolean keepalive,
        final boolean specialCaseProtocolViolation) throws Exception {
    logger.debug(url);//  ww  w  . jav  a2  s  .  c  om
    final DmapInputStream inputStream = new DmapInputStream(new ByteArrayInputStream(request(url, keepalive)),
            specialCaseProtocolViolation);
    final Chunk chunk = inputStream.getChunk();
    Closeables.close(inputStream, true);
    return (T) chunk;
}

From source file:org.jclouds.chef.handlers.ChefErrorHandler.java

public void handleError(HttpCommand command, HttpResponse response) {
    String message = errorParser.apply(response);
    Exception exception = new HttpResponseException(command, response, message);
    try {/*w  ww. j ava  2 s  .c o  m*/
        message = message != null ? message
                : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(),
                        response.getStatusLine());
        switch (response.getStatusCode()) {
        case 401:
        case 403:
            exception = new AuthorizationException(message, exception);
            break;
        case 404:
            if (!command.getCurrentRequest().getMethod().equals("DELETE")) {
                exception = new ResourceNotFoundException(message, exception);
            }
            break;
        }
    } finally {
        if (response.getPayload() != null) {
            try {
                Closeables.close(response.getPayload().getInput(), true);
            } catch (IOException e) {
                throw propagate(e);
            }
        }
        command.setException(exception);
    }
}

From source file:com.google.dart.compiler.backend.dart.DartBackend.java

@Override
public void compileUnit(DartUnit unit, DartSource src, DartCompilerContext context,
        CoreTypeProvider typeProvider) throws IOException {
    // Generate Javascript output.
    TextOutput out = new DefaultTextOutput(false);
    DartToSourceVisitor srcGenerator = new DartToSourceVisitor(out);
    // TODO(johnlenz): Determine if we want to make source maps
    // optional.//from   w  w  w.  j  a  v  a2s .  co  m
    srcGenerator.generateSourceMap(true);
    srcGenerator.accept(unit);
    Writer w = context.getArtifactWriter(src, "", EXTENSION_DART);
    boolean failed = true;
    try {
        w.write(out.toString());
        failed = false;
    } finally {
        Closeables.close(w, failed);
    }
    // Write out the source map.
    w = context.getArtifactWriter(src, "", EXTENSION_DART_SRC_MAP);
    failed = true;
    try {
        srcGenerator.writeSourceMap(w, src.getName());
        failed = false;
    } finally {
        Closeables.close(w, failed);
    }
}