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:co.cask.cdap.data.file.LiveFileReader.java

@Override
public int read(Collection<? super T> events, int maxEvents, long timeout, TimeUnit unit, ReadFilter readFilter)
        throws IOException, InterruptedException {
    if (currentReader == null) {
        currentReader = renewReader();//from   w  w  w .j a v a 2  s . c  om
    }
    // No data yet
    if (currentReader == null) {
        return 0;
    }

    long startTime = System.nanoTime();
    int eventCount = currentReader.read(events, maxEvents, timeout, unit, readFilter);
    long timeElapse = System.nanoTime() - startTime;

    if (eventCount > 0) {
        return eventCount;
    }

    if (nextReader == null) {
        nextReader = renewReader();
    }

    if (nextReader != null) {
        long readTimeout = unit.toNanos(timeout) - timeElapse;
        if (readTimeout < 0) {
            readTimeout = 0;
        }

        if (eventCount == 0) {
            // Not yet EOF. Since next reader is already available, it could either be the reader doesn't see
            // the last flush from the writer in the read() above or the writer actually crashed.
            // To handle these cases, an extra read is done when a new reader is available but current read
            // gives no event, so that
            // 1. If the writer properly closed the file, by the time we see a new file here, an extra read should be
            //    able to see events till the end of file, as writer won't create new file before old one is closed.
            // 2. If the writer crashed, an extra read will still yield no event, but that's ok, as no more write will
            //    be happening to the old file.
            eventCount = currentReader.read(events, maxEvents, readTimeout, TimeUnit.NANOSECONDS, readFilter);
        }

        if (eventCount <= 0) {
            // Only switch reader when nothing get read above as it guaranteed no more events can come from the
            // currentReader since new file is already available.
            Closeables.closeQuietly(currentReader);
            currentReader = nextReader;
            nextReader = null;

            // If it's EOF, ok to read from new reader one more time without adjusting the readTime because a EOF
            // read (happened above) should return immediately.
            // Otherwise, if no events from current reader, it's safe to read from the new one, but with 0 timeout,
            // assuming the read happened above used up all readTimeout allowed time.
            if (eventCount < 0) {
                eventCount = currentReader.read(events, maxEvents, readTimeout, TimeUnit.NANOSECONDS,
                        readFilter);
            } else {
                eventCount = currentReader.read(events, maxEvents, 0, TimeUnit.NANOSECONDS, readFilter);
            }
        }
    }

    // It never reach EOF
    return (eventCount < 0) ? 0 : eventCount;
}

From source file:net.oneandone.troilus.EmbeddedCassandra.java

@SuppressWarnings("unchecked")
protected static int prepare() throws IOException {

    String cassandraDirName = "target" + File.separator + "cassandra-junit-" + new Random().nextInt(1000000);

    File cassandraDir = new File(cassandraDirName);
    cassandraDir.mkdirs();//from   w w w.  ja va 2s .  com

    InputStream cassandraConfigurationInput = null;
    Writer cassandraConfigurationOutput = null;

    try {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        cassandraConfigurationInput = loader.getResourceAsStream(CASSANDRA_YAML_FILE);

        Yaml yaml = new Yaml();
        Map<String, Object> cassandraConfiguration = (Map<String, Object>) yaml
                .load(cassandraConfigurationInput);

        int rpcPort = findUnusedLocalPort();
        if (rpcPort == -1) {
            throw new RuntimeException("Can not start embedded cassandra: no unused local port found!");
        }
        cassandraConfiguration.put("rpc_port", rpcPort);

        int storagePort = findUnusedLocalPort();
        if (storagePort == -1) {
            throw new RuntimeException("Can not start embedded cassandra: no unused local port found!");
        }
        cassandraConfiguration.put("storage_port", storagePort);

        int nativeTransportPort = findUnusedLocalPort();
        if (nativeTransportPort == -1) {
            throw new RuntimeException("Can not start embedded cassandra: no unused local port found!");
        }
        cassandraConfiguration.put("native_transport_port", nativeTransportPort);

        cassandraConfiguration.put("start_native_transport", "true");

        cassandraConfigurationOutput = new OutputStreamWriter(
                new FileOutputStream(cassandraDirName + File.separator + CASSANDRA_YAML_FILE), Charsets.UTF_8);

        yaml.dump(cassandraConfiguration, cassandraConfigurationOutput);

        System.setProperty("cassandra.config",
                new File(cassandraDirName, CASSANDRA_YAML_FILE).toURI().toString());
        System.setProperty("cassandra-foreground", "true");

        DatabaseDescriptor.createAllDirectories();

        return nativeTransportPort;

    } finally {
        Closeables.closeQuietly(cassandraConfigurationInput);
        Closeables.close(cassandraConfigurationOutput, true);
    }
}

