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

The following examples show how to use org.netbeans.spi.editor.hints.Fix. 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: AnnotationProcessors.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a fix that changes the annotation to the current project's source
 * level.
 * @param target the target source version
 * @return 
 */
@NbBundle.Messages({
    "# {0} - project source level",
    "FIX_AnnoProcessor_UseProjectSourceLevel=Use the project's source level ({0})",
    "# {0} - the target level",
    "FIX_AnnoProcessor_SpecificSourceLevel=Use the source level {0}"
})
static Fix changeToCurrentSource(HintContext ctx, ProcessorHintSupport support, SourceVersion target) {
    TreePath rewriteAt = support.findSupportedAnnotation();
    if (rewriteAt == null) {
        return null;
    }
    String msg = ctx.getInfo().getSourceVersion().compareTo(target) == 0 ?
            Bundle.FIX_AnnoProcessor_SpecificSourceLevel(levelToString(target)) :
            Bundle.FIX_AnnoProcessor_UseProjectSourceLevel(levelToString(target));
    return JavaFixUtilities.rewriteFix(ctx, msg, rewriteAt, 
            "@javax.annotation.processing.SupportedSourceVersion(javax.lang.model.SourceVersion." + 
                    target.name() + ")");
}
 
Example #2
Source File: WSHintsTestBase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected final void testRule(Rule<? extends Element> instance, String testFile) throws IOException {
    System.out.println("Executing " + getName());
    System.out.println("Checking rule " + instance.getClass().getSimpleName());
    context.setFileObject(dataDir.getFileObject(testFile));
    JavaSource testSource = JavaSource.forFileObject(context.getFileObject());
    testSource.runUserActionTask(testTask, true);
    assertFalse("Expected non empty hints list.", ruleEngine.getProblemsFound().isEmpty());
    for(ErrorDescription ed:ruleEngine.getProblemsFound()) {
        for(Fix fix:ed.getFixes().getFixes()) {
            try {
                fix.implement();
            } catch (Exception ex) {
                log(ex.getLocalizedMessage());
            }
        }
    }
    testSource.runUserActionTask(testTask, true);
    assertTrue("Expected empty hints list.", ruleEngine.getProblemsFound().isEmpty());
}
 
Example #3
Source File: AddOrRemoveFinalModifier.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public List<Fix> run(CompilationInfo compilationInfo, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    Tree leaf = treePath.getLeaf();

    if (leaf.getKind() == Kind.IDENTIFIER) {
        Element el = compilationInfo.getTrees().getElement(treePath);
        if (el == null) {
            return null;
        }
        TreePath declaration = compilationInfo.getTrees().getPath(el);
        
        // do not offer any modifications for members in other CUs
        if (declaration != null && declaration.getCompilationUnit() == compilationInfo.getCompilationUnit()) {
            return Collections.singletonList((Fix) new FixImpl(compilationInfo.getFileObject(), el.getSimpleName().toString(), TreePathHandle.create(declaration, compilationInfo), fixDescription, type));
        }
    }
    
    return Collections.<Fix>emptyList();
}
 
Example #4
Source File: JavaFixUtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void performArithmeticTest(String orig, String nue) throws Exception {
    String code = replace("0");

    prepareTest("Test.java", code);
    ClassTree clazz = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0);
    VariableTree variable = (VariableTree) clazz.getMembers().get(1);
    ExpressionTree init = variable.getInitializer();
    TreePath tp = new TreePath(new TreePath(new TreePath(new TreePath(info.getCompilationUnit()), clazz), variable), init);
    Fix fix = JavaFixUtilities.rewriteFix(info, "A", tp, orig, Collections.<String, TreePath>emptyMap(), Collections.<String, Collection<? extends TreePath>>emptyMap(), Collections.<String, String>emptyMap(), Collections.<String, TypeMirror>emptyMap(), Collections.<String, String>emptyMap());
    fix.implement();

    String golden = replace(nue);
    String out = doc.getText(0, doc.getLength());

    assertEquals(golden, out);

    LifecycleManager.getDefault().saveAll();
}
 
