This is a record for sonar fixing for backend based on Java.
CERT issues
Rule: Increment (++) and decrement (–) operators should not be used in a method call or mixed with other operators in an expression
1. original code:
1 2
| u8a = ++u8b + u8c--; foo = bar++ / 4;
|
solution
1 2 3 4 5
| ++u8b; u8a = u8b + u8c; u8c--; foo = bar / 4; bar++;
|
2. original code:
1 2 3
| if (++searchCounter > portRange) { }
|
solution
1 2 3
| ++searchCounter; if (searchCounter > portRange) { }
|
3. original code:
1 2 3 4
| int retry = 0; while (retry++ < RETRY_NUM && ..) { }
|
solution
1 2 3 4 5
| int retry = 1; while (retry < RETRY_NUM + 1 && ..) { retry++; }
|
4. original code:
1 2 3 4
| int cnt = 0; while ((++cnt <= num) && (...)) { }
|
solution
1 2 3 4 5
| int cnt = 1; while ((cnt <= num) && (...)) { cnt++; }
|
Specify an appropriate locale when comparing locale-dependent data.
2. original code:
1
| String password = user.getPassword().toLowerCase();
|
solution
1
| String password = user.getPassword().toLowerCase(Locale.getDefault());
|
Classes and methods that rely on the default system encoding should not be used
Rule: 1. Remove this use of “toString”. 2. Remove this use of constructor “FileWriter(File,boolean)”. etc
1. original code:
1 2 3
| import java.io.FileWriter;
BufferedWriter csvFileBufferWriter = new BufferedWriter(new FileWriter(csvFile, true))
|
solution
1 2 3 4 5
| import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset;
BufferedWriter csvFileBufferWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile, true), Charset.defaultCharset()))
|
This solution came out with new sonar issue https://sonarqube.lmera.ericsson.se/coding_rules?open=fb-contrib%3AIOI_USE_OF_FILE_STREAM_CONSTRUCTORS&rule_key=fb-contrib%3AIOI_USE_OF_FILE_STREAM_CONSTRUCTORS
2nd modification:
1 2 3
| import java.nio.file.Files;
BufferedWriter csvFileBufferWriter = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(csvFile.toPath()), Charset.defaultCharset()))
|
another case:
1 2
| File file = new File(saiFileLocation); FileInputStream reader = new FileInputStream(file);
|
change to
1
| InputStream reader = Files.newInputStream(Paths.get(saiFileLocation));
|
2. original code:
1 2 3 4 5 6
| try { } catch (JAXBException e) { throw new RuntimeException(); } return bos.toString();
|
solution
1 2 3 4 5 6
| try { return bos.toString(Charset.defaultCharset().name()); } catch (JAXBException | UnsupportedEncodingException e) { throw new RuntimeException(); }
|
3. original code:
1 2 3 4 5
| import java.io.FileReader;
try (FileReader fileReader = new FileReader(fileName)) { List<..> list = unmarshal2List(fileReader); }
|
solution
1 2 3 4 5 6 7
| import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.charset.Charset;
try (FileInputStream fileReader = new FileInputStream(fileName)) { List<..> list = unmarshal2List(new InputStreamReader(fileReader, Charset.defaultCharset())); }
|