Skip to content

[java] New Rule: RelianceOnDefaultCharset #2186

@jjlharrison

Description

@jjlharrison

I'd like to suggest a new rule to detect reliance on the JVM default charset. This would need to cover multiple constructors/methods that have overloads with and without Charsets.

I'd be happy to contribute a pull request but would like some guidance on how it should be implemented. Should it be a single XPath rule that covers all of the APIs, or a separate rule for each?

APIs that I know of so far:

  1. java.io.InputStreamReader#InputStreamReader(java.io.InputStream)
  2. java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
  3. java.io.PrintStream#PrintStream(java.io.File)
  4. java.io.PrintStream#PrintStream(java.io.OutputStream)
  5. java.io.PrintStream#PrintStream(java.io.OutputStream, boolean)
  6. java.io.PrintWriter#PrintWriter(java.io.File)
  7. java.io.PrintWriter#PrintWriter(java.io.OutputStream)
  8. java.io.PrintWriter#PrintWriter(java.io.OutputStream, boolean)
  9. java.io.PrintWriter#PrintWriter(java.lang.String)
  10. java.lang.String#getBytes()
  11. java.lang.String#String(byte[], int, int, int)
  12. java.lang.String#String(byte[], int)
  13. java.util.Formatter#Formatter(java.lang.String)
  14. java.util.Formatter#Formatter(java.io.File)
  15. java.util.Formatter#Formatter(java.io.OutputStream)
  16. java.util.Scanner#Scanner(java.io.InputStream)
  17. java.util.Scanner#Scanner(java.io.File)
  18. java.util.Scanner#Scanner(java.nio.file.Path)
  19. java.util.Scanner#Scanner(java.nio.channels.ReadableByteChannel)
  20. java.util.Scanner#Scanner(java.io.InputStream)

Affects PMD Version:
6.20.0

Rule:
New Rule

Description:
Be sure to specify a character set for APIs that use the JVMs default character set to ensure stable decoding between different JVMs, programs, and servers.

Code Sample demonstrating the issue:

new InputStreamReader(inputStream);

should be written as, for example:

new InputStreamReader(inputStream, StandardCharset.UTF_8);

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:new-ruleProposal to add a new built-in rule

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions