List of usage examples for com.google.common.io Closeables close
public static void close(@Nullable Closeable closeable, boolean swallowIOException) throws IOException
From source file:eu.interedition.text.xml.XMLTransformer.java
public Text transform(Text source) throws IOException, XMLStreamException { Preconditions.checkArgument(source.getType() == Text.Type.XML); final Annotation layer = Iterables.getOnlyElement(Annotation.create(session, new Annotation(XML_TRANSFORM_NAME, new TextTarget(source, 0, source.getLength()), null))); this.source = source; this.target = Text.create(session, layer, Text.Type.TXT); try {/*from w w w. jav a 2s .c o m*/ Reader xmlReader = null; XMLStreamReader reader = null; try { xmlReader = source.read().getInput(); reader = xmlInputFactory.createXMLStreamReader(xmlReader); final Stack<XMLEntity> entities = new Stack<XMLEntity>(); start(); while (reader.hasNext()) { final int event = reader.next(); mapOffsetDelta(0, reader.getLocation().getCharacterOffset() - sourceOffset); switch (event) { case XMLStreamConstants.START_ELEMENT: endText(); nextSibling(); start(entities.push(XMLEntity.newElement(reader))); break; case XMLStreamConstants.END_ELEMENT: endText(); end(entities.pop()); break; case XMLStreamConstants.COMMENT: endText(); nextSibling(); emptyEntity(XMLEntity.newComment(reader)); break; case XMLStreamConstants.PROCESSING_INSTRUCTION: endText(); nextSibling(); emptyEntity(XMLEntity.newPI(reader)); break; case XMLStreamConstants.CHARACTERS: case XMLStreamConstants.ENTITY_REFERENCE: case XMLStreamConstants.CDATA: newText(reader.getText()); break; } } end(); } finally { XML.closeQuietly(reader); Closeables.close(xmlReader, false); } Reader textReader = null; try { return target.write(session, textReader = read()); } finally { Closeables.close(textReader, false); } } catch (Throwable t) { Throwables.propagateIfInstanceOf(t, IOException.class); Throwables.propagateIfInstanceOf(Throwables.getRootCause(t), XMLStreamException.class); throw Throwables.propagate(t); } }
From source file:com.twitter.common.net.http.handlers.AssetHandler.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { OutputStream responseBody = resp.getOutputStream(); if (checksumMatches(req)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else {/* w w w. j av a2s .c o m*/ setPayloadHeaders(resp); boolean gzip = supportsGzip(req); if (gzip) { resp.setHeader("Content-Encoding", GZIP_ENCODING); } InputStream in = new ByteArrayInputStream(gzip ? staticAsset.getGzipData() : staticAsset.getRawData()); ByteStreams.copy(in, responseBody); } Closeables.close(responseBody, /* swallowIOException */ true); }
From source file:org.apache.mahout.classifier.naivebayes.NaiveBayesModel.java
public void serialize(Path output, Configuration conf) throws IOException { FileSystem fs = output.getFileSystem(conf); FSDataOutputStream out = fs.create(new Path(output, "naiveBayesModel.bin")); try {//from w w w . j a va 2 s . co m out.writeFloat(alphaI); out.writeBoolean(isComplementary); VectorWritable.writeVector(out, weightsPerFeature); VectorWritable.writeVector(out, weightsPerLabel); if (isComplementary) { VectorWritable.writeVector(out, perlabelThetaNormalizer); } for (int row = 0; row < weightsPerLabelAndFeature.numRows(); row++) { VectorWritable.writeVector(out, weightsPerLabelAndFeature.viewRow(row)); } } finally { Closeables.close(out, false); } }
From source file:defrac.intellij.config.DefracConfig.java
public void write(@NotNull final Supplier<OutputStream> supplier) throws IOException { BufferedWriter out = null;/*from w w w .j a v a 2 s .c om*/ try { out = new BufferedWriter(new PrintWriter(supplier.get())); final Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); gson.toJson(this, DefracConfig.class, out); } finally { Closeables.close(out, true); } }
From source file:com.android.build.gradle.internal.NdkHandler.java
/** * Determine the location of the NDK directory. * * The NDK directory can be set in the local.properties file or using the ANDROID_NDK_HOME * environment variable.//from ww w . j a v a2 s .co m */ private static File findNdkDirectory(File projectDir) { File localProperties = new File(projectDir, FN_LOCAL_PROPERTIES); if (localProperties.isFile()) { Properties properties = new Properties(); InputStreamReader reader = null; try { //noinspection IOResourceOpenedButNotSafelyClosed FileInputStream fis = new FileInputStream(localProperties); reader = new InputStreamReader(fis, Charsets.UTF_8); properties.load(reader); } catch (FileNotFoundException ignored) { // ignore since we check up front and we don't want to fail on it anyway // in case there's an env var. } catch (IOException e) { throw new RuntimeException(String.format("Unable to read %1$s.", localProperties), e); } finally { try { Closeables.close(reader, true /* swallowIOException */); } catch (IOException e) { // ignore. } } String ndkDirProp = properties.getProperty("ndk.dir"); if (ndkDirProp != null) { return new File(ndkDirProp); } } else { String envVar = System.getenv("ANDROID_NDK_HOME"); if (envVar != null) { return new File(envVar); } } return null; }
From source file:org.codelibs.elasticsearch.taste.common.iterator.FileLineIterator.java
@Override public void close() throws IOException { endOfData(); Closeables.close(reader, true); }
From source file:org.apache.mahout.clustering.streaming.mapreduce.StreamingKMeansUtilsMR.java
/** * Writes centroids to a sequence file./*from ww w. j a va 2s . co m*/ * @param centroids the centroids to write. * @param path the path of the output file. * @param conf the configuration for the HDFS to write the file to. * @throws java.io.IOException */ public static void writeCentroidsToSequenceFile(Iterable<Centroid> centroids, Path path, Configuration conf) throws IOException { SequenceFile.Writer writer = null; try { writer = SequenceFile.createWriter(FileSystem.get(conf), conf, path, IntWritable.class, CentroidWritable.class); int i = 0; for (Centroid centroid : centroids) { writer.append(new IntWritable(i++), new CentroidWritable(centroid)); } } finally { Closeables.close(writer, true); } }
From source file:com.android.apigenerator.AndroidJarReader.java
public Map<String, ApiClass> getClasses() { HashMap<String, ApiClass> map = new HashMap<String, ApiClass>(); // Get all the android.jar. They are in platforms-# int apiLevel = mMinApi - 1; while (true) { apiLevel++;/*from ww w . j a va 2 s. c o m*/ try { File jar = null; if (apiLevel == mCurrentApi) { jar = mCurrentJar; } if (jar == null) { jar = getAndroidJarFile(apiLevel); } if (jar == null || !jar.isFile()) { System.out.println("Last API level found: " + (apiLevel - 1)); break; } System.out.println("Found API " + apiLevel + " at " + jar.getPath()); FileInputStream fis = new FileInputStream(jar); ZipInputStream zis = new ZipInputStream(fis); ZipEntry entry = zis.getNextEntry(); while (entry != null) { String name = entry.getName(); if (name.endsWith(".class")) { byte[] bytes = ByteStreams.toByteArray(zis); if (bytes == null) { System.err.println("Warning: Couldn't read " + name); entry = zis.getNextEntry(); continue; } ClassReader reader = new ClassReader(bytes); ClassNode classNode = new ClassNode(Opcodes.ASM5); reader.accept(classNode, 0 /*flags*/); ApiClass theClass = addClass(map, classNode.name, apiLevel, (classNode.access & Opcodes.ACC_DEPRECATED) != 0); // super class if (classNode.superName != null) { theClass.addSuperClass(classNode.superName, apiLevel); } // interfaces for (Object interfaceName : classNode.interfaces) { theClass.addInterface((String) interfaceName, apiLevel); } // fields for (Object field : classNode.fields) { FieldNode fieldNode = (FieldNode) field; if ((fieldNode.access & Opcodes.ACC_PRIVATE) != 0) { continue; } if (!fieldNode.name.startsWith("this$") && !fieldNode.name.equals("$VALUES")) { boolean deprecated = (fieldNode.access & Opcodes.ACC_DEPRECATED) != 0; theClass.addField(fieldNode.name, apiLevel, deprecated); } } // methods for (Object method : classNode.methods) { MethodNode methodNode = (MethodNode) method; if ((methodNode.access & Opcodes.ACC_PRIVATE) != 0) { continue; } if (!methodNode.name.equals("<clinit>")) { boolean deprecated = (methodNode.access & Opcodes.ACC_DEPRECATED) != 0; theClass.addMethod(methodNode.name + methodNode.desc, apiLevel, deprecated); } } } entry = zis.getNextEntry(); } Closeables.close(fis, true); } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } removeImplicitInterfaces(map); postProcessClasses(map); return map; }
From source file:org.grouplens.lenskit.data.dao.SimpleFileRatingDAO.java
@SuppressWarnings({ "PMD.AvoidCatchingThrowable", "unchecked" }) @Override// w ww . ja v a 2 s . c o m public <E extends Event> Cursor<E> streamEvents(Class<E> type, SortOrder order) { // if they don't want ratings, they get nothing if (!type.isAssignableFrom(Rating.class)) { return Cursors.empty(); } Comparator<Event> comp = order.getEventComparator(); Reader input = null; final String name = sourceFile.getPath(); logger.debug("Opening {}", sourceFile.getPath()); try { input = LKFileUtils.openInput(sourceFile, compression); // failing to close buffer & cursor in event of unlikely errors is OK BufferedReader buf; buf = new BufferedReader(input); Cursor<Rating> cursor; cursor = new DelimitedTextRatingCursor(buf, name, delimiter); if (comp == null) { return (Cursor<E>) cursor; } else { return (Cursor<E>) Cursors.sort(cursor, comp); } } catch (Throwable th) { // we got an exception, make sure we close the underlying reader since we won't be // returning a closeable. Otherwise we might leak file handles. if (input != null) { try { Closeables.close(input, true); } catch (IOException ioe) { // should never happen, we suppress exceptions throw new DataAccessException(ioe); } } Throwables.propagateIfPossible(th); throw new DataAccessException(th); } }
From source file:org.jclouds.examples.rackspace.DeleteAll.java
private void deleteCloudFiles() throws IOException { CloudFilesApi cloudFilesApi = ContextBuilder .newBuilder(System.getProperty("provider.cf", "rackspace-cloudfiles-us")) .credentials(username, apiKey).buildApi(CloudFilesApi.class); for (String region : cloudFilesApi.getConfiguredRegions()) { try {/*www .j ava 2s . c o m*/ System.out.format("Delete Containers of Objects in %s%n", region); ContainerApi containerApi = cloudFilesApi.getContainerApi(region); for (Container container : containerApi.list()) { System.out.format(" %s%n", container.getName()); ObjectApi objectApi = cloudFilesApi.getObjectApi(region, container.getName()); ObjectList objects = objectApi.list(); for (SwiftObject object : objects) { System.out.format(" %s%n", object.getName()); objectApi.delete(object.getName()); } cloudFilesApi.getContainerApi(region).deleteIfEmpty(container.getName()); } } catch (IllegalStateException e) { e.printStackTrace(); } } Closeables.close(cloudFilesApi, true); }