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

The following are top voted examples for showing how to use javax.lang.model.element.TypeElement. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: RIBs   File: RibProcessor.java   View source code 6 votes vote down vote up
@Override
public final boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

  if (roundEnv.processingOver()) {
    return false;
  }

  for (ProcessorPipeline processorPipeline : processorPipelines) {
    try {
      processorPipeline.process(annotations, roundEnv);
    } catch (Throwable e) {
      errorReporter.reportError(
          String.format(
              Locale.getDefault(),
              "Fatal error running %s processor: %s",
              processorPipeline.getAnnotationType().getSimpleName(),
              e.getMessage()));
    }
  }
  return false;
}
 
Example 2
Project: incubator-netbeans   File: SpringXMLConfigCompletionItem.java   View source code 6 votes vote down vote up
@Override
public StringBuilder visitDeclared(DeclaredType t, Boolean p) {
    Element e = t.asElement();
    if (e instanceof TypeElement) {
        TypeElement te = (TypeElement)e;
        DEFAULT_VALUE.append((p ? te.getQualifiedName() : te.getSimpleName()).toString());
        Iterator<? extends TypeMirror> it = t.getTypeArguments().iterator();
        if (it.hasNext()) {
            DEFAULT_VALUE.append("<"); //NOI18N
            while(it.hasNext()) {
                visit(it.next(), p);
                if (it.hasNext())
                    DEFAULT_VALUE.append(", "); //NOI18N
            }
            DEFAULT_VALUE.append(">"); //NOI18N
        }
        return DEFAULT_VALUE;
    } else {
        return DEFAULT_VALUE.append(UNKNOWN); //NOI18N
    }
}
 
Example 3
Project: incubator-netbeans   File: EqualsHashCodeGenerator.java   View source code 6 votes vote down vote up
private static KindOfType detectKind(CompilationInfo info, TypeMirror tm) {
    if (tm.getKind().isPrimitive()) {
        return KindOfType.valueOf(tm.getKind().name());
    }

    if (tm.getKind() == TypeKind.ARRAY) {
        return ((ArrayType) tm).getComponentType().getKind().isPrimitive() ? KindOfType.ARRAY_PRIMITIVE : KindOfType.ARRAY;
    }

    if (tm.getKind() == TypeKind.DECLARED) {
        Types t = info.getTypes();
        TypeElement en = info.getElements().getTypeElement("java.lang.Enum");

        if (en != null) {
            if (t.isSubtype(tm, t.erasure(en.asType()))) {
                return KindOfType.ENUM;
            }
        }

        if (((DeclaredType)tm).asElement().getKind().isClass() && ((TypeElement) ((DeclaredType) tm).asElement()).getQualifiedName().contentEquals("java.lang.String")) {
            return KindOfType.STRING;
        }
    }

    return KindOfType.OTHER;
}
 
Example 4
Project: openjdk-jdk10   File: SerializedFormBuilder.java   View source code 6 votes vote down vote up
/**
 * Build the package serialized form for the current package being processed.
 *
 * @param serializedSummariesTree content tree to which the documentation will be added
 * @throws DocletException if there is a problem while building the documentation
 */
protected void buildPackageSerializedForm(Content serializedSummariesTree) throws DocletException {
    Content packageSerializedTree = writer.getPackageSerializedHeader();
    SortedSet<TypeElement> classes = utils.getAllClassesUnfiltered(currentPackage);
    if (classes.isEmpty()) {
        return;
    }
    if (!serialInclude(utils, currentPackage)) {
        return;
    }
    if (!serialClassFoundToDocument(classes)) {
        return;
    }

    buildPackageHeader(packageSerializedTree);
    buildClassSerializedForm(packageSerializedTree);

    writer.addPackageSerializedTree(serializedSummariesTree, packageSerializedTree);
}
 
