org.netbeans.spi.editor.hints.ErrorDescription Java Examples

The following examples show how to use org.netbeans.spi.editor.hints.ErrorDescription. 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 Project: netbeans   Author: apache   File: Imports.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_Imports_EXCLUDED", description = "#DESC_Imports_EXCLUDED", category="imports", id="Imports_EXCLUDED", options=Options.QUERY)
@TriggerTreeKind(Kind.IMPORT)
public static ErrorDescription exlucded(HintContext ctx) throws IOException {
    ImportTree it = (ImportTree) ctx.getPath().getLeaf();

    if (it.isStatic() || !(it.getQualifiedIdentifier() instanceof MemberSelectTree)) {
        return null; // XXX
    }

    MemberSelectTree ms = (MemberSelectTree) it.getQualifiedIdentifier();
    String pkg = ms.getExpression().toString();
    String klass = ms.getIdentifier().toString();
    String exp = pkg + "." + (!klass.equals("*") ? klass : ""); //NOI18N
    if (Utilities.isExcluded(exp)) {
        return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), NbBundle.getMessage(Imports.class, "DN_Imports_EXCLUDED"));
    }

    return null;
}
 
Example #2
Source Project: netbeans   Author: apache   File: AssertWithSideEffects.java    License: Apache License 2.0 6 votes vote down vote up
@TriggerTreeKind(Tree.Kind.ASSERT)
public static ErrorDescription run(HintContext ctx) {
    CompilationInfo ci = ctx.getInfo();
    AssertTree at = (AssertTree)ctx.getPath().getLeaf();
    TreePath condPath = new TreePath(ctx.getPath(), at.getCondition());
    if (ci.getTreeUtilities().isCompileTimeConstantExpression(condPath)) {
        return null;
    }
    
    SideEffectVisitor visitor = new SideEffectVisitor(ctx);
    Tree culprit;
    try {
        visitor.scan(new TreePath(ctx.getPath(), at.getCondition()), null);
        return null;
    } catch (StopProcessing stop) {
        culprit = stop.getValue();
    }
    return ErrorDescriptionFactory.forTree(ctx, culprit, TEXT_AssertWithSideEffects());
}
 
Example #3
Source Project: netbeans   Author: apache   File: RestScanTask.java    License: Apache License 2.0 6 votes vote down vote up
private void doConfigureRest( Project project, RestServicesMetadata metadata ) 
{
    List<TypeElement> rest = getRestResources(metadata);
    if ( rest.isEmpty() ){
        return;
    }
    ClassTree tree = info.getTrees().getTree(rest.get(0));
    List<Integer> position = getElementPosition(info, tree);
    
    ErrorDescription description = ErrorDescriptionFactory
            .createErrorDescription(Severity.WARNING,
                    NbBundle.getMessage(RestScanTask.class,
                            "TXT_NoRestConfiguration"), // NOI18N
                    RestConfigHint.getConfigHints(project,
                            fileObject, factory, info.getClasspathInfo()), 
                            info.getFileObject(), position.get(0),
                            position.get(1));
    hints.add(description);
}
 
Example #4
Source Project: netbeans   Author: apache   File: RulesEngine.java    License: Apache License 2.0 6 votes vote down vote up
@Override public Void visitExecutableAsMethod(ExecutableElement operation, ProblemContext ctx){
    // apply operation-level rules
    for (Rule<ExecutableElement> rule : getOperationRules()){
        if (ctx.isCancelled()){
            break;
        }
        
        ErrorDescription problems[] = rule.execute(operation, ctx);
        
        if (problems != null){
            for (ErrorDescription problem : problems){
                if (problem != null){
                    problemsFound.add(problem);
                }
            }
        }
    }
    
     // visit all parameters
    for (VariableElement parameter : operation.getParameters()){
        parameter.accept(this, ctx);
    }
    
   return null;
}
 
