Java Code Examples for org.netbeans.api.java.source.CompilationInfo#getFileObject()

The following examples show how to use org.netbeans.api.java.source.CompilationInfo#getFileObject() . 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: 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 2
Source File: EnablePreviewAntProj.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();
    }

    final FileObject file = compilationInfo.getFileObject();
    Fix fix = null;
    if (file != null) {
        final Project prj = FileOwnerQuery.getOwner(file);

        if (isAntProject(prj)) {
            fix = new EnablePreviewAntProj.ResolveAntFix(prj);
        } else {
            fix = null;
        }
    }
    return (fix != null) ? Collections.<Fix>singletonList(fix) : Collections.<Fix>emptyList();
}
 
Example 3
Source File: DiffContext.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public DiffContext(CompilationInfo copy, Set<Tree> syntheticTrees) {
    this.tokenSequence = copy.getTokenHierarchy().tokenSequence(JavaTokenId.language());
    this.mainCode = this.origText = copy.getText();
    this.style = getCodeStyle(copy);
    this.context = JavaSourceAccessor.getINSTANCE().getJavacTask(copy).getContext();
    this.mainUnit = this.origUnit = (JCCompilationUnit) copy.getCompilationUnit();
    this.trees = copy.getTrees();
    this.doc = copy.getSnapshot().getSource().getDocument(false); //TODO: true or false?
    this.positionConverter = copy.getPositionConverter();
    this.file = copy.getFileObject();
    this.syntheticTrees = syntheticTrees;
    
    this.textLength = copy.getSnapshot() == null ? Integer.MAX_VALUE : copy.getSnapshot().getOriginalOffset(copy.getSnapshot().getText().length());
    this.blockSequences = new BlockSequences(this.tokenSequence, doc, textLength);
    
    this.forceInitialComment = false;
}
 
Example 4
Source File: DiffContext.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static final CodeStyle getCodeStyle(CompilationInfo info) {
    if (info != null) {
        try {
            Document doc = info.getDocument();
            if (doc != null) {
                CodeStyle cs = (CodeStyle)doc.getProperty(CodeStyle.class);
                return cs != null ? cs : CodeStyle.getDefault(doc);
            }
        } catch (IOException ioe) {
            // ignore
        }

        FileObject file = info.getFileObject();
        if (file != null) {
            return CodeStyle.getDefault(file);
        }
    }

    return CodeStyle.getDefault((Document)null);
}
 
Example 5
Source File: EnablePreviewSingleSourceFile.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();
    }

    final FileObject file = compilationInfo.getFileObject();

    Fix fix = null;
    if (file != null) {
        final Project prj = FileOwnerQuery.getOwner(file);
        if (prj == null) {
            fix = new EnablePreviewSingleSourceFile.ResolveFix(file);
        } else {
            fix = null;
        }
    }
    return (fix != null) ? Collections.<Fix>singletonList(fix) : Collections.<Fix>emptyList();
}
 
