Java Code Examples for javax.lang.model.element.ElementKind.PACKAGE

The following are Jave code examples for showing how to use PACKAGE of the javax.lang.model.element.ElementKind class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GitHub   File: Mirrors.java   View Source Code Vote up 6 votes
@Nullable
private TypeElement validated(Element element) {
  Element enclosingElement = element.getEnclosingElement();

  if (element.getKind() == ElementKind.ANNOTATION_TYPE
      && element.getModifiers().contains(Modifier.PUBLIC)
      && enclosingElement != null
      && (enclosingElement.getKind() != ElementKind.PACKAGE
      || !((PackageElement) enclosingElement).isUnnamed())) {
    return (TypeElement) element;
  }

  processing().getMessager().printMessage(
      Diagnostic.Kind.ERROR,
      "Element annotated with @Mirror.Annotation annotation should public annotation type in a package",
      element);

  return null;
}
 
Example 2
Project: incubator-netbeans   File: RenameRefactoringUI.java   View Source Code Vote up 5 votes
@Override
public CustomRefactoringPanel getPanel(ChangeListener parent) {
    if (panel == null) {
        String suffix = "";
        if(handle != null && handle.getKind() == Tree.Kind.LABELED_STATEMENT) {
            suffix = getString("LBL_Label");
        } else if (handle != null && handle.getElementHandle() !=null) {
            ElementKind kind = handle.getElementHandle().getKind();
            if (kind!=null && (kind.isClass() || kind.isInterface())) {
                suffix  = kind.isInterface() ? getString("LBL_Interface") : getString("LBL_Class");
            } else if (kind == ElementKind.METHOD) {
                suffix = getString("LBL_Method");
            } else if (kind == ElementKind.FIELD) {
                suffix = getString("LBL_Field");
            } else if (kind == ElementKind.LOCAL_VARIABLE) {
                suffix = getString("LBL_LocalVar");
            } else if (kind == ElementKind.PACKAGE || (handle == null && fromListener)) {
                suffix = pkgRename ? getString("LBL_Package") : getString("LBL_Folder");
            } else if (kind == ElementKind.PARAMETER) {
                suffix = getString("LBL_Parameter");
            }
        }
        suffix = suffix + " " + this.oldName; // NOI18N
        panel = new RenamePanel(handle, newName, parent, NbBundle.getMessage(RenamePanel.class, "LBL_Rename") + " " + suffix, !fromListener, fromListener && !byPassPakageRename);
    }
    return panel;
}
 
Example 3
Project: GitHub   File: Proto.java   View Source Code Vote up 5 votes
@Override
@Value.Derived
@Value.Auxiliary
public DeclaringPackage packageOf() {
  Element e = element();
  for (; e.getKind() != ElementKind.PACKAGE; e = e.getEnclosingElement()) {
  }
  return interner().forPackage(
      ImmutableProto.DeclaringPackage.builder()
          .environment(environment())
          .interner(interner())
          .element((PackageElement) e)
          .build());
}
 
Example 4
Project: incubator-netbeans   File: SpringXMLConfigCompletionItem.java   View Source Code Vote up 5 votes
private String getRelativeName(TypeElement elem) {
    StringBuilder sb = new StringBuilder();
    sb.append(elem.getSimpleName().toString());
    Element parent = elem.getEnclosingElement();
    while(parent.getKind() != ElementKind.PACKAGE) {
        sb.insert(0, parent.getSimpleName().toString() + "$"); // NOI18N
        parent = parent.getEnclosingElement();
    }

    return sb.toString();
}
 
Example 5
Project: incubator-netbeans   File: SourceUtilsEx.java   View Source Code Vote up 5 votes
/**
 * Returns a source file in which the passed element
 * is declared in. This tuned up version of {@code SourceUtils.getFile}
 * is necessary as sequential invocations of {@code SourceUtils.getFile} are
 * excessively slow.
 *
 * @param element an element to find {@link FileObject} for
 * @param cpInfo scope where the file will be searched
 * @param cache a cache
 * @return the source file
 * @see SourceUtils#getFile(org.netbeans.api.java.source.ElementHandle, org.netbeans.api.java.source.ClasspathInfo) SourceUtils.getFile
 */
