Java Code Examples for javax.lang.model.element.PackageElement

The following examples show how to use javax.lang.model.element.PackageElement. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: j2objc   Source File: PackagePrefixes.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the prefix for a specified package. If a prefix was specified
 * for the package, then that prefix is returned. Otherwise, a camel-cased
 * prefix is created from the package name.
 */
public String getPrefix(PackageElement packageElement) {
  if (packageElement == null) {
    return "";
  }
  String packageName = packageElement.getQualifiedName().toString();
  String prefix = getPrefix(packageName);
  if (prefix != null) {
    return prefix;
  }

  prefix = packageLookup.getObjectiveCName(packageName);
  if (prefix == null) {
    AnnotationMirror annotation = ElementUtil.getAnnotation(packageElement, ObjectiveCName.class);
    if (annotation != null) {
      prefix = (String) ElementUtil.getAnnotationValue(annotation, "value");
    }
  }
  if (prefix == null) {
    prefix = NameTable.camelCaseQualifiedName(packageName);
  }
  addPrefix(packageName, prefix);
  return prefix;
}
 
Example 2
Source Project: deptective   Source File: DeptectiveTreeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the qualified Package Name of the given Tree object or null if the package could not be determined
 */
protected String getQualifiedPackageName(Tree tree) {
    TypeMirror typeMirror = trees.getTypeMirror(getCurrentPath());
    if (typeMirror == null) {
        return null;
    }

    if (typeMirror.getKind() != TypeKind.DECLARED && typeMirror.getKind() != TypeKind.TYPEVAR) {
        return null;
    }

    Element typeMirrorElement = types.asElement(typeMirror);
    if (typeMirrorElement == null) {
        throw new IllegalStateException("Could not get Element for type '" + typeMirror + "'");
    }
    PackageElement pakkage = elements.getPackageOf(typeMirrorElement);
    return pakkage.getQualifiedName().toString();
}
 
Example 3
Source Project: core   Source File: SPIProcessor.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void handleBeanFactoryElement(Element element) {
    List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
    for (AnnotationMirror mirror : annotationMirrors) {
        final String annotationType = mirror.getAnnotationType().toString();
        if (annotationType.equals(BeanFactoryExtension.class.getName())) {
            PackageElement packageElement = processingEnv.getElementUtils().getPackageOf(element);
            String fqn = packageElement.getQualifiedName().toString() + "." +
                    element.getSimpleName().toString();
            System.out.println("Factory: " + fqn);
            discoveredBeanFactories.add(fqn);
        } else if (annotationType.equals("com.google.web.bindery.autobean.shared.AutoBeanFactory.Category")) {
            final Collection<? extends AnnotationValue> values = mirror.getElementValues().values();
            if (values.size() > 0) {
                for (AnnotationValue categoryClass : (List<? extends AnnotationValue>) values.iterator().next()
                        .getValue()) {
                    categoryClasses.add(categoryClass.getValue().toString());
                }
            }
        }
    }
}
 
Example 4
Source Project: j2objc   Source File: HeaderMap.java    License: Apache License 2.0 6 votes vote down vote up
public String get(TypeElement type) {
  String explicitHeader = ElementUtil.getHeader(type);
  if (explicitHeader != null) {
    return explicitHeader;
  }

  String qualifiedName = ElementUtil.getQualifiedName(type);

  String mappedHeader = map.get(qualifiedName);
  if (mappedHeader != null) {
    return mappedHeader;
  }

  String name = inferSourceName(type);
  PackageElement pkg = ElementUtil.getPackage(type);
  return outputDirFromPackage(pkg) + name + ".h";
}
 
Example 5
/**
 * Adds package index contents. Call appropriate methods from
 * the sub-classes. Adds it to the body HtmlTree
 *
 * @param packages a collection of packages to be documented
 * @param text string which will be used as the heading
 * @param tableSummary summary for the table
 * @param body the document tree to which the index contents will be added
 */
