javax.annotation.meta.When Java Examples

The following examples show how to use javax.annotation.meta.When. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FlowValue.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Determine whether given backwards FlowValue conflicts with given source.
 *
 * @param backwardsFlowValue
 *            a backwards FlowValue
 * @param source
 *            SourceSinkInfo object representing a source reached by the
 *            backwards flow value
 * @param typeQualifierValue
 *            TypeQualifierValue being checked
 * @param isIdentity TODO
 * @return true if backwards value conflicts with source, false if not
 */
public static boolean backwardsValueConflictsWithSource(FlowValue backwardsFlowValue, SourceSinkInfo source,
        TypeQualifierValue typeQualifierValue, boolean isIdentity) {

    When sourceWhen = source.getWhen();


    if (typeQualifierValue.isStrictQualifier() && !isIdentity) {
        // strict checking
        return (backwardsFlowValue == ALWAYS && sourceWhen != When.ALWAYS)
                || (backwardsFlowValue == NEVER && sourceWhen != When.NEVER);
    } else {
        // NOT strict checking
        return (backwardsFlowValue == ALWAYS && (sourceWhen == When.NEVER || sourceWhen == When.MAYBE))
                || (backwardsFlowValue == NEVER && (sourceWhen == When.ALWAYS || sourceWhen == When.MAYBE));
    }
}
 
Example #2
Source File: TypeQualifierAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static TypeQualifierAnnotation combineAnnotations(TypeQualifierAnnotation a, TypeQualifierAnnotation b,
        When[][] mergeMatrix) {
    assert a.typeQualifier.equals(b.typeQualifier);

    When aWhen = a.when;
    When bWhen = b.when;
    if (aWhen.ordinal() < bWhen.ordinal()) {
        When tmp = aWhen;
        aWhen = bWhen;
        bWhen = tmp;
    }

    When combined = mergeMatrix[aWhen.ordinal()][bWhen.ordinal()];
    if (combined != null) {
        return getValue(a.typeQualifier, combined);
    } else {
        return null;
    }
}
 
Example #3
Source File: TypeQualifierValue.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public When validate(@CheckForNull Object constantValue) {
    if (validator == null) {
        throw new IllegalStateException("No validator");
    }
    IAnalysisCache analysisCache = Global.getAnalysisCache();
    Profiler profiler = analysisCache.getProfiler();
    profiler.start(validator.getClass());
    try {
        return ValidationSecurityManager.sandboxedValidation(proxy, validator, constantValue);
    } catch (Exception e) {
        AnalysisContext.logError("Error executing custom validator for " + typeQualifier + " " + constantValue, e);
        return When.UNKNOWN;
    } finally {
        profiler.end(validator.getClass());
    }
}
 
Example #4
Source File: BackwardTypeQualifierDataflowAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void modelFieldStore(Location location) throws DataflowAnalysisException {
    // Model field stores
    XField writtenField = XFactory.createXField((FieldInstruction) location.getHandle().getInstruction(), cpg);
    TypeQualifierAnnotation tqa = TypeQualifierApplications.getEffectiveTypeQualifierAnnotation(writtenField,
            typeQualifierValue);
    When when = (tqa != null) ? tqa.when : When.UNKNOWN;

    // The ValueNumberFrame *before* the FieldInstruction should
    // have the ValueNumber of the stored value on the top of the stack.
    ValueNumberFrame vnaFrameAtStore = vnaDataflow.getFactAtLocation(location);
    if (vnaFrameAtStore.isValid()) {
        ValueNumber vn = vnaFrameAtStore.getTopValue();
        SourceSinkInfo sink = new SourceSinkInfo(SourceSinkType.FIELD_STORE, location, vn, when);
        registerSourceSink(sink);
    }
}
 