Example 6
Source File: ErrorDescriptionFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Creates a fix, which when invoked adds @SuppresWarnings(keys) to
 * nearest declaration.
 * @param compilationInfo CompilationInfo to work on
 * @param treePath TreePath to a tree. The method will find nearest outer
 *        declaration. (type, method, field or local variable)
 * @param keys keys to be contained in the SuppresWarnings annotation. E.g.
 *        @SuppresWarnings( "key" ) or @SuppresWarnings( {"key1", "key2", ..., "keyN" } ).
 * @throws IllegalArgumentException if keys are null or empty or id no suitable element
 *         to put the annotation on is found (e.g. if TreePath to CompilationUnit is given")
 */
static Fix createSuppressWarningsFix(CompilationInfo compilationInfo, TreePath treePath, String... keys ) {
    Parameters.notNull("compilationInfo", compilationInfo);
    Parameters.notNull("treePath", treePath);
    Parameters.notNull("keys", keys);

    if (keys.length == 0) {
        throw new IllegalArgumentException("key must not be empty"); // NOI18N
    }

    if (!isSuppressWarningsSupported(compilationInfo)) {
        return null;
    }

    while (treePath.getLeaf().getKind() != Kind.COMPILATION_UNIT && !DECLARATION.contains(treePath.getLeaf().getKind())) {
        treePath = treePath.getParentPath();
    }

    if (treePath.getLeaf().getKind() != Kind.COMPILATION_UNIT) {
        return new FixImpl(TreePathHandle.create(treePath, compilationInfo), compilationInfo.getFileObject(), keys);
    } else {
        return null;
    }
}
 
Example 7
Source File: ElementGrip.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ElementGrip(TreePathHandle delegateElementHandle, Element elm, CompilationInfo info) {
        this.delegateElementHandle = delegateElementHandle;
        this.handle = elm == null ? null : ElementHandle.create(elm);
        if (elm != null) {
            if (elm.getKind() == ElementKind.CLASS && elm.getSimpleName().length() == 0) {
                this.toString = ((TypeElement) elm).asType().toString();
                this.icon = ElementIcons.getElementIcon(elm.getKind(), elm.getModifiers());
            } else if(elm.getKind() == ElementKind.ENUM 
                    && elm.getSimpleName().length() == 0
                    && elm.getEnclosingElement() != null) {
                final Element enclosingElement = elm.getEnclosingElement();
                this.toString = enclosingElement.getSimpleName().toString();
                this.icon = ElementIcons.getElementIcon(enclosingElement.getKind(), enclosingElement.getModifiers());
            } else {
                // workaround for issue 171692
                this.toString = elm.getKind() != ElementKind.CONSTRUCTOR
                        ? elm.getSimpleName().toString()
                        : elm.getEnclosingElement().getSimpleName().toString();
                this.icon = ElementIcons.getElementIcon(elm.getKind(), elm.getModifiers());
//            this.toString = ElementHeaders.getHeader(treePath, info, ElementHeaders.NAME);
            }
        }
        this.fileObject = info.getFileObject();
    }
 
Example 8
Source File: IntroduceHint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void run(CompilationInfo info) {
    cancel.set(false);

    FileObject file = info.getFileObject();
    int[] selection = SelectionAwareJavaSourceTaskFactory.getLastSelection(file);

    if (selection == null) {
        //nothing to do....
        HintsController.setErrors(info.getFileObject(), IntroduceHint.class.getName(), Collections.<ErrorDescription>emptyList());
    } else {
        HintsController.setErrors(info.getFileObject(), IntroduceHint.class.getName(), computeError(info, selection[0], selection[1], null, new EnumMap<IntroduceKind, String>(IntroduceKind.class), cancel));

        Document doc = info.getSnapshot().getSource().getDocument(false);

        if (doc != null) {
            PositionRefresherHelperImpl.setVersion(doc, selection[0], selection[1]);
        }
    }
}
 
Example 9
Source File: GeneratorUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static CodeStyle getCodeStyle(CompilationInfo info) {
    if (info != null) {
        try {
            Document doc = info.getDocument();
            if (doc != null) {
                CodeStyle cs = (CodeStyle)doc.getProperty(CodeStyle.class);
                return cs != null ? cs : CodeStyle.getDefault(doc);
            }
        } catch (IOException ioe) {
            // ignore
        }
        
        FileObject file = info.getFileObject();
        if (file != null) {
            return CodeStyle.getDefault(file);
        }
    }
    
    return CodeStyle.getDefault((Document)null);
}
 
Example 10
Source File: ConvertAnonymousToInner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static Fix computeFix(CompilationInfo info, int selStart, int selEnd, boolean onlyHeader) {
    TreePath tp = findNCT(info, info.getTreeUtilities().pathFor((selStart + selEnd + 1) / 2), selStart, selEnd, onlyHeader);

    if (tp == null) {
        tp = findNCT(info, info.getTreeUtilities().pathFor((selStart + selEnd + 1) / 2 + 1), selStart, selEnd, onlyHeader);
    }
    
    if (tp == null) {
        return null;
    }
    
    return new FixImpl(TreePathHandle.create(tp, info), info.getJavaSource(), info.getFileObject());
}
 
Example 11
Source File: ElementJavadoc.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ElementJavadoc(CompilationInfo compilationInfo, Element element, final URL url, final Callable<Boolean> cancel) {
    this.cpInfo = compilationInfo.getClasspathInfo();
    this.fileObject = compilationInfo.getFileObject();
    this.handle = element == null ? null : ElementHandle.create(element);
    this.cancel = cancel;
    final StringBuilder header = getElementHeader(element, compilationInfo);
    try {
        //Optimisitic no http
        CharSequence doc = getElementDoc(element, compilationInfo, header, url, true);
        if (doc == null) {
            computeDocURL(Collections.emptyList(), true, cancel);
            doc = header.append(noJavadocFound());
        }
        this.content = new Now(doc.toString());
    } catch (JavadocHelper.RemoteJavadocException re) {
        if (fileObject == null || JavaSource.forFileObject(fileObject) == null) {
            header.append(noJavadocFound());
            this.content = new Now(header.toString());
            return;
        }
        this.content = new FutureTask<>(() -> {
            final JavaSourceUtil.Handle ch = JavaSourceUtil.createControllerHandle(fileObject, null);
            final CompilationController c = (CompilationController) ch.getCompilationController();
            c.toPhase(Phase.RESOLVED);
            final Element el = handle.resolve(c);
            CharSequence doc = getElementDoc(el, c, header, url, false);
            if (doc == null) {
                computeDocURL(Collections.emptyList(), false, cancel);
                doc = header.append(noJavadocFound());
            }
            return doc.toString();
        });
        RP.post((Runnable)this.content);
    }
}
 
Example 12
Source File: Analyzer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
Analyzer(CompilationInfo javac, TreePath currentPath, Access access, HintContext ctx) {
    this.javac = javac;
    this.file = javac.getFileObject();
    this.currentPath = currentPath;
    this.sourceVersion = resolveSourceVersion(javac.getFileObject());
    this.access = access;
    this.ctx = ctx;
}
 
Example 13
Source File: AsyncConverterTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void run( CompilationInfo compilationInfo ) throws Exception {
    FileObject fileObject = compilationInfo.getFileObject();
    
    if( !isApplicable(fileObject)){
        return;
    }
    
    AsyncHintsTask task = new AsyncHintsTask(compilationInfo);
    runTask.set(task);
    task.run();
    runTask.compareAndSet(task, null);
    HintsController.setErrors(fileObject, "REST Async Converter",         // NOI18N 
            task.getDescriptions()); 
}
 
Example 14
Source File: WhereUsedElement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static WhereUsedElement create(int start, int end, CompilationInfo compiler, boolean inTest, boolean inPlatform, boolean inDependency) {
    CharSequence content = compiler.getSnapshot().getText();
    LineMap lm = compiler.getCompilationUnit().getLineMap();
    long line = lm.getLineNumber(start);
    long endLine = lm.getLineNumber(end);
    long sta = lm.getStartPosition(line);
    int eof = content.length();
    long lastLine = lm.getLineNumber(eof);
    long en = lastLine > endLine ? lm.getStartPosition(endLine + 1) - 1 : eof;
    StringBuilder sb = new StringBuilder();
    sb.append(UIUtilities.getHtml(trimStart(content.subSequence((int) sta, start).toString())));
    sb.append("<b>"); //NOI18N
    sb.append(content.subSequence(start, end));
    sb.append("</b>");//NOI18N
    sb.append(UIUtilities.getHtml(trimEnd(content.subSequence(end, (int) en).toString())));
    
    DataObject dob = null;
    try {
        dob = DataObject.find(compiler.getFileObject());
    } catch (DataObjectNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    }
    CloneableEditorSupport ces = JavaWhereUsedQueryPlugin.findCloneableEditorSupport(dob);
    PositionRef ref1 = ces.createPositionRef(start, Bias.Forward);
    PositionRef ref2 = ces.createPositionRef(end, Bias.Forward);
    PositionBounds bounds = new PositionBounds(ref1, ref2);
    return new WhereUsedElement(bounds, sb.toString().trim(),
            content.subSequence((int)sta, (int)en).toString(),
            compiler.getFileObject(), null, compiler, null, inTest, inPlatform, inDependency, true, false);
}
 
Example 15
Source File: TopClassFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean passes(TypeElement topClass,
                      CompilationInfo compInfo) {
    if (!super.passes(topClass, compInfo)) {
        return false;
    }

    FileObject javaFileObj = compInfo.getFileObject();
    ClassPath sourceCP = compInfo.getClasspathInfo().getClassPath(PathKind.SOURCE);
    String qualifiedClassName = topClass.getQualifiedName().toString();
    return qualifiedClassName.equals(sourceCP.getResourceName(javaFileObj, '.', false));
}
 
Example 16
Source File: TopClassFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean passes(TypeElement topClass,
                      CompilationInfo compInfo) {
    if (!super.passes(topClass, compInfo)) {
        return false;
    }

    FileObject javaFileObj = compInfo.getFileObject();
    ClassPath sourceCP = compInfo.getClasspathInfo().getClassPath(PathKind.SOURCE);
    String qualifiedClassName = topClass.getQualifiedName().toString();
    return qualifiedClassName.equals(sourceCP.getResourceName(javaFileObj, '.', false));
}
 
Example 17
Source File: WebSocketMethodsTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void run(CompilationInfo compilationInfo) throws Exception {
    FileObject fileObject = compilationInfo.getFileObject();

    if (!isApplicable(fileObject)) {
        return;
    }

    WebSocketTask task = new WebSocketTask(compilationInfo);
    runTask.set(task);
    task.run();
    runTask.compareAndSet(task, null);
    HintsController.setErrors(fileObject, "WebSocket Methods Scanner", // NOI18N
            task.getDescriptions());
}
 
Example 18
Source File: ElementScanningTaskFactory.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
@Override
public void run(CompilationInfo p) throws Exception {
    final CompilationUnitTree compilationUnitTree = p.getCompilationUnit();
    final TreePath rootPath = new TreePath(compilationUnitTree);
    mappedElementExtractor = new MappedElementExtractor(p.getFileObject(), compilationUnitTree, p.getTrees(), rootPath);
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            targetModel.refresh(compilationUnitTree.accept(mappedElementExtractor, null));
            table.setModel(targetModel);
        }
    });
}
 