protected void addIndexContents(Collection<PackageElement> packages, String text,
        String tableSummary, Content body) {
    if (!packages.isEmpty()) {
        HtmlTree htmlTree = (configuration.allowTag(HtmlTag.NAV))
                ? HtmlTree.NAV()
                : new HtmlTree(HtmlTag.DIV);
        htmlTree.addStyle(HtmlStyle.indexNav);
        HtmlTree ul = new HtmlTree(HtmlTag.UL);
        addAllClassesLink(ul);
        if (configuration.showModules  && configuration.modules.size() > 1) {
            addAllModulesLink(ul);
        }
        htmlTree.addContent(ul);
        body.addContent(htmlTree);
        addPackagesList(packages, text, tableSummary, body);
    }
}
 
Example 6
Source Project: openjdk-jdk9   Source File: Utils.java    License: GNU General Public License v2.0 6 votes vote down vote up
public boolean isSpecified(Element e) {
    if (specifiedVisitor == null) {
        specifiedVisitor = new SimpleElementVisitor9<Boolean, Void>() {
            @Override
            public Boolean visitModule(ModuleElement e, Void p) {
                return configuration.getSpecifiedModuleElements().contains(e);
            }

            @Override
            public Boolean visitPackage(PackageElement e, Void p) {
                return configuration.getSpecifiedPackageElements().contains(e);
            }

            @Override
            public Boolean visitType(TypeElement e, Void p) {
                return configuration.getSpecifiedTypeElements().contains(e);
            }

            @Override
            protected Boolean defaultAction(Element e, Void p) {
                return false;
            }
        };
    }
    return specifiedVisitor.visit(e);
}
 
Example 7
void generate() throws DocFileIOException, SimpleDocletException {
    if (docEnv == null || outputdir == null) {
        return;
    }
    for (PackageElement pkg : configuration.getSpecifiedPackageElements()) {
        // If -nodeprecated option is set and the package is marked as deprecated,
        // do not convert the package files to HTML.
        if (!(configuration.nodeprecated && utils.isDeprecated(pkg)))
            convertPackage(pkg, outputdir);
    }
    for (TypeElement te : configuration.getSpecifiedTypeElements()) {
        // If -nodeprecated option is set and the class is marked as deprecated
        // or the containing package is deprecated, do not convert the
        // package files to HTML.
        if (!(configuration.nodeprecated &&
              (utils.isDeprecated(te) || utils.isDeprecated(utils.containingPackage(te)))))
            convertClass(te, outputdir);
    }
}
 
Example 8
Source Project: netbeans   Source File: ClassIndex.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a set of {@link ElementHandle}s containing reference(s) to given package element.
 * @param element the {@link ElementHandle} of a {@link PackageElement} for which usages should be found
 * @param searchKind type of reference, {@see SearchKind}
 * @param scope to search in {@see SearchScope}
 * @return set of {@link ElementHandle}s containing the reference(s)
 * It may return null when the caller is a CancellableTask&lt;CompilationInfo&gt; and is cancelled
 * inside call of this method.
 * @since 0.89
 */
public @NullUnknown Set<ElementHandle<TypeElement>> getElementsForPackage (
        final @NonNull ElementHandle<PackageElement> element,
        final @NonNull Set<SearchKind> searchKind,
        final @NonNull Set<? extends SearchScopeType> scope) {
    return searchImpl(
        element,
        searchKind,
        scope,
        new Convertor<ClassIndexImpl, Convertor<Document,ElementHandle<TypeElement>>>(){
            @NonNull
            @Override
            public Convertor<Document, ElementHandle<TypeElement>> convert(@NonNull final ClassIndexImpl p) {
                return DocumentUtil.typeElementConvertor();
            }
        });
}
 
Example 9
Source Project: netbeans   Source File: ReferencesCount.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns all packages used by classes on given source path (source root).
 * @return the used packages
 */