Example #5
Source File: ForwardTypeQualifierDataflowAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void registerParameterSources() {
    ValueNumberFrame vnaFrameAtEntry = vnaDataflow.getStartFact(cfg.getEntry());

    SignatureParser sigParser = new SignatureParser(xmethod.getSignature());
    int firstParamSlot = xmethod.isStatic() ? 0 : 1;

    int param = 0;
    int slotOffset = 0;

    for (String paramSig : sigParser.parameterSignatures()) {

        // Get the TypeQualifierAnnotation for this parameter
        SourceSinkInfo info;
        TypeQualifierAnnotation tqa = TypeQualifierApplications.getEffectiveTypeQualifierAnnotation(xmethod, param,
                typeQualifierValue);
        When when = (tqa != null) ? tqa.when : When.UNKNOWN;
        ValueNumber vn = vnaFrameAtEntry.getValue(slotOffset + firstParamSlot);
        info = new SourceSinkInfo(SourceSinkType.PARAMETER, cfg.getLocationAtEntry(), vn, when);
        info.setParameterAndLocal(param, slotOffset + firstParamSlot);
        registerSourceSink(info);

        param++;
        slotOffset += SignatureParser.getNumSlotsForType(paramSig);
    }
}
 
Example #6
Source File: AnnotatedElementUtilsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void getAllAnnotationAttributesOnLangType() {
	MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(
			NonNullApi.class, Nonnull.class.getName());
	assertNotNull("Annotation attributes map for @Nonnull on NonNullApi", attributes);
	assertEquals("value for NonNullApi", asList(When.ALWAYS), attributes.get("when"));
}
 
Example #7
Source File: ForwardTypeQualifierDataflowAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void registerReturnValueSource(Location location) throws DataflowAnalysisException {
    // Nothing to do if called method does not return a value
    InvokeInstruction inv = (InvokeInstruction) location.getHandle().getInstruction();
    if (inv instanceof INVOKEDYNAMIC) {
        return;
    }
    String calledMethodSig = inv.getSignature(cpg);
    if (calledMethodSig.endsWith(")V")) {
        return;
    }

    XMethod calledXMethod = XFactory.createXMethod(inv, cpg);
    if (TypeQualifierDataflowAnalysis.isIdentifyFunctionForTypeQualifiers(calledXMethod)) {
        return;
    }

    if (calledXMethod.isResolved()) {
        TypeQualifierAnnotation tqa = TypeQualifierApplications.getEffectiveTypeQualifierAnnotation(calledXMethod,
                typeQualifierValue);

        boolean interproc = false;
        if (TypeQualifierDatabase.USE_DATABASE && tqa == null) {
            // See if there's an entry in the interprocedural
            // type qualifier database.
            TypeQualifierDatabase tqdb = Global.getAnalysisCache().getDatabase(TypeQualifierDatabase.class);
            tqa = tqdb.getReturnValue(calledXMethod.getMethodDescriptor(), typeQualifierValue);
            if (tqa != null) {
                interproc = true;
            }
        }

        When when = (tqa != null) ? tqa.when : When.UNKNOWN;
        registerTopOfStackSource(SourceSinkType.RETURN_VALUE_OF_CALLED_METHOD, location, when, interproc, null);
    }
}
 
Example #8
Source File: ValidationSecurityManager.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static <A extends Annotation> When sandboxedValidation(A proxy, TypeQualifierValidator<A> v, @CheckForNull Object constantValue) {
    if (performingValidation.get()) {
        throw new IllegalStateException("recursive validation");
    }

    try {
        performingValidation.set(Boolean.TRUE);
        if (TypeQualifierValue.DEBUG_CLASSLOADING) {
            System.out.println("Performing validation in thread " + Thread.currentThread().getName());
        }
        try {
            When result = v.forConstantValue(proxy, constantValue);
            if (!performingValidation.get()) {
                throw new IllegalStateException("performingValidation not set when validation completes");
            }
            return result;
        } catch (ClassCastException e) {
            Class<? extends Annotation> c = proxy.getClass();
            System.out.println(c.getName() + " extends " + c.getSuperclass().getName());
            for (Class<?> i : c.getInterfaces()) {
                System.out.println("  " + i.getName());
            }
            throw e;
        }

    } finally {
        performingValidation.set(Boolean.FALSE);
        if (TypeQualifierValue.DEBUG_CLASSLOADING) {
            System.out.println("Validation finished in thread " + Thread.currentThread().getName());
        }

    }
}
 
