My custom rule is:
The name of class should be similar to name of package
I created the new rule NameClassByPackage.java
"Name of class by pakage"
Language : Java
Sonar Version : 6.7
Example
If the package name "service" its class should be <Name> + <Service>, for example "ClassService.java"
Other Example
package com.enterprise.controller
class:
NameClassOneController
NameClassTwoController
package com.enterprise.service
class:
NameClassOneService
NameClassTwoService
package com.enterprise.util
class:
NameClassOneUtil
NameClassTwoUtil
Etc.
My code: I want to get the name of package to compare with the name of class
package org.sonar.samples.java.checks;
import com.google.common.collect.ImmutableList;
import java.util.List;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.tree.ClassTree;
import org.sonar.plugins.java.api.tree.Tree;
/**
* Only to bring out the unit test requirement about classpath when bytecode methods used (see rule unit test class)
*/
@Rule(key = "NameClassByPackage")
public class NameClassByPackage extends IssuableSubscriptionVisitor {
//I need this
public static final List<String> PACKAGE_NAME = null;
//test
CharSequence charSERVICE = "Service";
@Override
public List<Tree.Kind> nodesToVisit() {
// Register to the kind of nodes you want to be called upon visit.
return ImmutableList.of(Tree.Kind.CLASS);
}
@Override
public void visitNode(Tree tree) {
ClassTree treeClazz = (ClassTree) tree;
if (treeClazz == null) {
return;
}
//test to contains
if (treeClazz.simpleName().toString().contains(charSERVICE)) {
System.out.println("Class Contain "+ treeClazz.simpleName());
System.out.println("charSERVICE "+ charSERVICE);
}
//Real test but I don't have name of package
// Check if the name class include in package
//if (PACKAGE_NAME.contains(treeClazz.simpleName())) {
// reportIssue(tree, String.format("The name of class is incorrect", treeClazz.simpleName()));
// }
}
}