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 File: RulesEngine.java    From netbeans with 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 #2
Source File: ReturnEncapsulation.java    From netbeans with 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 #3
Source File: RestScanTask.java    From netbeans with 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 File: UtilityClass.java    From netbeans with 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 #5
Source File: Tiny.java    From netbeans with 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 #6
Source File: MethodMetrics.java    From netbeans with 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 #7
Source File: Lambda.java    From netbeans with 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 #8
Source File: AnnotationHolderTest.java    From netbeans with 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 #9
Source File: EqualsMethodHint.java    From netbeans with 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 #10
Source File: HintsInvoker.java    From netbeans with 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 #11
Source File: ClassMetrics.java    From netbeans with 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 #12
Source File: AssertWithSideEffects.java    From netbeans with 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 #13
Source File: FileToURL.java    From netbeans with 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 #14
Source File: LoggerNotStaticFinal.java    From netbeans with 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 #15
Source File: UtilityClass.java    From netbeans with 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 #16
Source File: Imports.java    From netbeans with 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 #17
Source File: CollectionRemove.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerPattern(value="$col.remove($obj)",
                constraints={@ConstraintVariableType(variable="$col",
                                         type="java.util.Collection"),
                             @ConstraintVariableType(variable="$obj",
                                         type="java.lang.Object")
})
public static List<ErrorDescription> collectionRemove(HintContext ctx) {
    return run(ctx, "java.util.Collection.remove(java.lang.Object)", "java.util.Collection.add(java.lang.Object)", 0, 0);
}
 
Example #18
Source File: Nodes.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
        protected Node[] createNodes(ErrorDescription key) {
            List<Node> fixes = new LinkedList<Node>();
            
            for (FixDescription fd : errors2Fixes.get(key)) {
                fixes.add(new FixNode(key, fd));
            }
            
            return fixes.toArray(new Node[0]);
//            return new Node[] {new ErrorDescriptionNode(key, errors2Fixes)};
        }
 
Example #19
Source File: JavadocHint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(id = "error-in-javadoc", category = "JavaDoc", description = "#DESC_ERROR_IN_JAVADOC_HINT", displayName = "#DN_ERROR_IN_JAVADOC_HINT", hintKind = Hint.Kind.INSPECTION, severity = Severity.WARNING, customizerProvider = JavadocHint.CustomizerProviderImplError.class)
@TriggerTreeKind({Kind.METHOD, Kind.ANNOTATION_TYPE, Kind.CLASS, Kind.ENUM, Kind.INTERFACE, Kind.VARIABLE})
public static List<ErrorDescription> errorHint(final HintContext ctx) {
    Preferences pref = ctx.getPreferences();
    boolean correctJavadocForNonPublic = pref.getBoolean(AVAILABILITY_KEY + false, false);

    CompilationInfo javac = ctx.getInfo();
    Boolean publiclyAccessible = AccessibilityQuery.isPubliclyAccessible(javac.getFileObject().getParent());
    boolean isPubliclyA11e = publiclyAccessible == null ? true : publiclyAccessible;

    if (!isPubliclyA11e && !correctJavadocForNonPublic) {
        return null;
    }

    if (javac.getElements().getTypeElement("java.lang.Object") == null) { // NOI18N
        // broken java platform
        return Collections.<ErrorDescription>emptyList();
    }

    TreePath path = ctx.getPath();
    {
        Document doc = null;
        try {
            doc = javac.getDocument();
        } catch (IOException e) {
            Exceptions.printStackTrace(e);
        }
        if (doc != null && isGuarded(path.getLeaf(), javac, doc)) {
            return null;
        }
    }
    
    Access access = Access.resolve(pref.get(SCOPE_KEY, SCOPE_DEFAULT));
    Analyzer a = new Analyzer(javac, path, access, ctx);
    return a.analyze();
}
 
Example #20
Source File: HintsControllerImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void setErrors(Document doc, String layer, Collection<? extends ErrorDescription> errors) {
    DataObject od = (DataObject) doc.getProperty(Document.StreamDescriptionProperty);

    if (od == null)
        return ;
    
    try {
        setErrorsImpl(od.getPrimaryFile(), layer, errors);
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }
}
 