@NonNull
public Iterable<? extends ElementHandle<? extends PackageElement>> getUsedPackages() {
    try {
        init();
        return new AsHandlesIterable<String, ElementHandle<PackageElement>>(
            pkgFreqs.keySet(),
            new Convertor<String, ElementHandle<PackageElement>>() {
                @NonNull
                @Override
                public ElementHandle<PackageElement> convert(@NonNull final String p) {
                    return ElementHandleAccessor.getInstance().create(ElementKind.PACKAGE, p);
                }
            });
    } catch (InterruptedException ie) {
        return Collections.<ElementHandle<PackageElement>>emptySet();
    }
}
 
Example 10
Source Project: netbeans   Source File: ClasspathInfoTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testGetPackageDeclaration() throws Exception {
    ClasspathInfo ci = ClasspathInfo.create( bootPath, classPath, null);
    JavaFileManager fm = ClasspathInfoAccessor.getINSTANCE().createFileManager(ci, null);
    JarFile jf = new JarFile( rtJar );
    for( Enumeration entries = jf.entries(); entries.hasMoreElements(); ) {
        JarEntry je = (JarEntry)entries.nextElement();
        String jeName = je.getName();
        if ( je.isDirectory() ) {
            String packageName = jeName.replace( "/", "." );
            if ( !fm.list( StandardLocation.PLATFORM_CLASS_PATH,packageName, EnumSet.of( JavaFileObject.Kind.CLASS ), false).iterator().hasNext() ) {
                // empty package
                continue;
            }
            PackageElement pd = JavacParser.createJavacTask(ci,  (DiagnosticListener) null, (String) null, null, null, null, null, null, Collections.emptyList()).getElements().getPackageElement( packageName );
            assertNotNull( "Declaration for " + packageName + " should not be null.", pd );
        }
    }
}
 
Example 11
Source Project: openjdk-jdk9   Source File: ElementsTable.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Set<PackageElement> getAllModulePackages(ModuleElement mdle) throws ToolException {
    Set<PackageElement> result = new HashSet<>();
    ModuleSymbol msym = (ModuleSymbol) mdle;
    List<Location> msymlocs = getModuleLocation(locations, msym.name.toString());
    for (Location msymloc : msymlocs) {
        for (JavaFileObject fo : fmList(msymloc, "", sourceKinds, true)) {
            if (fo.getName().endsWith("module-info.java")) {
                continue;
            }
            String binaryName = fm.inferBinaryName(msymloc, fo);
            String pn = getPackageName(binaryName);
            PackageSymbol psym = syms.enterPackage(msym, names.fromString(pn));
            result.add((PackageElement) psym);
        }
    }
    return result;
}
 
Example 12
Source Project: netbeans   Source File: MemberAdditionTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testEmptyClass() throws Exception {
    performTest("EmptyClass");

    source.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy copy) throws IOException {
            copy.toPhase(Phase.RESOLVED);
            ClassTree topLevel = findTopLevelClass(copy);
            SourceUtilsTestUtil2.run(copy, new AddSimpleField(), topLevel);
        }
    }).commit();

    JavaSourceAccessor.getINSTANCE().revalidate(source);

    CompilationInfo check = SourceUtilsTestUtil.getCompilationInfo(source, Phase.RESOLVED);
    CompilationUnitTree cu = check.getCompilationUnit();

    assertEquals(check.getDiagnostics().toString(), 0, check.getDiagnostics().size());
    
    ClassTree newTopLevel = findTopLevelClass(check);
    Element clazz = check.getTrees().getElement(TreePath.getPath(cu, newTopLevel));
    Element pack = clazz.getEnclosingElement();
    
    assertEquals(ElementKind.PACKAGE, pack.getKind());
    assertEquals("test", ((PackageElement) pack).getQualifiedName().toString());
    assertEquals(clazz.getEnclosedElements().toString(), 1 + 1/*syntetic default constructor*/, clazz.getEnclosedElements().size());
}
 