Example #5
Source Project: netbeans   Author: apache   File: EqualsMethodHint.java    License: Apache License 2.0 6 votes vote down vote up
@TriggerPattern(value="$mods$ boolean equals(java.lang.Object $param) { $statements$; }")
public static ErrorDescription run(HintContext ctx) {
    TreePath paramPath = ctx.getVariables().get("$param");

    assert paramPath != null;

    Element param = ctx.getInfo().getTrees().getElement(paramPath);
    
    if (param == null || param.getKind() != ElementKind.PARAMETER) {
        return null;
    }
    
    for (TreePath st : ctx.getMultiVariables().get("$statements$")) {
        try {
            new VisitorImpl(ctx.getInfo(), param).scan(st, null);
        } catch (Found f) {
            return null;
        }
    }

    return ErrorDescriptionFactory.forName(ctx,
            ctx.getPath(),
            NbBundle.getMessage(EqualsMethodHint.class, "ERR_EQUALS_NOT_CHECKING_TYPE"));
}
 
Example #6
Source Project: netbeans   Author: apache   File: HintsInvoker.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Void scan(Tree tree, Map<HintDescription, List<ErrorDescription>> p) {
    if (tree == null)
        return null;

    TreePath tp = new TreePath(getCurrentPath(), tree);
    Kind k = tree.getKind();

    boolean b = pushSuppressWarrnings(tp);
    try {
        runAndAdd(tp, hints.get(k), p);

        if (isCanceled()) {
            return null;
        }

        return super.scan(tree, p);
    } finally {
        if (b) {
            suppresWarnings.pop();
        }
    }
}
 
Example #7
Source Project: netbeans   Author: apache   File: UtilityClass.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(id="org.netbeans.modules.java.hints.UtilityClass_1", displayName="#MSG_UtilityClass", description="#HINT_UtilityClass", category="api", enabled=false, severity=Severity.VERIFIER, suppressWarnings="UtilityClassWithoutPrivateConstructor")
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription utilityClass(HintContext ctx) {
    CompilationInfo compilationInfo = ctx.getInfo();
    TreePath treePath = ctx.getPath();
    Element e = compilationInfo.getTrees().getElement(treePath);
    if (e == null) {
        return null;
    }
    
    if (!isUtilityClass(compilationInfo, e)) return null;
    
    for (ExecutableElement c : ElementFilter.constructorsIn(e.getEnclosedElements())) {
        if (!compilationInfo.getElementUtilities().isSynthetic(c)) {
            return null;
        }
    }

    return ErrorDescriptionFactory.forName(ctx,
                                           treePath,
                                           NbBundle.getMessage(UtilityClass.class, "MSG_UtilityClass"),
                                           new FixImpl(true,
                                                       TreePathHandle.create(e, compilationInfo)
                                           ).toEditorFix());
}
 
Example #8
Source Project: netbeans   Author: apache   File: LoggerNotStaticFinal.java    License: Apache License 2.0 6 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern(value="$mods$ java.util.logging.Logger $LOG;"), //NOI18N
    @TriggerPattern(value="$mods$ java.util.logging.Logger $LOG = $init;") //NOI18N
})
public static ErrorDescription checkLoggerDeclaration(HintContext ctx) {
    Element e = ctx.getInfo().getTrees().getElement(ctx.getPath());
    if (e != null && e.getEnclosingElement().getKind() == ElementKind.CLASS &&
        (!e.getModifiers().contains(Modifier.STATIC) || !e.getModifiers().contains(Modifier.FINAL)) &&
        ctx.getInfo().getElementUtilities().outermostTypeElement(e) == e.getEnclosingElement()
    ) {
        return ErrorDescriptionFactory.forName(
                ctx,
                ctx.getPath(),
                NbBundle.getMessage(LoggerNotStaticFinal.class, "MSG_LoggerNotStaticFinal_checkLoggerDeclaration", e), //NOI18N
                new LoggerNotStaticFinalFix(NbBundle.getMessage(LoggerNotStaticFinal.class, "MSG_LoggerNotStaticFinal_checkLoggerDeclaration_fix", e), TreePathHandle.create(e, ctx.getInfo())).toEditorFix() //NOI18N
        );
    } else {
        return null;
    }
}
 
Example #9
Source Project: netbeans   Author: apache   File: Lambda.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(displayName="#DN_expression2Return", description="#DESC_expression2Return", category="suggestions", hintKind=Hint.Kind.ACTION,
        minSourceVersion = "8")