Example 5
Project: openjdk-jdk10   File: SourceCodeAnalysisImpl.java   View source code 6 votes vote down vote up
private Predicate<Element> createAccessibilityFilter(AnalyzeTask at, TreePath tp) {
    Scope scope = at.trees().getScope(tp);
    return el -> {
        switch (el.getKind()) {
            case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE:
                return at.trees().isAccessible(scope, (TypeElement) el);
            case PACKAGE:
            case EXCEPTION_PARAMETER: case PARAMETER: case LOCAL_VARIABLE: case RESOURCE_VARIABLE:
                return true;
            default:
                TypeMirror type = el.getEnclosingElement().asType();
                if (type.getKind() == TypeKind.DECLARED)
                    return at.trees().isAccessible(scope, el, (DeclaredType) type);
                else
                    return true;
        }
    };
}
 
Example 6
Project: incubator-netbeans   File: JavaUtils.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 7
Project: incubator-netbeans   File: ElementUtils.java   View source code 6 votes vote down vote up
public static TypeElement getTypeElementByBinaryName(JavacTask task, String name) {
    Set<? extends ModuleElement> allModules = task.getElements().getAllModuleElements();
    
    if (allModules.isEmpty()) {
        Context ctx = ((JavacTaskImpl) task).getContext();
        Symtab syms = Symtab.instance(ctx);
        
        return getTypeElementByBinaryName(task, syms.noModule, name);
    }
    
    TypeElement result = null;
    
    for (ModuleElement me : allModules) {
        TypeElement found = getTypeElementByBinaryName(task, me, name);
        
        if (found != null) {
            if (result != null) return null;
            result = found;
        }
    }
    
    return result;
}
 
Example 8
Project: incubator-netbeans   File: ElementUtilitiesEx.java   View source code 6 votes vote down vote up
public static Set<ElementHandle<TypeElement>> findImplementors(final ClasspathInfo cpInfo, final ElementHandle<TypeElement> baseType) {
    final Set<ClassIndex.SearchKind> kind = EnumSet.of(ClassIndex.SearchKind.IMPLEMENTORS);
    final Set<ClassIndex.SearchScope> scope = EnumSet.allOf(ClassIndex.SearchScope.class);
    
    final Set<ElementHandle<TypeElement>> allImplementors = new HashSet<ElementHandle<TypeElement>>();

    ParsingUtils.invokeScanSensitiveTask(cpInfo, new ScanSensitiveTask<CompilationController>(true) {
        @Override
        public void run(CompilationController cc) {
            Set<ElementHandle<TypeElement>> implementors = cpInfo.getClassIndex().getElements(baseType, kind, scope);
            do {
                Set<ElementHandle<TypeElement>> tmpImplementors = new HashSet<ElementHandle<TypeElement>>();
                allImplementors.addAll(implementors);

                for (ElementHandle<TypeElement> element : implementors) {
                    tmpImplementors.addAll(cpInfo.getClassIndex().getElements(element, kind, scope));
                }

                implementors = tmpImplementors;
            } while (!implementors.isEmpty());
        }
    });
    
    return allImplementors;
}
 
Example 9
Project: incubator-netbeans   File: TypeUtilities.java   View source code 6 votes vote down vote up
@Override
public StringBuilder visitWildcard(WildcardType t, Boolean p) {
    int len = DEFAULT_VALUE.length();
    DEFAULT_VALUE.append("?"); //NOI18N
    TypeMirror bound = t.getSuperBound();
    if (bound == null) {
        bound = t.getExtendsBound();
        if (bound != null) {
            DEFAULT_VALUE.append(" extends "); //NOI18N
            if (bound.getKind() == TypeKind.WILDCARD)
                bound = ((WildcardType)bound).getSuperBound();
            visit(bound, p);
        } else if (len == 0) {
            bound = SourceUtils.getBound(t);
            if (bound != null && (bound.getKind() != TypeKind.DECLARED || !((TypeElement)((DeclaredType)bound).asElement()).getQualifiedName().contentEquals("java.lang.Object"))) { //NOI18N
                DEFAULT_VALUE.append(" extends "); //NOI18N
                visit(bound, p);
            }
        }
    } else {
        DEFAULT_VALUE.append(" super "); //NOI18N
        visit(bound, p);
    }
    return DEFAULT_VALUE;
}
 
Example 10
Project: incubator-netbeans   File: Type.java   View source code 6 votes vote down vote up
@Override
public String getName() {
    if(typeName == null){
        Element elt = po != null ? getTypeElement(po) : element;
        if(elt != null){
            if(elt instanceof TypeElement) {
                typeName = ((TypeElement) elt).getQualifiedName().toString();
            }
            else {
                typeName = elt.asType().toString();
            }
        } else if (type != null) {
            typeName = type.getName();
        }
    }
    return typeName;
}
 