Example #5
Source File: InvalidWebMethodAnnotation.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected ErrorDescription[] apply(ExecutableElement subject, ProblemContext ctx) {
    AnnotationMirror methodAnn = Utilities.findAnnotation(subject, ANNOTATION_WEBMETHOD);

    Element classEl = subject.getEnclosingElement();
    if (classEl != null) {
        AnnotationMirror serviceAnn = Utilities.findAnnotation(classEl, ANNOTATION_WEBSERVICE);
        if (serviceAnn != null) {
            AnnotationValue val = Utilities.getAnnotationAttrValue
                    (serviceAnn, ANNOTATION_ATTRIBUTE_SEI);
            if (val != null) {
                String label = NbBundle.getMessage(InvalidWebMethodAnnotation.class,
                        "MSG_WebMethod_NotAllowed");
                Fix fix = new RemoveAnnotation(ctx.getFileObject(),
                        subject, methodAnn);
                Tree problemTree = ctx.getCompilationInfo().getTrees().getTree(subject, methodAnn);
                ctx.setElementToAnnotate(problemTree);
                ErrorDescription problem = createProblem(subject, ctx, label, fix);
                ctx.setElementToAnnotate(null);
                return new ErrorDescription[]{problem};
            }
        }
    }
    return null;
}
 
Example #6
Source File: ListCompletionView.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void renderHtml(Fix f, Graphics g, Font defaultFont, Color defaultColor,
int width, int height, boolean selected) {
    if (icon != null) {
        // The image of the ImageIcon should already be loaded
        // so no ImageObserver should be necessary
        g.drawImage(ImageUtilities.icon2Image(icon), BEFORE_ICON_GAP, (height - icon.getIconHeight()) /2, this);
    }
    int iconWidth = BEFORE_ICON_GAP + icon.getIconWidth() + AFTER_ICON_GAP;
    int textEnd = width - AFTER_ICON_GAP - subMenuIcon.getIconWidth() - AFTER_TEXT_GAP;
    FontMetrics fm = g.getFontMetrics(defaultFont);
    int textY = (height - fm.getHeight())/2 + fm.getHeight() - fm.getDescent();

    // Render left text
    if (textEnd > iconWidth) { // any space for left text?
        HtmlRenderer.renderHTML(f.getText(), g, iconWidth, textY, textEnd, textY,
            defaultFont, defaultColor, HtmlRenderer.STYLE_TRUNCATE, true);//, selected);
    }

    if (HintsControllerImpl.getSubfixes(f).iterator().hasNext()) {
        paintArrowIcon(g, textEnd + AFTER_TEXT_GAP, (height - subMenuIcon.getIconHeight()) /2);
    }
}
 
Example #7
Source File: ErrorDescriptionFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static ErrorDescription forName(HintContext context, Tree tree, String text, Fix... fixes) {
    int[] span;
    
    if (context.getHintMetadata().kind == Hint.Kind.INSPECTION) {
        span = computeNameSpan(tree, context);
    } else {
        span = new int[] {context.getCaretLocation(), context.getCaretLocation()};
    }
    
    if (span != null && span[0] != (-1) && span[1] != (-1)) {
        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(), span[0], span[1]);
    }

    return null;
}
 
Example #8
Source File: AddCast.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    List<Fix> result = new ArrayList<Fix>();
    List<TypeMirror> targetType = new ArrayList<TypeMirror>();
    TreePath[] tmTree = new TreePath[1];
    ExpressionTree[] expression = new ExpressionTree[1];
    Tree[] leaf = new Tree[1];
    
    computeType(info, offset, targetType, tmTree, expression, leaf);
    
    if (!targetType.isEmpty()) {
        TreePath expressionPath = TreePath.getPath(info.getCompilationUnit(), expression[0]); //XXX: performance
        for (TypeMirror type : targetType) {
            if (type.getKind() != TypeKind.NULL) {
                result.add(new AddCastFix(info, expressionPath, tmTree[0], type).toEditorFix());
            }
        }
    }
    
    return result;
}
 
Example #9
Source File: EnablePreviewMavenProj.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
@NonNull
public List<Fix> run(CompilationInfo compilationInfo, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {

    if (SourceVersion.latest() != compilationInfo.getSourceVersion()) {
        return Collections.<Fix>emptyList();
    }

    Fix fix = null;
    final FileObject file = compilationInfo.getFileObject();
    if (file != null) {
        final Project prj = FileOwnerQuery.getOwner(file);
        if (isMavenProject(prj)) {
            fix = new EnablePreviewMavenProj.ResolveMvnFix(prj);
        } else {
            fix = null;
        }

    }
    return (fix != null) ? Collections.<Fix>singletonList(fix) : Collections.<Fix>emptyList();
}
 
Example #10
Source File: ConvertTextBlockToString.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@TriggerTreeKind(Tree.Kind.STRING_LITERAL)
@Messages("ERR_ConvertTextBlockToString=Text block may not be supported")//NOI18N
public static ErrorDescription computeWarning(HintContext ctx) {
    TokenSequence<?> ts = ctx.getInfo().getTokenHierarchy().tokenSequence();
    if (ts == null) {
        return null;
    }
    int textBlockIndex = (int) ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getPath().getCompilationUnit(), ctx.getPath().getLeaf());
    if (textBlockIndex == -1) {
        return null;
    }
    ts.move(textBlockIndex);

    if (!ts.moveNext() || ts.token().id() != JavaTokenId.MULTILINE_STRING_LITERAL) {
        return null;
    }

    String orignalString = (String) ((LiteralTree) ctx.getPath().getLeaf()).getValue();
    String orignalStringArr[] = textBlockToStringArr(orignalString);
    Fix fix = new FixImpl(ctx.getInfo(), ctx.getPath(), orignalStringArr).toEditorFix();
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_ConvertTextBlockToString(), fix);
}
 
