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:com.metamx.druid.index.v1.MMappedIndexStorageAdapter.java

@Override
public DateTime getMinTime() {
    final IndexedLongs timestamps = index.getReadOnlyTimestamps();
    final DateTime retVal = new DateTime(timestamps.get(0));
    Closeables.closeQuietly(timestamps);
    return retVal;
}

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

@Override
public void close() throws IOException {
    Closeables.closeQuietly(inputStream);
}

From source file:org.prebake.os.PipeFlusher.java

public void start() {
    Runnable pipeDispatcher = new Runnable() {
        public void run() {
            boolean closed;
            synchronized (PipeFlusher.this) {
                closed = PipeFlusher.this.closed;
            }//w w w  .j ava  2 s.  c  om
            if (closed) {
                for (Pipe p; (p = livePipes.poll()) != null;) {
                    OutputStream out = p.from.getOutputStream();
                    if (out != null) {
                        Closeables.closeQuietly(out);
                    }
                    InputStream in = p.to.getInputStream();
                    if (in != null) {
                        Closeables.closeQuietly(in);
                    }
                }
                pipeDispatcherFuture.cancel(false);
                return;
            }
            for (Pipe p; (p = livePipes.poll()) != null;) {
                OutputStream out = p.to.getOutputStream();
                if (out == null) {
                    dropPipe(p);
                    continue;
                }
                InputStream in = p.from.getInputStream();
                try {
                    int n = in.available();
                    if (n > 0) {
                        handlePipe(in, out, p);
                    } else {
                        try {
                            if (p.noneAvailableCount++ >= 10) {
                                checkClosed(p);
                            } else {
                                pushPipe(p);
                            }
                        } catch (InterruptedException ex) {
                            dropPipe(p);
                        }
                    }
                } catch (IOException ex) {
                    dropPipe(p);
                }
            }
        }
    };
    pipeDispatcherFuture = execer.scheduleWithFixedDelay(pipeDispatcher, 50, 50, TimeUnit.MILLISECONDS);
}

From source file:de.cosmocode.palava.cache.JacksonMarshaller.java

@Override
public Serializable apply(@Nullable Object input) {
    if (input == null) {
        return null;
    }/*from w  w  w . j  av  a 2  s  . c  o m*/

    final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = null;

    try {
        objectOutputStream = new ObjectOutputStream(byteStream);

        // write metadata
        final Object value;
        if (input instanceof MetaValue) {
            final MetaValue metaValue = MetaValue.class.cast(input);
            objectOutputStream.writeBoolean(true);
            objectOutputStream.writeUTF(metaValue.getValueClassName());

            objectOutputStream.writeObject(metaValue.getKey());
            objectOutputStream.writeLong(metaValue.getIdleTimeInSeconds());
            objectOutputStream.writeLong(metaValue.getLifeTimeInSeconds());
            if (metaValue.getIdleTimeInSeconds() > 0) {
                objectOutputStream.writeLong(metaValue.getStoredAt().getTime());
                objectOutputStream.writeLong(metaValue.getLastAccessedAt().getTime());
            }
            value = metaValue.getValue();
        } else {
            objectOutputStream.writeBoolean(false);
            objectOutputStream.writeUTF(input.getClass().getName());
            value = input;
        }

        factory.createJsonGenerator(objectOutputStream, JsonEncoding.UTF8).writeObject(value);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    } finally {
        Closeables.closeQuietly(objectOutputStream);
    }

    final byte[] bytes = byteStream.toByteArray();

    if (LOG.isTraceEnabled()) {
        LOG.trace("Writing {}", new String(bytes, Charsets.UTF_8));
    }

    return bytes;
}

From source file:com.metamx.druid.index.v1.CompressedLongsSupplierSerializer.java

public void closeAndConsolidate(OutputSupplier<? extends OutputStream> consolidatedOut) throws IOException {
    endBuffer.limit(endBuffer.position());
    endBuffer.rewind();/*from   www  .  ja v  a  2s  .c o m*/
    flattener.write(StupidResourceHolder.create(endBuffer));
    endBuffer = null;

    flattener.close();

    OutputStream out = null;
    try {
        out = consolidatedOut.getOutput();

        out.write(CompressedLongsIndexedSupplier.version);
        out.write(Ints.toByteArray(numInserted));
        out.write(Ints.toByteArray(sizePer));
        ByteStreams.copy(flattener.combineStreams(), out);
    } finally {
        Closeables.closeQuietly(out);
    }
}

From source file:uk.co.unclealex.process.gobblers.StreamGobbler.java

/**
 * {@inheritDoc}
 */
@Override
public void close() throws IOException {
    Closeables.closeQuietly(getInputStream());
}

From source file:com.metamx.druid.http.FileRequestLogger.java

@LifecycleStop
public void stop() {
    synchronized (lock) {
        Closeables.closeQuietly(fileWriter);
    }
}

