Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix quality flaws 3 #1611

Merged
merged 8 commits into from
Dec 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public class HardcodedAccountCheck extends SquidCheck<Grammar> {
key = "regularExpression",
description = "literal regular expression rule",
defaultValue = DEFAULT_REGULAR_EXPRESSION)
private String regularExpression = DEFAULT_REGULAR_EXPRESSION;
private final String regularExpression = DEFAULT_REGULAR_EXPRESSION;

private Pattern pattern;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public class HardcodedIpCheck extends SquidCheck<Grammar> {
key = "regularExpression",
description = "The regular expression",
defaultValue = DEFAULT_REGULAR_EXPRESSION)
private String regularExpression = DEFAULT_REGULAR_EXPRESSION;
private final String regularExpression = DEFAULT_REGULAR_EXPRESSION;

@Override
public void init() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ private static boolean isNullPtr(AstNode node) {
@Override
public void init() {
subscribeTo(CxxTokenType.NUMBER);
for (String magicNumber : exceptions.split(",")) {
magicNumber = magicNumber.trim();
for (String m : exceptions.split(",")) {
final String magicNumber = m.trim();
if (!magicNumber.isEmpty()) {
exceptionsSet.add(magicNumber);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
@SqaleConstantRemediation("5min")
public class ReservedNamesCheck extends SquidCheck<Grammar> implements CxxCharsetAwareVisitor {

private static final String[] keywords = CxxKeyword.keywordValues();
private static final String[] KEYWORDS = CxxKeyword.keywordValues();
private static final Pattern DEFINE_DECLARATION_PATTERN = Pattern.compile("^\\s*#define\\s+([^\\s(]+).*$");
private Charset charset = StandardCharsets.UTF_8;

Expand All @@ -77,7 +77,7 @@ public void visitFile(AstNode astNode) {
"Reserved name used for macro (contains two consecutive underscores)", nr);
} else {
name = name.toLowerCase(Locale.ENGLISH);
for (String keyword : keywords) {
for (String keyword : KEYWORDS) {
if (name.equals(keyword)) {
getContext().createLineViolation(this,
"Reserved name used for macro (keyword or alternative token redefined)", nr);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
public class UseCorrectIncludeCheck extends SquidCheck<Grammar> implements CxxCharsetAwareVisitor {

private static final String REGULAR_EXPRESSION = "#include\\s+(?>\"|\\<)[\\\\/\\.]+";
private static Pattern pattern = Pattern.compile(REGULAR_EXPRESSION, Pattern.DOTALL);
private final static Pattern pattern = Pattern.compile(REGULAR_EXPRESSION, Pattern.DOTALL);
private Charset charset = StandardCharsets.UTF_8;

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public class UseCorrectTypeCheck extends SquidCheck<Grammar> {
key = "regularExpression",
description = "Type regular expression rule",
defaultValue = DEFAULT_REGULAR_EXPRESSION)
private String regularExpression = DEFAULT_REGULAR_EXPRESSION;
private final String regularExpression = DEFAULT_REGULAR_EXPRESSION;

/**
* message
Expand All @@ -74,7 +74,7 @@ public class UseCorrectTypeCheck extends SquidCheck<Grammar> {
key = "message",
description = "The violation message",
defaultValue = DEFAULT_MESSAGE)
private String message = DEFAULT_MESSAGE;
private final String message = DEFAULT_MESSAGE;

@Override
public void init() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ private void analyzeScopeComplexity() {
final int maxComplexity = getMaxComplexity();
final int currentComplexity = scope.getComplexity();
if (scope.getComplexity() > maxComplexity) {
final StringBuilder msg = new StringBuilder();
final StringBuilder msg = new StringBuilder(256);
msg.append("The Cyclomatic Complexity of this ").append(getScopeName()).append(" is ").append(currentComplexity)
.append(" which is greater than ").append(maxComplexity).append(" authorized.");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public void setMaxComplexity(int max) {
@Override
protected void analyzeComplexity(CxxComplexityScope scope) {
if (scope.getComplexity() > max) {
final StringBuilder msg = new StringBuilder();
final StringBuilder msg = new StringBuilder(256);
msg.append("The Cognitive Complexity of this function is ").append(scope.getComplexity())
.append(" which is greater than ").append(max).append(" authorized.");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public void docStyle1() throws UnsupportedEncodingException, IOException {
CxxFileTester tester = CxxFileTesterHelper.CreateCxxFileTester("src/test/resources/checks/UndocumentedApiCheck/doc_style1.h", ".");
SourceFile file = CxxAstScanner.scanSingleFile(tester.cxxFile, tester.sensorContext, CxxFileTesterHelper.mockCxxLanguage(), new UndocumentedApiCheck());

StringBuilder errors = new StringBuilder();
StringBuilder errors = new StringBuilder(1024);
for (CheckMessage msg : file.getCheckMessages()) {
errors.append("Line: ");
errors.append(msg.getLine());
Expand All @@ -118,7 +118,7 @@ public void docStyle2() throws UnsupportedEncodingException, IOException {
CxxFileTester tester = CxxFileTesterHelper.CreateCxxFileTester("src/test/resources/checks/UndocumentedApiCheck/doc_style2.h", ".");
SourceFile file = CxxAstScanner.scanSingleFile(tester.cxxFile, tester.sensorContext, CxxFileTesterHelper.mockCxxLanguage(), new UndocumentedApiCheck());

StringBuilder errors = new StringBuilder();
StringBuilder errors = new StringBuilder(1024);
for (CheckMessage msg : file.getCheckMessages()) {
errors.append("Line: ");
errors.append(msg.getLine());
Expand Down
2 changes: 1 addition & 1 deletion cxx-lint/src/main/java/org/sonar/cxx/cxxlint/CxxLint.java
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ public static void main(String[] args) {
}

JsonElement additionalOptions = parser.parse(fileContent).getAsJsonObject().get("additionalOptions");
StringBuilder elementsOfAdditionalOptions = new StringBuilder();
StringBuilder elementsOfAdditionalOptions = new StringBuilder(512);
if (additionalOptions != null) {
for (JsonElement option : additionalOptions.getAsJsonArray()) {
elementsOfAdditionalOptions.append(' ');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ public class CxxClangTidySensor extends CxxIssuesReportSensor {
public static final String DEFAULT_CHARSET_DEF = "UTF-8";
private static final Logger LOG = Loggers.get(CxxClangTidySensor.class);

private static final String regex = "(.+|[a-zA-Z]:\\\\.+):([0-9]+):([0-9]+): ([^:]+): ([^]]+) \\[([^]]+)\\]";
private static final Pattern pattern = Pattern.compile(regex);
private static final String REGEX = "(.+|[a-zA-Z]:\\\\.+):([0-9]+):([0-9]+): ([^:]+): ([^]]+) \\[([^]]+)\\]";
private static final Pattern PATTERN = Pattern.compile(REGEX);

/**
* CxxClangTidySensor for clang-tidy Sensor
Expand Down Expand Up @@ -80,7 +80,7 @@ protected void processReport(final SensorContext context, File report) {

while (scanner.hasNextLine()) {
String line = scanner.nextLine();
final Matcher matcher = pattern.matcher(line);
final Matcher matcher = PATTERN.matcher(line);
if (matcher.matches()) {
MatchResult m = matcher.toMatchResult();
String path = m.group(1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ private void processErrorTag(final SensorContext context, SMInputCursor errorCur
String primaryFile = primaryLocation.getFile();
String primaryLine = primaryLocation.getLine();

StringBuilder extendedInfo = new StringBuilder();
StringBuilder extendedInfo = new StringBuilder(512);
extendedInfo.append(makeRelativePath(file, primaryFile)).append(":").append(line).append(" ")
.append(info);
issue.addLocation(primaryFile, primaryLine, extendedInfo.toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public CxxDrMemorySensor(CxxLanguage language) {
}

private static String getFrameText(Location frame, int frameNr) {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder(512);
sb.append("#").append(frameNr).append(" ").append(frame.getFile()).append(":").append(frame.getLine());
return sb.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public static List<String> getElements(File file, String charset) {
List<String> list = new ArrayList<>();
try (InputStream input = java.nio.file.Files.newInputStream(file.toPath())) {
BufferedReader br = new BufferedReader(new InputStreamReader(input, charset));
StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder(4096);
String line;
int cnt = 0;
final Pattern whitespacesOnly = Pattern.compile("^\\s*$");
Expand All @@ -118,7 +118,7 @@ public static List<String> getElements(File file, String charset) {

br.close();
} catch (IOException e) {
String msg = new StringBuilder().append("Cannot feed the data into sonar, details: '")
String msg = new StringBuilder(512).append("Cannot feed the data into sonar, details: '")
.append(e)
.append("'").toString();
LOG.error(msg);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ private void transformFileList(final String baseDir, String stylesheet, List<Fil
CxxUtils.transformFile(new StreamSource(new File(stylesheet)), inputs.get(j),
new File(normalizedOutputFilename));
} catch (TransformerException e) {
String msg = new StringBuilder()
String msg = new StringBuilder(256)
.append("Cannot transform report files: '")
.append(e)
.append("'")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,10 @@ private Date getRequiredDateAttribute(XmlParserHelper xmlParserHelper, String na
}

private String keepOnlyMilliseconds(String value) {
StringBuffer sb = new StringBuffer();
StringBuffer sb = new StringBuffer(256);

Matcher matcher = millisecondsPattern.matcher(value);
StringBuilder trailingZeros = new StringBuilder();
StringBuilder trailingZeros = new StringBuilder(128);
while (matcher.find()) {
String milliseconds = matcher.group(2);
trailingZeros.setLength(0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public void execute(SensorContext context) {
LOG.debug("No reports found, nothing to process");
}
} catch (IOException | TransformerException | XMLStreamException e) {
String msg = new StringBuilder()
String msg = new StringBuilder(256)
.append("Cannot feed the data into SonarQube, details: '")
.append(e)
.append("'")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public int getTime() {
* Returns execution details as sonar-conform XML
*/
public String getDetails() {
StringBuilder details = new StringBuilder();
StringBuilder details = new StringBuilder(512);
details.append("<testcase status=\"")
.append(status)
.append("\" time=\"")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public void addTestCase(TestCase tc) {
* Returns execution details as sonar-conform XML
*/
public String getDetails() {
StringBuilder details = new StringBuilder();
StringBuilder details = new StringBuilder(512);
details.append("<tests-details>");
for (TestCase tc : testCases) {
details.append(tc.getDetails());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public void execute(SensorContext context) {
.save();
}
} catch (Exception e) {
String msg = new StringBuilder()
String msg = new StringBuilder(256)
.append("Cannot feed the data into sonar, details: '")
.append(e)
.append("'")
Expand Down Expand Up @@ -142,8 +142,10 @@ public InputFile getInputFileIfInProject(SensorContext sensorContext, String pat
final InputFile inputFile = sensorContext.fileSystem().inputFile(sensorContext.
fileSystem().predicates().hasPath(path));
if (inputFile == null) {
LOG.debug("Path '{}' couldn't be found in module '{}' base dir '{}'", path, sensorContext.module().key(),
sensorContext.fileSystem().baseDir());
if (LOG.isDebugEnabled()) {
LOG.debug("Path '{}' couldn't be found in module '{}' base dir '{}'", path, sensorContext.module().key(),
sensorContext.fileSystem().baseDir());
}
notFoundFiles.add(path);
}
return inputFile;
Expand All @@ -165,9 +167,7 @@ private void executeReport(SensorContext context, File report, int prevViolation
}
} catch (EmptyReportException e) {
LOG.warn("The report '{}' seems to be empty, ignoring.", report);
if (LOG.isDebugEnabled()) {
LOG.debug("Cannot read report", e);
}
LOG.debug("Cannot read report", e);
CxxUtils.validateRecovery(e, getLanguage());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ private static String[] tokenizeCommandLine(String cmdLine) {
List<String> args = new ArrayList<>();
boolean escape = false;
char stringOpen = 0;
StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder(512);

// Tokenize command line with support for escaping
for (char ch : cmdLine.toCharArray()) {
Expand All @@ -170,7 +170,7 @@ private static String[] tokenizeCommandLine(String cmdLine) {
} else if ((ch == ' ')
&& (sb.length() > 0)) {
args.add(sb.toString());
sb = new StringBuilder();
sb = new StringBuilder(512);
}
if (ch != ' ') {
sb.append(ch);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public CxxValgrindSensor(CxxLanguage language) {
}

private static String createErrorMsg(ValgrindError error, ValgrindStack stack, int stackNr) {
StringBuilder errorMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder(512);
errorMsg.append(error.getText());
if (error.getStacks().size() > 1) {
errorMsg.append(" (Stack ").append(stackNr).append(")");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public ValgrindError(String kind, String text, List<ValgrindStack> stacks) {
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder(512);
sb.append("ValgrindError [kind=").append(kind).append(", text=").append(text).append(", stacks=[");
for (ValgrindStack stack : stacks) {
sb.append(" ValgrindStack=[").append(stack).append("] ");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public ValgrindFrame(@Nullable String ip, @Nullable String obj, @Nullable String

@Override
public String toString() {
StringBuilder builder = new StringBuilder().append(ip).append(": ").append(fn);
StringBuilder builder = new StringBuilder(256).append(ip).append(": ").append(fn);
if (isLocationKnown()) {
builder.append(" (")
.append("".equals(file) ? ("in " + obj) : (file + getLineStr()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public List<ValgrindFrame> getFrames() {

@Override
public String toString() {
StringBuilder res = new StringBuilder();
StringBuilder res = new StringBuilder(256);
for (ValgrindFrame frame : frames) {
res.append(frame);
res.append('\n');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,8 @@ public void visitToken(Token token) {
cpdTokens.addToken(range, text);
} catch (IllegalArgumentException | IllegalStateException e) {
// ignore range errors: parsing errors could lead to wrong location data
if (LOG.isDebugEnabled()) {
LOG.debug("CPD error in file '{}' at line:{}, column:{}", getContext().getFile().getAbsoluteFile(),
token.getLine(), token.getColumn());
}
LOG.debug("CPD error in file '{}' at line:{}, column:{}", getContext().getFile().getAbsoluteFile(),
token.getLine(), token.getColumn());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,7 @@ private TokenLocation highlight(TokenLocation last, TokenLocation current, TypeO
// ignore highlight errors: parsing errors could lead to wrong location data
LOG.warn("Highligthing error in file '{}' at line:{}, column:{}", getContext().getFile().getAbsoluteFile(),
current.startLine(), current.startLineOffset());
if (LOG.isDebugEnabled()) {
LOG.debug("highlighing exception {}", ex);
}
LOG.debug("highlighing exception {}", ex);
}
return current;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,12 @@ public void shouldReportCorrectViolations() {
* 2 issues
*/
DefaultInputFile testFile0 = TestInputFileBuilder.create("ProjectKey", "src/lib/component0.cc").setLanguage("cpp")
.initMetadata(new String("asd\nasdas\nasda\n")).build();
.initMetadata("asd\nasdas\nasda\n").build();
/*
* 1 issue
*/
DefaultInputFile testFile1 = TestInputFileBuilder.create("ProjectKey", "src/lib/component1.cc").setLanguage("cpp")
.initMetadata(new String("asd\nasdas\nasda\n")).build();
.initMetadata("asd\nasdas\nasda\n").build();

context.fileSystem().add(testFile0);
context.fileSystem().add(testFile1);
Expand All @@ -99,12 +99,12 @@ public void shouldReportCorrectMetrics() {
* 2 issues
*/
DefaultInputFile testFile0 = TestInputFileBuilder.create("ProjectKey", "src/lib/component0.cc").setLanguage("cpp")
.initMetadata(new String("asd\nasdas\nasda\n")).build();
.initMetadata("asd\nasdas\nasda\n").build();
/*
* 1 issue
*/
DefaultInputFile testFile1 = TestInputFileBuilder.create("ProjectKey", "src/lib/component1.cc").setLanguage("cpp")
.initMetadata(new String("asd\nasdas\nasda\n")).build();
.initMetadata("asd\nasdas\nasda\n").build();

context.fileSystem().add(testFile0);
context.fileSystem().add(testFile1);
Expand Down Expand Up @@ -138,7 +138,7 @@ public void invalidReportReportsNoIssues() {
context.setSettings(settings);

context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "src/lib/component1.cc")
.setLanguage("cpp").initMetadata(new String("asd\nasdas\nasda\n")).build());
.setLanguage("cpp").initMetadata("asd\nasdas\nasda\n").build());

CxxClangSASensor sensor = new CxxClangSASensor(language);
sensor.execute(context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public void shouldReportCorrectViolations() {
context.setSettings(settings);

context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "sources/utils/code_chunks.cpp")
.setLanguage("cpp").initMetadata(new String("asd\nasdas\nasda\n")).build());
.setLanguage("cpp").initMetadata("asd\nasdas\nasda\n").build());

CxxClangTidySensor sensor = new CxxClangTidySensor(language);

Expand All @@ -90,7 +90,7 @@ public void invalidReportReportsNoIssues() {
context.setSettings(settings);

context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "sources/utils/code_chunks.cpp")
.setLanguage("cpp").initMetadata(new String("asd\nasdas\nasda\n")).build());
.setLanguage("cpp").initMetadata("asd\nasdas\nasda\n").build());

CxxClangTidySensor sensor = new CxxClangTidySensor(language);

Expand Down
Loading