The previous part of this tutorial showed how to create an EmptyMethodRule class and the stubs required for a custom audit. This part shows the actual code for those stubs.
Together organizes audits into groups:
The first coding step is to specify the group for the new audit.
public EmptyMethodRule() {
super(DECLARATION_GRP);
}
private boolean isEmpty(AstCompoundStatement body)
{
// if the method is not abstract
if(body != null) {
if(body.getStatements().length == 0) {
return true;
}
else {
return false;
}
}
return false;
}
If the body is null, this is an abstract method. Skip it and return false. If the body is not null, get the statements that make up the body. If there are no statements, isEmpty() should return true. Otherwise it should return false.
public void checkMethod(AstMethod arg0) {
if(isEmpty(arg0.getBody())) {
}
}
The arg0 parameter represents the current method.
public void checkMethod(AstMethod arg0) {
if(isEmpty(arg0.getBody())) {
message(arg0);
}
}
The body of the if statement calls message(),
passing it the current method that failed. message() handles
the reporting and constructing of the audit output to the Audit Results
Table.
|
import com.togethersoft.sca.ast.AstCompoundStatement;
import com.togethersoft.sca.ast.AstMethod;
import com.togethersoft.sca.plugin.audit.AuditRule;
public class EmptyMethodAudit extends AuditRule {
public EmptyMethodAudit() {
super(DECLARATION_GRP);
}
public void checkMethod(AstMethod arg0) {
if(isEmpty(arg0.getBody())) {
message(arg0);
}
}
private boolean isEmpty(AstCompoundStatement body){
//if the method is not abstract
if(body != null){
if(body.getStatements().length ==
0){
return true;
}
else {
return false;
}
}
return false;
}
}