From source file:org.locationtech.geogig.cli.porcelain.Apply.java

@Override
public void runInternal(GeogigCLI cli) throws IOException {
    checkParameter(patchFiles.size() < 2, "Only one single patch file accepted");
    checkParameter(!patchFiles.isEmpty(), "No patch file specified");

    ConsoleReader console = cli.getConsole();
    GeoGIG geogig = cli.getGeogig();/*  www.  j  a v  a2 s .c  o  m*/

    File patchFile = new File(patchFiles.get(0));
    checkParameter(patchFile.exists(), "Patch file cannot be found");
    FileInputStream stream;
    try {
        stream = new FileInputStream(patchFile);
    } catch (FileNotFoundException e1) {
        throw new CommandFailedException("Can't open patch file " + patchFile, e1);
    }
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        Closeables.closeQuietly(reader);
        Closeables.closeQuietly(stream);
        throw new CommandFailedException("Error reading patch file " + patchFile, e);
    }
    Patch patch = PatchSerializer.read(reader);
    Closeables.closeQuietly(reader);
    Closeables.closeQuietly(stream);

    if (reverse) {
        patch = patch.reversed();
    }

    if (summary) {
        console.println(patch.toString());
    } else if (check) {
        VerifyPatchResults verify = cli.getGeogig().command(VerifyPatchOp.class).setPatch(patch).call();
        Patch toReject = verify.getToReject();
        Patch toApply = verify.getToApply();
        if (toReject.isEmpty()) {
            console.println("Patch can be applied.");
        } else {
            console.println("Error: Patch cannot be applied\n");
            console.println("Applicable entries:\n");
            console.println(toApply.toString());
            console.println("\nConflicting entries:\n");
            console.println(toReject.toString());
        }
    } else {
        try {
            Patch rejected = geogig.command(ApplyPatchOp.class).setPatch(patch).setApplyPartial(reject).call();
            if (reject) {
                if (rejected.isEmpty()) {
                    console.println("Patch applied succesfully");
                } else {
                    int accepted = patch.count() - rejected.count();
                    StringBuilder sb = new StringBuilder();
                    File file = new File(patchFile.getAbsolutePath() + ".rej");
                    sb.append("Patch applied only partially.\n");
                    sb.append(Integer.toString(accepted) + " changes were applied.\n");
                    sb.append(Integer.toString(rejected.count()) + " changes were rejected.\n");
                    BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8);
                    PatchSerializer.write(writer, patch);
                    writer.flush();
                    writer.close();
                    sb.append("Patch file with rejected changes created at " + file.getAbsolutePath() + "\n");
                    throw new CommandFailedException(sb.toString());
                }
            } else {
                console.println("Patch applied succesfully");
            }
        } catch (CannotApplyPatchException e) {
            throw new CommandFailedException(e);
        }

    }

}

From source file:org.sonar.server.source.HtmlTextDecorator.java