Example #11
Source File: ReturnEncapsulation.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Fix fixFor(final HintContext ctx, ExecutableElement enclMethod, final TreePath tp) {
    CompilationInfo info = ctx.getInfo();
    
    assert info != null;
    assert tp != null;
    Element fe = info.getTrees().getElement(tp);
    if (fe == null) {
        return null;
    }
    String field = fe.getSimpleName().toString();
    final Types types = info.getTypes();
    final Elements elements = info.getElements();
    TypeMirror returnTypeEr = types.erasure(enclMethod.getReturnType());

    for (Entry<String, String> e : TO_UNMODIFIABLE.entrySet()) {
        TypeElement el = elements.getTypeElement(e.getKey());
        if (el != null && types.isSameType(returnTypeEr, types.erasure(el.asType()))) {
            return JavaFixUtilities.rewriteFix(ctx, NbBundle.getMessage(ReturnEncapsulation.class, "FIX_ReplaceWithUC",e.getValue(),field), tp, "java.util.Collections." + e.getValue() + "($expr)");
        }
    }
    return null;
}
 
Example #12
Source File: InterfaceEndpointInterface.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override public ErrorDescription[] apply(TypeElement subject, ProblemContext ctx){
    if(subject.getKind() == ElementKind.INTERFACE) {
        AnnotationMirror annEntity = Utilities.findAnnotation(subject,ANNOTATION_WEBSERVICE);
        AnnotationTree annotationTree = (AnnotationTree) ctx.getCompilationInfo().
                getTrees().getTree(subject, annEntity);
        //endpointInterface not allowed
        if(Utilities.getAnnotationAttrValue(annEntity, ANNOTATION_ATTRIBUTE_SEI)!=null) {
            String label = NbBundle.getMessage(InterfaceEndpointInterface.class, "MSG_IF_SEINotAllowed");
            Fix fix = new RemoveAnnotationArgument(ctx.getFileObject(),
                    subject, annEntity, ANNOTATION_ATTRIBUTE_SEI);
            Tree problemTree = Utilities.getAnnotationArgumentTree(annotationTree, ANNOTATION_ATTRIBUTE_SEI);
            ctx.setElementToAnnotate(problemTree);
            ErrorDescription problem = createProblem(subject, ctx, label, fix);
            ctx.setElementToAnnotate(null);
            return new ErrorDescription[]{problem};
        }
    }        
    return null;
}
 
Example #13
Source File: ClassNameMismatch.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    FileObject file = info.getFileObject();
    
    if (!file.getParent().canWrite()) return Collections.emptyList();

    //testcase unknown, bug #235033:
    if (!TreeUtilities.CLASS_TREE_KINDS.contains(treePath.getLeaf().getKind())) return Collections.emptyList();
    
    return Arrays.<Fix>asList(new RenameFile(file, ((ClassTree) treePath.getLeaf()).getSimpleName().toString()));
}
 
Example #14
Source File: HasNoArgContructor.java    From netbeans with 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 || ctx.getEjb() == null) {
        return Collections.emptyList();
    }

    boolean hasDefaultContructor = true;
    for (ExecutableElement constr : ElementFilter.constructorsIn(ctx.getClazz().getEnclosedElements())) {
        hasDefaultContructor = false;
        if (constr.getParameters().isEmpty()
                && (constr.getModifiers().contains(Modifier.PUBLIC)
                || constr.getModifiers().contains(Modifier.PROTECTED))) {
            return Collections.emptyList(); // found appropriate constructor
        }
    }

    if (hasDefaultContructor) {
        return Collections.emptyList(); // OK
    }

    Fix fix = new CreateDefaultConstructor(ctx.getFileObject(), ElementHandle.create(ctx.getClazz()));
    ErrorDescription err = HintsUtils.createProblem(ctx.getClazz(), hintContext.getInfo(),
            Bundle.HasNoArgContructor_err(), fix);

    return Collections.singletonList(err);
}
 