Example 13
Source Project: sundrio   Source File: TypeDefElementVisitor.java    License: Apache License 2.0 6 votes vote down vote up
public TypeDefBuilder visit(Element e) {
    if (e instanceof TypeElement) {
        return new TypeDefBuilder(ElementTo.TYPEDEF.apply((TypeElement) e));
    }
    String name = e.getSimpleName().toString();
    builder.withName(name);
    if (e.getKind() == ElementKind.INTERFACE) {
        builder.withKind(Kind.INTERFACE);
    } else if (e.getKind() == ElementKind.ENUM) {
        builder.withKind(Kind.ENUM);
    }else if (e.getKind() == ElementKind.ANNOTATION_TYPE) {
        builder.withKind(Kind.ANNOTATION);
    } else  {
        builder.withKind(Kind.CLASS);
    }

    if (e.getEnclosingElement() instanceof PackageElement) {
        String packageName = e.getEnclosingElement().toString();
        builder.withPackageName(packageName);
    }
    return builder;
}
 
Example 14
Source Project: netbeans   Source File: JavacPackageInfo.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Collection<SourceClassInfo> getClasses() {
    final List<SourceClassInfo> clzs = new ArrayList<SourceClassInfo>();
    
    ParsingUtils.invokeScanSensitiveTask(cpInfo, new ScanSensitiveTask<CompilationController> () {
        @Override
        public void run(CompilationController cc)
                throws Exception {
            cc.toPhase(JavaSource.Phase.PARSED);

            PackageElement pelem = cc.getElements().getPackageElement(getSimpleName());

            if (pelem != null) {
                for (TypeElement type : ElementFilter.typesIn(pelem.getEnclosedElements())) {
                    if ((type.getKind() == ElementKind.CLASS) || (type.getKind() == ElementKind.ENUM)) {
                        clzs.add(new JavacClassInfo(ElementHandle.create(type), indexInfo));
                    }
                }
            } else {
                LOGGER.log(Level.FINEST, "Package name {0} resulted into a NULL element", getBinaryName()); // NOI18N
            }
        }
    });

    return clzs;
}
 
Example 15
Source Project: buck   Source File: TreeBackedTypeResolutionSimulator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected TreeBackedResolvedType resolvePackage(
    TreePath referencingPath,
    PackageElement referencedPackage,
    QualifiedNameable canonicalPackage) {
  // PackageElements are not considered to be enclosed by their parent elements, but
  // our logic is a lot simpler if we can pretend they are.
  TreeBackedResolvedType enclosingElement = null;
  String qualifiedName = canonicalPackage.getQualifiedName().toString();
  int lastDot = qualifiedName.lastIndexOf('.');
  if (lastDot > 0) {
    String enclosingPackageQualifiedName = qualifiedName.substring(0, lastDot);
    PackageElement enclosingPackage =
        Objects.requireNonNull(
            MoreElements.getPackageElementEvenIfEmpty(elements, enclosingPackageQualifiedName));
    enclosingElement = resolveEnclosingElement(enclosingPackage);
  }

  return new TreeBackedResolvedType(referencingPath, canonicalPackage, enclosingElement);
}
 
Example 16
private PackageElement createPackageElement(AnalyzeTask at, String packageName) {
    Names names = Names.instance(at.getContext());
    Symtab syms = Symtab.instance(at.getContext());
    PackageElement existing = syms.enterPackage(syms.unnamedModule, names.fromString(packageName));

    return existing;
}
 
Example 17
Source Project: openjdk-jdk9   Source File: JavacTrees.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public DocCommentTree getDocCommentTree(Element e, String relativeFileName) throws IOException {
    PackageElement pkg = elements.getPackageOf(e);
    FileObject fileForInput = fileManager.getFileForInput(StandardLocation.SOURCE_PATH,
            pkg.getQualifiedName().toString(), relativeFileName);

    if (fileForInput == null) {
        throw new FileNotFoundException(relativeFileName);
    }
    return getDocCommentTree(fileForInput);
}
 