public static FileObject getFile(final Element element, final ClasspathInfo cpInfo, final Cache cache) {
    Parameters.notNull("element", element); //NOI18N
    Parameters.notNull("cpInfo", cpInfo);   //NOI18N
    Parameters.notNull("cache", cache);   //NOI18N

    Element current = element;
    Element prev = current.getKind() == ElementKind.PACKAGE ? current : null;
    while (current.getKind() != ElementKind.PACKAGE) {
        prev = current;
        current = current.getEnclosingElement();
    }
    if (prev == null) {
        return null;
    }

    final ElementKind kind = prev.getKind();
    String fqn;
    if (kind.isClass() || kind.isInterface()) {
        fqn = ((TypeElement) prev).getQualifiedName().toString();
    } else if (kind == ElementKind.PACKAGE) {
        fqn = ((PackageElement) prev).getQualifiedName().toString();
    } else {
        return null;
    }

    Object cached = cache.cacheOfSrcFiles.get(fqn);
    if (cached == null) {
        final ElementHandle<? extends Element> handle = ElementHandle.create(prev);
        cached = SourceUtils.getFile(handle, cpInfo);
        cache.cacheOfSrcFiles.put(fqn, cached != null ? cached : Cache.NULL);
    } else if (cached == Cache.NULL) {
        cached = null;
    }
    return (FileObject) cached;
}
 
Example 6
Project: incubator-netbeans   File: ElementHandle.java   View Source Code Vote up 5 votes
/**
 * Creates an {@link ElementHandle} representing a {@link PackageElement}.
 * @param packageName the name of the package
 * @return the created {@link ElementHandle}
 * @since 0.98
 */
@NonNull
public static ElementHandle<PackageElement> createPackageElementHandle (
    @NonNull final String packageName) {
    Parameters.notNull("packageName", packageName); //NOI18N
    return new ElementHandle<PackageElement>(ElementKind.PACKAGE, packageName);
}
 
Example 7
Project: incap   File: InputTypeFinder.java   View Source Code Vote up 5 votes
private TypeElement enclosingTypeElement(Element element) {

    if (element.getKind() == ElementKind.PACKAGE) {
      throw new IllegalArgumentException();
    }

    while (element != null && !isType(element)) {
      element = element.getEnclosingElement();
    }

    return (TypeElement) element;
  }
 
Example 8
Project: incubator-netbeans   File: Hinter.java   View Source Code Vote up 5 votes
private PackageElement findPackage(Element e) {
    if (e.getKind() == ElementKind.PACKAGE) {
        return ((PackageElement) e);
    }
    Element parent = e.getEnclosingElement();
    if (parent == null) {
        return null;
    }
    return findPackage(parent);
}
 
Example 9
Project: incubator-netbeans   File: MIMEResolverProcessor.java   View Source Code Vote up 5 votes
private String getName(Element e) {
    if (e.getKind().isClass() || e.getKind().isInterface()) {
        return processingEnv.getElementUtils().getBinaryName((TypeElement)e).toString();
    } else if (e.getKind() == ElementKind.PACKAGE) {
        return e.getSimpleName().toString();
    } else {
        return getName(e.getEnclosingElement()) + '.' + e.getSimpleName();
    }
}
 
Example 10
Project: incubator-netbeans   File: WorkingCopy.java   View Source Code Vote up 5 votes
FileObject doCreateFromTemplate(CompilationUnitTree cut) throws IOException {
    ElementKind kind;
    if ("package-info.java".equals(cut.getSourceFile().getName())) {
        kind = ElementKind.PACKAGE;
    } else if (cut.getTypeDecls().isEmpty()) {
        kind = null;
    } else {
        switch (cut.getTypeDecls().get(0).getKind()) {
            case CLASS:
                kind = ElementKind.CLASS;
                break;
            case INTERFACE:
                kind = ElementKind.INTERFACE;
                break;
            case ANNOTATION_TYPE:
                kind = ElementKind.ANNOTATION_TYPE;
                break;
            case ENUM:
                kind = ElementKind.ENUM;
                break;
            default:
                Logger.getLogger(WorkingCopy.class.getName()).log(Level.SEVERE, "Cannot resolve template for {0}", cut.getTypeDecls().get(0).getKind());
                kind = null;
        }
    }
    FileObject template = FileUtil.getConfigFile(template(kind));
    return doCreateFromTemplate(template, cut.getSourceFile());
}
 
Example 11
Project: openjdk-jdk10   File: Utils.java   View Source Code Vote up 4 votes
public boolean isPackage(Element e) {
    return e.getKind() == ElementKind.PACKAGE;
}
 
