SourceLineAnnotation.java

Index Score
edu.umd.cs.findbugs
FindBugs

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
JAVA0034JAVA0034 Missing braces in if statement
PARAMSNumber of formal parameter declarations
INTERFACE_COMPLEXITYInterface complexity
EXITSProcedure exits
DECL_COMMENTSComments in declarations
RETURNSNumber of return points from functions
SIZESize of the file in bytes
DOC_COMMENTNumber of javadoc comment lines
UNIQUE_OPERANDSNumber of unique operands
OPERANDSNumber of operands
CYCLOMATICCyclomatic complexity
FUNCTIONSNumber of function declarations
PROGRAM_VOCABHalstead program vocabulary
PROGRAM_LENGTHHalstead program length
OPERATORSNumber of operators
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
COMMENTSComment lines
LINESNumber of lines in the source file
LOGICAL_LINESNumber of statements
ELOCEffective lines of code
LOCLines of code
BLOCKSNumber of blocks
JAVA0068JAVA0068 Modifiers not declared in recommended order
COMPARISONSNumber of comparison operators
JAVA0116JAVA0116 Missing javadoc: field 'field'
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0173JAVA0173 Unused method parameter
JAVA0144JAVA0144 Line exceeds maximum M characters
JAVA0150JAVA0150 java.lang.Error (or subclass) thrown
UNIQUE_OPERATORSNumber of unique operators
JAVA0145JAVA0145 Tab character used in source file
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0138JAVA0138 N parameters defined for method (maximum: M)
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0117JAVA0117 Missing javadoc: method 'method'
EXEC_COMMENTSComments in executable code
LINE_COMMENTNumber of line comments
LOOPSNumber of loops
WHITESPACENumber of whitespace lines
NEST_DEPTHMaximum nesting depth
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2003-2008, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs; import java.io.File; import java.io.IOException; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.LineNumber; import org.apache.bcel.classfile.LineNumberTable; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.MethodGen; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.Hierarchy; import edu.umd.cs.findbugs.ba.JavaClassAndMethod; import edu.umd.cs.findbugs.ba.Location; import edu.umd.cs.findbugs.ba.SourceFinder; import edu.umd.cs.findbugs.ba.SourceInfoMap; import edu.umd.cs.findbugs.ba.XClass; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.IAnalysisCache; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; /** * A BugAnnotation that records a range of source lines * in a class. * * @author David Hovemeyer * @see BugAnnotation */ public class SourceLineAnnotation implements BugAnnotation { private static final long serialVersionUID = 1L; public static final String DEFAULT_ROLE = "SOURCE_LINE_DEFAULT"; public static final String DEFAULT_ROLE_UNKNOWN_LINE = "SOURCE_LINE_DEFAULT_UNKNOWN_LINE"; public static final String ROLE_ANOTHER_INSTANCE = "SOURCE_LINE_ANOTHER_INSTANCE"; public static final String ROLE_GENERATED_AT = "SOURCE_LINE_GENERATED_AT"; public static final String ROLE_OBLIGATION_CREATED = "SOURCE_LINE_OBLIGATION_CREATED"; public static final String ROLE_OBLIGATION_CREATED_BY_WILLCLOSE_PARAMETER = "SOURCE_LINE_OBLIGATION_CREATED_BY_WILLCLOSE_PARAMETER"; public static final String ROLE_PATH_CONTINUES = "SOURCE_LINE_PATH_CONTINUES"; /** * String returned if the source file is unknown. * This must match what BCEL uses when the source file is unknown. */ public static final String UNKNOWN_SOURCE_FILE = "<Unknown>"; private String description; final private String className; private String sourceFile; final private int startLine; final private int endLine; final private int startBytecode; final private int endBytecode; private boolean synthetic; public static final String DESCRIPTION_LAST_CHANGE = "SOURCE_LINE_LAST_CHANGE"; public static final String DESCRIPTION_LOOP_BOTTOM = "SOURCE_LINE_LOOP_BOTTOM"; /** * Constructor. * * @param className the class to which the line number(s) refer * @param sourceFile the name of the source file * @param startLine the first line (inclusive) * @param endLine the ending line (inclusive) * @param startBytecode the first bytecode offset (inclusive) * @param endBytecode the end bytecode offset (inclusive) */ public SourceLineAnnotation(@NonNull String className, @NonNull String sourceFile, int startLine, int endLine, int startBytecode, int endBytecode) { if (className == null) throw new IllegalArgumentException("class name is null"); if (sourceFile == null) throw new IllegalArgumentException("source file is null"); this.description = DEFAULT_ROLE; this.className = className; this.sourceFile = sourceFile; this.startLine = startLine; this.endLine = endLine; this.startBytecode = startBytecode; this.endBytecode = endBytecode; } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } /** * Factory method to create an unknown source line annotation. * * @param className the class name * @param sourceFile the source file name * @return the SourceLineAnnotation */ public static SourceLineAnnotation createUnknown(String className, String sourceFile) { return createUnknown(className, sourceFile, -1, -1); } /** * Factory method to create an unknown source line annotation. * This variant looks up the source filename automatically * based on the class using best effort. * * @param className the class name * @return the SourceLineAnnotation */ public static SourceLineAnnotation createUnknown(String className) { return createUnknown( className, AnalysisContext.currentAnalysisContext().lookupSourceFile(className), -1, -1); } /** * Factory method to create an unknown source line annotation. * This doesn't use the analysis context. * * @param className the class name * @return the SourceLineAnnotation */ public static SourceLineAnnotation createReallyUnknown(String className) { return createUnknown( className, SourceLineAnnotation.UNKNOWN_SOURCE_FILE, -1, -1); } /** * Factory method to create an unknown source line annotation. * This variant is used when bytecode offsets are known, * but not source lines. * * @param className the class name * @param sourceFile the source file name * @return the SourceLineAnnotation */ public static SourceLineAnnotation createUnknown(String className, String sourceFile, int startBytecode, int endBytecode) { SourceLineAnnotation result = new SourceLineAnnotation(className, sourceFile, -1, -1, startBytecode, endBytecode); // result.setDescription("SOURCE_LINE_UNKNOWN"); return result; } /** * Factory method for creating a source line annotation describing * an entire method. * * @param visitor a BetterVisitor which is visiting the method * @return the SourceLineAnnotation */ public static SourceLineAnnotation fromVisitedMethod(PreorderVisitor visitor) { SourceLineAnnotation sourceLines = getSourceAnnotationForMethod( visitor.getDottedClassName(), visitor.getMethodName(), visitor.getMethodSig()); return sourceLines; } /** * Factory method for creating a source line annotation describing an entire * method. * * @param methodGen * the method being visited * @return the SourceLineAnnotation, or null if we do not have line number * information for the method */ public static SourceLineAnnotation fromVisitedMethod(MethodGen methodGen, String sourceFile) { LineNumberTable lineNumberTable = methodGen.getLineNumberTable(methodGen.getConstantPool()); String className = methodGen.getClassName(); int codeSize = methodGen.getInstructionList().getLength(); if (lineNumberTable == null) return createUnknown(className, sourceFile, 0, codeSize - 1); return forEntireMethod(className, sourceFile, lineNumberTable, codeSize); } /** * Create a SourceLineAnnotation covering an entire method. * * @param className name of the class the method is in * @param sourceFile source file containing the method * @param lineNumberTable the method's LineNumberTable * @param codeSize size in bytes of the method's code * @return a SourceLineAnnotation covering the entire method */ public static SourceLineAnnotation forEntireMethod(String className, String sourceFile, LineNumberTable lineNumberTable, int codeSize) { LineNumber[] table = lineNumberTable.getLineNumberTable(); if (table != null && table.length > 0) { LineNumber first = table[0]; LineNumber last = table[table.length - 1]; return new SourceLineAnnotation(className, sourceFile, first.getLineNumber(), last.getLineNumber(), 0, codeSize - 1); } else { return createUnknown(className, sourceFile, 0, codeSize - 1); } } /** * Create a SourceLineAnnotation covering an entire method. * * @param javaClass JavaClass containing the method * @param method the method * @return a SourceLineAnnotation for the entire method */ public static SourceLineAnnotation forEntireMethod(JavaClass javaClass, @CheckForNull Method method) { String sourceFile = javaClass.getSourceFileName(); if (method == null) return createUnknown(javaClass.getClassName(), sourceFile); Code code = method.getCode(); LineNumberTable lineNumberTable = method.getLineNumberTable(); if (code == null || lineNumberTable == null) { return createUnknown(javaClass.getClassName(), sourceFile); } return forEntireMethod(javaClass.getClassName(), sourceFile, lineNumberTable, code.getLength()); } /** * Create a SourceLineAnnotation covering an entire method. * * @param javaClass JavaClass containing the method * @param xmethod the method * @return a SourceLineAnnotation for the entire method */ public static SourceLineAnnotation forEntireMethod(JavaClass javaClass, XMethod xmethod) { JavaClassAndMethod m = Hierarchy.findMethod(javaClass, xmethod.getName(), xmethod.getSignature()); if (m == null) { return createUnknown(javaClass.getClassName(), javaClass.getSourceFileName()); } else { return forEntireMethod(javaClass, m.getMethod()); } } /** * Make a best-effort attempt to * create a SourceLineAnnotation for the first line of a method. * * @param methodDescriptor a method * @return SourceLineAnnotation describing the first line of the method * (insofar as we can actually figure that out from the bytecode) */ public static SourceLineAnnotation forFirstLineOfMethod(MethodDescriptor methodDescriptor) { SourceLineAnnotation result = null; try { Method m = Global.getAnalysisCache().getMethodAnalysis(Method.class, methodDescriptor); XClass xclass = Global.getAnalysisCache().getClassAnalysis(XClass.class, methodDescriptor.getClassDescriptor()); LineNumberTable lnt = m.getLineNumberTable(); String sourceFile = xclass.getSource(); if (sourceFile != null && lnt != null) { int firstLine = Integer.MAX_VALUE; int bytecode = 0; LineNumber[] entries = lnt.getLineNumberTable(); for (LineNumber entry : entries) { if (entry.getLineNumber() < firstLine) { firstLine = entry.getLineNumber(); bytecode = entry.getStartPC(); } } if (firstLine < Integer.MAX_VALUE) { result = new SourceLineAnnotation( methodDescriptor.getClassDescriptor().toDottedClassName(), sourceFile, firstLine, firstLine, bytecode, bytecode); } } } catch (CheckedAnalysisException e) { // ignore } if (result == null) { result = createUnknown(methodDescriptor.getClassDescriptor().toDottedClassName()); } return result; } /** * Factory method for creating a source line annotation describing the * source line number for the instruction being visited by given visitor. * * @param visitor a BetterVisitor which is visiting the method * @param pc the bytecode offset of the instruction in the method * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstruction(BytecodeScanningDetector visitor, int pc) { return fromVisitedInstructionRange(visitor.getClassContext(), visitor, pc, pc); } /** * Factory method for creating a source line annotation describing the * source line number for the instruction being visited by given visitor. * * @param classContext the ClassContext * @param visitor a BetterVisitor which is visiting the method * @param pc the bytecode offset of the instruction in the method * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstruction(ClassContext classContext, PreorderVisitor visitor, int pc) { return fromVisitedInstructionRange(classContext, visitor, pc, pc); } /** * Create from Method and Location in a visited class. * * @param classContext ClassContext of visited class * @param method Method in visited class * @param loc Location in visited class * @return SourceLineAnnotation describing visited Location */ public static SourceLineAnnotation fromVisitedInstruction(ClassContext classContext, Method method, Location loc) { return fromVisitedInstruction(classContext, method, loc.getHandle()); } /** * Create from Method and InstructionHandle in a visited class. * * @param classContext ClassContext of visited class * @param method Method in visited class * @param handle InstructionHandle in visited class * @return SourceLineAnnotation describing visited instruction */ public static SourceLineAnnotation fromVisitedInstruction(ClassContext classContext, Method method, InstructionHandle handle) { return fromVisitedInstruction(classContext, method, handle.getPosition()); } /** * Create from MethodDescriptor and Location of visited instruction. * * @param methodDescriptor MethodDescriptor identifying analyzed method * @param location Location of instruction within analyed method * @return SourceLineAnnotation describing visited instruction */ public static SourceLineAnnotation fromVisitedInstruction(MethodDescriptor methodDescriptor, Location location) { return fromVisitedInstruction(methodDescriptor, location.getHandle().getPosition()); } public static SourceLineAnnotation fromVisitedInstruction(MethodDescriptor methodDescriptor, int position) { try { IAnalysisCache analysisCache = Global.getAnalysisCache(); JavaClass jclass = analysisCache.getClassAnalysis(JavaClass.class, methodDescriptor.getClassDescriptor()); Method method = analysisCache.getMethodAnalysis(Method.class, methodDescriptor); return fromVisitedInstruction(jclass, method, position); } catch (CheckedAnalysisException e) { return createReallyUnknown(methodDescriptor.getClassDescriptor().toDottedClassName()); } } /** * Create from Method and bytecode offset in a visited class. * * @param classContext ClassContext of visited class * @param method Method in visited class * @param pc bytecode offset in visited method * @return SourceLineAnnotation describing visited instruction */ public static SourceLineAnnotation fromVisitedInstruction(ClassContext classContext, Method method, int pc) { return fromVisitedInstruction(classContext.getJavaClass(), method, pc); } /** * Create from Method and bytecode offset in a visited class. * * @param jclass JavaClass of visited class * @param method Method in visited class * @param pc bytecode offset in visited method * @return SourceLineAnnotation describing visited instruction */ public static SourceLineAnnotation fromVisitedInstruction(JavaClass jclass, Method method, int pc) { LineNumberTable lineNumberTable = method.getCode().getLineNumberTable(); String className = jclass.getClassName(); String sourceFile = jclass.getSourceFileName(); if (lineNumberTable == null) return createUnknown(className, sourceFile, pc, pc); int startLine = lineNumberTable.getSourceLine(pc); return new SourceLineAnnotation(className, sourceFile, startLine, startLine, pc, pc); } /** * Factory method for creating a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstructionRange( BytecodeScanningDetector visitor, int startPC, int endPC) { LineNumberTable lineNumberTable = getLineNumberTable(visitor); String className = visitor.getDottedClassName(); String sourceFile = visitor.getSourceFile(); if (lineNumberTable == null) return createUnknown(className, sourceFile, startPC, endPC); int startLine = lineNumberTable.getSourceLine(startPC); int endLine = lineNumberTable.getSourceLine(endPC); return new SourceLineAnnotation(className, sourceFile, startLine, endLine, startPC, endPC); } /** * Factory method for creating a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * * @param classContext the ClassContext * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstructionRange( ClassContext classContext, PreorderVisitor visitor, int startPC, int endPC) { if (startPC > endPC) throw new IllegalArgumentException("Start pc " + startPC + " greater than end pc " + endPC); LineNumberTable lineNumberTable = getLineNumberTable(visitor); String className = visitor.getDottedClassName(); String sourceFile = visitor.getSourceFile(); if (lineNumberTable == null) return createUnknown(className, sourceFile, startPC, endPC); int startLine = lineNumberTable.getSourceLine(startPC); int endLine = lineNumberTable.getSourceLine(endPC); return new SourceLineAnnotation(className, sourceFile, startLine, endLine, startPC, endPC); } public static SourceLineAnnotation fromRawData(String className, String sourceFile, int startLine, int endLine, int startPC, int endPC) { if (startLine == -1) return createUnknown(className, sourceFile, startPC, endPC); return new SourceLineAnnotation(className, sourceFile, startLine, endLine, startPC, endPC); } /** * Factory method for creating a source line annotation describing the * source line number for the instruction being visited by given visitor. * * @param visitor a DismantleBytecode visitor which is visiting the method * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstruction(BytecodeScanningDetector visitor) { return fromVisitedInstruction(visitor.getClassContext(), visitor, visitor.getPC()); } /** * Factory method for creating a source line annotation describing the * source line number for a visited instruction. * * @param classContext the ClassContext * @param methodGen the MethodGen object representing the method * @param handle the InstructionHandle containing the visited instruction * @return the SourceLineAnnotation, or null if we do not have line number information * for the instruction */ public static SourceLineAnnotation fromVisitedInstruction(ClassContext classContext, MethodGen methodGen, String sourceFile, @NonNull InstructionHandle handle) { LineNumberTable table = methodGen.getLineNumberTable(methodGen.getConstantPool()); String className = methodGen.getClassName(); int bytecodeOffset = handle.getPosition(); if (table == null) return createUnknown(className, sourceFile, bytecodeOffset, bytecodeOffset); int lineNumber = table.getSourceLine(handle.getPosition()); return new SourceLineAnnotation( className, sourceFile, lineNumber, lineNumber, bytecodeOffset, bytecodeOffset); } /** * Factory method for creating a source line annotation describing * the source line numbers for a range of instruction in a method. * * @param classContext theClassContext * @param methodGen the method * @param start the start instruction * @param end the end instruction (inclusive) */ public static SourceLineAnnotation fromVisitedInstructionRange( ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start, InstructionHandle end) { LineNumberTable lineNumberTable = methodGen.getLineNumberTable(methodGen.getConstantPool()); String className = methodGen.getClassName(); if (lineNumberTable == null) return createUnknown(className, sourceFile, start.getPosition(), end.getPosition()); int startLine = lineNumberTable.getSourceLine(start.getPosition()); int endLine = lineNumberTable.getSourceLine(end.getPosition()); return new SourceLineAnnotation( className, sourceFile, startLine, endLine, start.getPosition(), end.getPosition()); } private static LineNumberTable getLineNumberTable(PreorderVisitor visitor) { Code code = visitor.getMethod().getCode(); if (code == null) return null; return code.getLineNumberTable(); } /** * Get the class name. */ public String getClassName() { return className; } /** * Get the source file name. */ public String getSourceFile() { return sourceFile; } /** * Is the source file known? */ public boolean isSourceFileKnown() { return !sourceFile.equals(UNKNOWN_SOURCE_FILE); } /** * Set the source file name. * * @param sourceFile the source file name */ public void setSourceFile(String sourceFile) { this.sourceFile = sourceFile; } /** * Get the simple class name (the part of the name after the dot) */ public String getSimpleClassName() { int lastDot = className.lastIndexOf('.'); return className.substring(lastDot+1); } /** * Get the package name. */ public String getPackageName() { int lastDot = className.lastIndexOf('.'); if (lastDot < 0) return ""; else return className.substring(0, lastDot); } /** * Get the start line (inclusive). */ public int getStartLine() { return startLine; } /** * Get the ending line (inclusive). */ public int getEndLine() { return endLine; } /** * Get start bytecode (inclusive). */ public int getStartBytecode() { return startBytecode; } /** * Get end bytecode (inclusive). */ public int getEndBytecode() { return endBytecode; } /** * Is this an unknown source line annotation? */ public boolean isUnknown() { return startLine < 0 || endLine < 0; } public void accept(BugAnnotationVisitor visitor) { visitor.visitSourceLineAnnotation(this); } public String format(String key, ClassAnnotation primaryClass) { if (key.equals("hash")) return ""; if (key.equals("")) { StringBuilder buf = new StringBuilder(); buf.append(sourceFile); appendLines(buf); return buf.toString(); } else if (key.equals("lineNumber")) { StringBuilder buf = new StringBuilder(); appendLinesRaw(buf); return buf.toString(); } else if (key.equals("full")) { StringBuilder buf = new StringBuilder(); String pkgName = getPackageName(); if (!pkgName.equals("")) { buf.append(pkgName.replace('.', '/')); buf.append('/'); } buf.append(sourceFile); appendLines(buf); return buf.toString(); } else throw new IllegalArgumentException("Unknown format key " + key); } private void appendLines(StringBuilder buf) { if (isUnknown()) return; buf.append(":["); appendLinesRaw(buf); buf.append(']'); } private void appendLinesRaw(StringBuilder buf) { if (isUnknown()) return; if (startLine == endLine) { buf.append("line "); buf.append(startLine); } else { buf.append("lines "); buf.append(startLine); buf.append('-'); buf.append(endLine); } } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { String desc = description; if (desc.equals(DEFAULT_ROLE) && isUnknown()) desc = DEFAULT_ROLE_UNKNOWN_LINE; String pattern = I18N.instance().getAnnotationDescription(desc); FindBugsMessageFormat format = new FindBugsMessageFormat(pattern); return format.format(new BugAnnotation[]{this}, null); } public int compareTo(BugAnnotation o) { if (!(o instanceof SourceLineAnnotation)) // All BugAnnotations must be comparable return this.getClass().getName().compareTo(o.getClass().getName()); SourceLineAnnotation other = (SourceLineAnnotation) o; int cmp = className.compareTo(other.className); if (cmp != 0) return cmp; cmp = startLine - other.startLine; if (cmp != 0) return cmp; return endLine - other.endLine; } @Override public int hashCode() { return className.hashCode() + startLine + 3 * endLine; } @Override public boolean equals(Object o) { if (!(o instanceof SourceLineAnnotation)) return false; SourceLineAnnotation other = (SourceLineAnnotation) o; return className.equals(other.className) && startLine == other.startLine && endLine == other.endLine; } /* ---------------------------------------------------------------------- * XML Conversion support * ---------------------------------------------------------------------- */ private static final String ELEMENT_NAME = "SourceLine"; public void writeXML(XMLOutput xmlOutput) throws IOException { writeXML(xmlOutput, false, false); } static final ThreadLocal<SourceFinder> sourceFinder = new ThreadLocal<SourceFinder>(); static final ThreadLocal<String> relativeSourceBase = new ThreadLocal<String>(); public static void generateRelativeSource(File relativeSourceBase, Project project) { try { SourceLineAnnotation.relativeSourceBase.set(relativeSourceBase.getCanonicalPath()); SourceFinder mySourceFinder = new SourceFinder(); sourceFinder.set(mySourceFinder); mySourceFinder.setSourceBaseList(project.getSourceDirList()); } catch (IOException e) { AnalysisContext.logError("Error resolving relative source base " + relativeSourceBase, e); } } public static void clearGenerateRelativeSource() { sourceFinder.remove(); relativeSourceBase.remove(); } public void writeXML(XMLOutput xmlOutput, boolean addMessages, boolean isPrimary) throws IOException { String classname = getClassName(); String sourcePath = getSourcePath(); XMLAttributeList attributeList = new XMLAttributeList() .addAttribute("classname", classname); if (isPrimary) attributeList.addAttribute("primary", "true"); int n = getStartLine(); // start/end are now optional (were too many "-1"s in the xml) if (n >= 0) attributeList.addAttribute("start", String.valueOf(n)); n = getEndLine(); if (n >= 0) attributeList.addAttribute("end", String.valueOf(n)); n = getStartBytecode(); // startBytecode/endBytecode haven't been set for a while now if (n >= 0) attributeList.addAttribute("startBytecode", String.valueOf(n)); n = getEndBytecode(); if (n >= 0) attributeList.addAttribute("endBytecode", String.valueOf(n)); if (isSourceFileKnown()) { attributeList.addAttribute("sourcefile", sourceFile); attributeList.addAttribute("sourcepath", sourcePath); SourceFinder mySourceFinder = sourceFinder.get(); if (mySourceFinder != null) { try { String fullPath = new File(mySourceFinder.findSourceFile(this).getFullFileName()).getCanonicalPath(); String myRelativeSourceBase = relativeSourceBase.get(); if (fullPath.startsWith(myRelativeSourceBase)) attributeList.addAttribute("relSourcepath", fullPath.substring(myRelativeSourceBase.length()+1)); } catch (IOException e) { assert true; } } } String role = getDescription(); if (!role.equals(DEFAULT_ROLE)) attributeList.addAttribute("role", getDescription()); if (synthetic) attributeList.addAttribute("synthetic", "true"); if (addMessages) { xmlOutput.openTag(ELEMENT_NAME, attributeList); xmlOutput.openTag("Message"); xmlOutput.writeText(this.toString()); xmlOutput.closeTag("Message"); xmlOutput.closeTag(ELEMENT_NAME); } else { xmlOutput.openCloseTag(ELEMENT_NAME, attributeList); } } public String getSourcePath() { String classname = getClassName(); String packageName = ""; if (classname.indexOf('.') > 0) packageName = classname.substring(0,1+classname.lastIndexOf('.')); String sourcePath = packageName.replace('.', '/')+sourceFile; return sourcePath; } /** * @param synthetic The synthetic to set. */ public void setSynthetic(boolean synthetic) { this.synthetic = synthetic; } /** * @return Returns the synthetic. */ public boolean isSynthetic() { return synthetic; } public boolean isSignificant() { return false; } /** * @param className * @param methodName * @param methodSig * @return */ static SourceLineAnnotation getSourceAnnotationForMethod( String className, String methodName, String methodSig) { JavaClassAndMethod targetMethod = null; Code code = null; try { JavaClass targetClass = AnalysisContext.currentAnalysisContext().lookupClass(className); targetMethod = Hierarchy.findMethod(targetClass, methodName, methodSig); if (targetMethod != null) { Method method = targetMethod.getMethod(); if (method != null) code = method.getCode(); } } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } SourceInfoMap sourceInfoMap = AnalysisContext.currentAnalysisContext().getSourceInfoMap(); SourceInfoMap.SourceLineRange range = sourceInfoMap.getMethodLine(className, methodName, methodSig); if (range != null) return new SourceLineAnnotation( className, AnalysisContext.currentAnalysisContext().lookupSourceFile(className), range.getStart(), range.getEnd(), 0, code == null ? -1 : code.getLength()); if (sourceInfoMap.fallBackToClassfile() && targetMethod != null) return forEntireMethod( targetMethod.getJavaClass(), targetMethod.getMethod()); // If we couldn't find the source lines, // create an unknown source line annotation referencing // the class and source file. return createUnknown(className); } /** * @param className * @return */ static SourceLineAnnotation getSourceAnnotationForClass(String className, String sourceFileName) { int lastLine = -1; int firstLine = Integer.MAX_VALUE; try { JavaClass targetClass = AnalysisContext.currentAnalysisContext().lookupClass(className); for (Method m : targetClass.getMethods()) { Code c = m.getCode(); if (c != null) { LineNumberTable table = c.getLineNumberTable(); if (table != null) for (LineNumber line : table.getLineNumberTable()) { lastLine = Math.max(lastLine, line.getLineNumber()); firstLine = Math.min(firstLine, line.getLineNumber()); } } } } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } if (firstLine < Integer.MAX_VALUE) return new SourceLineAnnotation(className, sourceFileName, firstLine, lastLine, -1, -1); return SourceLineAnnotation.createUnknown(className, sourceFileName); } } // vim:ts=4

The table below shows all metrics for SourceLineAnnotation.java.

MetricValueDescription
BLOCKS96.00Number of blocks
BLOCK_COMMENT21.00Number of block comment lines
COMMENTS285.00Comment lines
COMMENT_DENSITY 0.65Comment density
COMPARISONS63.00Number of comparison operators
CYCLOMATIC126.00Cyclomatic complexity
DECL_COMMENTS43.00Comments in declarations
DOC_COMMENT258.00Number of javadoc comment lines
ELOC437.00Effective lines of code
EXEC_COMMENTS 3.00Comments in executable code
EXITS118.00Procedure exits
FUNCTIONS58.00Number of function declarations
HALSTEAD_DIFFICULTY84.20Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY188.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 0.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 0.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 0.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 0.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA003437.00JAVA0034 Missing braces in if statement
JAVA0035 0.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 0.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 1.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 5.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA0076 0.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 0.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 0.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 0.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA0108 6.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA011011.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 0.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 1.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 0.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 9.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 5.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 0.00JAVA0128 Public constructor in non-public class
JAVA0130 0.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 1.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 2.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 0.00JAVA0143 Synchronized method
JAVA0144 3.00JAVA0144 Line exceeds maximum M characters
JAVA01451387.00JAVA0145 Tab character used in source file
JAVA0150 1.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 0.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 0.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 3.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 0.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 0.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 0.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 0.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 0.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES912.00Number of lines in the source file
LINE_COMMENT 6.00Number of line comments
LOC520.00Lines of code
LOGICAL_LINES276.00Number of statements
LOOPS 0.00Number of loops
NEST_DEPTH 5.00Maximum nesting depth
OPERANDS1493.00Number of operands
OPERATORS2546.00Number of operators
PARAMS92.00Number of formal parameter declarations
PROGRAM_LENGTH4039.00Halstead program length
PROGRAM_VOCAB513.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS96.00Number of return points from functions
SIZE32645.00Size of the file in bytes
UNIQUE_OPERANDS461.00Number of unique operands
UNIQUE_OPERATORS52.00Number of unique operators
WHITESPACE107.00Number of whitespace lines