Example #9
Source File: ForwardTypeQualifierDataflowAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void registerFieldLoadSource(Location location) throws DataflowAnalysisException {
    XField loadedField = XFactory.createXField((FieldInstruction) location.getHandle().getInstruction(), cpg);
    if (loadedField.isResolved()) {
        TypeQualifierAnnotation tqa = TypeQualifierApplications.getEffectiveTypeQualifierAnnotation(loadedField,
                typeQualifierValue);
        When when = (tqa != null) ? tqa.when : When.UNKNOWN;
        registerTopOfStackSource(SourceSinkType.FIELD_LOAD, location, when, false, null);
    }

}
 
Example #10
Source File: ForwardTypeQualifierDataflowAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void registerConstantSource(Location location, @CheckForNull Object constantValue) throws DataflowAnalysisException {

        When w;
        if (typeQualifierValue.canValidate(constantValue)) {
            w = typeQualifierValue.validate(constantValue);
        } else if (typeQualifierValue.isStrictQualifier()) {
            return;
        } else {
            w = When.UNKNOWN;
        }

        registerTopOfStackSource(SourceSinkType.CONSTANT_VALUE, location, w, false, constantValue);
    }
 
Example #11
Source File: FlowValue.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Convert a When value to a FlowValue value.
 *
 * @param when
 *            a When value
 * @return the corresponding FlowValue
 */
public static FlowValue flowValueFromWhen(When when) {
    switch (when) {
    case ALWAYS:
        return FlowValue.ALWAYS;
    case MAYBE:
        return FlowValue.UNKNOWN;
    case NEVER:
        return FlowValue.NEVER;
    case UNKNOWN:
        return FlowValue.UNKNOWN;
    default:
        throw new IllegalStateException();
    }
}
 
Example #12
Source File: CheckReturnValueAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@CheckForNull
public static CheckReturnValueAnnotation createFor(@NonNull When when) {
    switch (when.name()) {
    case "NEVER":
    case "UNKNOWN":
        return CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE;
    case "MAYBE":
        return CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM_BAD_PRACTICE;
    case "ALWAYS":
        return CheckReturnValueAnnotation.CHECK_RETURN_VALUE_HIGH;
    default:
        return null;
    }
}
 
Example #13
Source File: InconsistentAnnotations.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {

    JavaClass jclass = classContext.getJavaClass();

    for (Method method : jclass.getMethods()) {
        XMethod xmethod = XFactory.createXMethod(classContext.getJavaClass(), method);
        ParameterProperty nonnullParameters = AnalysisContext.currentAnalysisContext().getUnconditionalDerefParamDatabase()
                .getProperty(xmethod.getMethodDescriptor());
        if (nonnullParameters != null) {
            for (int p : nonnullParameters.iterable()) {
                TypeQualifierAnnotation directTypeQualifierAnnotation = TypeQualifierApplications
                        .getDirectTypeQualifierAnnotation(xmethod, p, nonnullTypeQualifierValue);
                if (directTypeQualifierAnnotation != null && directTypeQualifierAnnotation.when == When.UNKNOWN) {
                    //
                    // The LocalVariableAnnotation is constructed using the
                    // local variable
                    // number of the parameter, not the parameter number.
                    //
                    int paramLocal = xmethod.isStatic() ? p : p + 1;

                    reporter.reportBug(new BugInstance(this, "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE",
                            NORMAL_PRIORITY).addClassAndMethod(jclass, method).add(
                                    LocalVariableAnnotation.getParameterLocalVariableAnnotation(method, paramLocal)));

                }

            }
        }
    }

}
 
Example #14
Source File: CoreStitchAuth.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether or not the client is logged in.
 *
 * @return whether or not the client is logged in.
 */
@CheckReturnValue(when = When.NEVER)
public boolean isLoggedIn() {
  authLock.readLock().lock();
  try {
    return activeUser != null && activeUser.isLoggedIn();
  } finally {
    authLock.readLock().unlock();
  }
}
 
Example #15
Source File: CoreStitchAuth.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether or not the client is logged in.
 *
 * @return whether or not the client is logged in.
 */