List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder,
        @Nullable Integer from, @Nullable Integer to) {

    StringBuilder currentHtmlLine = new StringBuilder();
    List<String> decoratedHtmlLines = newArrayList();
    int currentLine = 1;

    BufferedReader stringBuffer = null;
    try {//from   www .  jav  a 2 s. c  o m
        stringBuffer = new BufferedReader(new StringReader(text));

        CharactersReader charsReader = new CharactersReader(stringBuffer);

        while (charsReader.readNextChar()) {
            if (shouldStop(currentLine, to)) {
                break;
            }
            if (shouldStartNewLine(charsReader)) {
                if (canAddLine(currentLine, from)) {
                    decoratedHtmlLines.add(currentHtmlLine.toString());
                }
                currentLine++;
                currentHtmlLine = new StringBuilder();
            }
            addCharToCurrentLine(charsReader, currentHtmlLine, decorationDataHolder);
        }

        closeCurrentSyntaxTags(charsReader, currentHtmlLine);

        if (shouldStartNewLine(charsReader)) {
            addLine(decoratedHtmlLines, currentHtmlLine.toString(), currentLine, from, to);
            currentLine++;
            addLine(decoratedHtmlLines, "", currentLine, from, to);
        } else if (currentHtmlLine.length() > 0) {
            addLine(decoratedHtmlLines, currentHtmlLine.toString(), currentLine, from, to);
        }

    } catch (IOException exception) {
        String errorMsg = "An exception occurred while highlighting the syntax of one of the project's files";
        Loggers.get(HtmlTextDecorator.class).error(errorMsg);
        throw new IllegalStateException(errorMsg, exception);
    } finally {
        Closeables.closeQuietly(stringBuffer);
    }

    return decoratedHtmlLines;
}

From source file:org.trancecode.xml.saxon.Saxon.java

public static XdmNode parse(final String xmlContent, final Processor processor) {
    final StringReader reader = new StringReader(xmlContent);
    try {/* www .  j a v  a2 s . co m*/
        return processor.newDocumentBuilder().build(new StreamSource(reader));
    } catch (final SaxonApiException e) {
        throw new IllegalStateException(e);
    } finally {
        Closeables.closeQuietly(reader);
    }
}

From source file:org.locationtech.geogig.remote.http.HttpUtils.java

/**
 * Consumes the provided input stream and then closes it.
 * /*from w ww .  j  av  a2s. c o m*/
 * @param stream the stream to consume and close
 * @throws IOException
 */
public static void consumeAndCloseStream(InputStream stream) throws IOException {
    if (stream != null) {
        try {
            // read the response body
            while (stream.read() > -1) {
                ; // $codepro.audit.disable extraSemicolon
            }
        } finally {
            // close the errorstream
            Closeables.closeQuietly(stream);
        }
    }
}

From source file:net.sourceforge.vaticanfetcher.model.parse.MSOffice2007Parser.java

@Override
protected ParseResult parse(File file, ParseContext context) throws ParseException {
    OPCPackage pkg = null;/*from  w w w.  j a v a2s  .  c  o  m*/
    try {
        pkg = OPCPackage.open(file.getPath(), PackageAccess.READ);
        String contents = extractText(pkg);

        // Open properties
        PackageProperties props = pkg.getPackageProperties();

        // Get author(s)
        String author = null;
        String defaultAuthor = props.getCreatorProperty().getValue();
        String lastAuthor = props.getLastModifiedByProperty().getValue();
        if (defaultAuthor == null) {
            if (lastAuthor != null)
                author = lastAuthor;
        } else if (lastAuthor == null) {
            author = defaultAuthor;
        } else {
            if (defaultAuthor.equals(lastAuthor))
                author = defaultAuthor;
            else
                author = defaultAuthor + ", " + lastAuthor; //$NON-NLS-1$
        }

        // Get other metadata
        String description = props.getDescriptionProperty().getValue();
        String keywords = props.getKeywordsProperty().getValue();
        String subject = props.getSubjectProperty().getValue();
        String title = props.getTitleProperty().getValue();

        return new ParseResult(contents).setTitle(title).addAuthor(author).addMiscMetadata(description)
                .addMiscMetadata(keywords).addMiscMetadata(subject);
    } catch (Exception e) {
        throw new ParseException(e);
    } finally {
        Closeables.closeQuietly(pkg);
    }
}

