@Test public void getFlattenedEnclosingElementsTree_withoutRoot_withoutMaxDepth() { // Prepare Element parameterElement = Mockito.mock(VariableElement.class); Element methodElement = Mockito.mock(ExecutableElement.class); Element typeElement = Mockito.mock(TypeElement.class); Element packageElement = Mockito.mock(PackageElement.class); Mockito.when(parameterElement.getEnclosingElement()).thenReturn(methodElement); Mockito.when(methodElement.getEnclosingElement()).thenReturn(typeElement); Mockito.when(typeElement.getEnclosingElement()).thenReturn(packageElement); // execute List<Element> result = ElementUtils.AccessEnclosingElements.getFlattenedEnclosingElementsTree(parameterElement, false); // validate MatcherAssert.assertThat(result, Matchers.containsInAnyOrder(methodElement, typeElement, packageElement)); MatcherAssert.assertThat(result, Matchers.not(Matchers.contains(parameterElement))); }
@Test public void getFlattenedEnclosingElementsTree_withRoot_withoutMaxDepth() { // Prepare Element parameterElement = Mockito.mock(VariableElement.class); Element methodElement = Mockito.mock(ExecutableElement.class); Element typeElement = Mockito.mock(TypeElement.class); Element packageElement = Mockito.mock(PackageElement.class); Mockito.when(parameterElement.getEnclosingElement()).thenReturn(methodElement); Mockito.when(methodElement.getEnclosingElement()).thenReturn(typeElement); Mockito.when(typeElement.getEnclosingElement()).thenReturn(packageElement); // execute List<Element> result = ElementUtils.AccessEnclosingElements.getFlattenedEnclosingElementsTree(parameterElement, true); // validate MatcherAssert.assertThat(result, Matchers.containsInAnyOrder(parameterElement, methodElement, typeElement, packageElement)); }
@Test public void getFlattenedEnclosingElementsTree_withoutRoot_withMaxDepth() { // Prepare Element parameterElement = Mockito.mock(VariableElement.class); Element methodElement = Mockito.mock(ExecutableElement.class); Element typeElement = Mockito.mock(TypeElement.class); Element packageElement = Mockito.mock(PackageElement.class); Mockito.when(parameterElement.getEnclosingElement()).thenReturn(methodElement); Mockito.when(methodElement.getEnclosingElement()).thenReturn(typeElement); Mockito.when(typeElement.getEnclosingElement()).thenReturn(packageElement); // execute List<Element> result = ElementUtils.AccessEnclosingElements.getFlattenedEnclosingElementsTree(parameterElement, false, 2); // validate MatcherAssert.assertThat(result, Matchers.containsInAnyOrder(methodElement, typeElement)); MatcherAssert.assertThat(result, Matchers.not(Matchers.contains(parameterElement, packageElement))); }
/** * 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); } }
/** * {@inheritDoc} */ public void addLinkToPackageContent(PackageElement pkg, Set<PackageElement> printedPackageHeaders, Content contentListTree) { //add link to summary Content link; if (pkg.isUnnamed()) { link = getHyperLink(getDocLink( SectionName.UNNAMED_PACKAGE_ANCHOR), contents.defaultPackageLabel, "", ""); } else { String parsedPackageName = utils.parsePackageName(pkg); Content packageNameContent = getPackageLabel(parsedPackageName); packageNameContent.addContent(".*"); link = getHyperLink(DocLink.fragment(parsedPackageName), packageNameContent, "", ""); PackageElement abbrevPkg = configuration.workArounds.getAbbreviatedPackageElement(pkg); printedPackageHeaders.add(abbrevPkg); } contentListTree.addContent(HtmlTree.LI(link)); }
/** * Returns each package name as a separate link. * * @param pkg PackageElement * @param mdle the module being documented * @return content for the package link */ protected Content getPackage(PackageElement pkg, ModuleElement mdle) { Content packageLinkContent; Content pkgLabel; if (!pkg.isUnnamed()) { pkgLabel = getPackageLabel(utils.getPackageName(pkg)); packageLinkContent = getHyperLink(pathString(pkg, DocPaths.PACKAGE_FRAME), pkgLabel, "", "packageFrame"); } else { pkgLabel = new StringContent("<unnamed package>"); packageLinkContent = getHyperLink(DocPaths.PACKAGE_FRAME, pkgLabel, "", "packageFrame"); } Content li = HtmlTree.LI(packageLinkContent); return li; }
@SuppressWarnings("unchecked") private FoundIndexedClassNames getIndexedClassNames(PackageElement glideGenPackage) { Set<String> glideModules = new HashSet<>(); Set<String> extensions = new HashSet<>(); List<? extends Element> glideGeneratedElements = glideGenPackage.getEnclosedElements(); for (Element indexer : glideGeneratedElements) { Index annotation = indexer.getAnnotation(Index.class); // If the annotation is null, it means we've come across another class in the same package // that we can safely ignore. if (annotation != null) { Collections.addAll(glideModules, annotation.modules()); Collections.addAll(extensions, annotation.extensions()); } } processorUtil.debugLog("Found GlideModules: " + glideModules); return new FoundIndexedClassNames(glideModules, extensions); }
/** * {@inheritDoc} */ protected void addModulePackagesList(Set<ModuleElement> modules, String text, String tableSummary, Content body, ModuleElement mdle) { Content moduleNameContent = new StringContent(mdle.getQualifiedName().toString()); Content heading = HtmlTree.HEADING(HtmlConstants.PACKAGE_HEADING, true, getTargetModuleLink("classFrame", moduleNameContent, mdle)); heading.addContent(Contents.SPACE); heading.addContent(contents.packagesLabel); HtmlTree htmlTree = (configuration.allowTag(HtmlTag.MAIN)) ? HtmlTree.MAIN(HtmlStyle.indexContainer, heading) : HtmlTree.DIV(HtmlStyle.indexContainer, heading); HtmlTree ul = new HtmlTree(HtmlTag.UL); ul.setTitle(contents.packagesLabel); Set<PackageElement> modulePackages = configuration.modulePackages.get(mdle); for (PackageElement pkg: modulePackages) { if ((!(configuration.nodeprecated && utils.isDeprecated(pkg)))) { ul.addContent(getPackage(pkg, mdle)); } } htmlTree.addContent(ul); body.addContent(htmlTree); }
private static void getLocalAndInheritedMethods( PackageElement pkg, TypeElement type, SetMultimap<String, ExecutableElement> methods) { for (TypeMirror superInterface : type.getInterfaces()) { getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(superInterface), methods); } if (type.getSuperclass().getKind() != TypeKind.NONE) { // Visit the superclass after superinterfaces so we will always see the implementation of a // method after any interfaces that declared it. getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(type.getSuperclass()), methods); } for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) { if (!method.getModifiers().contains(Modifier.STATIC) && methodVisibleFromPackage(method, pkg)) { methods.put(method.getSimpleName().toString(), method); } } }
@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; }
void collect(Element element) { switch (element.getKind()) { case ANNOTATION_TYPE: case INTERFACE: case CLASS: case ENUM: collectIncludedAndDefinedBy((TypeElement) element); break; case METHOD: case CONSTRUCTOR: collectDefinedBy((ExecutableElement) element); break; case PACKAGE: collectIncludedBy((PackageElement) element); break; default: Reporter.from(processing()) .withElement(element) .warning("Unmatched annotation will be skipped for annotation processing"); } }
@Value.Lazy Optional<DeclaringPackage> namedParentPackage() { String parentPackageName = SourceNames.parentPackageName(element()); if (!parentPackageName.isEmpty()) { @Nullable PackageElement parentPackage = environment().processing() .getElementUtils() .getPackageElement(parentPackageName); if (parentPackage != null) { return Optional.of(interner().forPackage( ImmutableProto.DeclaringPackage.builder() .environment(environment()) .interner(interner()) .element(parentPackage) .build())); } } return Optional.absent(); }
public static TypeElement findClassElementByBinaryName(final String binaryName, CompilationController cc) { if (!binaryName.contains("$")) { // NOI18N // fast search based on fqn return cc.getElements().getTypeElement(binaryName); } else { // get containing package String packageName = ""; // NOI18N int dotIndex = binaryName.lastIndexOf("."); // NOI18N if (dotIndex != -1) { packageName = binaryName.substring(0, dotIndex); } PackageElement packElem = cc.getElements().getPackageElement(packageName); if (packElem == null) { return null; } // scan for element matching the binaryName return new BinaryNameTypeScanner().visit(packElem, binaryName); } }
private String getBundleValue(String label, Annotation annotation, String annotationMethod) throws LayerGenerationException { String javaIdentifier = "(?:\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*)"; Matcher m = Pattern.compile("((?:" + javaIdentifier + "\\.)+[^\\s.#]+)?#(\\S*)").matcher(label); if (m.matches()) { String bundle = m.group(1); String key = m.group(2); if (bundle == null) { Element referenceElement = originatingElement; while (referenceElement != null && referenceElement.getKind() != ElementKind.PACKAGE) { referenceElement = referenceElement.getEnclosingElement(); } if (referenceElement == null) { throw new LayerGenerationException("No reference element to determine package in '" + label + "'", originatingElement); } bundle = ((PackageElement) referenceElement).getQualifiedName() + ".Bundle"; } return verifyBundleValue(bundle, key, m.group(1) == null, annotation, annotationMethod); } return label; }
private void computeSpecifiedPackages() throws ToolException { computeSubpackages(); Set<PackageElement> packlist = new LinkedHashSet<>(); cmdLinePackages.forEach((modpkg) -> { PackageElement pkg; if (modpkg.hasModule()) { ModuleElement mdle = toolEnv.elements.getModuleElement(modpkg.moduleName); pkg = toolEnv.elements.getPackageElement(mdle, modpkg.packageName); } else { pkg = toolEnv.elements.getPackageElement(modpkg.toString()); } if (pkg != null) { packlist.add(pkg); } else { messager.printWarningUsingKey("main.package_not_found", modpkg.toString()); } }); specifiedPackageElements = Collections.unmodifiableSet(packlist); }
/** * 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<CompilationInfo> 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(); } }); }
/** * Returns a set of source files 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 FileObject}s containing the reference(s) * It may return null when the caller is a CancellableTask<CompilationInfo> and is cancelled * inside call of this method. * @since 0.89 */ public @NullUnknown Set<FileObject> getResourcesForPackage ( 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,FileObject>>() { @NonNull @Override public Convertor<Document, FileObject> convert(@NonNull final ClassIndexImpl p) { return DocumentUtil.fileObjectConvertor (ClassIndex.ResourceType.SOURCE, p.getSourceRoots()); } }); }
/** * 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(); } }
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 ); } } }
/** * Adds list of packages in the index table. Generate link to each package. * * @param packages Packages to which link is to be generated * @param tbody the documentation tree to which the list will be added */ protected void addPackagesList(Collection<PackageElement> packages, Content tbody) { boolean altColor = true; for (PackageElement pkg : packages) { if (!pkg.isUnnamed()) { if (!(configuration.nodeprecated && utils.isDeprecated(pkg))) { Content packageLinkContent = getPackageLink(pkg, getPackageName(pkg)); Content thPackage = HtmlTree.TH_ROW_SCOPE(HtmlStyle.colFirst, packageLinkContent); HtmlTree tdSummary = new HtmlTree(HtmlTag.TD); tdSummary.addStyle(HtmlStyle.colLast); addSummaryComment(pkg, tdSummary); HtmlTree tr = HtmlTree.TR(thPackage); tr.addContent(tdSummary); tr.addStyle(altColor ? HtmlStyle.altColor : HtmlStyle.rowColor); tbody.addContent(tr); } } altColor = !altColor; } }
/** * Build the summary for each documented package. * * @param contentTree the tree to which the summaries will be added * @throws DocletException if there is a problem while building the documentation */ protected void buildConstantSummaries(Content contentTree) throws DocletException { printedPackageHeaders.clear(); Content summariesTree = writer.getConstantSummaries(); for (PackageElement aPackage : configuration.packages) { if (hasConstantField(aPackage)) { currentPackage = aPackage; //Build the documentation for the current package. buildPackageHeader(summariesTree); buildClassConstantSummary(summariesTree); first = false; } } writer.addConstantSummaries(contentTree, summariesTree); }
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; }
private static void simpleVisibility(Set<Modifier> targetMods, PackageElement targetPkg, String fromPkg, Element target) { if (fromPkg == null) { if (!targetMods.contains(Modifier.PUBLIC)) { throw new EasyPluginException(target.toString() + " must be public."); } } else { // TODO this is terrible if ((!targetPkg.getQualifiedName().toString().equals(fromPkg) || targetMods.contains(Modifier.PROTECTED) || targetMods.contains(Modifier.PRIVATE)) && !targetMods.contains(Modifier.PUBLIC)) { throw new EasyPluginException("Access modifiers block usage of " + target.toString()); } } }
private void process( @Nonnull final Element element ) throws IOException, ArezProcessorException { final PackageElement packageElement = processingEnv.getElementUtils().getPackageOf( element ); final TypeElement typeElement = (TypeElement) element; final ComponentDescriptor descriptor = parse( packageElement, typeElement ); emitTypeSpec( descriptor.getPackageName(), descriptor.buildType( processingEnv.getTypeUtils() ) ); if ( descriptor.shouldGenerateComponentDaggerModule() ) { emitTypeSpec( descriptor.getPackageName(), descriptor.buildComponentDaggerModule() ); } if ( descriptor.hasRepository() ) { emitTypeSpec( descriptor.getPackageName(), descriptor.buildRepository( processingEnv.getTypeUtils() ) ); } }
/** * Get the table caption and header for the constant summary table * * @param typeElement the TypeElement to be documented * @return constant members header content */ public Content getConstantMembersHeader(TypeElement typeElement) { //generate links backward only to public classes. Content classlink = (utils.isPublic(typeElement) || utils.isProtected(typeElement)) ? getLink(new LinkInfoImpl(configuration, LinkInfoImpl.Kind.CONSTANT_SUMMARY, typeElement)) : new StringContent(utils.getFullyQualifiedName(typeElement)); PackageElement enclosingPackage = utils.containingPackage(typeElement); if (!enclosingPackage.isUnnamed()) { Content cb = new ContentBuilder(); cb.addContent(enclosingPackage.getQualifiedName()); cb.addContent("."); cb.addContent(classlink); return getClassName(cb); } else { return getClassName(classlink); } }
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); }
@Override void initialize(final Element element, CompilationController info) { final String labelText = UIUtilities.createHeader((PackageElement) element, info.getElements().isDeprecated(element), false, false, true); final Icon labelIcon = ElementIcons.getElementIcon(element.getKind(), element.getModifiers()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Dimension preferredSize = label.getPreferredSize(); label.setText(labelText); label.setIcon(labelIcon); label.setPreferredSize(preferredSize); label.setMinimumSize(preferredSize); } }); }
/** Compose flat name for provided class element. Nested classes will be divided by '$' symbol. */ public String flatName(@NonNull final Element classInfo) { StringBuilder builder = new StringBuilder(); Element start = classInfo; String divider = ""; while (null != start && !(start instanceof PackageElement)) { builder.insert(0, start.getSimpleName() + divider); start = ((Symbol) start).owner; divider = "$"; } return builder.toString(); }
/** * {@inheritDoc} */ protected void addModulePackagesList(Map<ModuleElement, Set<PackageElement>> modules, String text, String tableSummary, Content body, ModuleElement mdle) { Content profNameContent = new StringContent(mdle.getQualifiedName().toString()); Content heading = HtmlTree.HEADING(HtmlConstants.PACKAGE_HEADING, true, getTargetModuleLink("classFrame", profNameContent, mdle)); heading.addContent(Contents.SPACE); heading.addContent(contents.packagesLabel); HtmlTree htmlTree = (configuration.allowTag(HtmlTag.MAIN)) ? HtmlTree.MAIN(HtmlStyle.indexContainer, heading) : HtmlTree.DIV(HtmlStyle.indexContainer, heading); HtmlTree ul = new HtmlTree(HtmlTag.UL); ul.setTitle(contents.packagesLabel); List<PackageElement> packages = new ArrayList<>(modules.get(mdle)); for (PackageElement pkg : packages) { if ((!(configuration.nodeprecated && utils.isDeprecated(pkg)))) { ul.addContent(getPackage(pkg, mdle)); } } htmlTree.addContent(ul); body.addContent(htmlTree); }
private void addPackageContent(PackageElement pe, EnumSet<ElementKind> kinds, DeclaredType baseType, Set<? extends Element> toExclude, String prefix, int substitutionOffset, JavadocContext jdctx) { CompilationInfo controller = jdctx.javac; Element srcEl = jdctx.handle.resolve(controller); Elements elements = controller.getElements(); Types types = controller.getTypes(); Trees trees = controller.getTrees(); TreeUtilities tu = controller.getTreeUtilities(); ElementUtilities eu = controller.getElementUtilities(); TreePath docpath = srcEl != null ? trees.getPath(srcEl) : null; Scope scope = docpath != null ? trees.getScope(docpath) : tu.scopeFor(caretOffset); for(Element e : pe.getEnclosedElements()) { if ((e.getKind().isClass() || e.getKind().isInterface()) && (toExclude == null || !toExclude.contains(e))) { String name = e.getSimpleName().toString(); if (Utilities.startsWith(name, prefix) && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(e)) && trees.isAccessible(scope, (TypeElement)e) && isOfKindAndType(e.asType(), e, kinds, baseType, scope, trees, types) && !Utilities.isExcluded(eu.getElementName(e, true))) { items.add(JavadocCompletionItem.createTypeItem(jdctx.javac, (TypeElement) e, substitutionOffset, null, elements.isDeprecated(e)/*, isOfSmartType(env, e.asType(), smartTypes)*/)); } } } }
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); } }
@Test public void getFirstEnclosingElementOfKind_validUsageWithHitForMethodKind() { // Prepare Element parameterElement = Mockito.mock(VariableElement.class); Element methodElement = Mockito.mock(ExecutableElement.class); Element embeddedTypeElement = Mockito.mock(TypeElement.class); Element typeElement = Mockito.mock(TypeElement.class); Element packageElement = Mockito.mock(PackageElement.class); Mockito.when(parameterElement.getKind()).thenReturn(ElementKind.PARAMETER); Mockito.when(methodElement.getKind()).thenReturn(ElementKind.METHOD); Mockito.when(embeddedTypeElement.getKind()).thenReturn(ElementKind.CLASS); Mockito.when(typeElement.getKind()).thenReturn(ElementKind.CLASS); Mockito.when(packageElement.getKind()).thenReturn(ElementKind.PACKAGE); Mockito.when(parameterElement.getEnclosingElement()).thenReturn(methodElement); Mockito.when(methodElement.getEnclosingElement()).thenReturn(embeddedTypeElement); Mockito.when(embeddedTypeElement.getEnclosingElement()).thenReturn(typeElement); Mockito.when(typeElement.getEnclosingElement()).thenReturn(packageElement); // execute Element result = ElementUtils.AccessEnclosingElements.getFirstEnclosingElementOfKind(parameterElement, ElementKind.METHOD); // validate MatcherAssert.assertThat(result, Matchers.is(methodElement)); }
@Test public void getFirstEnclosingElementOfKind_validUsageWithNoHit() { // Prepare Element parameterElement = Mockito.mock(VariableElement.class); Element methodElement = Mockito.mock(ExecutableElement.class); Element embeddedTypeElement = Mockito.mock(TypeElement.class); Element typeElement = Mockito.mock(TypeElement.class); Element packageElement = Mockito.mock(PackageElement.class); Mockito.when(parameterElement.getKind()).thenReturn(ElementKind.PARAMETER); Mockito.when(methodElement.getKind()).thenReturn(ElementKind.METHOD); Mockito.when(embeddedTypeElement.getKind()).thenReturn(ElementKind.CLASS); Mockito.when(typeElement.getKind()).thenReturn(ElementKind.CLASS); Mockito.when(packageElement.getKind()).thenReturn(ElementKind.PACKAGE); Mockito.when(parameterElement.getEnclosingElement()).thenReturn(methodElement); Mockito.when(methodElement.getEnclosingElement()).thenReturn(embeddedTypeElement); Mockito.when(embeddedTypeElement.getEnclosingElement()).thenReturn(typeElement); Mockito.when(typeElement.getEnclosingElement()).thenReturn(packageElement); // execute Element result = ElementUtils.AccessEnclosingElements.getFirstEnclosingElementOfKind(parameterElement, ElementKind.CONSTRUCTOR); // validate MatcherAssert.assertThat(result, Matchers.nullValue()); }
private String getClassString(TypeElement typeElement, String myPackage) { PackageElement packageElement = getPackageElement(typeElement); String packageString = packageElement.getQualifiedName().toString(); String className = typeElement.getQualifiedName().toString(); if (packageString != null && !packageString.isEmpty()) { if (packageString.equals(myPackage)) { className = cutPackage(myPackage, className); } else if (packageString.equals("java.lang")) { className = typeElement.getSimpleName().toString(); } } return className; }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (round++ != 0) return false; Elements elements = processingEnv.getElementUtils(); PackageElement pe = elements.getPackageElement(""); if (pe == null) { System.out.println("null"); } else { ModuleElement mod = (ModuleElement) pe.getEnclosingElement(); if (mod == null) { System.out.println("noModule"); } else if (mod.isUnnamed()) { System.out.println("unnamedModule"); } else { System.out.println(mod); } } ModuleElement m1x = elements.getModuleElement("m1x"); ModuleElement m2x = elements.getModuleElement("m2x"); if (m1x != null && m2x != null) { System.out.println("m1x: " + (elements.getPackageElement(m1x, "") != null)); System.out.println("m2x: " + (elements.getPackageElement(m2x, "") != null)); } return false; }
public HelperGenerator(TypeElement activity, TypeElement targetActivity, PackageElement targetPackage, List<ParameterWriter> parameterList, List<ResultModel> resultList) { super(activity, targetActivity, targetPackage); this.parameterList = parameterList; this.resultList = resultList; }
private String findPackage(Element e) { switch (e.getKind()) { case PACKAGE: return ((PackageElement) e).getQualifiedName().toString(); default: return findPackage(e.getEnclosingElement()); } }
private String readTemplateResource(TypeElement templateType, SwissArmyKnife knife) throws IOException { PackageElement packageElement = knife.elements.getPackageOf(templateType); return getTemplateText( knife.environment.getFiler(), templateType, packageElement); }
private String getTemplateText( Filer filer, TypeElement templateType, PackageElement packageElement) throws IOException { CharSequence relativeName = templateType.getSimpleName() + ".generator"; CharSequence packageName = packageElement.getQualifiedName(); List<Exception> suppressed = Lists.newArrayList(); try { return filer.getResource(StandardLocation.SOURCE_PATH, packageName, relativeName) .getCharContent(true) .toString(); } catch (Exception cannotGetFromSourcePath) { suppressed.add(cannotGetFromSourcePath); try { return filer.getResource(StandardLocation.CLASS_OUTPUT, packageName, relativeName) .getCharContent(true) .toString(); } catch (Exception cannotGetFromOutputPath) { suppressed.add(cannotGetFromOutputPath); try { return filer.getResource(StandardLocation.CLASS_PATH, "", packageName.toString().replace('.', '/') + '/' + relativeName) .getCharContent(true) .toString(); } catch (IOException cannotGetFromClasspath) { for (Exception e : suppressed) { cannotGetFromClasspath.addSuppressed(e); } throw cannotGetFromClasspath; } } } }
/** * Build the list of packages. * * @param contentTree the content tree to which the content list will be added */ protected void buildContents(Content contentTree) { Content contentListTree = writer.getContentsHeader(); printedPackageHeaders.clear(); for (PackageElement pkg : configuration.packages) { if (hasConstantField(pkg) && !hasPrintedPackageIndex(pkg)) { writer.addLinkToPackageContent(pkg, printedPackageHeaders, contentListTree); } } writer.addContentsList(contentTree, contentListTree); }