Example 19
Source File: ErrorHintsProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
ErrorDescription processRule(CompilationInfo info, Integer forPosition, Diagnostic d, String code, Map<String, List<ErrorRule>> code2Rules,
        Map<Class, Data> data, Document doc, boolean processDefault) throws IOException {
    List<ErrorRule> rules = code2Rules.get(code);
    List<ErrorRule> allRules = rules == null ? new ArrayList<ErrorRule>() : new ArrayList<>(rules);
    List<ErrorRule> catchAllRules = code2Rules.get("*");
    if (catchAllRules != null) {
        allRules.addAll(catchAllRules);
    }

    if (ERR.isLoggable(ErrorManager.INFORMATIONAL)) {
        ERR.log(ErrorManager.INFORMATIONAL, "code= " + code);
        ERR.log(ErrorManager.INFORMATIONAL, "rules = " + rules);
    }

    LazyFixList ehm;
    String desc = d.getMessage(null);

    int pos = (int) getPrefferedPosition(info, d);
    TreePath path = info.getTreeUtilities().pathFor(pos + 1);
    Data ruleData = new Data();
    
    int messageRuleCount = 0;
    for (ErrorRule r : allRules) {
        if (!(r instanceof OverrideErrorMessage)) {
            continue;
        }
        OverrideErrorMessage rcm = (OverrideErrorMessage) r;
        Data rd = data.get(rcm.getClass());
        if (rd == null) {
            rd = ruleData;
        }
        String msg = rcm.createMessage(info, d, pos, path, rd);
        if (msg != null) {
            if (msg.isEmpty()) {
                // ignore the error
                return null;
            }
            desc = msg;
            break;
        }
        if (rd.getData() != null) {
            data.put(rcm.getClass(), rd);
            ruleData = new Data();
        }
    }
    if (messageRuleCount < allRules.size()) {
        ehm = new CreatorBasedLazyFixList(info.getFileObject(), code, pos, allRules, data);
    } else if (processDefault) {
        ehm = ErrorDescriptionFactory.lazyListForFixes(Collections.<Fix>emptyList());
    } else {
        return null;
    }
    if (ERR.isLoggable(ErrorManager.INFORMATIONAL)) {
        ERR.log(ErrorManager.INFORMATIONAL, "ehm=" + ehm);
    }

    final Position[] range = getLine(info, d, doc, (int) getPrefferedPosition(info, d), (int) d.getEndPosition());

    if (isCanceled()) {
        return null;
    }

    if (range == null || range[0] == null || range[1] == null) {
        return null;
    }

    if (forPosition != null) {
        try {
            int posRowStart = org.netbeans.editor.Utilities.getRowStart((NbEditorDocument) doc, forPosition);
            int errRowStart = org.netbeans.editor.Utilities.getRowStart((NbEditorDocument) doc, range[0].getOffset());
            if (posRowStart != errRowStart) {
                return null;
            }
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    return ErrorDescriptionFactory.createErrorDescription(errorKind2Severity.get(d.getKind()), desc, ehm, doc, range[0], range[1]);
}
 
Example 20
Source File: ComputeOverriders.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Map<ElementHandle<? extends Element>, List<ElementDescription>> processImpl(CompilationInfo info, TypeElement te, ExecutableElement ee, boolean interactive) {
        FileObject file = info.getFileObject();
        FileObject thisSourceRoot;
        if (te != null ) {
            thisSourceRoot = findSourceRoot(SourceUtils.getFile(te, info.getClasspathInfo()));
        } else {
            thisSourceRoot = findSourceRoot(file);
        }
        
        if (thisSourceRoot == null) {
            return null;
        }


        //XXX: special case "this" source root (no need to create a new JS and load the classes again for it):
//        reverseSourceRoots.add(thisSourceRoot);

//        LOG.log(Level.FINE, "reverseSourceRoots: {0}", reverseSourceRoots); //NOI18N

//                if (LOG.isLoggable(Level.FINE)) {
//                    LOG.log(Level.FINE, "method: {0}", ee.toString()); //NOI18N
//                }


        final Map<ElementHandle<TypeElement>, List<ElementHandle<ExecutableElement>>> methods = new HashMap<ElementHandle<TypeElement>, List<ElementHandle<ExecutableElement>>>();

        if (ee == null) {
            if (te == null) {
                fillInMethods(info.getTopLevelElements(), methods);
            } else {
                methods.put(ElementHandle.create(te), Collections.<ElementHandle<ExecutableElement>>emptyList());
            }
        } else {
            TypeElement owner = (TypeElement) ee.getEnclosingElement();

            methods.put(ElementHandle.create(owner), Collections.singletonList(ElementHandle.create(ee)));
        }

        final Map<ElementHandle<? extends Element>, List<ElementDescription>> overriding = new HashMap<ElementHandle<? extends Element>, List<ElementDescription>>();

        long startTime = System.currentTimeMillis();
        long[] classIndexTime = new long[1];
        final Map<URL, Map<ElementHandle<TypeElement>, Set<ElementHandle<TypeElement>>>> users = computeUsers(info, thisSourceRoot, methods.keySet(), classIndexTime, interactive);
        long endTime = System.currentTimeMillis();

        if (users == null) {
            return null;
        }

        Logger.getLogger("TIMER").log(Level.FINE, "Overridden Candidates - Class Index", //NOI18N
            new Object[] {file, classIndexTime[0]});
        Logger.getLogger("TIMER").log(Level.FINE, "Overridden Candidates - Total", //NOI18N
            new Object[] {file, endTime - startTime});

	FileObject currentFileSourceRoot = findSourceRoot(file);

	if (currentFileSourceRoot != null) {
            URL rootURL = currentFileSourceRoot.toURL();
            Map<ElementHandle<TypeElement>, Set<ElementHandle<TypeElement>>> overridingHandles = users.remove(rootURL);

            if (overridingHandles != null) {
                computeOverridingForRoot(rootURL, overridingHandles, methods, overriding);
            }
	}

        for (Map.Entry<URL, Map<ElementHandle<TypeElement>, Set<ElementHandle<TypeElement>>>> data : users.entrySet()) {
	    computeOverridingForRoot(data.getKey(), data.getValue(), methods, overriding);
        }

	if (cancel.get()) return null;

        return overriding;
    }