Example 12
Project: incubator-netbeans   File: SafeDeleteUI.java   View Source Code Vote up 4 votes
@Override
public RefactoringUI create(CompilationInfo info, TreePathHandle[] handles, FileObject[] files, NonRecursiveFolder[] packages) {
    final boolean b = lookup.lookup(ExplorerContext.class)!=null;
    if (packages != null && packages.length == 1) {
        return new SafeDeleteUI(packages[0], b);
    }
    if (handles != null && handles.length == 0 || (files!=null && files.length > 1)) {
        return new SafeDeleteUI(files, Arrays.asList(handles), b);
    }
    
    if (b && files!=null && files.length == 1) {
        return new SafeDeleteUI(files, Arrays.asList(handles), b);
    }
    
    if (info == null) {
        return new SafeDeleteUI(handles);
    }
    
    TreePathHandle selectedElement = handles[0];
    Element selected = selectedElement.resolveElement(info);
    TreePath selectedTree = selectedElement.resolve(info);
    if (selected == null || selectedTree == null) {
        return null;
    }
    if (selected.getKind() == ElementKind.PACKAGE || selected.getEnclosingElement().getKind() == ElementKind.PACKAGE) {
        ElementHandle<Element> handle = ElementHandle.create(selected);
        FileObject file = SourceUtils.getFile(handle, info.getClasspathInfo());
        if (file == null) {
            return null;
        }
        if (file.getName().equals(selected.getSimpleName().toString())) {
            return new SafeDeleteUI(new FileObject[]{file}, Collections.singleton(selectedElement), b);
        }
    }
    if(!TreeUtilities.CLASS_TREE_KINDS.contains(selectedTree.getParentPath().getLeaf().getKind())
            && selectedTree.getParentPath().getLeaf().getKind() != Tree.Kind.COMPILATION_UNIT
            && selectedTree.getLeaf().getKind() == Tree.Kind.VARIABLE) {
        switch (selectedTree.getParentPath().getLeaf().getKind()) {
            case BLOCK:
            case METHOD:
                break;
            default:
                return null;
        }
    }
    return new SafeDeleteUI(new TreePathHandle[]{selectedElement});
}
 
Example 13
Project: openjdk-jdk10   File: Main.java   View Source Code Vote up 4 votes
public static PackageElement getPackage(TypeElement type) {
    Element owner = type;
    while (owner.getKind() != ElementKind.PACKAGE)
        owner = owner.getEnclosingElement();
    return (PackageElement)owner;
}
 
Example 14
Project: incubator-netbeans   File: ExportNonAccessibleElement.java   View Source Code Vote up 4 votes
public List<ErrorDescription> run(CompilationInfo compilationInfo,
                                      TreePath treePath) {
        stop = false;
        Element e = compilationInfo.getTrees().getElement(treePath);
        if (e == null) {
            return null;
        }
        Boolean b = e.accept(this, null);

        if (b) {
            Element parent = e;
            for (;;) {
                if (stop) {
                    return null;
                }

                if (parent == null || parent.getKind() == ElementKind.PACKAGE) {
                    break;
                }
                if (!parent.getModifiers().contains(Modifier.PUBLIC) && !parent.getModifiers().contains(Modifier.PROTECTED)) {
                    return null;
                }
                parent = parent.getEnclosingElement();
            }

            //#124456: disabling the fix:
//            List<Fix> fixes = Collections.<Fix>singletonList(new FixImpl(
//                "MSG_ExportNonAccessibleElementMakeNonVisible", // NOI18N
//                TreePathHandle.create(e, compilationInfo), 
//                compilationInfo.getFileObject()
//            ));

            int[] span = null;

            switch (treePath.getLeaf().getKind()) {
                case METHOD: span = compilationInfo.getTreeUtilities().findNameSpan((MethodTree) treePath.getLeaf()); break;
                case ANNOTATION_TYPE:
                case CLASS:
                case ENUM:
                case INTERFACE:
                    span = compilationInfo.getTreeUtilities().findNameSpan((ClassTree) treePath.getLeaf()); break;
                case VARIABLE: span = compilationInfo.getTreeUtilities().findNameSpan((VariableTree) treePath.getLeaf()); break;
            }

            if (span != null) {
                ErrorDescription ed = ErrorDescriptionFactory.createErrorDescription(
                        getSeverity().toEditorSeverity(),
                        NbBundle.getMessage(ExportNonAccessibleElement.class, "MSG_ExportNonAccessibleElement"),
//                        fixes,
                        compilationInfo.getFileObject(),
                        span[0],
                        span[1]
                        );

                return Collections.singletonList(ed);
            }
        }
        
        return null;
    }
 