Example 11
Project: qualifier   File: StaticQualifierMetamodelProcessor.java   View source code 6 votes vote down vote up
/** The super qualifier user to extend this property metadata. */
@Override public @Nullable PropertyReference extend() {
    if (mixinMetamodel != null && mixinProperty != null) {
        return new PropertyReference(mixinMetamodel, mixinProperty);
    }

    // apply bean Qualify(mixin) if this property has no explicit @Extend
    if (isProperty()) {
        Qualify beanQualify = beanElement.getAnnotation(Qualify.class);
        TypeElement classRepresenter = qualifyExtendValue(beanQualify);
        if (classRepresenter != null && !classRepresenter.equals(typeElementFor(Object.class))) {
            return new PropertyReference(
                    ClassName.bestGuess(getQualifierName(getFlatName(classRepresenter))),
                    isNullOrEmpty(mixinProperty) ? name : mixinProperty);
        }
    }

    return null;
}
 
Example 12
Project: incubator-netbeans   File: ClassIndex.java   View source code 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 13
Project: incubator-netbeans   File: SimpleBuilderResolver.java   View source code 6 votes vote down vote up
@Override
public String findBuilderClass(CompilationInfo cinfo, Source source, String beanClassName) {
    TypeElement classElement = cinfo.getElements().getTypeElement(beanClassName);
    if (classElement == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder(((PackageElement)classElement.getEnclosingElement()).getQualifiedName().toString());
    if (sb.length() > 0) {
        sb.append("."); // NOI18N
    }
    sb.append(classElement.getSimpleName().toString()).append("Builder"); // NOI18N
    
    TypeElement builderEl = cinfo.getElements().getTypeElement(sb.toString());
    return builderEl != null ?
            sb.toString() :
            null;
}
 
Example 14
Project: incubator-netbeans   File: TestGeneratorSetup.java   View source code 6 votes vote down vote up
/**
 */
private boolean hasTestableMethods(TypeElement classElem) {
    List<? extends Element> enclosedElems = classElem.getEnclosedElements();
    if (enclosedElems.isEmpty()) {
        return false;
    }
    
    List<ExecutableElement> methods = ElementFilter.methodsIn(enclosedElems);
    if (methods.isEmpty()) {
        return false;
    }
    
    for (ExecutableElement method : methods) {
        if (isMethodTestable(method)) {
            return true;
        }
    }
    
    return false;
}
 
Example 15
Project: openjdk-jdk10   File: ClassBuilder.java   View source code 6 votes vote down vote up
/**
 * Construct a new ClassBuilder.
 *
 * @param context  the build context
 * @param typeElement the class being documented.
 * @param writer the doclet specific writer.
 */
private ClassBuilder(Context context, TypeElement typeElement, ClassWriter writer) {
    super(context);
    this.typeElement = typeElement;
    this.writer = writer;
    this.utils = configuration.utils;
    if (utils.isInterface(typeElement)) {
        isInterface = true;
        isEnum = false;
    } else if (utils.isEnum(typeElement)) {
        isInterface = false;
        isEnum = true;
        utils.setEnumDocumentation(typeElement);
    } else {
        isInterface = false;
        isEnum = false;
    }
}
 
Example 16
Project: RxAndroidOrm   File: Processor.java   View source code 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    writeStaticJavaFiles();

    getMigrators(roundEnv);
    getDatabaseName(roundEnv);

    for (Element element : roundEnv.getElementsAnnotatedWith(Model.class)) {
        models.add(element);
        generateColumnEnums(element);
        generateEntityProxies(element);
        generateCursorHelperFiles(element);
        generateModelDaoFiles(element);
    }
    resolveDependencies();
    writeJavaFiles();
    return true;
}
 
Example 17
Project: incubator-netbeans   File: ClassIndex.java   View source code 6 votes vote down vote up
/**
 * Returns a set of source files containing reference(s) to given type element.
 * @param element the {@link ElementHandle} of a {@link TypeElement} 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&lt;CompilationInfo&gt; and is cancelled
 * inside call of this method.
 */