Example #15
Source File: RenameConstructorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected String toDebugString(CompilationInfo info, Fix f) {
    if (f instanceof RenameConstructorFix) {
        return ((RenameConstructorFix) f).toDebugString();
    }
    return super.toDebugString(info, f);
}
 
Example #16
Source File: RemoveUselessCast.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    TreePath path = info.getTreeUtilities().pathFor(offset + 1);
    
    if (path != null && path.getLeaf().getKind() == Kind.TYPE_CAST) {
        return Collections.singletonList(new FixImpl(info, path).toEditorFix());
    }
    
    return Collections.<Fix>emptyList();
}
 
Example #17
Source File: CreatorBasedLazyFixList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public synchronized List<Fix> getFixes() {
    if (!computed && !computing) {
        LazyHintComputationFactory.addToCompute(file, this);
        computing = true;
    }
    return fixes;
}
 
Example #18
Source File: RulesManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Collection<? extends ErrorDescription> createErrors(HintContext ctx) {
    currentHintPreferences.set(new LegacyHintConfiguration(true, ctx.getSeverity(), ctx.getPreferences()));
    Collection<? extends ErrorDescription> result = tr.run(ctx.getInfo(), ctx.getPath());
    currentHintPreferences.set(null); //XXX: in finally

    if (result == null) return result;

    Collection<ErrorDescription> wrapped = new LinkedList<ErrorDescription>();
    String id = tr instanceof AbstractHint ? ((AbstractHint) tr).getId() : "no-id";
    String description = tr instanceof AbstractHint ? ((AbstractHint) tr).getDescription() : null;

    for (ErrorDescription ed : result) {
        if (ed == null || ed.getRange() == null) continue;
        if (!ctx.getInfo().getFileObject().equals(ed.getFile())) {
            LOG.log(Level.SEVERE, "Got an ErrorDescription for different file, current file: {0}, error's file: {1}", new Object[] {ctx.getInfo().getFileObject().toURI(), ed.getFile().toURI()});
            continue;
        }
        List<Fix> fixesForED = JavaFixImpl.Accessor.INSTANCE.resolveDefaultFixes(ctx, ed.getFixes().getFixes().toArray(new Fix[0]));

        ErrorDescription nue = createErrorDescription("text/x-java:" + id,
                                                      ed.getSeverity(),
                                                      ed.getDescription(),
                                                      description,
                                                      org.netbeans.spi.editor.hints.ErrorDescriptionFactory.lazyListForFixes(fixesForED),
                                                      ed.getFile(),
                                                      ed.getRange());
        wrapped.add(nue);
    }

    return wrapped;
}
 
Example #19
Source File: MagicSurroundWithTryCatchFixTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void test207480() throws Exception {
    prepareTest("test/Test.java",
                "package test; import java.io.*; public class Test { public void getTestCase(URL url) throws FileNotFoundException { try(Reader r = new FileReader(\"\")) { } } }");
    
    int pos = positionForErrors();
    TreePath path = info.getTreeUtilities().pathFor(pos);
    
    List<Fix> fixes = computeFixes(info, pos, path);
    
    for (Fix e : fixes) {
        if (e instanceof MagicSurroundWithTryCatchFix) {
            fail ("Should not provide the MagicSurroundWithTryCatchFix!");
        }
    }
}
 
Example #20
Source File: MathRandomCast.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerPatterns(value = {
    @TriggerPattern(value = "(int)java.lang.Math.random()"),
    @TriggerPattern(value = "(int)java.lang.StrictMath.random()"),
    @TriggerPattern(value = "(long)java.lang.Math.random()"),
    @TriggerPattern(value = "(long)java.lang.StrictMath.random()"),

    @TriggerPattern(value = "(java.lang.Integer)java.lang.Math.random()"),
    @TriggerPattern(value = "(java.lang.Integer)java.lang.StrictMath.random()"),
    @TriggerPattern(value = "(java.lang.Long)java.lang.Math.random()"),
    @TriggerPattern(value = "(java.lang.Long)java.lang.StrictMath.random()")
})
public static ErrorDescription mathRandomCast(HintContext ctx) {
    TreePath path = ctx.getPath();

    if (path.getLeaf().getKind() != Tree.Kind.TYPE_CAST) {
        return null;
    }
    
    // traverse up to the expression chain
    TreePath expr = path;
    for (TreePath parent = path.getParentPath(); parent != null && EXPRESSION_KINDS.contains(parent.getLeaf().getKind()); parent = parent.getParentPath()) {
        expr = parent;
    }
    Fix fix = null;
    
    // do not provide hints if the cast was immediately used in a method call, assignment etc
    if (expr != path) {
        fix = new FixImpl(
                TreePathHandle.create(ctx.getPath(), ctx.getInfo()),
                TreePathHandle.create(expr, ctx.getInfo())).toEditorFix();
    }
    return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), TEXT_MathRandomCastInt(), fix);
}
 