Example 18
Source Project: sundrio   Source File: ModelUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static TypeElement getClassElement(Element element) {
    if (element instanceof PackageElement) {
        throw new IllegalArgumentException("Invalid element. A package element can't be used to retrieve a class element");
    } else if (element instanceof TypeElement) {
        return (TypeElement) element;
    } else {
        return getClassElement(element.getEnclosingElement());
    }
}
 
Example 19
private void verifyPackage(String[] packagesToTest, Set<String> acceptable) {
    for (String packageToTest : packagesToTest) {
        PackageElement packageElement = processingEnv.getElementUtils()
                .getPackageElement(packageToTest);

        verifyReferredTypesAcceptable(packageElement, acceptable);
    }
}
 
Example 20
/**
 * Build the serialized form summaries.
 *
 * @param node the XML element that specifies which components to document
 * @param serializedTree content tree to which the documentation will be added
 * @throws DocletException if there is a problem while building the documentation
 */
public void buildSerializedFormSummaries(XMLNode node, Content serializedTree)
        throws DocletException {
    Content serializedSummariesTree = writer.getSerializedSummariesHeader();
    for (PackageElement pkg : configuration.packages) {
        currentPackage = pkg;
        buildChildren(node, serializedSummariesTree);
    }
    serializedTree.addContent(writer.getSerializedContent(
            serializedSummariesTree));
}
 
Example 21
Source Project: sqlitemagic   Source File: Environment.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean visibleFromPackage(Element element, PackageElement pkg) {
  // We use Visibility.ofElement rather than .effectiveVisibilityOfElement because it doesn't
  // really matter whether the containing class is visible. If you inherit a public method
  // then you have a public method, regardless of whether you inherit it from a public class.
  Visibility visibility = Visibility.ofElement(element);
  switch (visibility) {
    case PRIVATE:
      return false;
    case DEFAULT:
      return getPackage(element).equals(pkg);
    default:
      return true;
  }
}
 
Example 22
Source Project: firebase-android-sdk   Source File: Names.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the class name that corresponds to a given element.
 *
 * <p>For top level classes returns the class name unchanged. For nested classes returns {@code
 * ParentNested} for {@code Parent$Nested} classes.
 */
static String generatedClassName(Element element) {
  StringBuilder sb = new StringBuilder(element.getSimpleName().toString());
  Element enclosingElement = element.getEnclosingElement();
  while (!(enclosingElement instanceof PackageElement)) {
    sb.insert(0, enclosingElement.getSimpleName().toString());
    enclosingElement = enclosingElement.getEnclosingElement();
  }
  return sb.toString();
}
 
Example 23
Source Project: firebase-android-sdk   Source File: Names.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns the AutoValue formatted class name for a given element. */
static String autoValueClassName(Element element) {
  StringBuilder sb = new StringBuilder(element.getSimpleName().toString());
  Element enclosingElement = element.getEnclosingElement();
  while (!(enclosingElement instanceof PackageElement)) {
    sb.insert(0, '_');
    sb.insert(0, enclosingElement.getSimpleName().toString());
    enclosingElement = enclosingElement.getEnclosingElement();
  }
  sb.insert(0, "AutoValue_");
  return sb.toString();
}
 
Example 24
Source Project: firebase-android-sdk   Source File: Names.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns the package name of an element. */
static String packageName(Element element) {
  Element enclosingElement = element.getEnclosingElement();
  while (!(enclosingElement instanceof PackageElement)) {
    enclosingElement = enclosingElement.getEnclosingElement();
  }
  return ((PackageElement) enclosingElement).getQualifiedName().toString();
}
 