public @NullUnknown Set<FileObject> getResources (
        final @NonNull ElementHandle<TypeElement> 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());
            }
        });
}
 
Example 18
Project: openjdk-jdk10   File: PubapiVisitor.java   View source code 6 votes vote down vote up
@Override @DefinedBy(Api.LANGUAGE_MODEL)
public Void visitType(TypeElement e, Void p) {
    if (isNonPrivate(e)) {
        PubApi prevApi = collectedApi;
        collectedApi = new PubApi();
        super.visitType(e, p);
        if (!isAnonymous(e)) {
            String name = ((ClassSymbol) e).flatname.toString();
            PubType t = new PubType(e.getModifiers(),
                                    name,
                                    //e.getQualifiedName().toString(),
                                    collectedApi);
            prevApi.types.put(t.fqName, t);
        }
        collectedApi = prevApi;
    }
    return null;
}
 
Example 19
Project: incubator-netbeans   File: TopClassFinder.java   View source code 6 votes vote down vote up
/**
 * 
 * @return  list of {@code Element}s representing top classes,
 *          or an empty list of none were found
 */
private static List<TypeElement> findTopClassElems(
                                    CompilationInfo compInfo,
                                    CompilationUnitTree compilationUnit,
                                    Filter filter) {
    List<? extends Tree> typeDecls = compilationUnit.getTypeDecls();
    if ((typeDecls == null) || typeDecls.isEmpty()) {
        return Collections.<TypeElement>emptyList();
    }
    
    List<TypeElement> result = new ArrayList<TypeElement>(typeDecls.size());

    Trees trees = compInfo.getTrees();
    for (Tree typeDecl : typeDecls) {
        if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
            Element element = trees.getElement(
                    new TreePath(new TreePath(compilationUnit), typeDecl));
            TypeElement typeElement = (TypeElement) element;
            if (filter.passes(typeElement, compInfo)) {
                result.add(typeElement);
            }
        }
    }

    return result;
}
 
Example 20
Project: EM   File: ActivatorAnnotationProcessor.java   View source code 6 votes vote down vote up
private void processRound(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
	loop: for (TypeElement annotation : annotations) {
		for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
			if (element.getAnnotation(Activator.class).extension()) {
				extensionActivator = element.asType().toString();
			} else {
				activator = element.asType().toString();
			}
			if (activator != null && extensionActivator != null) {
				break loop;
			}
		}
	}
	try {
		generateFile();
	} catch (IOException e) {
		messager.printMessage(Kind.ERROR, "IOException while generating file with contracts! " + e.getMessage());
		e.printStackTrace();
	}
}
 
Example 21
Project: incubator-netbeans   File: GoToSupportTest.java   View source code 6 votes vote down vote up
public void testGoToStaticImport() throws Exception {
    final boolean[] wasCalled = new boolean[1];
    String code = "package test; import static java.awt.Color.BLACK; public class Test {}";

    performTest(code, code.indexOf("BLACK") + 1, new OrigUiUtilsCaller() {
        public void open(FileObject fo, int pos) {
            fail("Should not be called.");
        }
        public void beep() {
            fail("Should not be called.");
        }
        public void open(ClasspathInfo info, Element el) {
            assertEquals(ElementKind.FIELD, el.getKind());
            assertEquals("java.awt.Color.BLACK",
                    ((TypeElement) el.getEnclosingElement()).getQualifiedName().toString() + '.' + el);
            wasCalled[0] = true;
        }
    }, false);

    assertTrue(wasCalled[0]);
}
 
Example 22
Project: incap   File: InputTypeFinderAnnotationTestProcessor.java   View source code 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

  if (roundEnv.processingOver()) {
    return false;
  }

  Set<? extends Element> elementsAnnotatedWith =
      roundEnv.getElementsAnnotatedWith(Annotation1.class);

  if (elementsAnnotatedWith.size() != 1) {
    throw new IllegalStateException(
        "There must be exactly one element to process. Actual=" + elementsAnnotatedWith.size());
  }

  for (Element element : elementsAnnotatedWith) {
    inputTypeForElement = inputTypeFinder.findInputTypeForElement(element);
  }

  return false;
}
 
