List of usage examples for com.google.common.io Closeables closeQuietly
public static void closeQuietly(@Nullable Reader reader)
From source file:co.cask.cdap.data2.transaction.stream.CombineStreamConsumer.java
@Override public void close() throws IOException { if (activeConsumer == firstConsumer) { Closeables.closeQuietly(firstConsumer); secondConsumer.close();/*from ww w. ja va 2 s .co m*/ } else { activeConsumer.close(); } }
From source file:core.routing.ITSupport.java
/** * Fetches file from given URL.//from w ww. ja v a 2 s. c o m * * @param url * @return * @throws IOException */ protected InputStream getPrefixFileFrom(final String url) throws IOException { InputStream entityStream = null; try { final HttpResponse httpResponse = executeGet(url); assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(200)); assertThat(httpResponse.getEntity(), is(notNullValue())); entityStream = httpResponse.getEntity().getContent(); return entityStream; } catch (IOException e) { Closeables.closeQuietly(entityStream); throw e; } }
From source file:org.jclouds.cloudsigma.handlers.CloudSigmaErrorHandler.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 {/*from ww w .jav a2 s . co 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 if (message != null && message.indexOf("currently in use") != -1) exception = new IllegalStateException(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:com.cloudera.data.filesystem.FileSystemMetadataProvider.java
@Override public DatasetDescriptor load(String name) throws IOException { logger.debug("Loading dataset metadata name:{}", name); Path directory = new Path(pathForDataset(name), METADATA_DIRECTORY); InputStream inputStream = null; Properties properties = new Properties(); DatasetDescriptor.Builder builder = new DatasetDescriptor.Builder(); try {//from ww w . j a v a2 s . c om inputStream = fileSystem.open(new Path(directory, DESCRIPTOR_FILE_NAME)); properties.load(inputStream); if (properties.containsKey(PARTITION_EXPRESSION_FIELD_NAME)) { builder.partitionStrategy( new PartitionExpression(properties.getProperty(PARTITION_EXPRESSION_FIELD_NAME), true) .evaluate()); } } finally { Closeables.closeQuietly(inputStream); } try { inputStream = fileSystem.open(new Path(directory, SCHEMA_FILE_NAME)); builder.schema( new Schema.Parser().parse(new String(ByteStreams.toByteArray(inputStream), Charsets.UTF_8))); } finally { Closeables.closeQuietly(inputStream); } return builder.get(); }
From source file:org.sonar.core.source.HtmlTextWrapper.java
public String wrapTextWithHtml(String text, SyntaxHighlightingRuleSet syntaxHighlighting) throws IOException { List<SyntaxHighlightingRule> highlightingRules = syntaxHighlighting.getSyntaxHighlightingRuleSet(); StringBuilder decoratedText = new StringBuilder(); BufferedReader stringBuffer = null; try {//from w ww. j a v a 2 s. c o m stringBuffer = new BufferedReader(new StringReader(text)); CharactersReader context = new CharactersReader(stringBuffer); while (context.readNextChar()) { if (shouldStartNewLine(context)) { decoratedText.append(OPEN_TABLE_LINE); if (shouldReopenPendingTags(context)) { reopenCurrentSyntaxTags(context, decoratedText); } } Collection<SyntaxHighlightingRule> tagsToClose = Collections2.filter(highlightingRules, new IndexRuleFilter(context.getCurrentIndex(), false)); closeCompletedTags(context, tagsToClose, decoratedText); if (shouldClosePendingTags(context)) { closeCurrentSyntaxTags(context, decoratedText); decoratedText.append(CLOSE_TABLE_LINE); } Collection<SyntaxHighlightingRule> tagsToOpen = Collections2.filter(highlightingRules, new IndexRuleFilter(context.getCurrentIndex(), true)); openNewTags(context, tagsToOpen, decoratedText); decoratedText.append((char) context.getCurrentValue()); } } catch (IOException exception) { String errorMsg = "An exception occurred while highlighting the syntax of one of the project's files"; LoggerFactory.getLogger(HtmlTextWrapper.class).error(errorMsg); throw new IllegalStateException(errorMsg, exception); } finally { Closeables.closeQuietly(stringBuffer); } return decoratedText.toString(); }
From source file:com.android.builder.internal.incremental.FileManager.java
/** * Loads the known state.// www. j ava 2 s. co m * * @param stateFile the file to load the state from. * @return false if the loading failed. * * @see #write(java.io.File) */ public boolean load(File stateFile) { if (!stateFile.exists()) { return false; } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(stateFile), Charsets.UTF_8)); String line = null; while ((line = reader.readLine()) != null) { // skip comments if (line.charAt(0) == '#') { continue; } // get the data with a regexp Matcher m = READ_PATTERN.matcher(line); if (m.matches()) { String path = m.group(4); File f = new File(path); FileEntity entity = new FileEntity(f, Long.parseLong(m.group(1)), Long.parseLong(m.group(2)), m.group(3)); mLoadedFiles.put(f, entity); } } return true; } catch (FileNotFoundException ignored) { // won't happen, we check up front. } catch (UnsupportedEncodingException ignored) { // shouldn't happen, but if it does, we just won't have a cache. } catch (IOException ignored) { // shouldn't happen, but if it does, we just won't have a cache. } finally { Closeables.closeQuietly(reader); } return false; }
From source file:org.iteventviewer.app.LicenseActivity.java
private static Observable<String> licenseTextStream(final AssetManager assetManager) { return Observable.create(new Observable.OnSubscribe<String>() { @Override/*from w w w . j av a2s . c o m*/ public void call(Subscriber<? super String> subscriber) { BufferedReader reader = null; try { String[] fileNames = assetManager.list("licenses"); for (String fileName : fileNames) { InputStream is = assetManager.open("licenses/" + fileName); reader = new BufferedReader(new InputStreamReader(is, Charsets.UTF_8)); StringBuilder builder = new StringBuilder(); char[] charBuffer = new char[8 * 1024]; int r; while ((r = reader.read(charBuffer)) != -1) { builder.append(charBuffer, 0, r); } subscriber.onNext(builder.toString()); } } catch (IOException e) { subscriber.onError(e); } finally { Closeables.closeQuietly(reader); subscriber.onCompleted(); } } }).observeOn(Schedulers.io()); }
From source file:org.jclouds.http.functions.ParseFirstJsonValueNamed.java
@Override public T apply(HttpResponse arg0) { if (arg0.getPayload() == null) return nothing(); JsonReader reader = null;//from w w w . j av a 2 s. c o m try { reader = new JsonReader(new InputStreamReader(arg0.getPayload().getInput())); // in case keys are not in quotes reader.setLenient(true); AtomicReference<String> name = Atomics.newReference(); JsonToken token = reader.peek(); for (; token != JsonToken.END_DOCUMENT && nnn(reader, token, name); token = skipAndPeek(token, reader)) { } if (name.get() == null) { logger.trace("did not object named %s in json from response %s", nameChoices, arg0); return nothing(); } else if (nameChoices.contains(name.get())) { return json.delegate().<T>fromJson(reader, type.getType()); } else { return nothing(); } } catch (IOException e) { throw new RuntimeException( String.format("error reading from stream, parsing object named %s from http response %s", nameChoices, arg0), e); } finally { Closeables.closeQuietly(reader); arg0.getPayload().release(); } }
From source file:com.cloudera.cdk.morphline.stdlib.GrokDictionaries.java
private void loadDictionaryFile(File fileOrDir) throws IOException { if (!fileOrDir.exists()) { throw new FileNotFoundException("File not found: " + fileOrDir); }/* w w w .j a v a 2s.co m*/ if (!fileOrDir.canRead()) { throw new IOException("Insufficient permissions to read file: " + fileOrDir); } if (fileOrDir.isDirectory()) { File[] files = fileOrDir.listFiles(); Arrays.sort(files); for (File file : files) { loadDictionaryFile(file); } } else { Reader reader = new InputStreamReader(new FileInputStream(fileOrDir), "UTF-8"); try { loadDictionary(reader); } finally { Closeables.closeQuietly(reader); } } }
From source file:co.cask.cdap.internal.app.runtime.flow.FlowletProgramController.java
@Override protected void doStop() throws Exception { LOG.info("Stopping flowlet: " + flowletContext); try {/*from w ww. ja v a 2s . com*/ driver.stopAndWait(); } finally { // Close all consumers for (ConsumerSupplier consumerSupplier : consumerSuppliers) { Closeables.closeQuietly(consumerSupplier); } flowletContext.close(); } LOG.info("Flowlet stopped: " + flowletContext); }