@Messages({
    "DN_expression2Return=Convert Lambda Body to Use a Block",
    "DESC_expression2Return=Converts lambda bodies to use blocks rather than expressions",
    "ERR_expression2Return=",
    "FIX_expression2Return=Use block as the lambda's body"
})
@TriggerPattern("($args$) -> $lambdaExpression")
public static ErrorDescription expression2Return(HintContext ctx) {
    if (((LambdaExpressionTree) ctx.getPath().getLeaf()).getBodyKind() != BodyKind.EXPRESSION) {
        return null;
    }
    
    TypeMirror lambdaExpressionType = ctx.getInfo().getTrees().getTypeMirror(ctx.getVariables().get("$lambdaExpression"));
    String target =   lambdaExpressionType == null || lambdaExpressionType.getKind() != TypeKind.VOID
                    ? "($args$) -> { return $lambdaExpression; }"
                    : "($args$) -> { $lambdaExpression; }";
    
    return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), Bundle.ERR_expression2Return(), JavaFixUtilities.rewriteFix(ctx, Bundle.FIX_expression2Return(), ctx.getPath(), target));
}
 
Example #10
Source Project: netbeans   Author: apache   File: Tiny.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_CanBeFinal", description = "#DESC_CanBeFinal", category="thread", suppressWarnings="FieldMayBeFinal")
@TriggerTreeKind(Kind.VARIABLE)
public static ErrorDescription canBeFinal(HintContext ctx) {
    Element ve = ctx.getInfo().getTrees().getElement(ctx.getPath());
    
    if (ve == null || ve.getKind() != ElementKind.FIELD || ve.getModifiers().contains(Modifier.FINAL) || /*TODO: the point of volatile?*/ve.getModifiers().contains(Modifier.VOLATILE)) return null;
    
    //we can't say much currently about non-private fields:
    if (!ve.getModifiers().contains(Modifier.PRIVATE)) return null;
    
    FlowResult flow = Flow.assignmentsForUse(ctx);
    
    if (flow == null || ctx.isCanceled()) return null;
    
    if (flow.getFinalCandidates().contains(ve)) {
        VariableTree vt = (VariableTree) ctx.getPath().getLeaf();
        Fix fix = null;
        if (flow.getFieldInitConstructors(ve).size() <= 1) {
            fix = FixFactory.addModifiersFix(ctx.getInfo(), new TreePath(ctx.getPath(), vt.getModifiers()), EnumSet.of(Modifier.FINAL), Bundle.FIX_CanBeFinal(ve.getSimpleName().toString()));
        }
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_CanBeFinal(ve.getSimpleName().toString()), fix);
    }
    
    return null;
}
 
Example #11
Source Project: netbeans   Author: apache   File: UtilityClass.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(id="org.netbeans.modules.java.hints.UtilityClass_2", displayName="#MSG_PublicConstructor", description="#HINT_PublicConstructor", category="api", enabled=false, severity=Severity.HINT, suppressWarnings="UtilityClassWithPublicConstructor")
@TriggerTreeKind(Kind.METHOD)
public static ErrorDescription constructor(HintContext ctx) {
    CompilationInfo compilationInfo = ctx.getInfo();
    TreePath treePath = ctx.getPath();
    Element e = compilationInfo.getTrees().getElement(treePath);
    if (e == null) {
        return null;
    }
    if (   e.getKind() != ElementKind.CONSTRUCTOR
        || compilationInfo.getElementUtilities().isSynthetic(e)
        || (!e.getModifiers().contains(Modifier.PROTECTED) && !e.getModifiers().contains(Modifier.PUBLIC))) {
        return null;
    }
    
    if (!isUtilityClass(compilationInfo, e.getEnclosingElement())) return null;
    
    return ErrorDescriptionFactory.forName(ctx,
                                           treePath,
                                           NbBundle.getMessage(UtilityClass.class, "MSG_PublicConstructor"),
                                           new FixImpl(false,
                                                       TreePathHandle.create(e, compilationInfo)
                                           ).toEditorFix());
}
 
Example #12
Source Project: netbeans   Author: apache   File: ReturnEncapsulation.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.encapsulation.ReturnEncapsulation.date", description = "#DESC_org.netbeans.modules.java.hints.encapsulation.ReturnEncapsulation.date", category="encapsulation", suppressWarnings={"ReturnOfDateField"}, enabled=false, options=Options.QUERY) //NOI18N
@TriggerPatterns({
    @TriggerPattern(value="return $expr",   //NOI18N
        constraints={
            @ConstraintVariableType(variable="$expr",type=DATE)   //NOI18N
    }),
    @TriggerPattern(value="return $expr",   //NOI18N
        constraints={
            @ConstraintVariableType(variable="$expr",type=CALENDAR)   //NOI18N
    })
})
public static ErrorDescription date(final HintContext ctx) {
    assert ctx != null;
    return create(ctx, NbBundle.getMessage(ReturnEncapsulation.class, "TXT_ReturnDate"),
        "ReturnOfDateField");   //NOI18N
}
 