Example 23
Project: incubator-netbeans   File: JavaSymbolProvider.java   View source code 6 votes vote down vote up
@Override
public StringBuilder visitDeclared(DeclaredType t, Boolean p) {
    Element e = t.asElement();
    if (e instanceof TypeElement) {
        TypeElement te = (TypeElement)e;
        DEFAULT_VALUE.append((p ? te.getQualifiedName() : te.getSimpleName()).toString());
        Iterator<? extends TypeMirror> it = t.getTypeArguments().iterator();
        if (it.hasNext()) {
            DEFAULT_VALUE.append("<"); //NOI18N
            while(it.hasNext()) {
                visit(it.next(), p);
                if (it.hasNext()) {
                    DEFAULT_VALUE.append(", "); //NOI18N
                }
            }
            DEFAULT_VALUE.append(">"); //NOI18N
        }
        return DEFAULT_VALUE;
    } else {
        return DEFAULT_VALUE.append(UNKNOWN); //NOI18N
    }
}
 
Example 24
Project: incubator-netbeans   File: GeneratorUtilitiesTest.java   View source code 6 votes vote down vote up
public void run(WorkingCopy copy) throws Exception {
    copy.toPhase(JavaSource.Phase.RESOLVED);
    TreePath tp = copy.getTreeUtilities().pathFor(offset);
    assertTrue(TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind()));
    ClassTree ct = (ClassTree)tp.getLeaf();
    TypeElement te = (TypeElement)copy.getTrees().getElement(tp);
    assertNotNull(te);
    List<? extends VariableElement> vars = ElementFilter.fieldsIn(te.getEnclosedElements());
    TypeElement sup = (TypeElement)((DeclaredType)te.getSuperclass()).asElement();
    assertNotNull(sup);
    List<? extends ExecutableElement> ctors = sup.getQualifiedName().contentEquals("java.lang.Object")
            ? null : ElementFilter.constructorsIn(sup.getEnclosedElements());
    if (ctors != null)
        assertEquals(numCtors, ctors.size());
    GeneratorUtilities utilities = GeneratorUtilities.get(copy);
    assertNotNull(utilities);
    ClassTree newCt = utilities.insertClassMember(ct, utilities.createConstructor(te, vars, ctors != null ? ctors.get(ctorToUse) : null));
    copy.rewrite(ct, newCt);
}
 
Example 25
Project: openjdk-jdk10   File: InlineTagsWithBraces.java   View source code 6 votes vote down vote up
public boolean run(DocletEnvironment root) {
        DocTrees trees = root.getDocTrees();
        TypeElement cd = ElementFilter.typesIn(root.getIncludedElements()).iterator().next();
        DocCommentTree docCommentTree = trees.getDocCommentTree(cd);
        List<? extends DocTree> tags = docCommentTree.getBody();

        for (int i = 0; i < tags.size(); i++) {
            System.out.println(tags.get(0).getKind());
//            if (!tags[i].name().equals(expectedTags[i]) ||
//                        !tags[i].text().equals(expectedText[i])) {
//                throw new Error("Tag \"" + tags[i] + "\" not as expected");
//            }
        }

        return true;
    }
 
Example 26
Project: incubator-netbeans   File: ClashingImportsTest.java   View source code 6 votes vote down vote up
public void testAddClashingImport2() throws IOException {
    testFile = getFile(getSourceDir(), getSourcePckg() + "ClashingImports3.java");
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree node = (MethodTree) clazz.getMembers().get(0);
            BlockTree body = node.getBody();
            List<StatementTree> stats = new ArrayList<StatementTree>();
            for(StatementTree st : body.getStatements())
                stats.add(st);
            TypeElement e = workingCopy.getElements().getTypeElement("java.awt.List");
            ExpressionTree type = make.QualIdent(e);
            stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "awtList", type, null));
            workingCopy.rewrite(body, make.Block(stats, false));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testAddClashingImport2.pass");
}
 
