javax.annotation.WillClose Java Examples
The following examples show how to use
javax.annotation.WillClose.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PropertyDatabase.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
/** * Write property database to an OutputStream. The OutputStream is * guaranteed to be closed, even if an exception is thrown. * * @param out * the OutputStream * @throws IOException */ public void write(@WillClose OutputStream out) throws IOException { boolean missingClassWarningsSuppressed = AnalysisContext.currentAnalysisContext().setMissingClassWarningsSuppressed(true); try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) { TreeSet<KeyType> sortedMethodSet = new TreeSet<>(propertyMap.keySet()); for (KeyType key : sortedMethodSet) { if (AnalysisContext.currentAnalysisContext().isApplicationClass(key.getClassDescriptor())) { ValueType property = propertyMap.get(key); writeKey(writer, key); writer.write("|"); writer.write(encodeProperty(property)); writer.write("\n"); } } } finally { AnalysisContext.currentAnalysisContext().setMissingClassWarningsSuppressed(missingClassWarningsSuppressed); } }
Example #2
Source File: FetchedData.java From caja with Apache License 2.0 | 6 votes |
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(); } }
Example #3
Source File: MicroWriter.java From ph-commons with Apache License 2.0 | 6 votes |
/** * Write a Micro Node to a {@link Writer}. * * @param aNode * The node to be serialized. May be any kind of node (incl. * documents). May not be <code>null</code>. * @param aWriter * The writer to write to. May not be <code>null</code>. The writer is * closed anyway directly after the operation finishes (on success and * on error). * @param aSettings * The settings to be used for the creation. May not be * <code>null</code>. * @return {@link ESuccess} */ @Nonnull public static ESuccess writeToWriter (@Nonnull final IMicroNode aNode, @Nonnull @WillClose final Writer aWriter, @Nonnull final IXMLWriterSettings aSettings) { ValueEnforcer.notNull (aNode, "Node"); ValueEnforcer.notNull (aWriter, "Writer"); ValueEnforcer.notNull (aSettings, "Settings"); try { final MicroSerializer aSerializer = new MicroSerializer (aSettings); aSerializer.write (aNode, aWriter); return ESuccess.SUCCESS; } finally { StreamHelper.close (aWriter); } }
Example #4
Source File: StreamHelper.java From ph-commons with Apache License 2.0 | 6 votes |
public static void readUntilEOF (@Nonnull @WillClose final Reader aReader, @Nonnull final char [] aBuffer, @Nonnull final ObjIntConsumer <? super char []> aConsumer) throws IOException { try { ValueEnforcer.notNull (aReader, "Reader"); ValueEnforcer.notNull (aBuffer, "Buffer"); ValueEnforcer.notNull (aConsumer, "Consumer"); _readUntilEOF (aReader, aBuffer, aConsumer); } finally { close (aReader); } }
Example #5
Source File: SettingsPersistenceJson.java From ph-commons with Apache License 2.0 | 6 votes |
@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 IJsonObject aProps = JsonReader.builder ().setSource (aIS, m_aCharset).setCustomizeCallback (aParser -> { aParser.setRequireStringQuotes (false); aParser.setAlwaysUseBigNumber (true); }).readAsObject (); if (aProps != null) for (final Map.Entry <String, IJson> aEntry : aProps) _recursiveReadSettings (aEntry.getKey (), aEntry.getValue (), aSettings); return aSettings; }
Example #6
Source File: PropertiesHelper.java From ph-commons with Apache License 2.0 | 6 votes |
@Nullable public static NonBlockingProperties loadProperties (@Nonnull @WillClose final InputStream aIS) { ValueEnforcer.notNull (aIS, "InputStream"); final InputStream aBufferedIS = StreamHelper.getBuffered (aIS); try { final NonBlockingProperties aProps = new NonBlockingProperties (); aProps.load (aBufferedIS); return aProps; } catch (final IOException ex) { return null; } finally { StreamHelper.close (aBufferedIS); StreamHelper.close (aIS); } }
Example #7
Source File: JsonReader.java From ph-commons with Apache License 2.0 | 6 votes |
/** * Set a {@link Reader} as JSON source. Internally it is ensured, that it is * buffered. * * @param aReader * The Reader to be used. May not be <code>null</code>. * @return this for chaining */ @Nonnull public Builder setSource (@Nonnull @WillClose final Reader aReader) { ValueEnforcer.notNull (aReader, "Reader"); if (m_aReader != null) LOGGER.warn ("Another source is already present - this may cause a resource leak, because the old source is not closed automatically"); m_aReader = aReader; // Use buffered? if (m_bUseBufferedReader) m_aReader = StreamHelper.getBuffered (m_aReader); // Don't close? if (m_bDontCloseSource) m_aReader = new NonClosingReader (m_aReader); return this; }
Example #8
Source File: SettingsPersistenceXML.java From ph-commons with Apache License 2.0 | 6 votes |
@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); } }
Example #9
Source File: StreamHelper.java From ph-commons with Apache License 2.0 | 6 votes |
/** * 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) { LOGGER.error ("Failed to write to output stream", _propagate (ex)); return ESuccess.FAILURE; } finally { close (aOS); } }
Example #10
Source File: CharProducer.java From caja with Apache License 2.0 | 6 votes |
/** * @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); }
Example #11
Source File: SuppressionDecorator.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
/** * @param rawIn * @throws IOException */ private void processPackageList(@WillClose Reader rawIn) throws IOException { try (BufferedReader in = new BufferedReader(rawIn)) { String s; while ((s = in.readLine()) != null) { 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(); } }
Example #12
Source File: XMLMapHandler.java From ph-commons with Apache License 2.0 | 6 votes |
/** * Read a mapping from the passed input stream. * * @param aIS * The input stream to read from. May not be <code>null</code>. * @param aTargetMap * The target map to be filled. * @return {@link ESuccess#SUCCESS} if the stream could be opened, if it could * be read as XML and if the root element was correct. * {@link ESuccess#FAILURE} otherwise. */ @Nonnull public static ESuccess readMap (@Nonnull @WillClose final InputStream aIS, @Nonnull final Map <String, String> aTargetMap) { ValueEnforcer.notNull (aIS, "InputStream"); ValueEnforcer.notNull (aTargetMap, "TargetMap"); try (final InputStream aCloseMe = aIS) { // open file final IMicroDocument aDoc = MicroReader.readMicroXML (aIS); if (aDoc != null) { readMap (aDoc.getDocumentElement (), aTargetMap); return ESuccess.SUCCESS; } } catch (final Exception ex) { if (LOGGER.isWarnEnabled ()) LOGGER.warn ("Failed to read mapping resource '" + aIS + "'", ex); } return ESuccess.FAILURE; }
Example #13
Source File: CharProducer.java From caja with Apache License 2.0 | 5 votes |
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"); } }
Example #14
Source File: JavaClassLoaderFuncTest.java From ph-commons with Apache License 2.0 | 5 votes |
private static void _assertNull (@WillClose final InputStream aIS) { try { assertNull (aIS); } finally { StreamHelper.close (aIS); } }
Example #15
Source File: Bug3415313.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
public static void closeStatement(@WillClose PreparedStatement ps) { try { if (ps != null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } }
Example #16
Source File: CharProducer.java From caja with Apache License 2.0 | 5 votes |
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); }
Example #17
Source File: Bug3600398.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
@WillClose protected void close(Object... objects) { if (objects != null) { for (Object object : objects) { close(object); } } }
Example #18
Source File: UsesWillCloseAnnotation.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
public void cleanup(@WillClose InputStream in) { try { in.close(); } catch (IOException e) { // ignore } }
Example #19
Source File: IWriteToStream.java From ph-commons with Apache License 2.0 | 5 votes |
/** * Write everything to the passed output stream and close it. * * @param aOS * The output stream to write to. May not be <code>null</code>. * @throws IOException * In case of IO error. Even than the OutputStream is closed! */ default void writeToAndClose (@Nonnull @WillClose final OutputStream aOS) throws IOException { try { writeTo (aOS); } finally { StreamHelper.close (aOS); } }
Example #20
Source File: DbUtil.java From Alpine with Apache License 2.0 | 5 votes |
@WillClose public static void close(ResultSet resultSet) { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException e) { // throw it away } }
Example #21
Source File: StreamHelper.java From ph-commons with Apache License 2.0 | 5 votes |
@Nullable public static NonBlockingStringWriter getCopyWithLimit (@Nonnull @WillClose final Reader aReader, @Nonnegative final long nLimit) { final NonBlockingStringWriter aWriter = new NonBlockingStringWriter (DEFAULT_BUFSIZE); if (copyReaderToWriterWithLimitAndCloseWriter (aReader, aWriter, nLimit).isFailure ()) return null; return aWriter; }
Example #22
Source File: SettingsPersistenceProperties.java From ph-commons with Apache License 2.0 | 5 votes |
@Nonnull public ESuccess writeSettings (@Nonnull final ISettings aSettings, @Nonnull @WillClose final OutputStream aOS) { ValueEnforcer.notNull (aOS, "OutputStream"); try { final NonBlockingProperties aProps = new NonBlockingProperties (); // Must not be sorted, as Properties sorts them as it wishes... for (final Map.Entry <String, Object> aEntry : aSettings.entrySet ()) { final String sName = aEntry.getKey (); final Object aValue = aEntry.getValue (); if (aValue instanceof ISettings) throw new IllegalArgumentException ("When saving settings to a Properties object, it may not contained nested settings! Now the key '" + sName + "' is mapped to a nested ISettings object!"); final String sValue = TypeConverter.convert (aValue, String.class); aProps.put (sName, sValue); } // Does not close the output stream! aProps.store (aOS, aSettings.getName ()); return ESuccess.SUCCESS; } catch (final IOException ex) { LOGGER.error ("Failed to write settings to properties file", ex); return ESuccess.FAILURE; } finally { StreamHelper.close (aOS); } }
Example #23
Source File: SettingsPersistenceXML.java From ph-commons with Apache License 2.0 | 5 votes |
@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 ()); }
Example #24
Source File: StreamHelper.java From ph-commons with Apache License 2.0 | 5 votes |
/** * Pass the content of the given reader to the given writer. The reader is * automatically closed, whereas the writer stays open! * * @param aReader * The reader to read from. May be <code>null</code>. Automatically * closed! * @param aWriter * The writer to write to. May be <code>null</code>. Not automatically * closed! * @return <code>{@link ESuccess#SUCCESS}</code> if copying took place, <code> * {@link ESuccess#FAILURE}</code> otherwise */ @Nonnull public static ESuccess copyReaderToWriter (@WillClose @Nullable final Reader aReader, @WillNotClose @Nullable final Writer aWriter) { return copyReaderToWriter (aReader, true, aWriter, false, createDefaultCopyBufferChars (), (Long) null, null, (MutableLong) null); }
Example #25
Source File: SAXReader.java From ph-commons with Apache License 2.0 | 5 votes |
@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); } }
Example #26
Source File: JavaClassLoaderFuncTest.java From ph-commons with Apache License 2.0 | 5 votes |
private static void _assertNotNull (@WillClose final InputStream aIS) { try { assertNotNull (aIS); } finally { StreamHelper.close (aIS); } }
Example #27
Source File: DOMReader.java From ph-commons with Apache License 2.0 | 5 votes |
@Nullable public static Document readXMLDOM (@WillClose @Nonnull final Reader aReader, @Nonnull final IDOMReaderSettings aSettings) { ValueEnforcer.notNull (aReader, "Reader"); try { return readXMLDOM (InputSourceFactory.create (aReader), aSettings); } finally { StreamHelper.close (aReader); } }
Example #28
Source File: XMLResourceBundle.java From ph-commons with Apache License 2.0 | 5 votes |
@Nonnull @ReturnsMutableCopy public static ICommonsOrderedMap <String, String> readFromPropertiesXML (@Nonnull @WillClose final InputStream aIS) { final ICommonsOrderedMap <String, String> ret = new CommonsLinkedHashMap <> (); final IMicroDocument aDoc = MicroReader.readMicroXML (aIS); if (aDoc != null) for (final IMicroElement eChild : aDoc.getDocumentElement ().getAllChildElements ("entry")) ret.put (eChild.getAttributeValue ("key"), eChild.getTextContent ()); return ret; }
Example #29
Source File: MicroReader.java From ph-commons with Apache License 2.0 | 5 votes |
/** * Read the passed input source as MicroXML. * * @param aInputSource * The input source to use. May be <code>null</code> in which case * <code>null</code> is directly returned. * @param aSettings * The settings to use. If <code>null</code> the default settings will * be used. * @return <code>null</code> if either the input source is <code>null</code> * or if the input was invalid XML. */ @Nullable public static IMicroDocument readMicroXML (@WillClose @Nullable final InputSource aInputSource, @Nullable final ISAXReaderSettings aSettings) { if (aInputSource == null) return null; final EntityResolver aEntityResolver = aSettings == null ? null : aSettings.getEntityResolver (); final MicroSAXHandler aMicroHandler = new MicroSAXHandler (false, aEntityResolver, true); // Copy and modify settings final SAXReaderSettings aRealSettings = SAXReaderSettings.createCloneOnDemand (aSettings); aRealSettings.setEntityResolver (aMicroHandler) .setDTDHandler (aMicroHandler) .setContentHandler (aMicroHandler) .setLexicalHandler (aMicroHandler); if (aRealSettings.getErrorHandler () == null) { // Use MicroHandler as default error handler if none is specified aRealSettings.setErrorHandler (aMicroHandler); } if (aEntityResolver instanceof EntityResolver2) { // Ensure to use the new aEntityResolver2 APIs if available aRealSettings.setFeatureValue (EXMLParserFeature.USE_ENTITY_RESOLVER2, true); } if (SAXReader.readXMLSAX (aInputSource, aRealSettings).isFailure ()) return null; return aMicroHandler.getDocument (); }
Example #30
Source File: XMLMapHandler.java From ph-commons with Apache License 2.0 | 5 votes |
/** * Read a mapping from the passed input stream. * * @param aIS * The input stream to read from. May not be <code>null</code>. * @return <code>null</code> if reading the map failed */ @Nullable @ReturnsMutableCopy public static ICommonsMap <String, String> readMap (@Nonnull @WillClose final InputStream aIS) { final ICommonsMap <String, String> ret = new CommonsHashMap <> (); if (readMap (aIS, ret).isFailure ()) return null; return ret; }