Example #13
Source Project: netbeans   Author: apache   File: MethodMetrics.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(
    category = "metrics",
    displayName = "#DN_MethodTooManyParameters",
    description = "#DESC_MethodTooManyParameters",
    options = { Hint.Options.QUERY, Hint.Options.HEAVY },
    enabled = false
)
@UseOptions(value = { OPTION_METHOD_PARAMETERS_LIMIT })
@TriggerPattern("$modifiers$ <$typeParams$> $returnType $name($args1, $arg2, $args$) throws $whatever$ { $body$; }")
public static ErrorDescription tooManyParameters(HintContext ctx) {
    Tree t = ctx.getPath().getLeaf();
    MethodTree method = (MethodTree)t;
    
    Collection<? extends TreePath> args = ctx.getMultiVariables().get("$args$"); // NOI18N
    int limit = ctx.getPreferences().getInt(OPTION_METHOD_PARAMETERS_LIMIT, DEFAULT_METHOD_PARAMETERS_LIMIT);
    int count = args.size() + 2;
    if (count <= limit) {
        return null;
    }
    return ErrorDescriptionFactory.forName(ctx, t, 
            methodOrConstructor(ctx) ?
            TEXT_ConstructorTooManyParameters(count) :
            TEXT_MethodTooManyParameters(method.getName().toString(), count)
    );
}
 
Example #14
Source Project: netbeans   Author: apache   File: AnnotationHolderTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test205675() throws Exception {
    doc.remove(0, doc.getLength());
    doc.insertString(0, "a\nb\nc\nd\ne\n", null);
    
    ErrorDescription ed0 = ErrorDescriptionFactory.createErrorDescription(Severity.ERROR, "0", file, 0, 1);
    ErrorDescription ed1 = ErrorDescriptionFactory.createErrorDescription(Severity.ERROR, "1", file, 2, 3);
    ErrorDescription ed2 = ErrorDescriptionFactory.createErrorDescription(Severity.ERROR, "2", file, 4, 5);
    AnnotationHolder ah = AnnotationHolder.getInstance(file);
    
    ah.setErrorDescriptions("test", Arrays.asList(ed0, ed1, ed2));
    
    assertEquals(Arrays.asList(ed0), ah.getErrorsGE(0));
    assertEquals(Arrays.asList(ed1), ah.getErrorsGE(1));
    assertEquals(Arrays.asList(ed1), ah.getErrorsGE(2));
    assertEquals(Arrays.asList(ed2), ah.getErrorsGE(3));
    assertEquals(Arrays.asList(ed2), ah.getErrorsGE(4));
    assertEquals(Arrays.asList(), ah.getErrorsGE(5));
}
 
Example #15
Source Project: netbeans   Author: apache   File: ClassMetrics.java    License: Apache License 2.0 6 votes vote down vote up
@Hint(
    displayName = "#DN_ClassTooCoupled",
    description = "#DESC_ClassTooCoupled",
    category = "metrics",
    options = { Hint.Options.HEAVY, Hint.Options.QUERY },
    enabled = false
)
@UseOptions({ OPTION_COUPLING_LIMIT, OPTION_COUPLING_IGNORE_JAVA })
@TriggerTreeKind(Tree.Kind.CLASS)
public static ErrorDescription tooCoupledClass(HintContext ctx) {
    ClassTree clazz = (ClassTree)ctx.getPath().getLeaf();
    DependencyCollector col = new DependencyCollector(ctx.getInfo());
    boolean ignoreJava = ctx.getPreferences().getBoolean(OPTION_COUPLING_IGNORE_JAVA, DEFAULT_COUPLING_IGNORE_JAVA);
    col.setIgnoreJavaLibraries(ignoreJava);
    col.scan(ctx.getPath(), null);
    
    int coupling = col.getSeenQNames().size();
    int limit = ctx.getPreferences().getInt(OPTION_COUPLING_LIMIT, DEFAULT_COUPLING_LIMIT);
    if (coupling > limit) {
        return ErrorDescriptionFactory.forName(ctx, 
                ctx.getPath(), 
                TEXT_ClassTooCoupled(clazz.getSimpleName().toString(), coupling));
    } else {
        return null;
    }
}
 