Example 27
Project: incubator-netbeans   File: AbstractTestGenerator.java   View source code 5 votes vote down vote up
/**
 * Checks {@literal List} of interfaces if are all of them allowed for LocalBean,
 * means if all interfaces are {@literal java.io.Serializable}, {@literal java.io.Externalizable} or
 * from package {@literal javax.ejb}
 * 
 * @param interfaces {@literal List} of interfaces which should be checked
 * @return {@literal true} if all interfaces are allowed for LocalBean, {@literal false} otherwise
 */
private static boolean areAllowedInterfacesForLocalBean(List<? extends TypeMirror> interfaces) {
    for (TypeMirror typeMirror : interfaces) {
        if (typeMirror instanceof DeclaredType) {
            TypeElement interfaceElement = (TypeElement) ((DeclaredType) typeMirror).asElement();
            String interfaceClassName = interfaceElement.getQualifiedName().toString();
            if (!interfaceClassName.equals("java.io.Serializable")          //NOI18N
                    && !interfaceClassName.equals("java.io.Externalizable") //NOI18N
                    && !interfaceClassName.startsWith("javax.ejb.")) {      //NOI18N
               return false;
            }
        }
    }
    return true;
}
 
Example 28
Project: gwt-jackson-apt   File: BaseInstanceBuilderTest.java   View source code 5 votes vote down vote up
void runTests() throws Exception {
    TestProcessor testProcessor = new TestProcessor();
    final boolean[] executed = {false};
    testProcessor.setDelegate((annotations, roundEnv, typeUtils, elementUtils, filer, messager) -> {
        Optional<? extends Element> element = roundEnv.getElementsAnnotatedWith(TestAnnotation.class).stream().findFirst();
        if (element.isPresent()) {
            executed[0] = true;
            ObjectMapperProcessor.typeUtils = typeUtils;
            ObjectMapperProcessor.elementUtils = elementUtils;
            ObjectMapperProcessor.messager = messager;

            TypeElement typeElement = (TypeElement) typeUtils.asElement(element.get().asType());
            Map<String, ? extends Element> elements = typeElement.getEnclosedElements().stream().filter(e -> ElementKind.FIELD.equals(e.getKind())).collect(Collectors.toMap(o -> o.getSimpleName().toString(), o -> o));
            testSubjects.forEach(testSubject -> {
                if (elements.containsKey(testSubject.fieldName)) {
                    CodeBlock instance = getMappersChainBuilder(element.get().asType()).getInstance(elements.get(testSubject.fieldName));
                    testSubject.tester.testField(instance.toString());
                } else {
                    fail("field not found [" + testSubject.fieldName + "]");
                }
            });
        }
    });

    Compilation compilation = javac().withProcessors(testProcessor).compile(JavaFileObjects.forResource("TestBean.java"));
    assertThat(compilation.status()).isEqualTo(Compilation.Status.SUCCESS);
    assertTrue("the processor did not execute.", executed[0]);
}
 
Example 29
Project: openjdk-jdk10   File: AnnotationTypeRequiredMemberWriterImpl.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void addAnnotationDetailsTreeHeader(TypeElement te,
        Content memberDetailsTree) {
    if (!writer.printedAnnotationHeading) {
        memberDetailsTree.addContent(writer.getMarkerAnchor(
                SectionName.ANNOTATION_TYPE_ELEMENT_DETAIL));
        Content heading = HtmlTree.HEADING(HtmlConstants.DETAILS_HEADING,
                contents.annotationTypeDetailsLabel);
        memberDetailsTree.addContent(heading);
        writer.printedAnnotationHeading = true;
    }
}
 
Example 30
Project: incubator-netbeans   File: InstanceRefFinder.java   View source code 5 votes vote down vote up
/**
 * Adds a super reference. Super reference is treated differently, as it forces a call
 * to a super method (possibly overriden in the subclass), it is not possible to call that
 * method from outside - the override would be called. For calls to super.method, an accessor
 * must be generated.
 * 
 * @param el 
 */
private void addSuperInstance(TypeElement el) {
    if (isEnclosingType(el)) {
        if (superReferences.isEmpty()) {
            superReferences = new HashSet<TypeElement>();
        }
        superReferences.add(el);
    }
    addRequiredInstance(el);
}
 
