List of usage examples for com.google.common.io Closeables closeQuietly
public static void closeQuietly(@Nullable Reader reader)
From source file:org.jage.platform.config.xml.loaders.RawDocumentLoader.java
@Override public Document loadDocument(final String path) throws ConfigurationException { InputStream input = null;/* ww w .ja v a 2s . c o m*/ try { final Resource resource = ResourceLoader.getResource(path); input = resource.getInputStream(); reader.setErrorHandler(new AgEXmlErrorHandler(path)); return reader.read(input); } catch (final IncorrectUriException e) { throw new ConfigurationException("Could not locate resource with path " + path, e); } catch (final IOException e) { throw new ConfigurationException("Could not open resource with path " + path, e); } catch (final DocumentException e) { throw new ConfigurationException("Could not read resource with path " + path, e); } finally { Closeables.closeQuietly(input); } }
From source file:org.sonar.java.resolve.BytecodeCompleter.java
@Override public void complete(JavaSymbol symbol) { String bytecodeName = formFullName(symbol); if (symbol.isPackageSymbol()) { bytecodeName = bytecodeName + ".package-info"; }/*w ww .j a v a2s.c om*/ JavaSymbol.TypeJavaSymbol classSymbol = getClassSymbol(bytecodeName); if (symbol.isPackageSymbol()) { ((JavaSymbol.PackageJavaSymbol) symbol).packageInfo = classSymbol; } Preconditions.checkState(symbol.isPackageSymbol() || classSymbol == symbol); InputStream inputStream = null; ClassReader classReader = null; try { inputStream = inputStreamFor(bytecodeName); if (inputStream != null) { classReader = new ClassReader(inputStream); } } catch (IOException e) { throw Throwables.propagate(e); } finally { Closeables.closeQuietly(inputStream); } if (classReader != null) { classReader.accept(new BytecodeVisitor(this, symbols, classSymbol, parametrizedTypeCache), ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG); } }
From source file:org.apache.s4.comm.ModulesLoaderFactory.java
private void addModuleToClasspath(File moduleFile, List<URL> classpath) { File moduleDir = null;/*from ww w . ja va2 s .c om*/ if (tmpDir == null) { moduleDir = Files.createTempDir(); moduleDir.deleteOnExit(); logger.warn( "s4.tmp.dir not specified, using temporary directory [{}] for unpacking S4R. You may want to specify a parent non-temporary directory.", moduleDir.getAbsolutePath()); } else { moduleDir = new File(tmpDir, moduleFile.getName() + "-" + System.currentTimeMillis()); if (!moduleDir.mkdir()) { throw new RuntimeException("Cannot create directory for unzipping S4R file in [" + moduleDir.getAbsolutePath() + "]. Aborting deployment."); } } logger.info("Unzipping S4R archive in [{}]", moduleDir.getAbsolutePath()); JarFile jar = null; try { jar = new JarFile(moduleFile); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (!entry.isDirectory()) { File to = new File(moduleDir, entry.getName()); Files.createParentDirs(to); InputStream is = jar.getInputStream(entry); OutputStream os = new FileOutputStream(to); try { ByteStreams.copy(is, os); } finally { Closeables.closeQuietly(is); Closeables.closeQuietly(os); } } } classpath.add(moduleDir.toURI().toURL()); addDirLibsToClassPath(classpath, moduleDir, "/lib"); } catch (IOException e) { logger.error("Cannot process S4R [{}]: {}", moduleFile.getAbsolutePath(), e.getClass().getName() + "/" + e.getMessage()); throw new RuntimeException("Cannot create S4R classloader", e); } }
From source file:com.atoito.jeauty.Beautifier.java
/** * Return the String representation of this node. * //w w w. ja v a2 s .c om * @return the String representation of this node */ private EnhancementResult beautify(String spacedSourceCode) { byte[] bytes = spacedSourceCode.getBytes(runOptions.getCharset()); InputStream in = new ByteArrayInputStream(bytes); CompilationUnit cu = null; try { cu = JavaParser.parse(in); } catch (Exception e) { return EnhancementResult.fail(e); } finally { Closeables.closeQuietly(in); } if (cu == null) { return EnhancementResult.fail("Unexpected error parsing sources (cu=null)"); } boolean printComments = true; final DumpVisitor visitor = new DumpVisitor(printComments); visitor.visit(cu, null); StringBuilder sb = new StringBuilder(); int beginLine = cu.getBeginLine(); if (beginLine > 1) { EnhancementResult headersResult = headerComments(spacedSourceCode, (beginLine - 1)); if (!headersResult.success) { return headersResult; } String headers = headersResult.contents; EnhancementResult codeResult = withoutHeaderComments(spacedSourceCode, (beginLine - 1)); if (!codeResult.success) { return codeResult; } String code = codeResult.contents; InputStream sin = null; try { sin = new ByteArrayInputStream(code.getBytes(runOptions.getCharset())); cu = JavaParser.parse(sin); } catch (Exception e) { return EnhancementResult.fail(e); } finally { Closeables.closeQuietly(sin); } if (cu == null) { return EnhancementResult.fail("Unexpected error parsing sources (cu=null)"); } final DumpVisitor nv = new DumpVisitor(printComments); nv.visit(cu, null); sb.append(headers); } PackageDeclaration pd = cu.getPackage(); sb.append(pd.toString()); List<ImportDeclaration> imports = cu.getImports(); if (imports != null && !imports.isEmpty()) { List<ImportDeclaration> javaImports = new ArrayList<>(); List<ImportDeclaration> otherImports = new ArrayList<>(); for (ImportDeclaration importDeclaration : imports) { NameExpr name = importDeclaration.getName(); if (name.toStringWithoutComments().startsWith("java.")) { javaImports.add(importDeclaration); } else { otherImports.add(importDeclaration); } } if (!javaImports.isEmpty()) { Collections.sort(javaImports, importsComparator); for (ImportDeclaration importDeclaration : javaImports) { sb.append(importDeclaration.toString()); } sb.append(runOptions.getEol()); } if (!otherImports.isEmpty()) { Collections.sort(otherImports, importsComparator); for (ImportDeclaration importDeclaration : otherImports) { sb.append(importDeclaration.toString()); } sb.append(runOptions.getEol()); } } List<Comment> orphanComments = cu.getOrphanComments(); if (orphanComments != null && !orphanComments.isEmpty()) { for (Comment comment : orphanComments) { sb.append(comment.toString()); } sb.append(runOptions.getEol()); } List<TypeDeclaration> types = cu.getTypes(); for (TypeDeclaration typeDeclaration : types) { sb.append(typeDeclaration.toString()); } if (runOptions.eofWithNewLine()) { sb.append(runOptions.getEol()); } return EnhancementResult.successful(sb.toString()); }
From source file:de.cosmocode.palava.core.Main.java
private static void printToStdErr(Exception e) { final OutputStream stream = new FileOutputStream(FileDescriptor.err); final PrintStream stderr = new PrintStream(stream); e.printStackTrace(stderr);/*from w w w . j av a 2 s . c om*/ Closeables.closeQuietly(stderr); }
From source file:com.zimbra.cs.index.RemoteQueryOperation.java
@Override public void close() throws IOException { Closeables.closeQuietly(results); super.close(); }
From source file:org.summer.dsl.builder.trace.TraceForStorageProvider.java
@Nullable public ITrace getTraceToSource(final IStorage derivedResource) { StorageAwareTrace result = traceToSourceProvider.get(); result.setLocalStorage(derivedResource); result.setTraceRegionProvider(new ITraceRegionProvider() { public AbstractTraceRegion getTraceRegion() { IStorage resource = derivedResource; if (resource instanceof IFile) { IStorage traceFile = getTraceFile(resource); if (traceFile instanceof IFile && ((IFile) traceFile).exists()) { InputStream contents = null; try { contents = traceFile.getContents(); return traceRegionSerializer.readTraceRegionFrom(contents); } catch (Exception e) { log.error(e.getMessage(), e); } finally { Closeables.closeQuietly(contents); }//w w w.ja v a2s.com } } throw new TraceNotFoundException(); } }); return result; }
From source file:org.sonar.core.source.HtmlTextDecorator.java
List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder) { StringBuilder currentHtmlLine = new StringBuilder(); List<String> decoratedHtmlLines = Lists.newArrayList(); BufferedReader stringBuffer = null; try {// w w w. ja v a2 s.c o m stringBuffer = new BufferedReader(new StringReader(text)); CharactersReader charsReader = new CharactersReader(stringBuffer); while (charsReader.readNextChar()) { if (shouldStartNewLine(charsReader)) { decoratedHtmlLines.add(currentHtmlLine.toString()); currentHtmlLine = new StringBuilder(); if (shouldReopenPendingTags(charsReader)) { reopenCurrentSyntaxTags(charsReader, currentHtmlLine); } } int numberOfTagsToClose = getNumberOfTagsToClose(charsReader.getCurrentIndex(), decorationDataHolder); closeCompletedTags(charsReader, numberOfTagsToClose, currentHtmlLine); if (shouldClosePendingTags(charsReader)) { closeCurrentSyntaxTags(charsReader, currentHtmlLine); } Collection<String> tagsToOpen = getTagsToOpen(charsReader.getCurrentIndex(), decorationDataHolder); openNewTags(charsReader, tagsToOpen, currentHtmlLine); if (shouldAppendCharToHtmlOutput(charsReader)) { char currentChar = (char) charsReader.getCurrentValue(); currentHtmlLine.append(normalize(currentChar)); } } closeCurrentSyntaxTags(charsReader, currentHtmlLine); if (shouldStartNewLine(charsReader)) { decoratedHtmlLines.add(currentHtmlLine.toString()); decoratedHtmlLines.add(""); } else if (currentHtmlLine.length() > 0) { decoratedHtmlLines.add(currentHtmlLine.toString()); } } catch (IOException exception) { String errorMsg = "An exception occurred while highlighting the syntax of one of the project's files"; LoggerFactory.getLogger(HtmlTextDecorator.class).error(errorMsg); throw new IllegalStateException(errorMsg, exception); } finally { Closeables.closeQuietly(stringBuffer); } return decoratedHtmlLines; }
From source file:com.metamx.druid.index.v1.CompressedFloatsIndexedSupplier.java
@Override public IndexedFloats get() { return new IndexedFloats() { int currIndex = -1; ResourceHolder<FloatBuffer> holder; FloatBuffer buffer;/* w w w . j a v a 2s.c o m*/ @Override public int size() { return totalSize; } @Override public float get(int index) { int bufferNum = index / sizePer; int bufferIndex = index % sizePer; if (bufferNum != currIndex) { loadBuffer(bufferNum); } return buffer.get(buffer.position() + bufferIndex); } @Override public void fill(int index, float[] toFill) { if (totalSize - index < toFill.length) { throw new IndexOutOfBoundsException( String.format("Cannot fill array of size[%,d] at index[%,d]. Max size[%,d]", toFill.length, index, totalSize)); } int bufferNum = index / sizePer; int bufferIndex = index % sizePer; int leftToFill = toFill.length; while (leftToFill > 0) { if (bufferNum != currIndex) { loadBuffer(bufferNum); } buffer.mark(); buffer.position(buffer.position() + bufferIndex); final int numToGet = Math.min(buffer.remaining(), leftToFill); buffer.get(toFill, toFill.length - leftToFill, numToGet); buffer.reset(); leftToFill -= numToGet; ++bufferNum; bufferIndex = 0; } } private void loadBuffer(int bufferNum) { Closeables.closeQuietly(holder); holder = baseFloatBuffers.get(bufferNum); buffer = holder.get(); currIndex = bufferNum; } @Override public String toString() { return "CompressedFloatsIndexedSupplier_Anonymous{" + "currIndex=" + currIndex + ", sizePer=" + sizePer + ", numChunks=" + baseFloatBuffers.size() + ", totalSize=" + totalSize + '}'; } @Override public void close() throws IOException { Closeables.close(holder, false); } }; }
From source file:org.apache.mahout.classifier.naivebayes.training.TrainUtils.java
/** Write the list of labels into a map file */ protected static void writeLabelIndex(Configuration conf, Iterable<String> labels, Path indexPath) throws IOException { FileSystem fs = FileSystem.get(indexPath.toUri(), conf); SequenceFile.Writer writer = new SequenceFile.Writer(fs, conf, indexPath, Text.class, IntWritable.class); try {//from w w w. j av a 2 s .co m int i = 0; for (String label : labels) { writer.append(new Text(label), new IntWritable(i++)); } } finally { Closeables.closeQuietly(writer); } }