Example #16
Source Project: netbeans   Author: apache   File: FileToURL.java    License: Apache License 2.0 6 votes vote down vote up
@TriggerTreeKind(Kind.METHOD_INVOCATION)
public static ErrorDescription computeTreeKind(HintContext ctx) {
    MethodInvocationTree mit = (MethodInvocationTree) ctx.getPath().getLeaf();

    if (!mit.getArguments().isEmpty() || !mit.getTypeArguments().isEmpty()) {
        return null;
    }

    CompilationInfo info = ctx.getInfo();
    Element e = info.getTrees().getElement(new TreePath(ctx.getPath(), mit.getMethodSelect()));

    if (e == null || e.getKind() != ElementKind.METHOD) {
        return null;
    }

    if (e.getSimpleName().contentEquals("toURL") && info.getElementUtilities().enclosingTypeElement(e).getQualifiedName().contentEquals("java.io.File")) {
        ErrorDescription w = ErrorDescriptionFactory.forName(ctx, mit, "Use of java.io.File.toURL()");

        return w;
    }

    return null;
}
 
Example #17
Source Project: netbeans   Author: apache   File: ErrorPositionRefresherHelper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isUpToDate(Context context, Document doc, DocumentVersionImpl oldVersion) {
    List<ErrorDescription> errors = oldVersion.errorsContent;

    for (ErrorDescription ed : errors) {
        if (ed.getRange().getBegin().getOffset() <= context.getPosition() && context.getPosition() <= ed.getRange().getEnd().getOffset()) {
            if (!ed.getFixes().isComputed()) return false;
        }
    }

    return true;
}
 
Example #18
Source Project: netbeans   Author: apache   File: ClassStructure.java    License: Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.markerInterface", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.markerInterface", category = "class_structure", enabled = false, suppressWarnings = {"MarkerInterface"}, options=Options.QUERY) //NOI18N
@TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE})
public static ErrorDescription markerInterface(HintContext context) {
    final ClassTree cls = (ClassTree) context.getPath().getLeaf();
    if (context.getInfo().getTreeUtilities().isInterface(cls) && cls.getMembers().isEmpty() && cls.getImplementsClause().size() < 2) {
        return ErrorDescriptionFactory.forName(context, cls, NbBundle.getMessage(ClassStructure.class, "MSG_MarkerInterface", cls.getSimpleName())); //NOI18N
    }
    return null;
}
 
Example #19
Source Project: netbeans   Author: apache   File: RedundantIf.java    License: Apache License 2.0 5 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern("if ($cond) return false; else return true;"),
    @TriggerPattern("if ($cond) return false; return true;")
})
public static ErrorDescription redundantIfNeg(HintContext ctx) {
    Fix f = JavaFixUtilities.rewriteFix(ctx, Bundle.ERR_redundantIf(), ctx.getPath(), "return !$cond;");
    
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_redundantIf(), f);
}
 
Example #20
Source Project: netbeans   Author: apache   File: BMnotPartOfRBIandLBI.java    License: Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Tree.Kind.CLASS)
public static Collection<ErrorDescription> run(HintContext hintContext) {
    List<ErrorDescription> problems = new ArrayList<>();
    final EJBProblemContext ctx = HintsUtils.getOrCacheContext(hintContext);
    if (ctx != null && ctx.getEjb() instanceof Session) {
        final Collection<ExecutableElement> localMethods = new ArrayList<>();
        final Map<String, ExecutableElement> remoteMethods = new HashMap<>();

        // local methods
        localMethods.addAll(getMethodsFromClasses(hintContext.getInfo(), ctx.getEjbData().getBusinessLocal()));
        // remote methods
        for (ExecutableElement method : getMethodsFromClasses(hintContext.getInfo(), ctx.getEjbData().getBusinessRemote())) {
            remoteMethods.put(method.getSimpleName().toString(), method);
        }

        for (ExecutableElement localMethod : localMethods) {
            ExecutableElement sameNameRemoteMethod = remoteMethods.get(
                    localMethod.getSimpleName().toString());

            if (sameNameRemoteMethod != null) {
                if (JavaUtils.isMethodSignatureSame(hintContext.getInfo(),
                        localMethod, sameNameRemoteMethod)) {
                    ErrorDescription err = HintsUtils.createProblem(ctx.getClazz(), hintContext.getInfo(),
                            Bundle.BMnotPartOfRBIandLBI_err(), Severity.WARNING);

                    return Collections.singletonList(err);
                }
            }
        }
    }
    return problems;
}
 