From source file:org.apache.mahout.classifier.rbm.network.DeepBoltzmannMachine.java

/**
 * Serialize to the output.//  ww  w.  j av a2  s  .  c  om
 *
 * @param output the output
 * @param conf the conf
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void serialize(Path output, Configuration conf) throws IOException {
    FileSystem fs = output.getFileSystem(conf);
    FSDataOutputStream out = fs.create(output, true);

    try {
        new IntWritable(rbms.size()).write(out);
        for (int i = 0; i < rbms.size(); i++) {
            if (i == 0)
                out.writeChars(rbms.get(i).getVisibleLayer().getClass().getName() + " ");
            out.writeChars(rbms.get(i).getHiddenLayer().getClass().getName() + " ");

            if (i < rbms.size() - 1)
                MatrixWritable.writeMatrix(out, ((SimpleRBM) rbms.get(i)).getWeightMatrix());
            else {
                MatrixWritable.writeMatrix(out, ((LabeledSimpleRBM) rbms.get(i)).getWeightMatrix());
                MatrixWritable.writeMatrix(out, ((LabeledSimpleRBM) rbms.get(i)).getWeightLabelMatrix());
            }
        }
    } finally {
        Closeables.closeQuietly(out);
    }
}

From source file:de.cosmocode.palava.core.inject.csv.CsvConverter.java

@Override
public List<String[]> convert(String value, TypeLiteral<?> toType) {
    final CloseableIterator<String[]> iterator = converter.convert(value, CsvIteratorConverter.LITERAL);

    try {/* w w w . j a v a2  s  .c  o m*/
        final List<String[]> lines = Lists.newArrayList(iterator);
        Preconditions.checkArgument(lines.size() > 0, "%s is empty", value);

        final String[] header = lines.get(0);

        for (int index = 1; index < lines.size(); index++) {
            final String[] line = lines.get(index);

            if (line.length == header.length) {
                continue;
            } else if (line.length < header.length) {
                final String[] copy = new String[header.length];
                Arrays.fill(copy, "");
                System.arraycopy(line, 0, copy, 0, line.length);
                lines.set(index, copy);
            } else {
                // we skip the header, but we count from line 1
                throw new IllegalArgumentException(String.format("Line #%s is too long", index - 1));
            }
        }

        return lines;
    } finally {
        Closeables.closeQuietly(iterator);
    }
}

From source file:zookeeper.example.discovery.DiscoveryExample.java

private static void processCommands(ServiceDiscovery<InstanceDetails> serviceDiscovery,
        Map<String, ServiceProvider<InstanceDetails>> providers, CuratorFramework client) throws Exception {
    // More scaffolding that does a simple command line processor

    printHelp();/*www. j  a va 2  s . co m*/

    List<ExampleServer> servers = Lists.newArrayList();
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        boolean done = false;
        while (!done) {
            System.out.print("> ");

            String command = in.readLine().trim();
            String[] parts = command.split("\\s");
            if (parts.length == 0) {
                continue;
            }
            String operation = parts[0];
            String args[] = Arrays.copyOfRange(parts, 1, parts.length);

            if (operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?")) {
                printHelp();
            } else if (operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit")) {
                done = true;
            } else if (operation.equals("add")) {
                addInstance(args, client, command, servers);
            } else if (operation.equals("delete")) {
                deleteInstance(args, command, servers);
            } else if (operation.equals("random")) {
                listRandomInstance(args, serviceDiscovery, providers, command);
            } else if (operation.equals("list")) {
                listInstances(serviceDiscovery);
            }
        }
    } finally {
        for (ExampleServer server : servers) {
            Closeables.closeQuietly(server);
        }
    }
}