Example 31
Project: incubator-netbeans   File: JDIWrappersTest.java   View source code 5 votes vote down vote up
private boolean testWrappers(FileObject fo) throws Exception {
    System.out.println("testWrappers("+fo+")");
    ClassPath bootPath = ClassPath.getClassPath(fo, ClassPath.BOOT);
    if (bootPath == null) {
        bootPath = JavaPlatformManager.getDefault().getDefaultPlatform().getBootstrapLibraries();
    }
    ClassPath srcPath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
    ClassPath compilePath = ClassPathSupport.createClassPath(System.getProperty("java.class.path"));
    ClasspathInfo cpi = ClasspathInfo.create(bootPath, compilePath, srcPath);
    JavaSource source = JavaSource.create(cpi, fo);//forFileObject(fo);
    if (source == null) {
        return true;
    }
    final boolean[] successPtr = new boolean[] { true };
    source.runUserActionTask(new Task<CompilationController>() {
        @Override
        public void run(CompilationController ci) throws Exception {
            if (ci.toPhase(Phase.UP_TO_DATE).compareTo(Phase.UP_TO_DATE) < 0) {
                fail("Unable to resolve "+ci.getFileObject()+" to phase "+Phase.UP_TO_DATE+", current phase = "+ci.getPhase()+
                     "\nDiagnostics = "+ci.getDiagnostics()+
                     "\nFree memory = "+Runtime.getRuntime().freeMemory());
                return;
            }
            List<? extends TypeElement> topElements = ci.getTopLevelElements();
            for (TypeElement el : topElements) {
                ClassTree ct = ci.getTrees().getTree(el);
                JDICallsScanner scanner =
                        new JDICallsScanner(ci.getTrees(), ci.getTypes(), ci.getElements(), ci.getCompilationUnit());
                ct.accept(scanner, null);
                successPtr[0] = scanner.isFailed() && successPtr[0];
            }
        }
    }, true);
    return successPtr[0];
}
 
Example 32
Project: incubator-netbeans   File: JUnit3TestGenerator.java   View source code 5 votes vote down vote up
/**
 */
private TypeElement getTestTypeElem(Elements elements) {
    if (testTypeElem == null) {
        testTypeElem = getElemForClassName(
                                    "junit.framework.Test",     //NOI18N
                                    elements);
    }
    return testTypeElem;
}
 
Example 33
Project: incubator-netbeans   File: MainClassChooser.java   View source code 5 votes vote down vote up
public MainClassChooser (final Collection<ElementHandle<TypeElement>> mainClassesInFile, final String subtitle) {
    assert mainClassesInFile != null;
    dialogSubtitle = subtitle;
    this.initComponents();
    jMainClassList.setCellRenderer(new MainClassRenderer());
    initClassesView();
    initClassesModel (mainClassesInFile);
}
 
Example 34
Project: incubator-netbeans   File: ElementUtilities.java   View source code 5 votes vote down vote up
private DeclaredType getDeclaredType(TypeElement e, HashMap<? extends Element, ? extends TypeMirror> map, Types types) {
    List<? extends TypeParameterElement> tpes = e.getTypeParameters();
    TypeMirror[] targs = new TypeMirror[tpes.size()];
    int i = 0;
    for (Iterator<? extends TypeParameterElement> it = tpes.iterator(); it.hasNext();) {
        TypeParameterElement tpe = it.next();
        TypeMirror t = map.get(tpe);
        targs[i++] = t != null ? t : tpe.asType();
    }
    Element encl = e.getEnclosingElement();
    if ((encl.getKind().isClass() || encl.getKind().isInterface()) && !((TypeElement)encl).getTypeParameters().isEmpty())
            return types.getDeclaredType(getDeclaredType((TypeElement)encl, map, types), e, targs);
    return types.getDeclaredType(e, targs);
}
 