Example #21
Source File: HintsTests.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public List<Fix> getFixes(FileObject fileToTest) {
    fixes = new ArrayList<Fix>();
    for (ErrorDescription errorDescription : getProblems(fileToTest)) {
        fixes.addAll(errorDescription.getFixes().getFixes());
    }
    Collections.sort(fixes, new Comparator<Fix>() {

        public int compare(Fix o1, Fix o2) {
            return o1.getText().compareTo(o2.getText());
        }
    });
    return fixes;
}
 
Example #22
Source File: VarCompDeclaration.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {

    Tree.Kind parentKind = treePath.getParentPath().getLeaf().getKind();
    if (parentKind != Tree.Kind.BLOCK && parentKind != Tree.Kind.CASE) {
        return null;
    }

    return Collections.<Fix>singletonList(new VarCompDeclaration.FixImpl(info, treePath).toEditorFix());
}
 
Example #23
Source File: CreateElement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<Fix> prepareCreateMethodFix(CompilationInfo info, TreePath invocation, Set<Modifier> modifiers, TypeElement target, String simpleName, List<? extends ExpressionTree> arguments, List<? extends TypeMirror> returnTypes) {
       //return type:
       //XXX: should reasonably consider all the found type candidates, not only the one:
       TypeMirror returnType = returnTypes != null ? Utilities.resolveTypeForDeclaration(info, returnTypes.get(0)) : null;

       //currently, we cannot handle error types, TYPEVARs and WILDCARDs:
       if (returnType != null && Utilities.containsErrorsRecursively(returnType)) {
           return Collections.<Fix>emptyList();
       }
       
       //create method:
       MethodArguments formalArguments = Utilities.resolveArguments(info, invocation, arguments, target, returnType);

       //currently, we cannot handle error types, TYPEVARs and WILDCARDs:
       if (formalArguments == null) {
           return Collections.<Fix>emptyList();
       }

      	//IZ 111048 -- don't offer anything if target file isn't writable
if(!Utilities.isTargetWritable(target, info))
    return Collections.<Fix>emptyList();

       FileObject targetFile = SourceUtils.getFile(ElementHandle.create(target), info.getClasspathInfo());
       if (targetFile == null)
           return Collections.<Fix>emptyList();

       return Collections.<Fix>singletonList(new CreateMethodFix(info, simpleName, modifiers, target, returnType, formalArguments.parameterTypes, formalArguments.parameterNames, formalArguments.typeParameterTypes, formalArguments.typeParameterNames, targetFile));
   }
 
Example #24
Source File: IndexOfToContains.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern(value="$site.indexOf($substring) == (-1)", constraints = {
        @ConstraintVariableType(variable = "$substring", type = "java.lang.String"),
        @ConstraintVariableType(variable = "$site", type = "java.lang.String"),
    }),
    @TriggerPattern(value="$site.indexOf($substring) <= (-1)", constraints = {
        @ConstraintVariableType(variable = "$substring", type = "java.lang.String"),
        @ConstraintVariableType(variable = "$site", type = "java.lang.String"),
    }),
    @TriggerPattern(value="$site.indexOf($substring) < (0)", constraints = {
        @ConstraintVariableType(variable = "$substring", type = "java.lang.String"),
        @ConstraintVariableType(variable = "$site", type = "java.lang.String"),
    }),
    @TriggerPattern(value="$site.indexOf($substring) == -1", constraints = {
        @ConstraintVariableType(variable = "$substring", type = "java.lang.String"),
        @ConstraintVariableType(variable = "$site", type = "java.lang.String"),
    }),
    @TriggerPattern(value="$site.indexOf($substring) <= -1", constraints = {
        @ConstraintVariableType(variable = "$substring", type = "java.lang.String"),
        @ConstraintVariableType(variable = "$site", type = "java.lang.String"),
    }),
    @TriggerPattern(value="$site.indexOf($substring) < 0", constraints = {
        @ConstraintVariableType(variable = "$substring", type = "java.lang.String"),
        @ConstraintVariableType(variable = "$site", type = "java.lang.String"),
    })
})
public static ErrorDescription notContainsForIndexOf(HintContext ctx) {
    String target = "!$site.contains($substring)";
    
    Fix fix = JavaFixUtilities.rewriteFix(ctx, Bundle.FIX_containsForIndexOf(), ctx.getPath(), target);
    
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_containsForIndexOf(), fix);
}
 