Example 15
Project: incubator-netbeans   File: CreateSubclass.java   View Source Code Vote up 4 votes
@TriggerTreeKind({Tree.Kind.CLASS, Tree.Kind.INTERFACE})
public static ErrorDescription check(HintContext context) {
    TreePath tp = context.getPath();
    ClassTree cls = (ClassTree) tp.getLeaf();
    CompilationInfo info = context.getInfo();
    SourcePositions sourcePositions = info.getTrees().getSourcePositions();
    long startPos = sourcePositions.getStartPosition(tp.getCompilationUnit(), cls);
    if (startPos > Integer.MAX_VALUE) {
        return null;
    }
    int[] bodySpan = info.getTreeUtilities().findBodySpan(cls);
    if (bodySpan == null || bodySpan[0] <= startPos) {
        return null;
    }
    int caret = context.getCaretLocation();
    if (startPos < 0 || caret < 0 || caret < startPos || caret >= bodySpan[0]) {
        return null;
    }

    // #222487
    // If there is a compile-time error on the class, then don't offer to
    // create a subclass.
    List<Diagnostic> errors = info.getDiagnostics();
    if (!errors.isEmpty()) {
        for (Diagnostic d : errors) {
            if (d.getKind() != Diagnostic.Kind.ERROR) {
                continue;
            }
            // Check that the error's start position is within the class header
            // Note: d.getEndPosition() is not used because, for example,
            // a "compiler.err.does.not.override.abstract" error ends at
            // the end of the class tree.
            if (startPos <= d.getStartPosition() && d.getStartPosition() <= bodySpan[0]) {
                return null;
            }
        }
    }

    TypeElement typeElement = (TypeElement) info.getTrees().getElement(tp);
    
    if (typeElement == null || typeElement.getModifiers().contains(Modifier.FINAL)) return null;

    Element outer = typeElement.getEnclosingElement();
    // do not offer the hint for non-static inner classes. Permit for classes nested into itnerface - no enclosing instance
    if (outer != null && outer.getKind() != ElementKind.PACKAGE && outer.getKind() != ElementKind.INTERFACE) {
        if (outer.getKind() != ElementKind.CLASS && outer.getKind() != ElementKind.ENUM) {
            return null;
        }
        if (!typeElement.getModifiers().contains(Modifier.STATIC)) {
            return null;
        }
    }

    
    ClassPath cp = info.getClasspathInfo().getClassPath(PathKind.SOURCE);
    FileObject root = cp.findOwnerRoot(info.getFileObject());
    if (root == null) { //File not part of any project
        return null;
    }

    PackageElement packageElement = (PackageElement) info.getElementUtilities().outermostTypeElement(typeElement).getEnclosingElement();
    CreateSubclassFix fix = new CreateSubclassFix(info, root, packageElement.getQualifiedName().toString(), typeElement.getSimpleName().toString() + "Impl", typeElement); //NOI18N
    return ErrorDescriptionFactory.forTree(context, context.getPath(), NbBundle.getMessage(CreateSubclass.class, typeElement.getKind() == ElementKind.CLASS
            ? typeElement.getModifiers().contains(Modifier.ABSTRACT) ? "ERR_ImplementAbstractClass" : "ERR_CreateSubclass" : "ERR_ImplementInterface"), fix); //NOI18N
}
 
Example 16
Project: incubator-netbeans   File: IllegalInstanceOf.java   View Source Code Vote up 4 votes
public List<ErrorDescription> run(CompilationInfo info, TreePath treePath) {
    if (treePath.getLeaf().getKind() != Kind.INSTANCE_OF) {
        return null;
    }
    
    InstanceOfTree iot = (InstanceOfTree) treePath.getLeaf();
    TypeMirror     leftTypeMirror = info.getTrees().getTypeMirror(new TreePath(treePath, iot.getExpression()));
    Element        rightType = info.getTrees().getElement(new TreePath(treePath, iot.getType()));
    
    if (leftTypeMirror == null || leftTypeMirror.getKind() != TypeKind.DECLARED) {
        return null;
    }
    
    Element leftType = ((DeclaredType) leftTypeMirror).asElement();
    
    if (leftType == null || rightType == null || !leftType.getKind().isInterface() || !rightType.getKind().isInterface()) {
        //no problem:
        return null;
    }
    
    TypeElement left = (TypeElement) leftType;
    TypeElement right = (TypeElement) rightType;
    
    if (   left.getEnclosingElement().getKind() != ElementKind.PACKAGE
        || right.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
        return null;
    }
    
    PackageElement leftPackage = (PackageElement) left.getEnclosingElement();
    PackageElement rightPackage = (PackageElement) right.getEnclosingElement();
    
    String leftPackageFQN = leftPackage.getQualifiedName().toString();
    String rightPackageFQN = rightPackage.getQualifiedName().toString();
    
    if (packagesToCheck.containsKey(leftPackageFQN) && leftPackageFQN.equals(rightPackageFQN)) {
        String verifyClass = packagesToCheck.get(leftPackageFQN);
        TypeElement loadedVerify = info.getElements().getTypeElement(verifyClass);
        
        if (loadedVerify == null || !info.getTypes().isSubtype(left.asType(), loadedVerify.asType()))
            return null;
        
        if (!info.getTypes().isSubtype(right.asType(), loadedVerify.asType()))
            return null;
        
        int start = (int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), iot);
        int end   = (int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), iot);
        return Collections.<ErrorDescription>singletonList(
                   ErrorDescriptionFactory.createErrorDescription(getSeverity().toEditorSeverity(),
                                                                  NbBundle.getMessage(IllegalInstanceOf.class, "MSG_IllegalInstanceOf"),
                                                                  info.getFileObject(),
                                                                  start,
                                                                  end
                                                                 )
               );
    }
    
    return null;
}
 