Example #21
Source File: GsfHintsManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<ErrorDescription> merge(List<ErrorDescription> a, List<ErrorDescription> b) {
    if (a == null) {
        return b;
    } else if (b == null) {
        return a;
    }
    // assume a is mutable
    a.addAll(b);
    return a;
}
 
Example #22
Source File: ConvertSwitchToRuleSwitch.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Tree.Kind.SWITCH)
@Messages({"ERR_ConvertSwitchToRuleSwitch=Convert switch to rule switch", "ERR_ConvertSwitchToSwitchExpression=Convert to switch expression"})
public static ErrorDescription switch2RuleSwitch(HintContext ctx) {
    if (Utilities.isJDKVersionLower(SWITCH_RULE_PREVIEW_JDK_VERSION) && !CompilerOptionsQuery.getOptions(ctx.getInfo().getFileObject()).getArguments().contains("--enable-preview"))
        return null;
    SwitchTree st = (SwitchTree) ctx.getPath().getLeaf();
    boolean completesNormally = false;
    boolean wasDefault = false;
    boolean wasEmpty = false;
    for (CaseTree ct : st.getCases()) {
        if (ct.getStatements() == null) //TODO: test
            return null;
        if (completesNormally) {
            if (!wasEmpty) //fall-through from a non-empty case
                return null;
            if (wasDefault) //fall-through from default to a case
                return null;
            if (!wasDefault && ct.getExpression() == null) //fall-through from a case to default
                return null;
        }
        completesNormally = Utilities.completesNormally(ctx.getInfo(), new TreePath(ctx.getPath(), ct));
        wasDefault = ct.getExpression() == null;
        wasEmpty = ct.getStatements().isEmpty();
    }
    if (wasDefault && Utilities.isCompatibleWithSwitchExpression(st)) {
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_ConvertSwitchToSwitchExpression(), new FixImpl1(ctx.getInfo(), ctx.getPath()).toEditorFix());
    } else {
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_ConvertSwitchToRuleSwitch(), new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix());
    }
}
 
Example #23
Source File: ClassStructure.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.classMayBeInterface", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.classMayBeInterface", category = "class_structure", enabled = false, suppressWarnings = {"ClassMayBeInterface"}, options=Options.NO_BATCH) //NOI18N
@TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE})
public static ErrorDescription classMayBeInterface(HintContext context) {
    final ClassTree cls = (ClassTree) context.getPath().getLeaf();
    final TreeUtilities treeUtilities = context.getInfo().getTreeUtilities();
    if (treeUtilities.isClass(cls) && testClassMayBeInterface(context.getInfo().getTrees(), treeUtilities, context.getPath())) {
        return ErrorDescriptionFactory.forName(context, cls, NbBundle.getMessage(ClassStructure.class, "MSG_ClassMayBeInterface", cls.getSimpleName()), //NOI18N
                new ConvertClassToInterfaceFixImpl(TreePathHandle.create(context.getPath(), context.getInfo()), NbBundle.getMessage(ClassStructure.class, "FIX_ConvertClassToInterface", cls.getSimpleName())).toEditorFix()); //NOI18N
    }
    return null;
}
 
Example #24
Source File: AnnotationHolder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<ErrorDescription> getErrorsForLine(Position line, boolean create) {
    List<ErrorDescription> errors = line2Errors.get(line);

    if (errors == null && create) {
        line2Errors.put(line, errors = new ArrayList<ErrorDescription>());
    }

    if (errors != null && errors.isEmpty() && !create) {
        //clean:
        line2Errors.remove(line);
        errors = null;
    }

    return errors;
}
 
