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

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

Introduction

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

Prototype

public static void closeQuietly(@Nullable Reader reader) 

Source Link

Document

Closes the given Reader , logging any IOException that's thrown rather than propagating it.

Usage

From source file:org.apache.sqoop.connector.kite.KiteDatasetExecutor.java

public void closeReader() {
    if (reader != null) {
        Closeables.closeQuietly(reader);
        reader = null;
    }
}

From source file:com.netflix.exhibitor.core.index.LogIndexer.java

public void index() throws Exception {
    if (!logParser.isValid()) {
        return;/* w  w  w. java 2 s .  c  o  m*/
    }

    final AtomicInteger count = new AtomicInteger(0);
    final AtomicLong from = new AtomicLong(Long.MAX_VALUE);
    final AtomicLong to = new AtomicLong(Long.MIN_VALUE);
    try {
        logParser.parse(new LogEntryReceiver() {
            @Override
            public void receiveEntry(TxnHeader header, Record record) throws Exception {
                indexRecord(header, record, count, from, to);
            }
        });

        IndexMetaData metaData = new IndexMetaData(new Date(from.get()), new Date(to.get()), count.get());
        IndexMetaData.write(metaData, IndexMetaData.getMetaDataFile(indexDirectory));
    } finally {
        Closeables.closeQuietly(writer);
        Closeables.closeQuietly(directory);
    }

    if (count.get() == 0) {
        exhibitor.getLog().add(ActivityLog.Type.INFO, sourceName + " has no entries and has not been indexed");
        exhibitor.getIndexCache().delete(indexDirectory);
    }
}

From source file:co.cask.cdap.data2.transaction.stream.CombineStreamConsumer.java

@Override
public void postTxCommit() {
    activeConsumer.postTxCommit();//from   w ww  .java  2  s .  com

    // If the first consumer has empty dequeue result in the poll call,
    // it's ok to switch to second consumer permanently in post commit call.
    if (activeConsumer == firstConsumer && emptyResult) {
        activeConsumer = secondConsumer;
        Closeables.closeQuietly(firstConsumer);
    }
}

From source file:com.eviware.loadui.impl.conversion.ReferenceToFileConverter.java

@Override
public File convert(Reference source) {
    if (source.getId().charAt(0) == ':')
        return new File(source.getId().substring(1));

    File target = getOrCreate(source);
    String hash = source.getId();

    synchronized (target) {
        while (!target.exists() || filesInProgress.contains(hash)) {
            try {
                log.debug("waiting for {}", source.getId());
                target.wait();// w w  w. j a  va 2s .  c om
            } catch (InterruptedException e) {
                log.debug("got waken up, was waiting for {}", source.getId());
            }
        }
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(target);
            String md5Hex = DigestUtils.md5Hex(fis);
            log.debug("target is: {} and is {} bytes with hash " + md5Hex, target, target.length());
        } catch (IOException e) {
            log.error("Exception while verifying hash", e);
            e.printStackTrace();
        } finally {
            Closeables.closeQuietly(fis);
        }
    }

    return target;
}

From source file:org.trancecode.xproc.step.XslFormatterStepProcessor.java