Example #21
Source Project: netbeans   Author: apache   File: Nodes.java    License: Apache License 2.0 5 votes vote down vote up
private static <A> Map<A, Map<AnalyzerFactory, List<ErrorDescription>>> sortErrors(Map<AnalyzerFactory, List<ErrorDescription>> errs, AttributeRetriever<A> attributeRetriever) {
    Map<A, Map<AnalyzerFactory, List<ErrorDescription>>> sorted = new HashMap<A, Map<AnalyzerFactory, List<ErrorDescription>>>();

    for (Entry<AnalyzerFactory, List<ErrorDescription>> e : errs.entrySet()) {
        for (ErrorDescription ed : e.getValue()) {
            if (ed == null) {
                //XXX:
                LOG.log(Level.FINE, "null ErrorDescription produced by {0} ({1})", new Object[] {SPIAccessor.ACCESSOR.getAnalyzerDisplayName(e.getKey()), e.getKey().getClass()});
                continue;
            }
            
            A attribute = attributeRetriever.getAttribute(e.getKey(), ed);
            Map<AnalyzerFactory, List<ErrorDescription>> errorsPerAttributeValue = sorted.get(attribute);

            if (errorsPerAttributeValue == null) {
                sorted.put(attribute, errorsPerAttributeValue = new HashMap<AnalyzerFactory, List<ErrorDescription>>());
            }

            List<ErrorDescription> errors = errorsPerAttributeValue.get(e.getKey());

            if (errors == null) {
                errorsPerAttributeValue.put(e.getKey(), errors = new ArrayList<ErrorDescription>());
            }

            errors.add(ed);
        }
    }

    return sorted;
}
 
Example #22
Source Project: netbeans   Author: apache   File: HintTest.java    License: Apache License 2.0 5 votes vote down vote up
/**Find a specific warning.
 *
 * @param warning the warning to find - must be equivalent to {@code toString()}
 *                results of the {@link ErrorDescription}.
 * @return a wrapper about the given specific warnings
 * @throws AssertionError if the given warning cannot be found
 */
public HintWarning findWarning(String warning) {
    ErrorDescription toFix = null;

    for (ErrorDescription d : errors) {
        if (warning.equals(d.toString())) {
            toFix = d;
            break;
        }
    }

    assertNotNull("Warning: \"" + warning + "\" not found. All ErrorDescriptions: " + errors.toString(), toFix);

    return new HintWarning(toFix, requiresJavaFix.contains(toFix));
}
 
Example #23
Source Project: nb-springboot   Author: AlexFalappa   File: SyntaxErrorHighlightingTask.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void internalRun(CfgPropsParser.CfgPropsParserResult cfgResult, SchedulerEvent se, BaseDocument document,
        List<ErrorDescription> errors, Severity severity) {
    logger.fine("Highlighting syntax errors");
    try {
        final InputBuffer ibuf = cfgResult.getParbResult().inputBuffer;
        final List<ParseError> parseErrors = cfgResult.getParbResult().parseErrors;
        for (ParseError error : parseErrors) {
            String message = error.getErrorMessage() != null
                    ? error.getErrorMessage()
                    : error instanceof InvalidInputError
                            ? formatter.format((InvalidInputError) error)
                            : error.getClass().getSimpleName();
            ErrorDescription errDesc = ErrorDescriptionFactory.createErrorDescription(
                    severity,
                    message,
                    document,
                    document.createPosition(ibuf.getOriginalIndex(error.getStartIndex())),
                    document.createPosition(ibuf.getOriginalIndex(error.getEndIndex()))
            );
            errors.add(errDesc);
            if (canceled) {
                break;
            }
        }
    } catch (BadLocationException | ParseException ex) {
        Exceptions.printStackTrace(ex);
    }
    if (!errors.isEmpty()) {
        logger.log(Level.FINE, "Found {0} syntax errors", errors.size());
    }
}
 