Example #25
Source File: AnnotationHolderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testComputeHighlightsTwoLayers1() throws Exception {
    ErrorDescription ed1 = ErrorDescriptionFactory.createErrorDescription(Severity.ERROR, "1", file, 1, 3);
    ErrorDescription ed2 = ErrorDescriptionFactory.createErrorDescription(Severity.WARNING, "2", file, 5, 7);
    
    List<ErrorDescription> errors = Arrays.asList(ed1, ed2);
    final OffsetsBag bag = AnnotationHolder.computeHighlights(doc, errors);
    
    assertHighlights("",bag, new int[] {1, 3, 5, 7}, new AttributeSet[] {AnnotationHolder.getColoring(ERROR, doc), AnnotationHolder.getColoring(WARNING, doc)});
}
 
Example #26
Source File: CdiEditorAnalysisFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static ErrorDescription createNotification( Severity severity, 
        VariableElement element, ExecutableElement parent , 
        WebBeansModel model, CompilationInfo info ,String description, Fix fix)
{
    VariableElement var = resolveParameter(element, parent, info);
    if ( var == null ){
        return null;
    }
    Tree elementTree = info.getTrees().getTree(var);
    return createNotification(severity, elementTree, info, description, fix );
}
 
Example #27
Source File: Ifs.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(displayName="#DN_ToOrIf", description="#DESC_ToOrIf", category="suggestions", hintKind=Hint.Kind.ACTION)
@TriggerPattern("if ($cond1) $then; else if ($cond2) $then; else $else$;")
@Messages({"ERR_ToOrIf=",
           "FIX_ToOrIf=Join ifs using ||"})
public static ErrorDescription toOrIf(HintContext ctx) {
    SourcePositions sp = ctx.getInfo().getTrees().getSourcePositions();
    CompilationUnitTree cut = ctx.getInfo().getCompilationUnit();
    boolean caretAccepted = ctx.getCaretLocation() <= sp.getStartPosition(cut, ctx.getPath().getLeaf()) + 2 || caretInsideToLevelElseKeyword(ctx);
    if (!caretAccepted) return null;
    return ErrorDescriptionFactory.forSpan(ctx, ctx.getCaretLocation(), ctx.getCaretLocation(), Bundle.ERR_ToOrIf(), JavaFixUtilities.rewriteFix(ctx, Bundle.FIX_ToOrIf(), ctx.getPath(), "if ($cond1 || $cond2) $then; else $else$;"));
}
 
Example #28
Source File: ErrorDescriptionFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static ErrorDescription forTree(HintContext context, Tree tree, String text, Fix... fixes) {
    int start;
    int end;
    int javacEnd;
    
    if (context.getHintMetadata().kind == Hint.Kind.INSPECTION) {
        start = (int) context.getInfo().getTrees().getSourcePositions().getStartPosition(context.getInfo().getCompilationUnit(), tree);
        javacEnd = (int) context.getInfo().getTrees().getSourcePositions().getEndPosition(context.getInfo().getCompilationUnit(), tree);
        end = Math.min(javacEnd, findLineEnd(context.getInfo(), start));
    } else {
        start = javacEnd = end = context.getCaretLocation();
    }

    if (start != (-1) && end != (-1)) {
        if (start > end) {
            LOG.log(Level.WARNING, "Wrong positions reported for tree (start = {0}, end = {1}): {2}",
                new Object[] {
                    start, end, 
                    tree
                }
            );
        }
        LazyFixList fixesForED = org.netbeans.spi.editor.hints.ErrorDescriptionFactory.lazyListForFixes(resolveDefaultFixes(context, fixes));
        return org.netbeans.spi.editor.hints.ErrorDescriptionFactory.createErrorDescription("text/x-java:" + context.getHintMetadata().id, context.getSeverity(), text, context.getHintMetadata().description, fixesForED, context.getInfo().getFileObject(), start, end);
    }
    return null;
}
 
Example #29
Source File: ErrorPositionRefresherHelper.java    From netbeans with 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 #30
Source File: HintTestTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription hint(HintContext ctx) {
    if (ctx.getInfo().getClasspathInfo().getClassPath(PathKind.SOURCE).findOwnerRoot(ctx.getInfo().getFileObject()) == null) {
        return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), "Broken Source Path");
    }

    return null;
}