rspec/rules/S5764/java/rule.adoc

84 lines
2.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
The class ``++java.util.zip.GZIPInputStream++`` is already buffering its input while reading. Thus passing a ``++java.io.BufferedInputStream++`` to a ``++java.util.zip.GZIPInputStream++`` is redundant. It is more efficient to directly pass the original input stream to ``++java.util.zip.GZIPInputStream++``.
Note that the default buffer size of ``++GZIPInputStream++`` is not the same as the one in ``++BufferedInputStream++``. Configure it if need be.
This rule raises an issue when a ``++java.util.zip.GZIPInputStream++`` reads from a ``++java.io.BufferedInputStream++``.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
import java.io.*;
import java.util.zip.GZIPInputStream;
public class Noncompliant {
void deflateFile(final File file) throws IOException {
try (
FileInputStream fileStream = new FileInputStream(file);
BufferedInputStream bufferedStream = new BufferedInputStream(fileStream);
InputStream input = new GZIPInputStream(bufferedStream); // Noncompliant
) {
// process the input
}
}
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
import java.io.*;
import java.util.zip.GZIPInputStream;
public class Compliant {
void deflateFile(final File file) throws IOException {
try (
FileInputStream fileStream = new FileInputStream(file);
InputStream input = new GZIPInputStream(fileStream);
) {
// process the input
}
}
}
----
== Resources
2021-04-28 16:49:39 +02:00
2022-09-07 16:08:38 +02:00
* Stackoverflow question about usage of GZIPInputStream and the BufferedInputStream - https://stackoverflow.com/questions/4438085/seeking-out-the-optimum-size-for-bufferedinputstream-in-java/4438217#4438217[GZIPInputStream and the BufferedInputStream]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove the intermediate BufferedInputStream
=== Highlighting
Primary location: the GZIPInputStream instantiation
Secondary location: the BufferedInputStream instantiation.
'''
== Comments And Links
(visible only on this page)
=== on 9 Jul 2020, 09:37:33 Nicolas Harraudeau wrote:
\[~pierre-loup.tristant] There are a few references in other articles but this one explains it the best so I would prefer to keep it if possible. Otherwise I'll replace it with https://stackoverflow.com/a/4438217[this stack overflow link]
endif::env-github,rspecator-view[]