code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
@SuppressFBWarnings("ES_COMPARING_STRINGS_WITH_EQ")
public String getDottedClassConstantOperand() {
if (dottedClassConstantOperand != null) {
assert dottedClassConstantOperand != NOT_AVAILABLE;
return dottedClassConstantOperand;
}
if (classConstantOperand == NOT_AVAILABLE) {
throw new IllegalStateException("getDottedClassConstantOperand called but value not available");
}
dottedClassConstantOperand = ClassName.toDottedClassName(classConstantOperand);
return dottedClassConstantOperand;
} | java |
@Deprecated
@SuppressFBWarnings("ES_COMPARING_STRINGS_WITH_EQ")
public String getRefConstantOperand() {
if (refConstantOperand == NOT_AVAILABLE) {
throw new IllegalStateException("getRefConstantOperand called but value not available");
}
if (refConstantOperand == null) {
String dottedClassConstantOperand = getDottedClassConstantOperand();
StringBuilder ref = new StringBuilder(dottedClassConstantOperand.length() + nameConstantOperand.length()
+ sigConstantOperand.length() + 5);
ref.append(dottedClassConstantOperand).append(".").append(nameConstantOperand).append(" : ")
.append(replaceSlashesWithDots(sigConstantOperand));
refConstantOperand = ref.toString();
}
return refConstantOperand;
} | java |
public int getPrevOpcode(int offset) {
if (offset < 0) {
throw new IllegalArgumentException("offset (" + offset + ") must be nonnegative");
}
if (offset >= prevOpcode.length || offset > sizePrevOpcodeBuffer) {
return Const.NOP;
}
int pos = currentPosInPrevOpcodeBuffer - offset;
if (pos < 0) {
pos += prevOpcode.length;
}
return prevOpcode[pos];
} | java |
public void append(DetectorFactory factory) {
if (!memberSet.contains(factory)) {
throw new IllegalArgumentException("Detector " + factory.getFullName() + " appended to pass it doesn't belong to");
}
this.orderedFactoryList.addLast(factory);
} | java |
public Set<DetectorFactory> getUnpositionedMembers() {
HashSet<DetectorFactory> result = new HashSet<>(memberSet);
result.removeAll(orderedFactoryList);
return result;
} | java |
protected void mergeInto(FrameType other, FrameType result) throws DataflowAnalysisException {
// Handle if result Frame or the other Frame is the special "TOP" value.
if (result.isTop()) {
// Result is the identity element, so copy the other Frame
result.copyFrom(other);
return;
} else if (other.isTop()) {
// Other Frame is the identity element, so result stays the same
return;
}
// Handle if result Frame or the other Frame is the special "BOTTOM"
// value.
if (result.isBottom()) {
// Result is the bottom element, so it stays that way
return;
} else if (other.isBottom()) {
// Other Frame is the bottom element, so result becomes the bottom
// element too
result.setBottom();
return;
}
// If the number of slots in the Frames differs,
// then the result is the special "BOTTOM" value.
if (result.getNumSlots() != other.getNumSlots()) {
result.setBottom();
return;
}
// Usual case: ordinary Frames consisting of the same number of values.
// Merge each value in the two slot lists element-wise.
for (int i = 0; i < result.getNumSlots(); ++i) {
mergeValues(other, result, i);
}
} | java |
public LockSet getFactAtLocation(Location location) throws DataflowAnalysisException {
if (lockDataflow != null) {
return lockDataflow.getFactAtLocation(location);
} else {
LockSet lockSet = cache.get(location);
if (lockSet == null) {
lockSet = new LockSet();
lockSet.setDefaultLockCount(0);
if (method.isSynchronized() && !method.isStatic()) {
// LockSet contains just the "this" reference
ValueNumber instance = vnaDataflow.getAnalysis().getThisValue();
lockSet.setLockCount(instance.getNumber(), 1);
} else {
// LockSet is completely empty - nothing to do
}
cache.put(location, lockSet);
}
return lockSet;
}
} | java |
public Object getMethodAnalysis(Class<?> analysisClass, MethodDescriptor methodDescriptor) {
Map<MethodDescriptor, Object> objectMap = getObjectMap(analysisClass);
return objectMap.get(methodDescriptor);
} | java |
public void purgeMethodAnalyses(MethodDescriptor methodDescriptor) {
Set<Map.Entry<Class<?>, Map<MethodDescriptor, Object>>> entrySet = methodAnalysisObjectMap.entrySet();
for (Iterator<Map.Entry<Class<?>, Map<MethodDescriptor, Object>>> i = entrySet.iterator(); i.hasNext();) {
Map.Entry<Class<?>, Map<MethodDescriptor, Object>> entry = i.next();
Class<?> cls = entry.getKey();
// FIXME: hack
if (!DataflowAnalysis.class.isAssignableFrom(cls) && !Dataflow.class.isAssignableFrom(cls)) {
// There is really no need to purge analysis results
// that aren't CFG-based.
// Currently, only dataflow analyses need
// to be purged.
continue;
}
entry.getValue().remove(methodDescriptor);
}
} | java |
public Method getMethod(MethodGen methodGen) {
Method[] methodList = jclass.getMethods();
for (Method method : methodList) {
if (method.getName().equals(methodGen.getName()) && method.getSignature().equals(methodGen.getSignature())
&& method.getAccessFlags() == methodGen.getAccessFlags()) {
return method;
}
}
return null;
} | java |
@CheckForNull
static public BitSet getBytecodeSet(JavaClass clazz, Method method) {
XMethod xmethod = XFactory.createXMethod(clazz, method);
if (cachedBitsets().containsKey(xmethod)) {
return cachedBitsets().get(xmethod);
}
Code code = method.getCode();
if (code == null) {
return null;
}
byte[] instructionList = code.getCode();
// Create callback
UnpackedBytecodeCallback callback = new UnpackedBytecodeCallback(instructionList.length);
// Scan the method.
BytecodeScanner scanner = new BytecodeScanner();
scanner.scan(instructionList, callback);
UnpackedCode unpackedCode = callback.getUnpackedCode();
BitSet result = null;
if (unpackedCode != null) {
result = unpackedCode.getBytecodeSet();
}
cachedBitsets().put(xmethod, result);
return result;
} | java |
public ExceptionSet duplicate() {
ExceptionSet dup = factory.createExceptionSet();
dup.exceptionSet.clear();
dup.exceptionSet.or(this.exceptionSet);
dup.explicitSet.clear();
dup.explicitSet.or(this.explicitSet);
dup.size = this.size;
dup.universalHandler = this.universalHandler;
dup.commonSupertype = this.commonSupertype;
return dup;
} | java |
public boolean isSingleton(String exceptionName) {
if (size != 1) {
return false;
}
ObjectType e = iterator().next();
return e.toString().equals(exceptionName);
} | java |
public void add(ObjectType type, boolean explicit) {
int index = factory.getIndexOfType(type);
if (!exceptionSet.get(index)) {
++size;
}
exceptionSet.set(index);
if (explicit) {
explicitSet.set(index);
}
commonSupertype = null;
} | java |
public void addAll(ExceptionSet other) {
exceptionSet.or(other.exceptionSet);
explicitSet.or(other.explicitSet);
size = countBits(exceptionSet);
commonSupertype = null;
} | java |
public void clear() {
exceptionSet.clear();
explicitSet.clear();
universalHandler = false;
commonSupertype = null;
size = 0;
} | java |
public boolean containsCheckedExceptions() throws ClassNotFoundException {
for (ThrownExceptionIterator i = iterator(); i.hasNext();) {
ObjectType type = i.next();
if (!Hierarchy.isUncheckedException(type)) {
return true;
}
}
return false;
} | java |
public boolean containsExplicitExceptions() {
for (ThrownExceptionIterator i = iterator(); i.hasNext();) {
i.next();
if (i.isExplicit()) {
return true;
}
}
return false;
} | java |
public void fileReused(File f) {
if (!recentFiles.contains(f)) {
throw new IllegalStateException("Selected a recent project that doesn't exist?");
} else {
recentFiles.remove(f);
recentFiles.add(f);
}
} | java |
public void fileNotFound(File f) {
if (!recentFiles.contains(f)) {
throw new IllegalStateException("Well no wonder it wasn't found, its not in the list.");
} else {
recentFiles.remove(f);
}
} | java |
@Override
public int compareTo(Edge other) {
int cmp = super.compareTo(other);
if (cmp != 0) {
return cmp;
}
return type - other.type;
} | java |
public String formatAsString(boolean reverse) {
BasicBlock source = getSource();
BasicBlock target = getTarget();
StringBuilder buf = new StringBuilder();
buf.append(reverse ? "REVERSE_EDGE(" : "EDGE(");
buf.append(getLabel());
buf.append(") type ");
buf.append(edgeTypeToString(type));
buf.append(" from block ");
buf.append(reverse ? target.getLabel() : source.getLabel());
buf.append(" to block ");
buf.append(reverse ? source.getLabel() : target.getLabel());
InstructionHandle sourceInstruction = source.getLastInstruction();
InstructionHandle targetInstruction = target.getFirstInstruction();
String exInfo = " -> ";
if (targetInstruction == null && target.isExceptionThrower()) {
targetInstruction = target.getExceptionThrower();
exInfo = " => ";
}
if (sourceInstruction != null && targetInstruction != null) {
buf.append(" [bytecode ");
buf.append(sourceInstruction.getPosition());
buf.append(exInfo);
buf.append(targetInstruction.getPosition());
buf.append(']');
} else if (source.isExceptionThrower()) {
if (type == FALL_THROUGH_EDGE) {
buf.append(" [successful check]");
} else {
buf.append(" [failed check for ");
buf.append(source.getExceptionThrower().getPosition());
if (targetInstruction != null) {
buf.append(" to ");
buf.append(targetInstruction.getPosition());
}
buf.append(']');
}
}
return buf.toString();
} | java |
public static @Type
int stringToEdgeType(String s) {
s = s.toUpperCase(Locale.ENGLISH);
if ("FALL_THROUGH".equals(s)) {
return FALL_THROUGH_EDGE;
} else if ("IFCMP".equals(s)) {
return IFCMP_EDGE;
} else if ("SWITCH".equals(s)) {
return SWITCH_EDGE;
} else if ("SWITCH_DEFAULT".equals(s)) {
return SWITCH_DEFAULT_EDGE;
} else if ("JSR".equals(s)) {
return JSR_EDGE;
} else if ("RET".equals(s)) {
return RET_EDGE;
} else if ("GOTO".equals(s)) {
return GOTO_EDGE;
} else if ("RETURN".equals(s)) {
return RETURN_EDGE;
} else if ("UNHANDLED_EXCEPTION".equals(s)) {
return UNHANDLED_EXCEPTION_EDGE;
} else if ("HANDLED_EXCEPTION".equals(s)) {
return HANDLED_EXCEPTION_EDGE;
} else if ("START".equals(s)) {
return START_EDGE;
} else if ("BACKEDGE_TARGET_EDGE".equals(s)) {
return BACKEDGE_TARGET_EDGE;
} else if ("BACKEDGE_SOURCE_EDGE".equals(s)) {
return BACKEDGE_SOURCE_EDGE;
} else if ("EXIT_EDGE".equals(s)) {
return EXIT_EDGE;
} else {
throw new IllegalArgumentException("Unknown edge type: " + s);
}
} | java |
public boolean isSameOrNewerThan(JavaVersion other) {
return this.major > other.major || (this.major == other.major && this.minor >= other.minor);
} | java |
public @CheckForNull
TypeQualifierAnnotation getEffectiveTypeQualifierAnnotation() {
boolean firstPartialResult = true;
TypeQualifierAnnotation effective = null;
for (PartialResult partialResult : partialResultList) {
if (firstPartialResult) {
effective = partialResult.getTypeQualifierAnnotation();
firstPartialResult = false;
} else {
effective = combine(effective, partialResult.getTypeQualifierAnnotation());
}
}
return effective;
} | java |
protected void clearCaches() {
DescriptorFactory.clearInstance();
ObjectTypeFactory.clearInstance();
TypeQualifierApplications.clearInstance();
TypeQualifierAnnotation.clearInstance();
TypeQualifierValue.clearInstance();
// Make sure the codebases on the classpath are closed
AnalysisContext.removeCurrentAnalysisContext();
Global.removeAnalysisCacheForCurrentThread();
IO.close(classPath);
} | java |
public static void registerBuiltInAnalysisEngines(IAnalysisCache analysisCache) {
new edu.umd.cs.findbugs.classfile.engine.EngineRegistrar().registerAnalysisEngines(analysisCache);
new edu.umd.cs.findbugs.classfile.engine.asm.EngineRegistrar().registerAnalysisEngines(analysisCache);
new edu.umd.cs.findbugs.classfile.engine.bcel.EngineRegistrar().registerAnalysisEngines(analysisCache);
} | java |
public static void registerPluginAnalysisEngines(DetectorFactoryCollection detectorFactoryCollection,
IAnalysisCache analysisCache) throws IOException {
for (Iterator<Plugin> i = detectorFactoryCollection.pluginIterator(); i.hasNext();) {
Plugin plugin = i.next();
Class<? extends IAnalysisEngineRegistrar> engineRegistrarClass = plugin.getEngineRegistrarClass();
if (engineRegistrarClass != null) {
try {
IAnalysisEngineRegistrar engineRegistrar = engineRegistrarClass.newInstance();
engineRegistrar.registerAnalysisEngines(analysisCache);
} catch (InstantiationException e) {
IOException ioe = new IOException("Could not create analysis engine registrar for plugin "
+ plugin.getPluginId());
ioe.initCause(e);
throw ioe;
} catch (IllegalAccessException e) {
IOException ioe = new IOException("Could not create analysis engine registrar for plugin "
+ plugin.getPluginId());
ioe.initCause(e);
throw ioe;
}
}
}
} | java |
private void buildClassPath() throws InterruptedException, IOException, CheckedAnalysisException {
IClassPathBuilder builder = classFactory.createClassPathBuilder(bugReporter);
{
HashSet<String> seen = new HashSet<>();
for (String path : project.getFileArray()) {
if (seen.add(path)) {
builder.addCodeBase(classFactory.createFilesystemCodeBaseLocator(path), true);
}
}
for (String path : project.getAuxClasspathEntryList()) {
if (seen.add(path)) {
builder.addCodeBase(classFactory.createFilesystemCodeBaseLocator(path), false);
}
}
}
builder.scanNestedArchives(analysisOptions.scanNestedArchives);
builder.build(classPath, progressReporter);
appClassList = builder.getAppClassList();
if (PROGRESS) {
System.out.println(appClassList.size() + " classes scanned");
}
// If any of the application codebases contain source code,
// add them to the source path.
// Also, use the last modified time of application codebases
// to set the project timestamp.
List<String> pathNames = new ArrayList<>();
for (Iterator<? extends ICodeBase> i = classPath.appCodeBaseIterator(); i.hasNext();) {
ICodeBase appCodeBase = i.next();
if (appCodeBase.containsSourceFiles()) {
String pathName = appCodeBase.getPathName();
if (pathName != null) {
pathNames.add(pathName);
}
}
project.addTimestamp(appCodeBase.getLastModifiedTime());
}
project.addSourceDirs(pathNames);
} | java |
private void configureAnalysisFeatures() {
for (AnalysisFeatureSetting setting : analysisOptions.analysisFeatureSettingList) {
setting.configure(AnalysisContext.currentAnalysisContext());
}
AnalysisContext.currentAnalysisContext().setBoolProperty(AnalysisFeatures.MERGE_SIMILAR_WARNINGS,
analysisOptions.mergeSimilarWarnings);
} | java |
private void createExecutionPlan() throws OrderingConstraintException {
executionPlan = new ExecutionPlan();
// Use user preferences to decide which detectors are enabled.
DetectorFactoryChooser detectorFactoryChooser = new DetectorFactoryChooser() {
HashSet<DetectorFactory> forcedEnabled = new HashSet<>();
@Override
public boolean choose(DetectorFactory factory) {
boolean result = FindBugs.isDetectorEnabled(FindBugs2.this, factory, rankThreshold) || forcedEnabled.contains(factory);
if (ExecutionPlan.DEBUG) {
System.out.printf(" %6s %s %n", result, factory.getShortName());
}
return result;
}
@Override
public void enable(DetectorFactory factory) {
forcedEnabled.add(factory);
factory.setEnabledButNonReporting(true);
}
};
executionPlan.setDetectorFactoryChooser(detectorFactoryChooser);
if (ExecutionPlan.DEBUG) {
System.out.println("rank threshold is " + rankThreshold);
}
// Add plugins
for (Iterator<Plugin> i = detectorFactoryCollection.pluginIterator(); i.hasNext();) {
Plugin plugin = i.next();
if (DEBUG) {
System.out.println("Adding plugin " + plugin.getPluginId() + " to execution plan");
}
executionPlan.addPlugin(plugin);
}
// Build the execution plan
executionPlan.build();
// Stash the ExecutionPlan in the AnalysisCache.
Global.getAnalysisCache().eagerlyPutDatabase(ExecutionPlan.class, executionPlan);
if (PROGRESS) {
System.out.println(executionPlan.getNumPasses() + " passes in execution plan");
}
} | java |
private void logRecoverableException(ClassDescriptor classDescriptor, Detector2 detector, Throwable e) {
bugReporter.logError(
"Exception analyzing " + classDescriptor.toDottedClassName() + " using detector "
+ detector.getDetectorClassName(), e);
} | java |
public static <E> Set<E> newSetFromMap(Map<E, Boolean> m) {
return new SetFromMap<>(m);
} | java |
protected VertexType getNextSearchTreeRoot() {
// FIXME: slow linear search, should improve
for (Iterator<VertexType> i = graph.vertexIterator(); i.hasNext();) {
VertexType vertex = i.next();
if (visitMe(vertex)) {
return vertex;
}
}
return null;
} | java |
private void classifyUnknownEdges() {
Iterator<EdgeType> edgeIter = graph.edgeIterator();
while (edgeIter.hasNext()) {
EdgeType edge = edgeIter.next();
int dfsEdgeType = getDFSEdgeType(edge);
if (dfsEdgeType == UNKNOWN_EDGE) {
int srcDiscoveryTime = getDiscoveryTime(getSource(edge));
int destDiscoveryTime = getDiscoveryTime(getTarget(edge));
if (srcDiscoveryTime < destDiscoveryTime) {
// If the source was visited earlier than the
// target, it's a forward edge.
dfsEdgeType = FORWARD_EDGE;
} else {
// If the source was visited later than the
// target, it's a cross edge.
dfsEdgeType = CROSS_EDGE;
}
setDFSEdgeType(edge, dfsEdgeType);
}
}
} | java |
protected void consumeStack(Instruction ins) {
ConstantPoolGen cpg = getCPG();
TypeFrame frame = getFrame();
int numWordsConsumed = ins.consumeStack(cpg);
if (numWordsConsumed == Const.UNPREDICTABLE) {
throw new InvalidBytecodeException("Unpredictable stack consumption for " + ins);
}
if (numWordsConsumed > frame.getStackDepth()) {
throw new InvalidBytecodeException("Stack underflow for " + ins + ", " + numWordsConsumed + " needed, " + frame.getStackDepth() + " avail, frame is " + frame);
}
try {
while (numWordsConsumed-- > 0) {
frame.popValue();
}
} catch (DataflowAnalysisException e) {
throw new InvalidBytecodeException("Stack underflow for " + ins + ": " + e.getMessage());
}
} | java |
protected void pushReturnType(InvokeInstruction ins) {
ConstantPoolGen cpg = getCPG();
Type type = ins.getType(cpg);
if (type.getType() != Const.T_VOID) {
pushValue(type);
}
} | java |
@Override
public void modelNormalInstruction(Instruction ins, int numWordsConsumed, int numWordsProduced) {
if (VERIFY_INTEGRITY) {
if (numWordsProduced > 0) {
throw new InvalidBytecodeException("missing visitor method for " + ins);
}
}
super.modelNormalInstruction(ins, numWordsConsumed, numWordsProduced);
} | java |
private Iterator<Edge> logicalPredecessorEdgeIterator(BasicBlock block) {
return isForwards ? cfg.incomingEdgeIterator(block) : cfg.outgoingEdgeIterator(block);
} | java |
private int stackEntryThatMustBeNonnegative(int seen) {
switch (seen) {
case Const.INVOKEINTERFACE:
if ("java/util/List".equals(getClassConstantOperand())) {
return getStackEntryOfListCallThatMustBeNonnegative();
}
break;
case Const.INVOKEVIRTUAL:
if ("java/util/LinkedList".equals(getClassConstantOperand())
|| "java/util/ArrayList".equals(getClassConstantOperand())) {
return getStackEntryOfListCallThatMustBeNonnegative();
}
break;
case Const.IALOAD:
case Const.AALOAD:
case Const.SALOAD:
case Const.CALOAD:
case Const.BALOAD:
case Const.LALOAD:
case Const.DALOAD:
case Const.FALOAD:
return 0;
case Const.IASTORE:
case Const.AASTORE:
case Const.SASTORE:
case Const.CASTORE:
case Const.BASTORE:
case Const.LASTORE:
case Const.DASTORE:
case Const.FASTORE:
return 1;
}
return -1;
} | java |
private void flush() {
if (pendingAbsoluteValueBug != null) {
absoluteValueAccumulator.accumulateBug(pendingAbsoluteValueBug, pendingAbsoluteValueBugSourceLine);
pendingAbsoluteValueBug = null;
pendingAbsoluteValueBugSourceLine = null;
}
accumulator.reportAccumulatedBugs();
if (sawLoadOfMinValue) {
absoluteValueAccumulator.clearBugs();
} else {
absoluteValueAccumulator.reportAccumulatedBugs();
}
if (gcInvocationBugReport != null && !sawCurrentTimeMillis) {
// Make sure the GC invocation is not in an exception handler
// for OutOfMemoryError.
boolean outOfMemoryHandler = false;
for (CodeException handler : exceptionTable) {
if (gcInvocationPC < handler.getHandlerPC() || gcInvocationPC > handler.getHandlerPC() + OOM_CATCH_LEN) {
continue;
}
int catchTypeIndex = handler.getCatchType();
if (catchTypeIndex > 0) {
ConstantPool cp = getThisClass().getConstantPool();
Constant constant = cp.getConstant(catchTypeIndex);
if (constant instanceof ConstantClass) {
String exClassName = (String) ((ConstantClass) constant).getConstantValue(cp);
if ("java/lang/OutOfMemoryError".equals(exClassName)) {
outOfMemoryHandler = true;
break;
}
}
}
}
if (!outOfMemoryHandler) {
bugReporter.reportBug(gcInvocationBugReport);
}
}
sawCurrentTimeMillis = false;
gcInvocationBugReport = null;
exceptionTable = null;
} | java |
public boolean isNullCheck() {
// Null check blocks must be exception throwers,
// and are always empty. (The only kind of non-empty
// exception throwing block is one terminated by an ATHROW).
if (!isExceptionThrower() || getFirstInstruction() != null) {
return false;
}
short opcode = exceptionThrower.getInstruction().getOpcode();
return nullCheckInstructionSet.get(opcode);
} | java |
public @CheckForNull
InstructionHandle getSuccessorOf(InstructionHandle handle) {
if (VERIFY_INTEGRITY && !containsInstruction(handle)) {
throw new IllegalStateException();
}
return handle == lastInstruction ? null : handle.getNext();
} | java |
public InstructionHandle getPredecessorOf(InstructionHandle handle) {
if (VERIFY_INTEGRITY && !containsInstruction(handle)) {
throw new IllegalStateException();
}
return handle == firstInstruction ? null : handle.getPrev();
} | java |
public void addInstruction(InstructionHandle handle) {
if (firstInstruction == null) {
firstInstruction = lastInstruction = handle;
} else {
if (VERIFY_INTEGRITY && handle != lastInstruction.getNext()) {
throw new IllegalStateException("Adding non-consecutive instruction");
}
lastInstruction = handle;
}
} | java |
public boolean containsInstruction(InstructionHandle handle) {
Iterator<InstructionHandle> i = instructionIterator();
while (i.hasNext()) {
if (i.next() == handle) {
return true;
}
}
return false;
} | java |
public boolean containsInstructionWithOffset(int offset) {
Iterator<InstructionHandle> i = instructionIterator();
while (i.hasNext()) {
if (i.next().getPosition() == offset) {
return true;
}
}
return false;
} | java |
public static void writeFile(IFile file, final FileOutput output, IProgressMonitor monitor) throws CoreException {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
output.writeFile(bos);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
if (!file.exists()) {
mkdirs(file, monitor);
file.create(bis, true, monitor);
} else {
file.setContents(bis, true, false, monitor);
}
} catch (IOException e) {
IStatus status = FindbugsPlugin.createErrorStatus("Exception while " + output.getTaskDescription(), e);
throw new CoreException(status);
}
} | java |
public static void writeFile(final File file, final FileOutput output, final IProgressMonitor monitor) throws CoreException {
try (FileOutputStream fout = new FileOutputStream(file);
BufferedOutputStream bout = new BufferedOutputStream(fout)) {
if (monitor != null) {
monitor.subTask("writing data to " + file.getName());
}
output.writeFile(bout);
bout.flush();
} catch (IOException e) {
IStatus status = FindbugsPlugin.createErrorStatus("Exception while " + output.getTaskDescription(), e);
throw new CoreException(status);
}
} | java |
public static void createMarkers(final IJavaProject javaProject, final SortedBugCollection theCollection, final ISchedulingRule rule, IProgressMonitor monitor) {
if (monitor.isCanceled()) {
return;
}
final List<MarkerParameter> bugParameters = createBugParameters(javaProject, theCollection, monitor);
if (monitor.isCanceled()) {
return;
}
WorkspaceJob wsJob = new WorkspaceJob("Creating SpotBugs markers") {
@Override
public IStatus runInWorkspace(IProgressMonitor monitor1) throws CoreException {
IProject project = javaProject.getProject();
try {
new MarkerReporter(bugParameters, theCollection, project).run(monitor1);
} catch (CoreException e) {
FindbugsPlugin.getDefault().logException(e, "Core exception on add marker");
return e.getStatus();
}
return monitor1.isCanceled()? Status.CANCEL_STATUS : Status.OK_STATUS;
}
};
wsJob.setRule(rule);
wsJob.setSystem(true);
wsJob.setUser(false);
wsJob.schedule();
} | java |
public static List<MarkerParameter> createBugParameters(IJavaProject project, BugCollection theCollection,
IProgressMonitor monitor) {
List<MarkerParameter> bugParameters = new ArrayList<>();
if (project == null) {
FindbugsPlugin.getDefault().logException(new NullPointerException("project is null"), "project is null");
return bugParameters;
}
Iterator<BugInstance> iterator = theCollection.iterator();
while (iterator.hasNext() && !monitor.isCanceled()) {
BugInstance bug = iterator.next();
DetectorFactory detectorFactory = bug.getDetectorFactory();
if(detectorFactory != null && !detectorFactory.getPlugin().isGloballyEnabled()){
continue;
}
MarkerParameter mp = createMarkerParameter(project, bug);
if (mp != null) {
bugParameters.add(mp);
}
}
return bugParameters;
} | java |
public static void removeMarkers(IResource res) throws CoreException {
// remove any markers added by our builder
// This triggers resource update on IResourceChangeListener's
// (BugTreeView)
res.deleteMarkers(FindBugsMarker.NAME, true, IResource.DEPTH_INFINITE);
if (res instanceof IProject) {
IProject project = (IProject) res;
FindbugsPlugin.clearBugCollection(project);
}
} | java |
public static void redisplayMarkers(final IJavaProject javaProject) {
final IProject project = javaProject.getProject();
FindBugsJob job = new FindBugsJob("Refreshing SpotBugs markers", project) {
@Override
protected void runWithProgress(IProgressMonitor monitor) throws CoreException {
// TODO in case we removed some of previously available
// detectors, we should
// throw away bugs reported by them
// Get the saved bug collection for the project
SortedBugCollection bugs = FindbugsPlugin.getBugCollection(project, monitor);
// Remove old markers
project.deleteMarkers(FindBugsMarker.NAME, true, IResource.DEPTH_INFINITE);
// Display warnings
createMarkers(javaProject, bugs, project, monitor);
}
};
job.setRule(project);
job.scheduleInteractive();
} | java |
public static @CheckForNull
BugInstance findBugInstanceForMarker(IMarker marker) {
BugCollectionAndInstance bci = findBugCollectionAndInstanceForMarker(marker);
if (bci == null) {
return null;
}
return bci.bugInstance;
} | java |
public static @CheckForNull
BugCollectionAndInstance findBugCollectionAndInstanceForMarker(IMarker marker) {
IResource resource = marker.getResource();
IProject project = resource.getProject();
if (project == null) {
// Also shouldn't happen.
FindbugsPlugin.getDefault().logError("No project for warning marker");
return null;
}
if (!isFindBugsMarker(marker)) {
// log disabled because otherwise each selection in problems view
// generates
// 6 new errors (we need refactor all bug views to get rid of this).
// FindbugsPlugin.getDefault().logError("Selected marker is not a FindBugs marker");
// FindbugsPlugin.getDefault().logError(marker.getType());
// FindbugsPlugin.getDefault().logError(FindBugsMarker.NAME);
return null;
}
// We have a FindBugs marker. Get the corresponding BugInstance.
String bugId = marker.getAttribute(FindBugsMarker.UNIQUE_ID, null);
if (bugId == null) {
FindbugsPlugin.getDefault().logError("Marker does not contain unique id for warning");
return null;
}
try {
BugCollection bugCollection = FindbugsPlugin.getBugCollection(project, null);
if (bugCollection == null) {
FindbugsPlugin.getDefault().logError("Could not get BugCollection for SpotBugs marker");
return null;
}
String bugType = (String) marker.getAttribute(FindBugsMarker.BUG_TYPE);
Integer primaryLineNumber = (Integer) marker.getAttribute(FindBugsMarker.PRIMARY_LINE);
// compatibility
if (primaryLineNumber == null) {
primaryLineNumber = Integer.valueOf(getEditorLine(marker));
}
if (bugType == null) {
FindbugsPlugin.getDefault().logError(
"Could not get find attributes for marker " + marker + ": (" + bugId + ", " + primaryLineNumber + ")");
return null;
}
BugInstance bug = bugCollection.findBug(bugId, bugType, primaryLineNumber.intValue());
if(bug == null) {
FindbugsPlugin.getDefault().logError(
"Could not get find bug for marker on " + resource + ": (" + bugId + ", " + primaryLineNumber + ")");
return null;
}
return new BugCollectionAndInstance(bugCollection, bug);
} catch (CoreException e) {
FindbugsPlugin.getDefault().logException(e, "Could not get BugInstance for SpotBugs marker");
return null;
}
} | java |
public static Set<IMarker> getMarkerFromSelection(ISelection selection) {
Set<IMarker> markers = new HashSet<>();
if (!(selection instanceof IStructuredSelection)) {
return markers;
}
IStructuredSelection sSelection = (IStructuredSelection) selection;
for (Iterator<?> iter = sSelection.iterator(); iter.hasNext();) {
Object next = iter.next();
markers.addAll(getMarkers(next));
}
return markers;
} | java |
public static IMarker getMarkerFromEditor(ITextSelection selection, IEditorPart editor) {
IResource resource = (IResource) editor.getEditorInput().getAdapter(IFile.class);
IMarker[] allMarkers;
if (resource != null) {
allMarkers = getMarkers(resource, IResource.DEPTH_ZERO);
} else {
IClassFile classFile = (IClassFile) editor.getEditorInput().getAdapter(IClassFile.class);
if (classFile == null) {
return null;
}
Set<IMarker> markers = getMarkers(classFile.getType());
allMarkers = markers.toArray(new IMarker[markers.size()]);
}
// if editor contains only one FB marker, do some cheating and always
// return it.
if (allMarkers.length == 1) {
return allMarkers[0];
}
// +1 because it counts real lines, but editor shows lines + 1
int startLine = selection.getStartLine() + 1;
for (IMarker marker : allMarkers) {
int line = getEditorLine(marker);
if (startLine == line) {
return marker;
}
}
return null;
} | java |
@Nonnull
public static IMarker[] getMarkers(IResource fileOrFolder, int depth) {
if(fileOrFolder.getType() == IResource.PROJECT) {
if(!fileOrFolder.isAccessible()) {
// user just closed the project decorator is working on, avoid exception here
return EMPTY;
}
}
try {
return fileOrFolder.findMarkers(FindBugsMarker.NAME, true, depth);
} catch (CoreException e) {
FindbugsPlugin.getDefault().logException(e, "Cannot collect SpotBugs warnings from: " + fileOrFolder);
}
return EMPTY;
} | java |
private void syncMenu() {
if (bugInstance != null) {
BugProperty severityProperty = bugInstance.lookupProperty(BugProperty.SEVERITY);
if (severityProperty != null) {
try {
int severity = severityProperty.getValueAsInt();
if (severity > 0 && severity <= severityItemList.length) {
selectSeverity(severity);
return;
}
} catch (NumberFormatException e) {
// Ignore: we'll allow the user to select a valid severity
}
}
// We didn't get a valid severity from the BugInstance.
// So, leave the menu items enabled but cleared, so
// the user can select a severity.
resetMenuItems(true);
} else {
// No BugInstance - disable all menu items.
resetMenuItems(false);
}
} | java |
private void selectSeverity(int severity) {
// Severity is 1-based, but the menu item list is 0-based
int index = severity - 1;
for (int i = 0; i < severityItemList.length; ++i) {
MenuItem menuItem = severityItemList[i];
menuItem.setEnabled(true);
menuItem.setSelection(i == index);
}
} | java |
private void resetMenuItems(boolean enable) {
for (int i = 0; i < severityItemList.length; ++i) {
MenuItem menuItem = severityItemList[i];
menuItem.setEnabled(enable);
menuItem.setSelection(false);
}
} | java |
public ValueNumber[] lookupOutputValues(Entry entry) {
if (DEBUG) {
System.out.println("VN cache lookup: " + entry);
}
ValueNumber[] result = entryToOutputMap.get(entry);
if (DEBUG) {
System.out.println(" result ==> " + Arrays.toString(result));
}
return result;
} | java |
public Binding lookup(String varName) {
if (varName.equals(binding.getVarName())) {
return binding;
}
return parent != null ? parent.lookup(varName) : null;
} | java |
private IsNullValueFrame replaceValues(IsNullValueFrame origFrame, IsNullValueFrame frame, ValueNumber replaceMe,
ValueNumberFrame prevVnaFrame, ValueNumberFrame targetVnaFrame, IsNullValue replacementValue) {
if (!targetVnaFrame.isValid()) {
throw new IllegalArgumentException("Invalid frame in " + methodGen.getClassName() + "." + methodGen.getName() + " : "
+ methodGen.getSignature());
}
// If required, make a copy of the frame
frame = modifyFrame(origFrame, frame);
assert frame.getNumSlots() == targetVnaFrame.getNumSlots() : " frame has " + frame.getNumSlots() + ", target has "
+ targetVnaFrame.getNumSlots() + " in " + classAndMethod;
// The VNA frame may have more slots than the IsNullValueFrame
// if it was produced by an IF comparison (whose operand or operands
// are subsequently popped off the stack).
final int targetNumSlots = targetVnaFrame.getNumSlots();
final int prefixNumSlots = Math.min(frame.getNumSlots(), prevVnaFrame.getNumSlots());
if (trackValueNumbers) {
AvailableLoad loadForV = prevVnaFrame.getLoad(replaceMe);
if (DEBUG && loadForV != null) {
System.out.println("For " + replaceMe + " availableLoad is " + loadForV);
ValueNumber[] matchingValueNumbers = targetVnaFrame.getAvailableLoad(loadForV);
if (matchingValueNumbers != null) {
for (ValueNumber v2 : matchingValueNumbers) {
System.out.println(" matches " + v2);
}
}
}
if (loadForV != null) {
ValueNumber[] matchingValueNumbers = targetVnaFrame.getAvailableLoad(loadForV);
if (matchingValueNumbers != null) {
for (ValueNumber v2 : matchingValueNumbers) {
if (!replaceMe.equals(v2)) {
frame.setKnownValue(v2, replacementValue);
if (DEBUG) {
System.out.println("For " + loadForV + " switch from " + replaceMe + " to " + v2);
}
}
}
}
}
frame.setKnownValue(replaceMe, replacementValue);
}
// Here's the deal:
// - "replaceMe" is the value number from the previous frame (at the if
// branch)
// which indicates a value that we have updated is-null information
// about
// - in the target value number frame (at entry to the target block),
// we find the value number in the stack slot corresponding to the
// "replaceMe"
// value; this is the "corresponding" value
// - all instances of the "corresponding" value in the target frame have
// their is-null information updated to "replacementValue"
// This should thoroughly make use of the updated information.
for (int i = 0; i < prefixNumSlots; ++i) {
if (prevVnaFrame.getValue(i).equals(replaceMe)) {
ValueNumber corresponding = targetVnaFrame.getValue(i);
for (int j = 0; j < targetNumSlots; ++j) {
if (targetVnaFrame.getValue(j).equals(corresponding)) {
frame.setValue(j, replacementValue);
}
}
}
}
return frame;
} | java |
protected void obtainFindBugsMarkers() {
// Delete old markers
markers.clear();
if (editor == null || ruler == null) {
return;
}
// Obtain all markers in the editor
IResource resource = (IResource) editor.getEditorInput().getAdapter(IFile.class);
if(resource == null){
return;
}
IMarker[] allMarkers = MarkerUtil.getMarkers(resource, IResource.DEPTH_ZERO);
if(allMarkers.length == 0) {
return;
}
// Discover relevant markers, i.e. FindBugsMarkers
AbstractMarkerAnnotationModel model = getModel();
IDocument document = getDocument();
for (int i = 0; i < allMarkers.length; i++) {
if (includesRulerLine(model.getMarkerPosition(allMarkers[i]), document)) {
if (MarkerUtil.isFindBugsMarker(allMarkers[i])) {
markers.add(allMarkers[i]);
}
}
}
} | java |
protected boolean includesRulerLine(Position position, IDocument document) {
if (position != null && ruler != null) {
try {
int markerLine = document.getLineOfOffset(position.getOffset());
int line = ruler.getLineOfLastMouseButtonActivity();
if (line == markerLine) {
return true;
}
} catch (BadLocationException x) {
FindbugsPlugin.getDefault().logException(x, "Error getting marker line");
}
}
return false;
} | java |
@CheckForNull
protected AbstractMarkerAnnotationModel getModel() {
if(editor == null) {
return null;
}
IDocumentProvider provider = editor.getDocumentProvider();
IAnnotationModel model = provider.getAnnotationModel(editor.getEditorInput());
if (model instanceof AbstractMarkerAnnotationModel) {
return (AbstractMarkerAnnotationModel) model;
}
return null;
} | java |
protected IDocument getDocument() {
Assert.isNotNull(editor);
IDocumentProvider provider = editor.getDocumentProvider();
return provider.getDocument(editor.getEditorInput());
} | java |
public void setProjectChanged(boolean b) {
if (curProject == null) {
return;
}
if (projectChanged == b) {
return;
}
projectChanged = b;
mainFrameMenu.setSaveMenu(this);
getRootPane().putClientProperty(WINDOW_MODIFIED, b);
} | java |
void callOnClose() {
if (projectChanged && !SystemProperties.getBoolean("findbugs.skipSaveChangesWarning")) {
Object[] options = {
L10N.getLocalString("dlg.save_btn", "Save"),
L10N.getLocalString("dlg.dontsave_btn", "Don't Save"),
L10N.getLocalString("dlg.cancel_btn", "Cancel"),
};
int value = JOptionPane.showOptionDialog(this, getActionWithoutSavingMsg("closing"),
L10N.getLocalString("msg.confirm_save_txt", "Do you want to save?"),
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (value == 2 || value == JOptionPane.CLOSED_OPTION) {
return;
} else if (value == 0) {
if (saveFile == null) {
if (!mainFrameLoadSaveHelper.saveAs()) {
return;
}
} else {
mainFrameLoadSaveHelper.save();
}
}
}
GUISaveState guiSaveState = GUISaveState.getInstance();
guiLayout.saveState();
guiSaveState.setFrameBounds(getBounds());
guiSaveState.setExtendedWindowState(getExtendedState());
guiSaveState.save();
System.exit(0);
} | java |
public boolean openAnalysis(File f, SaveType saveType) {
if (!f.exists() || !f.canRead()) {
throw new IllegalArgumentException("Can't read " + f.getPath());
}
mainFrameLoadSaveHelper.prepareForFileLoad(f, saveType);
mainFrameLoadSaveHelper.loadAnalysis(f);
return true;
} | java |
public void updateTitle() {
Project project = getProject();
String name = project.getProjectName();
if ((name == null || "".equals(name.trim())) && saveFile != null) {
name = saveFile.getAbsolutePath();
}
if (name == null) {
name = "";//Project.UNNAMED_PROJECT;
}
String oldTitle = this.getTitle();
String newTitle = TITLE_START_TXT + ("".equals(name.trim()) ? "" : " - " + name);
if (oldTitle.equals(newTitle)) {
return;
}
this.setTitle(newTitle);
} | java |
public void loadProject(String arg) throws IOException {
Project newProject = Project.readProject(arg);
newProject.setConfiguration(project.getConfiguration());
project = newProject;
projectLoadedFromFile = true;
} | java |
public void execute() {
Iterator<?> elementIter = XMLUtil.selectNodes(document, "/BugCollection/BugInstance").iterator();
Iterator<BugInstance> bugInstanceIter = bugCollection.iterator();
Set<String> bugTypeSet = new HashSet<>();
Set<String> bugCategorySet = new HashSet<>();
Set<String> bugCodeSet = new HashSet<>();
// Add short and long descriptions to BugInstance elements.
// We rely on the Document and the BugCollection storing
// the bug instances in the same order.
while (elementIter.hasNext() && bugInstanceIter.hasNext()) {
Element element = (Element) elementIter.next();
BugInstance bugInstance = bugInstanceIter.next();
String bugType = bugInstance.getType();
bugTypeSet.add(bugType);
BugPattern bugPattern = bugInstance.getBugPattern();
bugCategorySet.add(bugPattern.getCategory());
bugCodeSet.add(bugPattern.getAbbrev());
element.addElement("ShortMessage").addText(bugPattern.getShortDescription());
element.addElement("LongMessage").addText(bugInstance.getMessage());
// Add pre-formatted display strings in "Message"
// elements for all bug annotations.
Iterator<?> annElementIter = element.elements().iterator();
Iterator<BugAnnotation> annIter = bugInstance.annotationIterator();
while (annElementIter.hasNext() && annIter.hasNext()) {
Element annElement = (Element) annElementIter.next();
BugAnnotation ann = annIter.next();
annElement.addElement("Message").addText(ann.toString());
}
}
// Add BugPattern elements for each referenced bug types.
addBugCategories(bugCategorySet);
addBugPatterns(bugTypeSet);
addBugCodes(bugCodeSet);
} | java |
private void addBugCategories(Set<String> bugCategorySet) {
Element root = document.getRootElement();
for (String category : bugCategorySet) {
Element element = root.addElement("BugCategory");
element.addAttribute("category", category);
Element description = element.addElement("Description");
description.setText(I18N.instance().getBugCategoryDescription(category));
BugCategory bc = DetectorFactoryCollection.instance().getBugCategory(category);
if (bc != null) { // shouldn't be null
String s = bc.getAbbrev();
if (s != null) {
Element abbrev = element.addElement("Abbreviation");
abbrev.setText(s);
}
s = bc.getDetailText();
if (s != null) {
Element details = element.addElement("Details");
details.setText(s);
}
}
}
} | java |
private void addBugCodes(Set<String> bugCodeSet) {
Element root = document.getRootElement();
for (String bugCode : bugCodeSet) {
Element element = root.addElement("BugCode");
element.addAttribute("abbrev", bugCode);
Element description = element.addElement("Description");
description.setText(I18N.instance().getBugTypeDescription(bugCode));
}
} | java |
public static Constant merge(Constant a, Constant b) {
if (!a.isConstant() || !b.isConstant()) {
return NOT_CONSTANT;
}
if (a.value.getClass() != b.value.getClass() || !a.value.equals(b.value)) {
return NOT_CONSTANT;
}
return a;
} | java |
private void createBugCategoriesGroup(Composite parent, final IProject project) {
Group checkBoxGroup = new Group(parent, SWT.SHADOW_ETCHED_OUT);
checkBoxGroup.setText(getMessage("property.categoriesGroup"));
checkBoxGroup.setLayout(new GridLayout(1, true));
checkBoxGroup.setLayoutData(new GridData(SWT.BEGINNING, SWT.TOP, true, true));
List<String> bugCategoryList = new LinkedList<>(DetectorFactoryCollection.instance().getBugCategories());
chkEnableBugCategoryList = new LinkedList<>();
ProjectFilterSettings origFilterSettings = propertyPage.getOriginalUserPreferences().getFilterSettings();
for (String category : bugCategoryList) {
Button checkBox = new Button(checkBoxGroup, SWT.CHECK);
checkBox.setText(I18N.instance().getBugCategoryDescription(category));
checkBox.setSelection(origFilterSettings.containsCategory(category));
GridData layoutData = new GridData();
layoutData.horizontalIndent = 10;
checkBox.setLayoutData(layoutData);
// Every time a checkbox is clicked, rebuild the detector factory
// table
// to show only relevant entries
checkBox.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
syncSelectedCategories();
}
});
checkBox.setData(category);
chkEnableBugCategoryList.add(checkBox);
}
} | java |
protected void syncSelectedCategories() {
ProjectFilterSettings filterSettings = getCurrentProps().getFilterSettings();
for (Button checkBox : chkEnableBugCategoryList) {
String category = (String) checkBox.getData();
if (checkBox.getSelection()) {
filterSettings.addCategory(category);
} else {
filterSettings.removeCategory(category);
}
}
propertyPage.getVisibleDetectors().clear();
} | java |
@SlashedClassName
@SuppressFBWarnings("TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SINK")
public static String toSlashedClassName(@SlashedClassName(when = When.UNKNOWN) String className) {
if (className.indexOf('.') >= 0) {
return className.replace('.', '/');
}
return className;
} | java |
@DottedClassName
@SuppressFBWarnings("TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_NEVER_SINK")
public static String toDottedClassName(@SlashedClassName(when = When.UNKNOWN) String className) {
if (className.indexOf('/') >= 0) {
return className.replace('/', '.');
}
return className;
} | java |
public static boolean isAnonymous(String className) {
int i = className.lastIndexOf('$');
if (i >= 0 && ++i < className.length()) {
while(i < className.length()) {
if(!Character.isDigit(className.charAt(i))) {
return false;
}
i++;
}
return true;
}
return false;
} | java |
public static @SlashedClassName
String extractClassName(String originalName) {
String name = originalName;
if (name.charAt(0) != '[' && name.charAt(name.length() - 1) != ';') {
return name;
}
while (name.charAt(0) == '[') {
name = name.substring(1);
}
if (name.charAt(0) == 'L' && name.charAt(name.length() - 1) == ';') {
name = name.substring(1, name.length() - 1);
}
if (name.charAt(0) == '[') {
throw new IllegalArgumentException("Bad class name: " + originalName);
}
return name;
} | java |
public static @CheckForNull
TypeQualifierAnnotation combineReturnTypeAnnotations(TypeQualifierAnnotation a, TypeQualifierAnnotation b) {
return combineAnnotations(a, b, combineReturnValueMatrix);
} | java |
public final @DottedClassName
String getPackageName() {
int lastDot = className.lastIndexOf('.');
if (lastDot < 0) {
return "";
} else {
return className.substring(0, lastDot);
}
} | java |
protected static String removePackageName(String typeName) {
int index = typeName.lastIndexOf('.');
if (index >= 0) {
typeName = typeName.substring(index + 1);
}
return typeName;
} | java |
public void downgradeOnControlSplit() {
final int numSlots = getNumSlots();
for (int i = 0; i < numSlots; ++i) {
IsNullValue value = getValue(i);
value = value.downgradeOnControlSplit();
setValue(i, value);
}
if (knownValueMap != null) {
for (Map.Entry<ValueNumber, IsNullValue> entry : knownValueMap.entrySet()) {
entry.setValue(entry.getValue().downgradeOnControlSplit());
}
}
} | java |
public static void printCode(Method[] methods) {
for (Method m : methods) {
System.out.println(m);
Code code = m.getCode();
if (code != null) {
System.out.println(code);
}
}
} | java |
protected boolean isReferenceType(byte type) {
return type == Const.T_OBJECT || type == Const.T_ARRAY || type == T_NULL || type == T_EXCEPTION;
} | java |
protected ReferenceType mergeReferenceTypes(ReferenceType aRef, ReferenceType bRef) throws DataflowAnalysisException {
if (aRef.equals(bRef)) {
return aRef;
}
byte aType = aRef.getType();
byte bType = bRef.getType();
try {
// Special case: ExceptionObjectTypes.
// We want to preserve the ExceptionSets associated,
// in order to track the exact set of exceptions
if (isObjectType(aType) && isObjectType(bType)
&& ((aType == T_EXCEPTION || isThrowable(aRef)) && (bType == T_EXCEPTION || isThrowable(bRef)))) {
ExceptionSet union = exceptionSetFactory.createExceptionSet();
if (aType == Const.T_OBJECT && "Ljava/lang/Throwable;".equals(aRef.getSignature())) {
return aRef;
}
if (bType == Const.T_OBJECT && "Ljava/lang/Throwable;".equals(bRef.getSignature())) {
return bRef;
}
updateExceptionSet(union, (ObjectType) aRef);
updateExceptionSet(union, (ObjectType) bRef);
Type t = ExceptionObjectType.fromExceptionSet(union);
if (t instanceof ReferenceType) {
return (ReferenceType) t;
}
}
if (aRef instanceof GenericObjectType && bRef instanceof GenericObjectType
&& aRef.getSignature().equals(bRef.getSignature())) {
GenericObjectType aG = (GenericObjectType) aRef;
GenericObjectType bG = (GenericObjectType) bRef;
if (aG.getTypeCategory() == bG.getTypeCategory()) {
switch (aG.getTypeCategory()) {
case PARAMETERIZED:
List<? extends ReferenceType> aP = aG.getParameters();
List<? extends ReferenceType> bP = bG.getParameters();
assert aP != null;
assert bP != null;
if (aP.size() != bP.size()) {
break;
}
ArrayList<ReferenceType> result = new ArrayList<>(aP.size());
for (int i = 0; i < aP.size(); i++) {
result.add(mergeReferenceTypes(aP.get(i), bP.get(i)));
}
GenericObjectType rOT = GenericUtilities.getType(aG.getClassName(), result);
return rOT;
}
}
}
if (aRef instanceof GenericObjectType) {
aRef = ((GenericObjectType) aRef).getObjectType();
}
if (bRef instanceof GenericObjectType) {
bRef = ((GenericObjectType) bRef).getObjectType();
}
if (Subtypes2.ENABLE_SUBTYPES2_FOR_COMMON_SUPERCLASS_QUERIES) {
return AnalysisContext.currentAnalysisContext().getSubtypes2().getFirstCommonSuperclass(aRef, bRef);
} else {
return aRef.getFirstCommonSuperclass(bRef);
}
} catch (ClassNotFoundException e) {
lookupFailureCallback.reportMissingClass(e);
return Type.OBJECT;
}
} | java |
public void read() {
File prefFile = new File(SystemProperties.getProperty("user.home"), PREF_FILE_NAME);
if (!prefFile.exists() || !prefFile.isFile()) {
return;
}
try {
read(new FileInputStream(prefFile));
} catch (IOException e) {
// Ignore - just use default preferences
}
} | java |
public void write() {
try {
File prefFile = new File(SystemProperties.getProperty("user.home"), PREF_FILE_NAME);
write(new FileOutputStream(prefFile));
} catch (IOException e) {
if (FindBugs.DEBUG) {
e.printStackTrace(); // Ignore
}
}
} | java |
public void useProject(String projectName) {
removeProject(projectName);
recentProjectsList.addFirst(projectName);
while (recentProjectsList.size() > MAX_RECENT_FILES) {
recentProjectsList.removeLast();
}
} | java |
public void removeProject(String projectName) {
// It should only be in list once (usually in slot 0) but check entire
// list...
Iterator<String> it = recentProjectsList.iterator();
while (it.hasNext()) {
// LinkedList, so remove() via iterator is faster than
// remove(index).
if (projectName.equals(it.next())) {
it.remove();
}
}
} | java |
public void enableAllDetectors(boolean enable) {
detectorEnablementMap.clear();
Collection<Plugin> allPlugins = Plugin.getAllPlugins();
for (Plugin plugin : allPlugins) {
for (DetectorFactory factory : plugin.getDetectorFactories()) {
detectorEnablementMap.put(factory.getShortName(), enable);
}
}
} | java |
private static Map<String, Boolean> readProperties(Properties props, String keyPrefix) {
Map<String, Boolean> filters = new TreeMap<>();
int counter = 0;
boolean keyFound = true;
while (keyFound) {
String property = props.getProperty(keyPrefix + counter);
if (property != null) {
int pipePos = property.indexOf(BOOL_SEPARATOR);
if (pipePos >= 0) {
String name = property.substring(0, pipePos);
String enabled = property.substring(pipePos + 1);
filters.put(name, Boolean.valueOf(enabled));
} else {
filters.put(property, Boolean.TRUE);
}
counter++;
} else {
keyFound = false;
}
}
return filters;
} | java |
private static void writeProperties(Properties props, String keyPrefix, Map<String, Boolean> filters) {
int counter = 0;
Set<Entry<String, Boolean>> entrySet = filters.entrySet();
for (Entry<String, Boolean> entry : entrySet) {
props.setProperty(keyPrefix + counter, entry.getKey() + BOOL_SEPARATOR + entry.getValue());
counter++;
}
// remove obsolete keys from the properties file
boolean keyFound = true;
while (keyFound) {
String key = keyPrefix + counter;
String property = props.getProperty(key);
if (property == null) {
keyFound = false;
} else {
props.remove(key);
}
}
} | java |
public AnalysisFeatureSetting[] getAnalysisFeatureSettings() {
if (EFFORT_DEFAULT.equals(effort)) {
return FindBugs.DEFAULT_EFFORT;
} else if (EFFORT_MIN.equals(effort)) {
return FindBugs.MIN_EFFORT;
}
return FindBugs.MAX_EFFORT;
} | java |
public JavaClass parse() throws IOException {
JavaClass jclass = classParser.parse();
Repository.addClass(jclass);
return jclass;
} | java |
void setSourceBaseList(Iterable<String> sourceBaseList) {
for (String repos : sourceBaseList) {
if (repos.endsWith(".zip") || repos.endsWith(".jar") || repos.endsWith(".z0p.gz")) {
// Zip or jar archive
try {
if (repos.startsWith("http:") || repos.startsWith("https:") || repos.startsWith("file:")) {
String url = SystemProperties.rewriteURLAccordingToProperties(repos);
repositoryList.add(makeInMemorySourceRepository(url));
} else {
repositoryList.add(new ZipSourceRepository(new ZipFile(repos)));
}
} catch (IOException e) {
// Ignored - we won't use this archive
AnalysisContext.logError("Unable to load " + repos, e);
}
} else {
File dir = new File(repos);
if (dir.canRead() && dir.isDirectory()) {
repositoryList.add(new DirectorySourceRepository(repos));
} else {
AnalysisContext.logError("Unable to load " + repos);
}
}
}
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.