List of usage examples for com.google.common.io Closeables closeQuietly
public static void closeQuietly(@Nullable Reader reader)
From source file:com.netflix.exhibitor.core.config.zookeeper.ZookeeperConfigProvider.java
@Override public void close() throws IOException { state.set(State.CLOSED); Closeables.closeQuietly(cache); }
From source file:org.apache.mahout.classifier.BayesFileFormatter.java
/** * Write the input files to the outdir, one output file per input file * /*from www. j a va 2s . co m*/ * @param label * The label of the file * @param analyzer * The analyzer to use * @param input * The input file or directory. May not be null * @param charset * The Character set of the input files * @param outDir * The output directory. Files will be written there with the same name as the input file */ public static void format(String label, Analyzer analyzer, File input, Charset charset, File outDir) throws IOException { if (input.isDirectory()) { input.listFiles(new FileProcessor(label, analyzer, charset, outDir)); } else { Writer writer = Files.newWriter(new File(outDir, input.getName()), charset); try { writeFile(label, analyzer, input, charset, writer); } finally { Closeables.closeQuietly(writer); } } }
From source file:org.sonar.api.server.rule.RulesDefinitionXmlLoader.java
public void load(RulesDefinition.NewRepository repo, InputStream input, String encoding) { Reader reader = null;/*from ww w . j a va 2 s. c o m*/ try { reader = new InputStreamReader(input, encoding); load(repo, reader); } catch (IOException e) { throw new IllegalStateException("Fail to load XML file", e); } finally { Closeables.closeQuietly(reader); } }
From source file:hihex.cs.Preferences.java
private String readDefaultLogFilter() { final InputStream stream = mContext.getResources().openRawResource(R.raw.default_filter_config); final Reader reader = new InputStreamReader(stream, Charsets.UTF_8); try {//www. java 2 s . c o m return CharStreams.toString(reader); } catch (final IOException e) { // Should not happen throw new RuntimeException(e); } finally { Closeables.closeQuietly(reader); } }
From source file:com.zimbra.cs.index.TermsFilter.java
/** (non-Javadoc) * @see org.apache.lucene.search.Filter#getDocIdSet(org.apache.lucene.index.IndexReader) *///w w w . j av a2s.c o m @Override public DocIdSet getDocIdSet(IndexReader reader) throws IOException { OpenBitSet result = new OpenBitSet(reader.maxDoc()); TermDocs td = reader.termDocs(); try { for (Iterator<Term> iter = terms.iterator(); iter.hasNext();) { Term term = iter.next(); td.seek(term); while (td.next()) { result.set(td.doc()); } } } finally { Closeables.closeQuietly(td); } return result; }
From source file:org.geogit.cli.porcelain.Apply.java
@Override public void runInternal(GeogitCLI cli) throws IOException { checkParameter(patchFiles.size() < 2, "Only one single patch file accepted"); checkParameter(!patchFiles.isEmpty(), "No patch file specified"); ConsoleReader console = cli.getConsole(); GeoGIT geogit = cli.getGeogit();/*from w ww. ja v a 2s . com*/ 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.getGeogit().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 = geogit.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.apache.mahout.classifier.sequencelearning.hmm.hadoop.MapWritableCache.java
/** * Loads a MapWritable from the specified path. Returns null if no map exists. * * @param conf configuration object/*from w w w.j a v a 2s .com*/ * @param input path of the MapWritable in {@link DistributedCache} * @return MapWritable * @throws IOException */ public static MapWritable load(Configuration conf, Path input) throws IOException { SequenceFileValueIterator<MapWritable> iterator = new SequenceFileValueIterator<MapWritable>(input, true, conf); try { return iterator.next(); } finally { Closeables.closeQuietly(iterator); } }
From source file:org.apache.mahout.common.DevURandomSeedGenerator.java
/** * @return The requested number of random bytes, read directly from {@literal /dev/urandom}. * @throws SeedException If {@literal /dev/urandom} does not exist or is not accessible *//*from w w w.j a v a2 s . c o m*/ @Override public byte[] generateSeed(int length) throws SeedException { FileInputStream in = null; try { in = new FileInputStream(DEV_URANDOM); return ByteStreams.toByteArray(new LimitInputStream(in, length)); } catch (IOException ex) { throw new SeedException("Failed reading from " + DEV_URANDOM.getName(), ex); } catch (SecurityException ex) { // Might be thrown if resource access is restricted (such as in // an applet sandbox). throw new SeedException("SecurityManager prevented access to " + DEV_URANDOM.getName(), ex); } finally { Closeables.closeQuietly(in); } }
From source file:org.jclouds.elasticstack.handlers.ElasticStackErrorHandler.java
public void handleError(HttpCommand command, HttpResponse response) { // it is important to always read fully and close streams String message = parseMessage(response); Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); try {//ww w . j a v a 2 s . c o m message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: if ((command.getCurrentRequest().getEndpoint().getPath().endsWith("/info")) || (message != null && message.indexOf("could not be found") != -1)) exception = new ResourceNotFoundException(message, exception); else exception = new IllegalArgumentException(message, exception); break; case 401: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 405: exception = new IllegalArgumentException(message, exception); break; case 409: exception = new IllegalStateException(message, exception); break; } } finally { Closeables.closeQuietly(response.getPayload()); command.setException(exception); } }
From source file:org.apache.curator.framework.recipes.locks.SemaphoreClient.java
@Override public Void call() throws Exception { shouldRun = true;/*ww w. j ava 2 s .c o m*/ client.getConnectionStateListenable().addListener(this); try { while (shouldRun) { try { acquireAndRun(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // propagate up, don't sleep throw e; } catch (Exception e) { Thread.sleep(CLIENT_EXCEPTION_HANDLER_SLEEP_TIME_SECS * 1000L); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { Closeables.closeQuietly(client); } return null; }