@Override
protected void execute(final StepInput input, final StepOutput output) throws Exception {
    LOG.trace("{@method}");

    final XdmNode source = input.readNode(XProcPorts.SOURCE);

    final URI baseUri = source.getBaseURI();
    final String href = input.getOptionValue(XProcOptions.HREF, null);
    assert href != null;
    final OutputStream resultOutputStream = input.getPipelineContext().getOutputResolver()
            .resolveOutputStream(href, baseUri.toString());
    try {//from w  w w. j ava 2s  .c  o m
        final String contentType = input.getOptionValue(XProcOptions.CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
        final FopFactoryBuilder fopFactoryBuilder = new FopFactoryBuilder(baseUri, new ResourceResolver() {
            @Override
            public Resource getResource(URI uri) throws IOException {
                final URI resolvedUri = Uris.resolve(uri, baseUri);
                final InputStream inputStream = input.getPipelineContext().getInputResolver()
                        .resolveInputStream(resolvedUri);
                return new Resource(inputStream);
            }

            @Override
            public OutputStream getOutputStream(URI uri) throws IOException {
                return null;
            }
        });
        final FopFactory fopFactory = fopFactoryBuilder.build();
        final Fop fop = fopFactory.newFop(contentType, resultOutputStream);
        /*fop.getUserAgent().setURIResolver((href1, base) -> {
        final URI uri = Uris.resolve(href1, base);
        final InputStream inputStream = input.getPipelineContext().getInputResolver()
                .resolveInputStream(href1, base);
        return new StreamSource(inputStream, uri.toString());
        });
        fop.getUserAgent().setBaseURL(source.getBaseURI().toString());*/

        final TransformerFactory factory = TransformerFactory.newInstance();
        final Transformer transformer = factory.newTransformer();

        final SAXResult fopResult = new SAXResult(fop.getDefaultHandler());

        transformer.transform(source.asSource(), fopResult);
    } finally {
        Closeables.closeQuietly(resultOutputStream);
    }

    output.writeNodes(XProcPorts.RESULT,
            input.newResultElement(Uris.resolve(href, baseUri.toString()).toString()));
}

From source file:co.cask.cdap.logging.gateway.handlers.ChunkedLogReaderCallback.java

@Override
public void close() {
    try {/*from   w  w  w.  j  a  v  a  2  s  . co m*/
        // Write the last chunk
        encodeSend(CharBuffer.allocate(0), true);
        // Flush the encoder
        CoderResult coderResult;
        do {
            coderResult = charsetEncoder.flush(chunkBuffer);
            chunkBuffer.flip();
            chunkResponder.sendChunk(ChannelBuffers.copiedBuffer(chunkBuffer));
            chunkBuffer.clear();
        } while (coderResult.isOverflow());
    } catch (IOException e) {
        // If cannot send chunks, nothing can be done (since the client closed connection).
        // Just log the error as debug.
        LOG.debug("Failed to send chunk", e);
    } finally {
        try {
            patternLayout.stop();
        } finally {
            Closeables.closeQuietly(chunkResponder);
        }
    }
}

From source file:com.mucommander.ui.viewer.text.TextViewer.java

private String detectEncoding(AbstractFile file) throws IOException {
    InputStream in = null;/*from w w w.j av  a  2s  . c o  m*/

    try {
        in = file.getInputStream();

        String encoding = EncodingDetector.detectEncoding(in);
        // If the encoding could not be detected or the detected encoding is not supported, default to UTF-8
        if (encoding == null || !Charset.isSupported(encoding))
            encoding = "UTF-8";

        return encoding;
    } finally {
        Closeables.closeQuietly(in);
    }
}

From source file:org.activityinfo.server.endpoint.gwtrpc.PersistentPolicyProvider.java

private SerializationPolicy tryFetchFromBlobService(String key) {
    try {/*w ww  .  j  a  v  a2  s  .c om*/
        LOGGER.fine("Trying to read serialization policy from blobservice at " + key);
        InputSupplier<? extends InputStream> inputSupplier = blobService.get(key);
        InputStream in = inputSupplier.getInput();
        try {
            SerializationPolicy policy = SerializationPolicyLoader.loadFromStream(in, null);

            LOGGER.info("Read serialization policy from blob service at " + key);

            return policy;
        } finally {
            Closeables.closeQuietly(in);
        }

    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Could not load serialization policy from cache", e);
    }
    return null;
}

From source file:com.netflix.exhibitor.core.config.filesystem.FileSystemConfigProvider.java

@Override
public LoadedInstanceConfig loadConfig() throws Exception {
    File propertiesFile = new File(propertiesDirectory, propertyFileName);
    Properties properties = new Properties();
    if (propertiesFile.exists()) {
        RandomAccessFile raf = new RandomAccessFile(propertiesFile, "rw");
        try {//from  w w  w . j  a  v  a 2 s. c  o  m
            FileLock lock = raf.getChannel().lock();
            try {
                properties.load(Channels.newInputStream(raf.getChannel()));
            } finally {
                lock.release();
            }
        } finally {
            Closeables.closeQuietly(raf);
        }
    }
    PropertyBasedInstanceConfig config = new PropertyBasedInstanceConfig(properties, defaults);
    return new LoadedInstanceConfig(config, propertiesFile.lastModified());
}