Example 25
Source Project: openjdk-8   Source File: TestSymtabItems.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitPackage(PackageElement e, Void p) {
    show("package", e);
    indent(+1);
    super.visitPackage(e, p);
    indent(-1);
    return null;
}
 
Example 26
private void verifyPackage(String[] packagesToTest, Set<String> acceptable) {
    for (String packageToTest : packagesToTest) {
        PackageElement packageElement = processingEnv.getElementUtils()
                .getPackageElement(packageToTest);

        verifyReferredTypesAcceptable(packageElement, acceptable);
    }
}
 
Example 27
private void verifyPackage(String[] packagesToTest, Set<String> acceptable) {
    for (String packageToTest : packagesToTest) {
        PackageElement packageElement = processingEnv.getElementUtils()
                .getPackageElement(packageToTest);

        verifyReferredTypesAcceptable(packageElement, acceptable);
    }
}
 
Example 28
protected void preProcessWebService(WebService webService, TypeElement element) {
    processedMethods = new HashSet<String>();
    seiContext = context.getSeiContext(element);
    String targetNamespace = null;
    if (webService != null)
        targetNamespace = webService.targetNamespace();
    PackageElement packageElement = builder.getProcessingEnvironment().getElementUtils().getPackageOf(element);
    if (targetNamespace == null || targetNamespace.length() == 0) {
        String packageName = packageElement.getQualifiedName().toString();
        if (packageName == null || packageName.length() == 0) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_NO_PACKAGE_CLASS_MUST_HAVE_TARGETNAMESPACE(
                    element.getQualifiedName()), element);
        }
        targetNamespace = RuntimeModeler.getNamespace(packageName);
    }
    seiContext.setNamespaceUri(targetNamespace);
    if (serviceImplName == null)
        serviceImplName = seiContext.getSeiImplName();
    if (serviceImplName != null) {
        seiContext.setSeiImplName(serviceImplName);
        context.addSeiContext(serviceImplName, seiContext);
    }
    portName = ClassNameInfo.getName(element.getSimpleName().toString().replace('$', '_'));
    packageName = packageElement.getQualifiedName();
    portName = webService != null && webService.name() != null && webService.name().length() > 0 ?
            webService.name() : portName;
    serviceName = ClassNameInfo.getName(element.getQualifiedName().toString()) + WebServiceConstants.SERVICE.getValue();
    serviceName = webService != null && webService.serviceName() != null && webService.serviceName().length() > 0 ?
            webService.serviceName() : serviceName;
    wsdlNamespace = seiContext.getNamespaceUri();
    typeNamespace = wsdlNamespace;

    SOAPBinding soapBinding = element.getAnnotation(SOAPBinding.class);
    if (soapBinding != null) {
        pushedSoapBinding = pushSoapBinding(soapBinding, element, element);
    } else if (element.equals(typeElement)) {
        pushedSoapBinding = pushSoapBinding(new MySoapBinding(), element, element);
    }
}
 
Example 29
@Override @DefinedBy(Api.COMPILER_TREE)
public DocTreePath getDocTreePath(FileObject fileObject, PackageElement packageElement) {
    JavaFileObject jfo = asJavaFileObject(fileObject);
    DocCommentTree docCommentTree = getDocCommentTree(jfo);
    TreePath treePath = makeTreePath((PackageSymbol)packageElement, jfo, docCommentTree);
    return new DocTreePath(treePath, docCommentTree);
}
 
Example 30
Source Project: openjdk-jdk9   Source File: Utils.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Map<ModuleElement, Set<PackageElement>> getModulePackageMap() {
    if (modulePackageMap == null) {
        modulePackageMap = new HashMap<>();
        Set<PackageElement> pkgs = configuration.getIncludedPackageElements();
        pkgs.forEach((pkg) -> {
            ModuleElement mod = elementUtils.getModuleOf(pkg);
            modulePackageMap.computeIfAbsent(mod, m -> new HashSet<>()).add(pkg);
        });
    }
    return modulePackageMap;
}