From source file:net.sourceforge.docfetcher.model.search.HighlightService.java

@MutableCopy
@NotNull//from  w  ww .  java  2  s.  c  o  m
@SuppressWarnings("unchecked")
private static List<Range> highlightPhrases(@NotNull Query query, @NotNull String text)
        throws CheckedOutOfMemoryError {
    // FastVectorHighlighter only supports TermQuery, PhraseQuery and BooleanQuery
    FastVectorHighlighter highlighter = new FastVectorHighlighter(true, true, null, null);
    FieldQuery fieldQuery = highlighter.getFieldQuery(query);
    Directory directory = new RAMDirectory();
    try {
        /*
         * Hack: We have to put the given text in a RAM index, because the
         * fast-vector highlighter can only work on index readers
         */
        IndexWriterAdapter writer = new IndexWriterAdapter(directory);
        Document doc = new Document();
        doc.add(Fields.createContent(text, true)); // must store token positions and offsets
        writer.add(doc);
        Closeables.closeQuietly(writer); // flush unwritten documents into index
        IndexReader indexReader = IndexReader.open(directory);

        // This might throw an OutOfMemoryError
        FieldTermStack fieldTermStack = new FieldTermStack(indexReader, 0, Fields.CONTENT.key(), fieldQuery);

        FieldPhraseList fieldPhraseList = new FieldPhraseList(fieldTermStack, fieldQuery);

        // Hack: We'll use reflection to access a private field
        java.lang.reflect.Field field = fieldPhraseList.getClass().getDeclaredField("phraseList");
        field.setAccessible(true);
        LinkedList<WeightedPhraseInfo> infoList = (LinkedList<WeightedPhraseInfo>) field.get(fieldPhraseList);

        List<Range> ranges = new ArrayList<Range>(infoList.size());
        for (WeightedPhraseInfo phraseInfo : infoList) {
            int start = phraseInfo.getStartOffset();
            int end = phraseInfo.getEndOffset();
            ranges.add(new Range(start, end - start));
        }
        return ranges;
    } catch (OutOfMemoryError e) {
        throw new CheckedOutOfMemoryError(e);
    } catch (Exception e) {
        return new ArrayList<Range>(0);
    }
}

From source file:org.akraievoy.cnet.net.vo.VertexData.java

public InputStream createStream() {
    return new InputStream() {
        StreamState state = StreamState.DEF;
        int defPos = 0;
        byte[] defBits = new byte[8];
        InputStream edgeStoreIn = null;

        @Override//w ww . java2  s  .  c  om
        public int read() throws IOException {
            switch (state) {
            case DEF: {
                if (defPos == 0) {
                    longBits(Double.doubleToLongBits(nullElement), defBits);
                }
                final int res = escapeByte(defBits[defPos++]);
                if (defPos == defBits.length) {
                    state = StreamState.WIDTH;
                }
                return res;
            }
            case WIDTH:
                state = StreamState.DATA;
                return escapeByte((byte) data.width().ordinal());
            case DATA: {
                if (edgeStoreIn == null) {
                    edgeStoreIn = data.createStream();
                }
                int res = edgeStoreIn.read();

                if (res < 0) {
                    state = StreamState.COMPLETE;
                }

                return res;
            }
            case COMPLETE:
                return -1;
            default:
                throw new IllegalStateException("implement handling state " + state);
            }
        }

        @Override
        public void close() throws IOException {
            Closeables.closeQuietly(edgeStoreIn);
        }
    };
}

From source file:co.cask.cdap.gateway.handlers.TransactionHttpHandler.java

/**
 * Retrieve the state of the transaction manager.
 *//*from w  ww.jav  a2s  .  c  o  m*/
@Path("/transactions/state")
@GET
public void getTxManagerSnapshot(HttpRequest request, HttpResponder responder) {
    try {
        LOG.trace("Taking transaction manager snapshot at time {}", System.currentTimeMillis());
        LOG.trace("Took and retrieved transaction manager snapshot successfully.");
        try (InputStream in = txClient.getSnapshotInputStream()) {
            ChunkResponder chunkResponder = responder.sendChunkStart(HttpResponseStatus.OK,
                    ImmutableMultimap.<String, String>of());
            while (true) {
                // netty doesn't copy the readBytes buffer, so we have to reallocate a new buffer
                byte[] readBytes = new byte[4096];
                int res = in.read(readBytes, 0, 4096);
                if (res == -1) {
                    break;
                }
                // If failed to send chunk, IOException will be raised.
                // It'll just propagated to the netty-http library to handle it
                chunkResponder.sendChunk(ChannelBuffers.wrappedBuffer(readBytes, 0, res));
            }
            Closeables.closeQuietly(chunkResponder);
        }
    } catch (Exception e) {
        LOG.error("Could not take transaction manager snapshot", e);
        responder.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
}