Example #24
Source Project: netbeans   Author: apache   File: Imports.java    License: Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_Imports_STAR", description = "#DESC_Imports_STAR", category="imports", id="Imports_STAR", enabled=false, options=Options.QUERY, suppressWarnings={"", "OnDemandImport"})
@TriggerTreeKind(Kind.IMPORT)
public static ErrorDescription starImport(HintContext ctx) {
    ImportTree it = (ImportTree) ctx.getPath().getLeaf();

    if (it.isStatic() || !(it.getQualifiedIdentifier() instanceof MemberSelectTree)) {
        return null; // XXX
    }

    MemberSelectTree ms = (MemberSelectTree) it.getQualifiedIdentifier();

    if (!"*".equals(ms.getIdentifier().toString())) return null;

    return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), NbBundle.getMessage(Imports.class, "DN_Imports_STAR"));
}
 
Example #25
Source Project: netbeans   Author: apache   File: FlowScopedBeanWithoutCdi.java    License: Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Tree.Kind.CLASS)
public static Collection<ErrorDescription> run(HintContext hintContext) {
    List<ErrorDescription> problems = new ArrayList<>();
    final JsfHintsContext ctx = JsfHintsUtils.getOrCacheContext(hintContext);

    Project project = ctx.getProject();
    if (project == null) {
        return problems;
    }

    CompilationInfo info = hintContext.getInfo();
    for (TypeElement typeElement : info.getTopLevelElements()) {
        for (AnnotationMirror annotationMirror : typeElement.getAnnotationMirrors()) {
            if (FLOW_SCOPED.equals(annotationMirror.getAnnotationType().toString())) {
                // it's FlowScoped bean -> check the CDI
                CdiUtil cdiUtil = project.getLookup().lookup(CdiUtil.class);
                if (cdiUtil == null || !cdiUtil.isCdiEnabled()) {
                    Tree tree = info.getTrees().getTree(typeElement, annotationMirror);
                    problems.add(JsfHintsUtils.createProblem(
                            tree,
                            info,
                            Bundle.FlowScopedBeanWithoutCdi_display_name(),
                            Severity.WARNING,
                            Arrays.<Fix>asList(new FixCdiAvailability(project))));
                }
            }
        }
    }
    return problems;
}
 
Example #26
Source Project: netbeans   Author: apache   File: WSisSLSB.java    License: Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Tree.Kind.CLASS)
public static Collection<ErrorDescription> run(HintContext hintContext) {
    final EJBProblemContext ctx = HintsUtils.getOrCacheContext(hintContext);
    if (ctx == null) {
        return Collections.emptyList();
    }

    boolean isEJB = false;
    J2eeModuleProvider provider = ctx.getProject().getLookup().lookup(J2eeModuleProvider.class);
    if (provider != null) {
        J2eeModule module = provider.getJ2eeModule();
        isEJB = module != null && J2eeModule.Type.EJB.equals(module.getType());
    }
    //disable this rule for non ejb project
    if (!isEJB) {
        return null;
    }
    AnnotationMirror annWebService = JavaUtils.findAnnotation(ctx.getClazz(),
            EJBAPIAnnotations.WEB_SERVICE);

    if (annWebService != null) {
        ClassTree classTree = hintContext.getInfo().getTrees().getTree(ctx.getClazz());
        if (classTree.getKind() == Tree.Kind.INTERFACE) {
            return null; // ok, interfaces can have @WebService without ejb annotations
        }
        if (ctx.getEjb() instanceof Session) {
            if (Session.SESSION_TYPE_STATELESS.equals(ctx.getEjbData().getSessionType())
                    || Session.SESSION_TYPE_SINGLETON.equals(ctx.getEjbData().getSessionType())) {
                return Collections.emptyList(); //OK
            }
        }
        ErrorDescription err = HintsUtils.createProblem(
                ctx.getClazz(),
                hintContext.getInfo(),
                Bundle.WSisSLSB_err());
        return Collections.singletonList(err);
    }
    return Collections.emptyList();
}
 