Example 17
Project: incubator-netbeans   File: LazyJavaCompletionItem.java   View Source Code Vote up 4 votes
private boolean isInDefaultPackage(Element e) {
    while (e != null && e.getKind() != ElementKind.PACKAGE) {
        e = e.getEnclosingElement();
    }
    return e != null && e.getSimpleName().length() == 0;
}
 
Example 18
Project: openjdk-jdk10   File: Symbol.java   View Source Code Vote up 4 votes
@DefinedBy(Api.LANGUAGE_MODEL)
public ElementKind getKind() {
    return ElementKind.PACKAGE;
}
 
Example 19
Project: incubator-netbeans   File: HTMLDialogProcessor.java   View Source Code Vote up 4 votes
private static PackageElement findPkg(Element e) {
    while (e.getKind() != ElementKind.PACKAGE) {
        e = e.getEnclosingElement();
    }
    return (PackageElement)e;
}
 
Example 20
Project: incubator-netbeans   File: PersistentClassIndex.java   View Source Code Vote up 4 votes
@Override
public <T> void search (
        @NonNull final ElementHandle<?> element,
        @NonNull final Set<? extends UsageType> usageType,
        @NonNull final Set<? extends ClassIndex.SearchScopeType> scope,
        @NonNull final Convertor<? super Document, T> convertor,
        @NonNull final Set<? super T> result) throws InterruptedException, IOException {
    Parameters.notNull("element", element); //NOI18N
    Parameters.notNull("usageType", usageType); //NOI18N
    Parameters.notNull("scope", scope); //NOI18N
    Parameters.notNull("convertor", convertor); //NOI18N
    Parameters.notNull("result", result);   //NOI18N
    final Pair<Convertor<? super Document, T>,Index> ctu = indexPath.getPatch(convertor);
    try {
        final String binaryName = SourceUtils.getJVMSignature(element)[0];
        final ElementKind kind = element.getKind();
        if (kind == ElementKind.PACKAGE) {
            IndexManager.priorityAccess(() -> {
                final Query q = QueryUtil.scopeFilter(
                        QueryUtil.createPackageUsagesQuery(binaryName,usageType,Occur.SHOULD),
                        scope);
                if (q != null) {
                    index.query(result, ctu.first(), DocumentUtil.declaredTypesFieldSelector(false, false), cancel.get(), q);
                    if (ctu.second() != null) {
                        ctu.second().query(result, convertor, DocumentUtil.declaredTypesFieldSelector(false, false), cancel.get(), q);
                    }
                }
                return null;
            });
        } else if (kind.isClass() ||
                   kind.isInterface() ||
                   kind == ElementKind.OTHER) {
            if (BinaryAnalyser.OBJECT.equals(binaryName)) {
                getDeclaredElements(
                    "", //NOI18N
                    ClassIndex.NameKind.PREFIX,
                    scope,
                    DocumentUtil.declaredTypesFieldSelector(false, false),
                    convertor,
                    result);
            } else {
                IndexManager.priorityAccess(() -> {
                    final Query usagesQuery = QueryUtil.scopeFilter(
                            QueryUtil.createUsagesQuery(binaryName, usageType, Occur.SHOULD),
                            scope);
                    if (usagesQuery != null) {
                        index.query(result, ctu.first(), DocumentUtil.declaredTypesFieldSelector(false, false), cancel.get(), usagesQuery);
                        if (ctu.second() != null) {
                            ctu.second().query(result, convertor, DocumentUtil.declaredTypesFieldSelector(false, false), cancel.get(), usagesQuery);
                        }
                    }
                    return null;
                });
            }
        } else {
            throw new IllegalArgumentException(element.toString());
        }
    } catch (IOException ioe) {
        this.<Void,IOException>handleException(null, ioe, root);
    }
}