@CheckReturnValue(when = When.NEVER)
public boolean isLoggedInInterruptibly() throws InterruptedException {
  authLock.readLock().lockInterruptibly();
  try {
    return activeUser != null && activeUser.isLoggedIn();
  } finally {
    authLock.readLock().unlock();
  }
}
 
Example #16
Source File: ForwardTypeQualifierDataflowAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void registerTopOfStackSource(SourceSinkType sourceSinkType, Location location, When when, boolean interproc,
        @CheckForNull Object constantValue) throws DataflowAnalysisException {
    if (when == When.UNKNOWN && !typeQualifierValue.isStrictQualifier()) {
        return;
    }
    ValueNumberFrame vnaFrameAfterInstruction = vnaDataflow.getFactAfterLocation(location);
    if (vnaFrameAfterInstruction.isValid()) {
        ValueNumber tosValue = vnaFrameAfterInstruction.getTopValue();
        SourceSinkInfo sourceSinkInfo = new SourceSinkInfo(sourceSinkType, location, tosValue, when);
        sourceSinkInfo.setInterproc(interproc);
        sourceSinkInfo.setConstantValue(constantValue);
        registerSourceSink(sourceSinkInfo);
    }
}
 
Example #17
Source File: BackwardTypeQualifierDataflowAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void modelReturn(TypeQualifierAnnotation returnValueAnnotation, Location location) throws DataflowAnalysisException {
    When when = (returnValueAnnotation != null) ? returnValueAnnotation.when : When.UNKNOWN;

    // Model return statement
    ValueNumberFrame vnaFrameAtReturn = vnaDataflow.getFactAtLocation(location);
    if (vnaFrameAtReturn.isValid()) {
        ValueNumber topValue = vnaFrameAtReturn.getTopValue();
        SourceSinkInfo sink = new SourceSinkInfo(SourceSinkType.RETURN_VALUE, location, topValue, when);
        registerSourceSink(sink);
    }
}
 
Example #18
Source File: Analysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param result
 * @param applicableApplications
 */
public static void addKnownTypeQualifiers(HashSet<? super TypeQualifierValue<?>> result,
        Collection<TypeQualifierAnnotation> applicableApplications) {
    for (TypeQualifierAnnotation t : applicableApplications) {
        if (t.when != When.UNKNOWN) {
            result.add(t.typeQualifier);
        }
    }
}
 
Example #19
Source File: TypeQualifierAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static @Nonnull Collection<TypeQualifierAnnotation> getValues(Map<TypeQualifierValue<?>, When> map) {
    Collection<TypeQualifierAnnotation> result = new LinkedList<>();
    for (Map.Entry<TypeQualifierValue<?>, When> e : map.entrySet()) {
        result.add(getValue(e.getKey(), e.getValue()));
    }
    return result;
}
 
Example #20
Source File: TypeQualifierAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static @Nonnull TypeQualifierAnnotation getValue(TypeQualifierValue<?> desc, When when) {
    DualKeyHashMap<TypeQualifierValue<?>, When, TypeQualifierAnnotation> map = instance.get();
    TypeQualifierAnnotation result = map.get(desc, when);
    if (result != null) {
        return result;
    }
    result = new TypeQualifierAnnotation(desc, when);
    map.put(desc, when, result);
    return result;
}
 
Example #21
Source File: TypeQualifierNullnessAnnotationDatabase.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean parameterMustBeNonNull(XMethod m, int param) {
    if (DEBUG) {
        System.out.print("Checking " + m + " param " + param + " for @Nonnull...");
    }
    TypeQualifierAnnotation tqa = TypeQualifierApplications.getEffectiveTypeQualifierAnnotation(m, param,
            nonnullTypeQualifierValue);

    if (tqa == null && param == 0) {
        String name = m.getName();
        String signature = m.getSignature();
        if ("main".equals(name) && "([Ljava/lang/String;)V".equals(signature) && m.isStatic() && m.isPublic()) {
            return true;
        } else if (assertsFirstParameterIsNonnull(m)) {
            return true;
        } else if ("compareTo".equals(name) && ")Z".equals(signature.substring(signature.indexOf(';') + 1)) && !m.isStatic()) {
            return true;
        }
    }
    boolean answer = (tqa != null) && tqa.when == When.ALWAYS;

    if (DEBUG) {
        System.out.println(answer ? "yes" : "no");
    }

    return answer;
}
 