Example #27
Source Project: netbeans   Author: apache   File: ClassStructure.java    License: Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.finalMethodInFinalClass", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.finalMethodInFinalClass", category = "class_structure", enabled = false, suppressWarnings = {"FinalMethodInFinalClass"}) //NOI18N
@TriggerTreeKind(Kind.METHOD)
public static ErrorDescription finalMethodInFinalClass(HintContext context) {
    final MethodTree mth = (MethodTree) context.getPath().getLeaf();
    final Tree parent = context.getPath().getParentPath().getLeaf();
    if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getKind()) && mth.getModifiers().getFlags().contains(Modifier.FINAL) && ((ClassTree) parent).getModifiers().getFlags().contains(Modifier.FINAL)) {
        // see defect #236974; although redundant, if the method is annotated with @SafeVarargs, we must permit final modifier.
        ExecutableElement ee = (ExecutableElement)context.getInfo().getTrees().getElement(context.getPath());
        if (ee == null || ee.getAnnotation(SafeVarargs.class) == null) {
            return ErrorDescriptionFactory.forName(context, mth, NbBundle.getMessage(ClassStructure.class, "MSG_FinalMethodInFinalClass", mth.getName()), //NOI18N
                    FixFactory.removeModifiersFix(context.getInfo(), TreePath.getPath(context.getPath(), mth.getModifiers()), EnumSet.of(Modifier.FINAL), NbBundle.getMessage(ClassStructure.class, "FIX_RemoveFinalFromMethod", mth.getName()))); //NOI18N
        }
    }
    return null;
}
 
Example #28
Source Project: netbeans   Author: apache   File: AnnotationHolder.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized boolean hasErrors() {
    for (ErrorDescription e : errors2Lines.keySet()) {
        if (e.getSeverity() == Severity.ERROR)
            return true;
    }

    return false;
}
 
Example #29
Source Project: netbeans   Author: apache   File: Tiny.java    License: Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.perf.Tiny.stringConstructor", description = "#DESC_org.netbeans.modules.java.hints.perf.Tiny.stringConstructor", category="performance", suppressWarnings="RedundantStringConstructorCall")
@UseOptions(SC_IGNORE_SUBSTRING)
@TriggerPattern(value="new java.lang.String($original)",
                [email protected](variable="$original", type="java.lang.String"))
public static ErrorDescription stringConstructor(HintContext ctx) {
    TreePath original = ctx.getVariables().get("$original");

    if (ctx.getPreferences().getBoolean(SC_IGNORE_SUBSTRING, SC_IGNORE_SUBSTRING_DEFAULT)) {
        if (   MatcherUtilities.matches(ctx, original, "$str1.substring($s)", true)
            || MatcherUtilities.matches(ctx, original, "$str2.substring($s, $e)", true)) {
            TreePath str = ctx.getVariables().get("$str1") != null ? ctx.getVariables().get("$str1") : ctx.getVariables().get("$str2");

            assert str != null;

            TypeMirror type = ctx.getInfo().getTrees().getTypeMirror(str);

            if (type != null && type.getKind() == TypeKind.DECLARED) {
                TypeElement te = (TypeElement) ((DeclaredType) type).asElement();

                if (te.getQualifiedName().contentEquals("java.lang.String")) {
                    return null;
                }
            }
        }
    }

    String fixDisplayName = NbBundle.getMessage(Tiny.class, "FIX_StringConstructor");
    Fix f = JavaFixUtilities.rewriteFix(ctx, fixDisplayName, ctx.getPath(), "$original");
    String displayName = NbBundle.getMessage(Tiny.class, "ERR_StringConstructor");
    return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), displayName, f);
}
 
Example #30
Source Project: netbeans   Author: apache   File: FieldEncapsulation.java    License: Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.encapsulation.FieldEncapsulation.publicField", description = "#DESC_org.netbeans.modules.java.hints.encapsulation.FieldEncapsulation.publicField", category="encapsulation", suppressWarnings={"PublicField"}, enabled=false, options=Options.QUERY) //NOI18N
@UseOptions(ALLOW_ENUMS_KEY)
@TriggerTreeKind(Kind.VARIABLE)
public static ErrorDescription publicField(final HintContext ctx) {
    return create(ctx,
        Visibility.PUBLIC,
        NbBundle.getMessage(FieldEncapsulation.class, "TXT_PublicField"));
}