Example 35
Project: incubator-netbeans   File: ClassCompleter.java   View source code 5 votes vote down vote up
Set<ElementHandle<TypeElement>> loadDescenantsOfNode() {
    if (namePrefix.length() < PREFIX_TRESHOLD) {
        return loadDescenantsOfNode2();
    }
    TypeElement baseClass = getBaseClass();
    if (baseClass == null) {
        return Collections.emptySet();
    }
    Set<ElementHandle<TypeElement>> handles = new HashSet<ElementHandle<TypeElement>>();

    Set<ElementHandle<TypeElement>> els = ctx.getClasspathInfo().getClassIndex().
            getDeclaredTypes(namePrefix, ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX, 
            EnumSet.of(ClassIndex.SearchScope.DEPENDENCIES, ClassIndex.SearchScope.SOURCE));
    TypeMirror nodeType = baseClass.asType();
    for (Iterator<ElementHandle<TypeElement>> it = els.iterator(); it.hasNext(); ) {
        ElementHandle<TypeElement> h = it.next();
        TypeElement e = h.resolve(ctx.getCompilationInfo());
        if (e == null ||
            !acceptsQName(e.getQualifiedName(), e.getSimpleName()) ||
            e.getModifiers().contains(Modifier.ABSTRACT) ||
            !FxClassUtils.isFxmlAccessible(e) ||
            !ctx.getCompilationInfo().getTypes().isAssignable(e.asType(), nodeType)) {
                continue;
        }
        handles.add(h);
    }
    return handles;
}
 
Example 36
Project: GitHub   File: TypeHierarchyCollector.java   View source code 5 votes vote down vote up
private void collectHierarchyMirrors(TypeMirror typeMirror, String stringRepresentation) {
  if (typeMirror.getKind() != TypeKind.DECLARED
      || typeMirror.toString().equals(Object.class.getName())) {
    return;
  }

  DeclaredType declaredType = toDeclaredType(typeMirror);
  TypeElement e = toTypeElement(declaredType);
  TypevarContext context = new TypevarContext(e, stringRepresentation);

  collectInterfacesMirrors(declaredType, context);

  TypeMirror superclassMirror = e.getSuperclass();
  if (superclassMirror.getKind() != TypeKind.NONE) {
    DeclaredType superclass = toDeclaredType(superclassMirror);
    String stringified = stringify(superclass, context);

    if (!stringified.equals(Object.class.getName())) {
      extendedClasses.add(toTypeElement(superclass));
      extendedClassNames.add(stringified);
      collectHierarchyMirrors(superclass, stringified);
    }
  }

  for (TypeMirror m : e.getInterfaces()) {
    collectUnresolvedInterface(m, context);
    collectInterfacesMirrors(m, context);
  }
}
 
Example 37
Project: domino   File: InjectContextProcessor.java   View source code 5 votes vote down vote up
private String getExtensionPoint(Element e) {
    AnnotationMirror
            providerAnnotation = MoreElements.getAnnotationMirror(e, InjectContext.class).get();
    DeclaredType providerInterface = this.getProviderInterface(providerAnnotation);
    TypeElement typeElement = asTypeElement(providerInterface);
    return typeElement.getQualifiedName().toString();

}
 
Example 38
Project: RNLearn_Project1   File: ReactPropertyProcessor.java   View source code 5 votes vote down vote up
private ClassInfo parseClass(ClassName className, TypeElement typeElement) {
  TypeName targetType = getTargetType(typeElement.asType());
  TypeName viewType = targetType.equals(SHADOW_NODE_TYPE) ? null : targetType;

  ClassInfo classInfo = new ClassInfo(className, typeElement, viewType);
  findProperties(classInfo, typeElement);

  return classInfo;
}
 
Example 39
Project: openjdk-jdk10   File: AnnotationParser.java   View source code 5 votes vote down vote up
private void filterClass(Collection<TypeElement> rootElements, Collection<? extends Element> elements) {
    for (Element element : elements) {
        if (element.getKind().equals(ElementKind.CLASS) || element.getKind().equals(ElementKind.INTERFACE) ||
                element.getKind().equals(ElementKind.ENUM)) {
            rootElements.add((TypeElement) element);
            filterClass(rootElements, ElementFilter.typesIn(element.getEnclosedElements()));
        }
    }
}
 
Example 40
Project: android-auto-mapper   File: AutoMappperProcessor.java   View source code 5 votes vote down vote up
private TypeElement getClassToMapFrom(TypeElement type) {
    TypeMirror map = getMap(type.getAnnotation(AutoMapper.class));
    if (map != null && map.getClass() != null && !map.getClass().getCanonicalName().equals(void.class.getCanonicalName())) {
        return (TypeElement) processingEnv.getTypeUtils().asElement(map);
    }

    return null;
}