下面列出了怎么用javax.annotation.WillClose的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @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();
}
}
/**
* 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);
}
}
/**
* 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;
}
/**
* @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);
}
@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);
}
}
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 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);
}
}
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);
}
}
@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;
}
@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);
}
}
/**
* 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);
}
}
/**
* 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;
}
@WillClose
public static void close(ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
// throw it away
}
}
/**
* Pass the content of the given input stream to the given output stream. The
* input stream is automatically closed, whereas the output stream stays open!
*
* @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>. Not
* automatically closed!
* @return <code>{@link ESuccess#SUCCESS}</code> if copying took place, <code>
* {@link ESuccess#FAILURE}</code> otherwise
*/
@Nonnull
public static ESuccess copyInputStreamToOutputStream (@WillClose @Nullable final InputStream aIS,
@WillNotClose @Nullable final OutputStream aOS)
{
return copyInputStreamToOutputStream (aIS,
true,
aOS,
false,
createDefaultCopyBufferBytes (),
(Long) null,
null,
(MutableLong) null);
}
@SuppressFBWarnings("OBL_UNSATISFIED_OBLIGATION")
public void sendTestMkvStream(final ClientConfiguration config) throws Exception {
@WillClose
final InputStream testMkvStream = new FileInputStream("testdata/test_depth_cal.mkv");
final Long streamStartTime = 1498511782000L;
//TODO: Add as a cmd line parameter.
PutMediaClient.builder().putMediaDestinationUri(config.getStreamUri()).mkvStream(testMkvStream).streamName(config.getStreamName()).timestamp(streamStartTime).fragmentTimecodeType(ABSOLUTE).signWith(signer).receiveAcks(new StreamConsumer(config.getApiName())).build().putMediaInBackground();
}
public final void reportBugsFromXml(@WillClose InputStream in, Project theProject) throws IOException, DocumentException {
SortedBugCollection theCollection = new SortedBugCollection(theProject);
theCollection.readXML(in);
for (BugInstance bug : theCollection.getCollection()) {
doReportBug(bug);
}
}
/**
* Read all characters from the passed reader into a char array.
*
* @param aReader
* The reader to read from. May be <code>null</code>.
* @return The character array or <code>null</code> if the reader is
* <code>null</code>.
*/
@Nullable
public static char [] getAllCharacters (@Nullable @WillClose final Reader aReader)
{
if (aReader == null)
return null;
final NonBlockingStringWriter aWriter = getCopy (aReader);
if (aWriter == null)
return null;
return aWriter.getAsCharArray ();
}
public static void readFrom(Collection<String> result, @WillClose Reader r) throws IOException {
BufferedReader in = new BufferedReader(r);
while (true) {
String s = in.readLine();
if (s == null) {
in.close();
return;
}
result.add(s);
}
}
/**
* Read the content of the passed stream line by line and invoking a callback
* on all matching lines.
*
* @param aIS
* The input stream to read from. May be <code>null</code>.
* @param aCharset
* The character set to use. May not be <code>null</code>.
* @param nLinesToSkip
* The 0-based index of the first line to read. Pass in 0 to indicate
* to read everything.
* @param nLinesToRead
* The number of lines to read. Pass in {@link CGlobal#ILLEGAL_UINT} to
* indicate that all lines should be read. If the number passed here
* exceeds the number of lines in the file, nothing happens.
* @param aLineCallback
* The callback that is invoked for all read lines. Each passed line
* does NOT contain the line delimiter! Note: it is not invoked for
* skipped lines!
*/
public static void readStreamLines (@WillClose @Nullable final InputStream aIS,
@Nonnull @Nonempty final Charset aCharset,
@Nonnegative final int nLinesToSkip,
final int nLinesToRead,
@Nonnull final Consumer <? super String> aLineCallback)
{
try
{
ValueEnforcer.notNull (aCharset, "Charset");
ValueEnforcer.isGE0 (nLinesToSkip, "LinesToSkip");
final boolean bReadAllLines = nLinesToRead == CGlobal.ILLEGAL_UINT;
ValueEnforcer.isTrue (bReadAllLines || nLinesToRead >= 0,
() -> "Line count may not be that negative: " + nLinesToRead);
ValueEnforcer.notNull (aLineCallback, "LineCallback");
// Start the action only if there is something to read
if (aIS != null)
if (bReadAllLines || nLinesToRead > 0)
{
try (final NonBlockingBufferedReader aBR = new NonBlockingBufferedReader (createReader (aIS, aCharset)))
{
// read with the passed charset
_readFromReader (nLinesToSkip, nLinesToRead, aLineCallback, bReadAllLines, aBR);
}
catch (final IOException ex)
{
LOGGER.error ("Failed to read from reader", _propagate (ex));
}
}
}
finally
{
// Close input stream anyway
close (aIS);
}
}
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);
}
}
/**
* Write the BugCollection to given output stream as XML. The output stream
* will be closed, even if an exception is thrown.
*
* @param out
* the OutputStream to write to
*/
@Override
public void writeXML(@WillClose Writer out) throws IOException {
assert project != null;
bugsPopulated();
XMLOutput xmlOutput;
// if (project == null) throw new NullPointerException("No project");
xmlOutput = new OutputStreamXMLOutput(out);
writeXML(xmlOutput);
}
/**
* 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();
}
}
/**
* Write UserPreferences to given OutputStream. The OutputStream is
* guaranteed to be closed by this method.
*
* @param out
* the OutputStream
* @throws IOException
*/
public void write(@WillClose OutputStream out) throws IOException {
Properties props = new SortedProperties();
for (int i = 0; i < recentProjectsList.size(); i++) {
String projectName = recentProjectsList.get(i);
String key = "recent" + i;
props.put(key, projectName);
}
for (Entry<String, Boolean> entry : detectorEnablementMap.entrySet()) {
props.put("detector" + entry.getKey(), entry.getKey() + BOOL_SEPARATOR + String.valueOf(entry.getValue().booleanValue()));
}
// Save ProjectFilterSettings
props.put(FILTER_SETTINGS_KEY, filterSettings.toEncodedString());
props.put(FILTER_SETTINGS2_KEY, filterSettings.hiddenToEncodedString());
// Backwards-compatibility: save minimum warning priority as integer.
// This will allow the properties file to work with older versions
// of FindBugs.
props.put(DETECTOR_THRESHOLD_KEY, String.valueOf(filterSettings.getMinPriorityAsInt()));
props.put(RUN_AT_FULL_BUILD, String.valueOf(runAtFullBuild));
props.setProperty(EFFORT_KEY, effort);
writeProperties(props, KEY_INCLUDE_FILTER, includeFilterFiles);
writeProperties(props, KEY_EXCLUDE_FILTER, excludeFilterFiles);
writeProperties(props, KEY_EXCLUDE_BUGS, excludeBugsFiles);
writeProperties(props, KEY_PLUGIN, customPlugins);
try (OutputStream prefStream = new BufferedOutputStream(out)) {
props.store(prefStream, "SpotBugs User Preferences");
prefStream.flush();
}
}
public static void closeSilently(@WillClose InputStream in) {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
assert true;
}
}
/**
* @deprecated Use try-with-resources instead. And basically {@link IOException} from {@link OutputStream#close()}
* is not good to ignore.
*/
@Deprecated
public static void closeSilently(@WillClose Closeable out) {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
assert true;
}
}
/**
* @deprecated Use try-with-resources instead.
*/
@Deprecated
public static void closeSilently(@WillClose ZipFile zip) {
try {
if (zip != null) {
zip.close();
}
} catch (IOException e) {
assert true;
}
}
public void writeToWriterAndClose (@Nonnull final IJson aJson,
@Nonnull @WillClose final Writer aWriter) throws IOException
{
ValueEnforcer.notNull (aJson, "Json");
ValueEnforcer.notNull (aWriter, "Writer");
try
{
writeToWriter (aJson, aWriter);
}
finally
{
StreamHelper.close (aWriter);
}
}
private static void _assertNull (@WillClose final InputStream aIS)
{
try
{
assertNull (aIS);
}
finally
{
StreamHelper.close (aIS);
}
}
/**
* 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);
}
}
public void cleanup(@WillClose InputStream in) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}