Example #25
Source File: ProfilesAnalyzer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NbBundle.Messages ({
    "MSG_ProjectHigherProfile=Project requires profile: {0}",
    "DESC_ProjectHigherProfile=The project {0} located in {1} requires profile: {2}",
})
private static void verifySubProjects(
    @NonNull final Collection<? extends Project> projectRefs,
    @NonNull final Project owner,
    @NonNull final SourceLevelQuery.Profile profile,
    @NonNull final Result result) {
    for (Project p : projectRefs) {
        final FileObject pHome = p.getProjectDirectory();
        final SourceLevelQuery.Profile pProfile = SourceLevelQuery.getSourceLevel2(pHome).getProfile();
        if (pProfile.compareTo(profile) > 0) {
            result.reportError(owner, ErrorDescriptionFactory.createErrorDescription(
                    null,
                    Severity.ERROR,
                    Bundle.MSG_ProjectHigherProfile(pProfile.getDisplayName()),
                    Bundle.DESC_ProjectHigherProfile(
                        ProjectUtils.getInformation(p).getDisplayName(),
                        FileUtil.getFileDisplayName(pHome),
                        profile.getDisplayName()),
                    ErrorDescriptionFactory.lazyListForFixes(Collections.<Fix>emptyList()),
                    p.getProjectDirectory(),
                    null));
        }
    }
}
 
Example #26
Source File: CreateMethodTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Fix> computeFixes(CompilationInfo info, String diagnosticCode, int pos, TreePath path) throws Exception {
    List<Fix> fixes = new CreateElement().analyze(info, diagnosticCode, pos);
    List<Fix> result=  new LinkedList<Fix>();
    
    for (Fix f : fixes) {
        if (f instanceof CreateMethodFix)
            result.add(f);
    }
    
    return result;
}
 
Example #27
Source File: JavaxFacesBeanIsGonnaBeDeprecated.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<Fix> getFixesForType(CompilationInfo info, TypeElement typeElement, AnnotationMirror am) {
    List<Fix> fixes = new ArrayList<>();
    String annotationType = am.getAnnotationType().toString();
    if (DEPRECATED_TO_FIX.containsKey(annotationType)) {
        TreePath path = info.getTrees().getPath(typeElement, am);
        fixes.add(new ChangeClassFix(info, path, typeElement, am, annotationType, DEPRECATED_TO_FIX.get(annotationType)).toEditorFix());
    }
    return fixes;
}
 
Example #28
Source File: RedundantIf.java    From netbeans with 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 #29
Source File: CreateQualifier.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<Fix> createQualifierFix( CompilationInfo compilationInfo,
        Element annotation, Element classElement )
{
    PackageElement packageElement = compilationInfo.getElements()
            .getPackageOf(classElement);
    FileObject targetFile = SourceUtils.getFile(
            ElementHandle.create(classElement),
            compilationInfo.getClasspathInfo());
    return Collections.<Fix> singletonList(new CreateQualifierFix(
            compilationInfo, annotation.getSimpleName().toString(),
            packageElement.getQualifiedName().toString(),
            targetFile));
}
 
Example #30
Source File: HintTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**Verifies that the current warning provides the given fixes.
 *
 * @param fixes the {@link Fix#getText() } of the expected fixes
 * @return itself
 * @throws AssertionError if the expected fixes do not match the provided fixes
 * @since 1.1
 */
public HintWarning assertFixes(String... expectedFixes) throws Exception {
    assertTrue("Must be computed", warning.getFixes().isComputed());

    List<String> fixNames = new LinkedList<String>();

    for (Fix f : warning.getFixes().getFixes()) {
        if (f instanceof SyntheticFix) continue;
        fixNames.add(f.getText());
    }

    assertEquals("Fixes for the current warning do not match the expected fixes. All fixes: " + fixNames.toString(), Arrays.asList(expectedFixes), fixNames);

    return this;
}