...
Code Block | ||||
---|---|---|---|---|
| ||||
public static void processTag(String tag) { if (tag.equalsIgnoreCase("SCRIPT")) { return; } // Process tag } |
This solution is compliant because equalIgnoreCase()
compares two strings, one of which is plain ASCII, and therefore its behavior is well-understood, even if the other string is not plain ASCII. Calling equalIgnoreCase()
where both strings may not be ASCII is not recommended, simply because equalIgnoreCase()
may not behave as expected by the developer.
Noncompliant Code Example (FileReader
)
...
The concepts of days and years are universal, but the way in which dates are represented varies across cultures and are therefore specific to locales. This noncompliant code example examines the current date and prints one of two messages, depending on whether or not the month is June.:
Code Block | ||||
---|---|---|---|---|
| ||||
import java.util.Date; import java.text.DateFormat; import java.util.Locale; // ... public static void isJune(Date date) { String myString = DateFormat.getDateInstance().format(date); System.out.println("The date is " + myString); if (myString.startsWith("Jun ")) { System.out.println("Enjoy June!"); } else { System.out.println("It's not June."); } } |
...
but fails on other locales. For example, the output for a German locale (specified by -Duser.language=de
) is:
Code Block |
---|
The date is 20.06.2014 It's not June. |
...
This compliant solution forces the date to be printed in an English format, regardless of the current locale.:
Code Block | ||||
---|---|---|---|---|
| ||||
String myString = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US).format(rightNow.getTime()); /* ...restRest of code unchanged... */ |
Compliant Solution (Bypass Locale)
...
Code Block | ||||
---|---|---|---|---|
| ||||
if (rightNow.get(Calendar.MONTH) == Calendar.JUNE) { /* ...restRest of code unchanged... */ |
Risk Assessment
Failure to specify the appropriate locale when using locale-dependent methods on local-dependent data without specifying the appropriate locale may result in unexpected behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
STR02-J | Medium | Probable | Medium | P8 | L2 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
The Checker Framework |
| Tainting Checker | Trust and security errors (see Chapter 8) | ||||||
Parasoft Jtest |
| CERT.STR02.CCL CERT.STR02.CTLC | Use the optional java.util.Locale parameter Do not call 'Character.toLowerCase(char)' or 'Character.toUpperCase(char)' in an internationalized environment | ||||||
SonarQube |
| S1449 | Locale should be used in String operations |
Android Implementation Details
A developer can specify locale on Android using java.util.Locale
.
Bibliography
[API 2006] | Class |
[Seacord 2015] | |
[Schindler 12] | The Policeman’s Horror: Default Locales, Default Charsets, and Default Timezones |
...
...