Example #22
Source File: CheckReturnAnnotationDatabase.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Try to find default {@link CheckReturnValueAnnotation} for methods inside of target class.
 *
 */
@CheckForNull
private CheckReturnValueAnnotation parsePackage(@DottedClassName String packageName) {
    String className = ClassName.toSlashedClassName(packageName) + "/package-info";
    ClassDescriptor descriptor = DescriptorFactory.createClassDescriptor(className);
    // ClassInfoAnalysisEngine doesn't support parsing package-info to generate XClass, so use JavaClass instead
    JavaClass clazz;
    try {
        clazz = AnalysisContext.currentAnalysisContext().lookupClass(descriptor);
    } catch (ClassNotFoundException e) {
        // no annotation on package
        return null;
    }

    for (AnnotationEntry entry : clazz.getAnnotationEntries()) {
        @SlashedClassName
        String type = entry.getAnnotationType();

        switch (type) {
        case NAME_OF_CHECK_RETURN_NULL_SPOTBUGS:
            return createSpotBugsAnnotation(entry);
        case NAME_OF_CHECK_RETURN_NULL_JSR305:
            return createJSR305Annotation(entry);
        case NAME_OF_CHECK_RETURN_NULL_ERRORPRONE:
            return CheckReturnValueAnnotation.createFor(When.ALWAYS);
        case NAME_OF_CAN_IGNORE_RETURN_VALUE:
            return CheckReturnValueAnnotation.createFor(When.NEVER);
        default:
            // check next annotation
        }
    }

    return null;
}
 
Example #23
Source File: CheckReturnAnnotationDatabase.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private CheckReturnValueAnnotation createJSR305Annotation(AnnotationEntry entry) {
    for (ElementValuePair pair : entry.getElementValuePairs()) {
        if (pair.getNameString().equals("when")) {
            return CheckReturnValueAnnotation.createFor(When.valueOf(pair.getValue().stringifyValue()));
        }
    }
    // use default value
    return CheckReturnValueAnnotation.createFor(When.ALWAYS);
}
 
Example #24
Source File: ClassName.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Convert class name to slashed format. If the class name is already in
 * slashed format, it is returned unmodified.
 *
 * @param className
 *            a class name
 * @return the same class name in slashed format
 */
@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;
}
 
Example #25
Source File: ClassName.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Convert class name to dotted format. If the class name is already in
 * dotted format, it is returned unmodified.
 *
 * @param className
 *            a class name
 * @return the same class name in dotted format
 */
@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;
}
 
Example #26
Source File: ValidationSecurityManagerTest.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public @Nonnull When forConstantValue(@Nonnull SlashedClassName annotation, Object value) {
    Thread t = new Thread() {
        @Override
        public void run() {
            System.out.println("bang");
        }
    };
    t.start();
    return When.NEVER;
}
 
Example #27
Source File: AnnotatedElementUtilsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void getAllAnnotationAttributesOnJavaxType() {
	MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(
			ParametersAreNonnullByDefault.class, Nonnull.class.getName());
	assertNotNull("Annotation attributes map for @Nonnull on NonNullApi", attributes);
	assertEquals("value for NonNullApi", asList(When.ALWAYS), attributes.get("when"));
}
 
Example #28
Source File: TestFooNoControlFlow2.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void requiresFoo(@Foo(when = When.ALWAYS) Object x) {
}
 
Example #29
Source File: TestFooUnknownSource.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@ExpectWarning("TQ")
int unknownSourceToNeverSourceFalsePositive(@Foo(when = When.UNKNOWN) String c) {
    return g(c); // should generate a warning here
}
 
Example #30
Source File: TestFooUnknownSource.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@ExpectWarning("TQ")
int unknownSourceToNeverSinkFalsePositive(@Foo(when = When.UNKNOWN) String c) {
    return f(c); // should generate a warning here
}