Writing Custom Rules for Java Regarding HardCoded Source Code

Hi All,

I’m new to SonarQube and I have a requirement in which they want SonarQube to be able to find the hardcoded in the source code that Sonarqube has scanned. So far as I have learned, there is no Rules in SonarQube that can find hardcoded in the source code immediately. For example if I write “String abc = "1234567890"”, SonarQube won’t be able to mark that line of code as findings immediately and I need to do custom rules.

I have read it here : https://docs.sonarqube.org/display/PLUG/Writing+Custom+Java+Rules+101

And I’m finding it quite difficult since I’m not used to Maven, so my question is, is there any template rules from SonarQube that I can custom in SonarQube immediately regarding this hardcoded in source code? Or is there any custom rules developed regarding this hardcoded in source code that I can use immediately?

Please help and advise.

Thank you very much

Hello,

Just to be clear, because it’s rather blurry for me.

What do you mean by finding “the hardcoded” ? The hardcoded what?
According to your (small) example, are your only searching for all the hardcoded String literals?!

Regards,
Michael

Hi,

Thanks for your reply.

Sorry for being blurry. By hardcoded I mean hardcoded of Variabels in our programming code.

for example :

String text = “1234567890”;

I want to make a rules that could detect and inform me that at the lines containing String text, the contains of the variabels is being hardcoded and an action is needed to be taken.

If I’m still being unclear, please inform me. I hope somebody could help me, because reading the tutorials of creating custom rules using Maven is quite difficult for me.

Thanks!

Hello @denny1995v6,

Sorry for the late reply. I missed your answer back then. Did you managed to write your rule targeting string literals?

Easiest way would have been to go for Tree.Kind.VARIABLE, and check if the initializer is a Tree.Kind.STRING_LITERAL. Please don’t ask me how, everything is described in the tutorial.

Now, I’m afraid that if writing custom rules (after following the tutorial) is difficult to you, writing specific custom rules is going to be huge challenge. You better first getting familiar with java, maven, concepts of static analysis (google?) and the SonarJava static analyzer code source and rules before jumping into custom rules.

Regards,
Michael