/** * @param r read and closed as a side-effect of this operation. */ public static CharProducer create(@WillClose Reader r, FilePosition pos) throws IOException { int limit = 0; char[] buf = new char[4096]; try { for (int n = 0; (n = r.read(buf, limit, buf.length - limit)) > 0;) { limit += n; if (limit == buf.length) { char[] newBuf = new char[buf.length * 2]; System.arraycopy(buf, 0, newBuf, 0, limit); buf = newBuf; } } } finally { r.close(); } return new CharProducerImpl(buf, limit, pos); }
protected static byte[] readStream(@WillClose InputStream is) throws IOException { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] barr = new byte[4096]; int totalLen = 0; for (int n; (n = is.read(barr)) > 0;) { if ((totalLen += n) > MAX_RESPONSE_SIZE_BYTES) { throw new IOException("Response too large"); } buffer.write(barr, 0, n); } return buffer.toByteArray(); } finally { is.close(); } }
/** * Write the passed object to an {@link OutputStream}. * * @param aObject * The object to be written. May not be <code>null</code>. * @param aOS * The output stream to write to. Will always be closed. May not be * <code>null</code>. * @return {@link ESuccess} */ @Nonnull default ESuccess write (@Nonnull final JAXBTYPE aObject, @Nonnull @WillClose final OutputStream aOS) { try { if (USE_JAXB_CHARSET_FIX) { return write (aObject, SafeXMLStreamWriter.create (aOS, getXMLWriterSettings ())); } return write (aObject, TransformResultFactory.create (aOS)); } finally { // Needs to be manually closed StreamHelper.close (aOS); } }
@Nonnull public ISettings readSettings (@Nonnull @WillClose final InputStream aIS) { ValueEnforcer.notNull (aIS, "InputStream"); // Create the settings object final ISettings aSettings = m_aSettingsFactory.apply (getReadSettingsName ()); // Read the properties file from the input stream final NonBlockingProperties aProps = PropertiesHelper.loadProperties (aIS); if (aProps != null) for (final Map.Entry <String, String> aEntry : aProps.entrySet ()) aSettings.putIn (aEntry.getKey (), aEntry.getValue ()); return aSettings; }
@Nonnull public ESuccess writeSettings (@Nonnull final ISettings aSettings, @Nonnull @WillClose final OutputStream aOS) { ValueEnforcer.notNull (aSettings, "Settings"); ValueEnforcer.notNull (aOS, "OutputStream"); try { // Inside try so that OS is closed ValueEnforcer.notNull (aSettings, "Settings"); // No event manager invocation on writing final SettingsMicroDocumentConverter <T> aConverter = new SettingsMicroDocumentConverter <> (m_aSettingsFactory); final IMicroDocument aDoc = new MicroDocument (); aDoc.appendChild (aConverter.convertToMicroElement (GenericReflection.uncheckedCast (aSettings), getWriteNamespaceURI (), getWriteElementName ())); // auto-closes the stream return MicroWriter.writeToStream (aDoc, aOS, m_aXWS); } finally { StreamHelper.close (aOS); } }
/** * Check if the passed reader can be resembled to valid CSS content. This is * accomplished by fully parsing the CSS each time the method is called. This * is similar to calling * {@link #readFromStream(IHasInputStream, Charset, ECSSVersion)} and checking * for a non-<code>null</code> result. * * @param aReader * The reader to use. May not be <code>null</code>. * @param eVersion * The CSS version to use. May not be <code>null</code>. * @return <code>true</code> if the CSS is valid according to the version, * <code>false</code> if not */ public static boolean isValidCSS (@Nonnull @WillClose final Reader aReader, @Nonnull final ECSSVersion eVersion) { ValueEnforcer.notNull (aReader, "Reader"); ValueEnforcer.notNull (eVersion, "Version"); try { final CSSCharStream aCharStream = new CSSCharStream (aReader); final CSSNode aNode = _readStyleDeclaration (aCharStream, eVersion, getDefaultParseErrorHandler (), new DoNothingCSSParseExceptionCallback ()); return aNode != null; } finally { StreamHelper.close (aReader); } }
/** * @param rawIn * @throws IOException */ private void processPackageList(@WillClose Reader rawIn) throws IOException { try { BufferedReader in = new BufferedReader(rawIn); while (true) { String s = in.readLine(); if (s == null) break; s = s.trim(); if (s.length() == 0) continue; String packageName = s.substring(1).trim(); if (s.charAt(0) == '+') { check.add(packageName); dontCheck.remove(packageName); } else if (s.charAt(0) == '-') { dontCheck.add(packageName); check.remove(packageName); } else throw new IllegalArgumentException("Can't parse " + category + " filter line: " + s); } } finally { rawIn.close(); } }
/** * Check if the passed reader can be resembled to valid CSS content. This is * accomplished by fully parsing the CSS each time the method is called. This * is similar to calling * {@link #readFromStream(IHasInputStream, Charset, ECSSVersion)} and checking * for a non-<code>null</code> result. * * @param aReader * The reader to use. May not be <code>null</code>. * @param eVersion * The CSS version to use. May not be <code>null</code>. * @return <code>true</code> if the CSS is valid according to the version, * <code>false</code> if not */ public static boolean isValidCSS (@Nonnull @WillClose final Reader aReader, @Nonnull final ECSSVersion eVersion) { ValueEnforcer.notNull (aReader, "Reader"); ValueEnforcer.notNull (eVersion, "Version"); try { final CSSCharStream aCharStream = new CSSCharStream (aReader); final CSSNode aNode = _readStyleSheet (aCharStream, eVersion, getDefaultParseErrorHandler (), new DoNothingCSSParseExceptionCallback (), false); return aNode != null; } finally { StreamHelper.close (aReader); } }
@Nullable public static IMicroDocument readMicroXML (@WillClose @Nullable final InputStream aIS, @Nullable final ISAXReaderSettings aSettings) { if (aIS == null) return null; try { return readMicroXML (InputSourceFactory.create (aIS), aSettings); } finally { StreamHelper.close (aIS); } }
@CheckForNull private Document parseDocument(@WillClose InputStream is) { try { if (builder == null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); } return builder.parse(is); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } catch (SAXException e) { FindbugsPlugin.getDefault().logException(e, "Failed to parse xml file"); return null; } catch (IOException e) { FindbugsPlugin.getDefault().logException(e, "Failed to read the xml file"); return null; } finally { try { is.close(); } catch (IOException e) { assert true; } } }
public static byte[] readAll(@WillClose InputStream in, int size) throws IOException { try { if (size == 0) throw new IllegalArgumentException(); byte[] result = new byte[size]; int pos = 0; while (true) { int sz; while ((sz = in.read(result, pos, size - pos)) > 0) { pos += sz; } if (pos < size) return Arrays.copyOf(result, pos); int nextByte = in.read(); if (nextByte == -1) return result; size = size * 2 + 500; result = Arrays.copyOf(result, size); result[pos++] = (byte) nextByte; } } finally { close(in); } }
/** * Write the passed map to the passed output stream using the predefined XML * layout. * * @param aMap * The map to be written. May not be <code>null</code>. * @param aOS * The output stream to write to. The stream is closed independent of * success or failure. May not be <code>null</code>. * @return {@link ESuccess#SUCCESS} when everything went well, * {@link ESuccess#FAILURE} otherwise. */ @Nonnull public static ESuccess writeMap (@Nonnull final Map <String, String> aMap, @Nonnull @WillClose final OutputStream aOS) { ValueEnforcer.notNull (aMap, "Map"); ValueEnforcer.notNull (aOS, "OutputStream"); try { final IMicroDocument aDoc = createMapDocument (aMap); return MicroWriter.writeToStream (aDoc, aOS, XMLWriterSettings.DEFAULT_XML_SETTINGS); } finally { StreamHelper.close (aOS); } }
/** * Write the passed collection to the passed output stream using the * predefined XML layout. * * @param aCollection * The map to be written. May not be <code>null</code>. * @param aOS * The output stream to write to. The stream is closed independent of * success or failure. May not be <code>null</code>. * @return {@link ESuccess#SUCCESS} when everything went well, * {@link ESuccess#FAILURE} otherwise. */ @Nonnull public static ESuccess writeList (@Nonnull final Collection <String> aCollection, @Nonnull @WillClose final OutputStream aOS) { ValueEnforcer.notNull (aCollection, "Collection"); ValueEnforcer.notNull (aOS, "OutputStream"); try { final IMicroDocument aDoc = createListDocument (aCollection); return MicroWriter.writeToStream (aDoc, aOS, XMLWriterSettings.DEFAULT_XML_SETTINGS); } finally { StreamHelper.close (aOS); } }
public void writeEnabledMatchersAsXML(@WillClose OutputStream out) throws IOException { XMLOutput xmlOutput = new OutputStreamXMLOutput(out); try { xmlOutput.beginDocument(); xmlOutput.openTag("FindBugsFilter"); Iterator<Matcher> i = childIterator(); while (i.hasNext()) { Matcher child = i.next(); if (!disabled.containsKey(child)) { child.writeXML(xmlOutput, false); } } xmlOutput.closeTag("FindBugsFilter"); } finally { xmlOutput.finish(); } }
@Nonnull private static ByteBuffer _convert (@Nonnull @WillClose final ReadableByteChannel aChannel) throws IOException { try { final ByteBuffer buf = ByteBuffer.allocate (1024); final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream (); final WritableByteChannel aOutChannel = Channels.newChannel (aBAOS); while (aChannel.read (buf) > 0) { buf.flip (); aOutChannel.write (buf); } return ByteBuffer.wrap (aBAOS.toByteArray ()); } finally { StreamHelper.close (aChannel); } }
/** * Close the passed object, without trying to call flush on it. * * @param aCloseable * The object to be closed. May be <code>null</code>. * @return {@link ESuccess#SUCCESS} if the object was successfully closed. */ @Nonnull public static ESuccess closeWithoutFlush (@Nullable @WillClose final AutoCloseable aCloseable) { if (aCloseable != null) { try { // close stream aCloseable.close (); return ESuccess.SUCCESS; } catch (final Exception ex) { if (!isKnownEOFException (ex)) s_aLogger.error ("Failed to close object " + aCloseable.getClass ().getName (), ex instanceof IMockException ? null : ex); } } return ESuccess.FAILURE; }
/** * Write the current workbook to an output stream. * * @param aOS * The output stream to write to. May not be <code>null</code>. Is * automatically closed independent of the success state. * @return {@link ESuccess} */ @Nonnull public ESuccess writeTo (@Nonnull @WillClose final OutputStream aOS) { try { ValueEnforcer.notNull (aOS, "OutputStream"); if (m_nCreatedCellStyles > 0 && s_aLogger.isDebugEnabled ()) s_aLogger.debug ("Writing Excel workbook with " + m_nCreatedCellStyles + " different cell styles"); m_aWB.write (aOS); return ESuccess.SUCCESS; } catch (final IOException ex) { if (!StreamHelper.isKnownEOFException (ex)) s_aLogger.error ("Failed to write Excel workbook to output stream " + aOS, ex); return ESuccess.FAILURE; } finally { StreamHelper.close (aOS); } }
/** * Pass the content of the given input stream to the given output stream. Both * the input stream and the output stream are automatically closed. * * @param aIS * The input stream to read from. May be <code>null</code>. * Automatically closed! * @param aOS * The output stream to write to. May be <code>null</code>. * Automatically closed! * @param nLimit * The maximum number of bytes to be copied to the output stream. Must * be ≥ 0. * @return <code>{@link ESuccess#SUCCESS}</code> if copying took place, <code> * {@link ESuccess#FAILURE}</code> otherwise */ @Nonnull public static ESuccess copyInputStreamToOutputStreamWithLimitAndCloseOS (@WillClose @Nullable final InputStream aIS, @WillClose @Nullable final OutputStream aOS, @Nonnegative final long nLimit) { try { return copyInputStreamToOutputStream (aIS, aOS, new byte [DEFAULT_BUFSIZE], (MutableLong) null, Long.valueOf (nLimit)); } finally { close (aOS); } }
/** * Write bytes to an {@link OutputStream}. * * @param aOS * The output stream to write to. May not be <code>null</code>. Is * closed independent of error or success. * @param aBuf * The byte array from which is to be written. May not be * <code>null</code>. * @param nOfs * The 0-based index to the first byte in the array to be written. May * not be < 0. * @param nLen * The non-negative amount of bytes to be written. May not be < 0. * @return {@link ESuccess} */ @Nonnull public static ESuccess writeStream (@WillClose @Nonnull final OutputStream aOS, @Nonnull final byte [] aBuf, @Nonnegative final int nOfs, @Nonnegative final int nLen) { try { ValueEnforcer.notNull (aOS, "OutputStream"); ValueEnforcer.isArrayOfsLen (aBuf, nOfs, nLen); aOS.write (aBuf, nOfs, nLen); aOS.flush (); return ESuccess.SUCCESS; } catch (final IOException ex) { s_aLogger.error ("Failed to write to output stream", ex instanceof IMockException ? null : ex); return ESuccess.FAILURE; } finally { close (aOS); } }
public static void readUntilEOF (@Nonnull @WillClose final InputStream aIS, @Nonnull final byte [] aBuffer, @Nonnull final ObjIntConsumer <? super byte []> aConsumer) throws IOException { try { ValueEnforcer.notNull (aIS, "InputStream"); ValueEnforcer.notNull (aBuffer, "Buffer"); ValueEnforcer.notNull (aConsumer, "Consumer"); _readUntilEOF (aIS, aBuffer, aConsumer); } finally { close (aIS); } }
/** * Forwards the call to the {@link TFileTreeModel} * and scrolls the tree so that the copied node * is selected and visible. * * @throws IOException on any I/O error. */ public void cp(final @WillClose InputStream in, final TFile node) throws IOException { final TFileTreeModel ftm = getModel(); final TreePath path = ftm.newTreePath(node); if (null == path) throw new IllegalArgumentException("node"); ftm.cp(in, node); setSelectionPath(path); scrollPathToVisible(path); }
/** * Stream will be closed automatically. */ public void importLdif(@WillClose InputStream is) throws Exception { Preconditions.checkState(directoryService.isStarted(), "Directory service not started"); try { LdifReader entries = new LdifReader(is); CoreSession rootDSE = directoryService.getAdminSession(); for (LdifEntry ldifEntry : entries) { rootDSE.add(new DefaultServerEntry(rootDSE.getDirectoryService().getRegistries(), ldifEntry.getEntry())); } } finally { Closeables.closeQuietly(is); } }
private static void _compressPayload (@Nonnull @WillClose final InputStream aUncompressed, @Nonnull @WillClose final OutputStream aOut) throws IOException { try (final InputStream aSrc = aUncompressed; final GZIPOutputStream aGZIPOut = new GZIPOutputStream (aOut)) { StreamHelper.copyInputStreamToOutputStream (aSrc, aGZIPOut); } }
private static void _decompressPayload (@Nonnull @WillClose final InputStream aIn, @Nonnull @WillClose final OutputStream aOut) throws IOException { try (final GZIPInputStream aGZIPIn = new GZIPInputStream (aIn); final OutputStream aDest = aOut) { StreamHelper.copyInputStreamToOutputStream (aGZIPIn, aDest); } }
@Nonnull static public LoadedImage create(@WillClose @Nonnull InputStream is, @Nullable Dimension maxSize, @Nullable List<Object> resourceList) throws Exception { try { File tmp = FileTool.copyStreamToTmpFile(is); return create(tmp, maxSize, resourceList); } finally { is.close(); } }
@Nonnull private static void parse(@Nonnull Output output, @Nonnull @WillClose Reader r) throws IOException { try { BufferedReader br = new BufferedReader(r); int lineNumber = 1; String line; while ((line = br.readLine()) != null) { List<String> words = split(line); if (words.isEmpty()) continue; if (words.size() < 2) throw error(lineNumber, words, "not enough words on line."); String type = words.get(0); if (type.equals("rule")) { if (words.size() < 3) throw error(lineNumber, words, "'rule' requires 2 arguments."); output.addClassRename(new ClassRename(words.get(1), words.get(2))); } else if (type.equals("zap")) { output.addClassDelete(new ClassDelete(words.get(1))); } else if (type.equals("keep")) { output.addClassKeepTransitive(new ClassKeepTransitive(words.get(1))); } else { throw error(lineNumber, words, "Unrecognized keyword " + type); } lineNumber++; } } finally { r.close(); } }
public static CharProducer create( @WillClose StringReader r, InputSource src) { try { return create((Reader) r, FilePosition.startOfFile(src)); } catch (IOException ex) { throw new SomethingWidgyHappenedError( "Error reading chars from String"); } }
public static CharProducer create( @WillClose StringReader r, FilePosition pos) { try { return create((Reader) r, pos); } catch (IOException ex) { throw new SomethingWidgyHappenedError( "Error reading chars from String"); } }
public static CharProducer fromHtmlAttribute( @WillClose CharProducer p) { return DecodingCharProducer.make(new DecodingCharProducer.Decoder() { @Override void decode(char[] chars, int offset, int limit) { long packedEndAndCodepoint = HtmlEntities.decodeEntityAt( chars, offset, limit); this.codePoint = (int) (packedEndAndCodepoint & 0xffffffL); this.end = (int) (packedEndAndCodepoint >>> 32); } }, p); }
InMemorySourceRepository(@WillClose ZipInputStream in) throws IOException { try { while (true) { ZipEntry e = in.getNextEntry(); if (e == null) break; if (!e.isDirectory()) { String name = e.getName(); long size = e.getSize(); if (size > Integer.MAX_VALUE) throw new IOException(name + " is too big at " + size + " bytes"); ByteArrayOutputStream out; if (size <= 0) out = new ByteArrayOutputStream(); else out = new ByteArrayOutputStream((int) size); GZIPOutputStream gOut = new GZIPOutputStream(out); IO.copy(in, gOut); gOut.close(); byte data[] = out.toByteArray(); contents.put(name, data); lastModified.put(name, e.getTime()); } in.closeEntry(); } } finally { Util.closeSilently(in); } }
@Nonnull public T readSettings (@Nonnull @WillClose final InputStream aIS) { ValueEnforcer.notNull (aIS, "InputStream"); final IMicroDocument aDoc = MicroReader.readMicroXML (aIS); if (aDoc == null) throw new IllegalArgumentException ("Passed XML document is illegal"); // read items final SettingsMicroDocumentConverter <T> aConverter = new SettingsMicroDocumentConverter <> (m_aSettingsFactory); return aConverter.convertToNative (aDoc.getDocumentElement ()); }
public static byte[] readAll(@WillClose InputStream in) throws IOException { try { ByteArrayOutputStream byteSink = new ByteArrayOutputStream(); copy(in, byteSink); return byteSink.toByteArray(); } finally { close(in); } }
public static void closeSilently(@WillClose InputStream in) { try { if (in != null) in.close(); } catch (IOException e) { assert true; } }
public static void closeSilently(@WillClose Closeable out) { try { if (out != null) out.close(); } catch (IOException e) { assert true; } }
/** * Report statistics as an XML document to given output stream. */ public void reportSummary(@WillClose OutputStream out) throws IOException { XMLOutput xmlOutput = new OutputStreamXMLOutput(out); try { writeXML(xmlOutput); } finally { xmlOutput.finish(); } }
@Nonnull public static ESuccess readXMLSAX (@Nonnull @WillClose final Reader aReader, @Nonnull final ISAXReaderSettings aSettings) { ValueEnforcer.notNull (aReader, "Reader"); try { return readXMLSAX (InputSourceFactory.create (aReader), aSettings); } finally { StreamHelper.close (aReader); } }
@Nullable public static Document readXMLDOM (@Nonnull @WillClose final InputStream aIS, @Nonnull final IDOMReaderSettings aSettings) throws SAXException { ValueEnforcer.notNull (aIS, "InputStream"); try { return readXMLDOM (InputSourceFactory.create (aIS), aSettings); } finally { StreamHelper.close (aIS); } }
@Nullable public static Document readXMLDOM (@WillClose @Nonnull final Reader aReader, @Nonnull final IDOMReaderSettings aSettings) throws SAXException { ValueEnforcer.notNull (aReader, "Reader"); try { return readXMLDOM (InputSourceFactory.create (aReader), aSettings); } finally { StreamHelper.close (aReader); } }