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

The following are top voted examples for showing how to use javax.lang.model.element.Element. 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: openjdk-jdk10   File: ModuleTestBase.java   View source code 6 votes vote down vote up
Set<Element> getAllSelectedElements(DocletEnvironment docenv) {
    Set<Element> result = new TreeSet<Element>((Element e1, Element e2) -> {
        // some grouping by kind preferred
        int rc = e1.getKind().compareTo(e2.getKind());
        if (rc != 0) return rc;
        rc = e1.toString().compareTo(e2.toString());
        if (rc != 0) return rc;
        return Integer.compare(e1.hashCode(), e2.hashCode());
    });
    Set<? extends Element> elements = docenv.getIncludedElements();
    for (ModuleElement me : ElementFilter.modulesIn(elements)) {
        addEnclosedElements(docenv, result, me);
    }
    for (PackageElement pe : ElementFilter.packagesIn(elements)) {
        ModuleElement mdle = docenv.getElementUtils().getModuleOf(pe);
        if (mdle != null)
            addEnclosedElements(docenv, result, mdle);
        addEnclosedElements(docenv, result, pe);
    }
    for (TypeElement te : ElementFilter.typesIn(elements)) {
        addEnclosedElements(docenv, result, te);
    }
    return result;
}
 
Example 2
Project: easy-plugins   File: Util.java   View source code 6 votes vote down vote up
/**
 * Checks that {@code target} is visible from {@code fromPkg}.
 * If {@code fromPkg} is {@code null}, we take that to mean that {@code target} should be visible everywhere.
 * Throws an {@link EasyPluginException} with a proper error message if the target element does not match
 * the visibility constraint.
 * @param eles Elements
 * @param target The target element to check for visibility
 * @param fromPkg The package to check for visibility from.
 *                Null indicates it needs to be globally visible.
 * @throws EasyPluginException if it's not visible
 */
static void checkElementVisibility(Elements eles, Element target, String fromPkg) {
    // I would have used a switch, but that messed up compilation somehow.
    // I guess it generated another class file?
    // Anyways, this works.
    if (target.getKind().isClass() || target.getKind().isInterface()) {
        checkClassVisibility(eles, (TypeElement) target, fromPkg);
    } else if (target.getKind().isField()
            || target.getKind() == ElementKind.METHOD
            || target.getKind() == ElementKind.CONSTRUCTOR) {
        checkMemberVisibility(eles, target, fromPkg);
    } else if (target.getKind() == ElementKind.ENUM_CONSTANT) {
        checkClassVisibility(eles, (TypeElement) target.getEnclosingElement(), fromPkg);
    } else {
        // This isn't an EasyPluginException because our code shouldn't be dumb
        // enough to check the visibility of any other kind of element.
        throw new IllegalArgumentException("Bad kind for element visibility check: " + target.getKind());
    }
}
 
Example 3
Project: incubator-netbeans   File: NPECheck.java   View source code 6 votes vote down vote up
@Override
public State visitIdentifier(IdentifierTree node, Void p) {
    super.visitIdentifier(node, p);
    
    Element e = info.getTrees().getElement(getCurrentPath());

    if (e == null || !isVariableElement(e)) {
        return State.POSSIBLE_NULL;
    }
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
        // enum constants are never null
        return State.NOT_NULL;
    }

    State s = variable2State.get((VariableElement) e);
    if (s != null) {
        return s;
    }
    
    return getStateFromAnnotations(info, e);
}
 
Example 4
Project: incubator-netbeans   File: DeleteTransformer.java   View source code 6 votes vote down vote up
private void deleteDeclIfMatch(Tree tree, Element elementToFind) {
    if (JavaPluginUtils.isSyntheticPath(workingCopy, getCurrentPath())) {
        return ;
    }
    
    Element el = workingCopy.getTrees().getElement(getCurrentPath());
    if (isMatch(el, elementToFind)) {
        Tree parent = getCurrentPath().getParentPath().getLeaf();
        Tree newOne = null;
        if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getKind())) {
            newOne = make.removeClassMember((ClassTree) parent, tree);
        } else if (parent.getKind() == Tree.Kind.COMPILATION_UNIT) {
            newOne = make.removeCompUnitTypeDecl((CompilationUnitTree) parent, tree);
        } else if (tree.getKind() == Tree.Kind.VARIABLE) {
            if (parent.getKind() == Tree.Kind.METHOD) {
                newOne = make.removeMethodParameter((MethodTree)parent, (VariableTree) tree);
            } else {
                newOne = make.removeBlockStatement((BlockTree)parent, (VariableTree) tree);
            }
        }
        if (newOne!=null) {
            rewrite(parent,newOne);
        }
    }
}
 
Example 5
Project: incubator-netbeans   File: FindLocalUsagesQuery.java   View source code 6 votes vote down vote up
@Override
public Void visitClass(ClassTree tree, Void d) {
    Element el = info.getTrees().getElement(getCurrentPath());
    if (toFind.equals(el)) {
        try {
            int[] span = treeUtils.findNameSpan(tree);
            if(span != null) {
                MutablePositionRegion region = createRegion(doc, span[0], span[1]);
                usages.add(region);
            }
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    handleJavadoc(getCurrentPath());
    return super.visitClass(tree, d);
}
 
Example 6
Project: prefpin   File: PrefPinProcessor.java   View source code 6 votes vote down vote up
private void buildOnChangeBinding(MethodSpec.Builder constructorBuilder, Element element) {
  OnPrefChange onPrefChange = element.getAnnotation(OnPrefChange.class);
  if (onPrefChange != null) {
    int[] resourceIds = onPrefChange.value();

    for (int resourceId : resourceIds) {
      constructorBuilder.addStatement("target.findPreference(target.getString($L))"
          + ".setOnPreferenceChangeListener(new $T(){\n"
          + "@Override public boolean onPreferenceChange($T preference, Object newValue) {\n"
          + "\t\ttarget.$L(preference, newValue);\n"
          + "\t\treturn true;\n"
          + "\t}\n"
          + "})", resourceId, CHANGE_LISTENER, PREFERENCE, element.getSimpleName());
    }
  }
}
 
Example 7
Project: incubator-netbeans   File: CreateElementUtilities.java   View source code 6 votes vote down vote up
private static List<? extends TypeMirror> computeReturn(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ReturnTree rt = (ReturnTree) parent.getLeaf();
    
    if (rt.getExpression() == error) {
        TreePath method = findMethod(parent);
        
        if (method == null) {
            return null;
        }
        
        Element el = info.getTrees().getElement(method);
        
        if (el == null || el.getKind() != ElementKind.METHOD) {
            return null;
        }
        
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(((ExecutableElement) el).getReturnType());
    }
    
    return null;
}
 
Example 8
Project: javaide   File: PrintingProcessor.java   View source code 6 votes vote down vote up
private void printDocComment(Element e) {
    String docComment = elementUtils.getDocComment(e);

    if (docComment != null) {
        // Break comment into lines
        StringTokenizer st = new StringTokenizer(docComment,
                                                          "\n\r");
        indent();
        writer.println("/**");

        while(st.hasMoreTokens()) {
            indent();
            writer.print(" *");
            writer.println(st.nextToken());
        }

        indent();
        writer.println(" */");
    }
}
 
Example 9
Project: Pogamut3   File: ClassCrawler.java   View source code 6 votes vote down vote up
private List<ParamInfo> getMethodParams(Element classElement) {
    List<ParamInfo> methodParams = new LinkedList<ParamInfo>();
    ExecutableElement methodElement = (ExecutableElement) classElement;

    for (VariableElement methodParam : methodElement.getParameters()) {
        try {
            String name = getParamName(methodParam);
            ParamInfo.Type type = getParamType(methodParam);
            String clsName = getParamClsName(methodParam);
            
            methodParams.add(new ParamInfo(name, type, clsName));
        } catch (IllegalArgumentException ex) {
            // Do nothing, thrown when we are missing some info.
        }
    }
    return methodParams;
}
 
Example 10
Project: incubator-netbeans   File: GoToSupport.java   View source code 6 votes vote down vote up
private static int overridableKind(Element el) {
    if (   el.getModifiers().contains(Modifier.FINAL)
        || el.getModifiers().contains(Modifier.PRIVATE)) {
        return -1;
    }

    if (el.getKind().isClass() || el.getKind().isInterface()) {
        return el.getModifiers().contains(Modifier.ABSTRACT) ? 0 : 1;
    }

    if (   el.getKind() == ElementKind.METHOD
        && !el.getModifiers().contains(Modifier.STATIC)
        && !el.getEnclosingElement().getModifiers().contains(Modifier.FINAL)) {
        return el.getModifiers().contains(Modifier.ABSTRACT) ? 2 : 3;
    }

    return -1;
}
 
Example 11
Project: javaide   File: JavacTaskImpl.java   View source code 6 votes vote down vote up
private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) {
    for (Env<AttrContext> env: queue) {
        switch (env.tree.getTag()) {
            case JCTree.CLASSDEF:
                JCClassDecl cdef = (JCClassDecl) env.tree;
                if (cdef.sym != null)
                    elems.append(cdef.sym);
                break;
            case JCTree.TOPLEVEL:
                JCCompilationUnit unit = (JCCompilationUnit) env.tree;
                if (unit.packge != null)
                    elems.append(unit.packge);
                break;
        }
    }
    genList.addAll(queue);
}
 
Example 12
Project: incubator-netbeans   File: JavaRefactoringPlugin.java   View source code 6 votes vote down vote up
/**
 * Checks if the element is still available. Tests if it is still valid.
 * (Was not deleted by matching mechanism.)
 * If element is available, returns null, otherwise it creates problem.
 * (Helper method for refactoring implementation as this problem is
 * general for all refactorings.)
 *
 * @param   e  element to check
 * @param info 
 * @return  problem message or null if the element is valid
 */
protected static Problem isElementAvail(TreePathHandle e, CompilationInfo info) {
    if (e==null) {
        //element is null or is not valid.
        return new Problem(true, NbBundle.getMessage(FindVisitor.class, "DSC_ElNotAvail")); // NOI18N
    } else {
        Element el = e.resolveElement(info);
        String elName = el != null ? el.getSimpleName().toString() : null;
        if (el == null || el.asType().getKind() == TypeKind.ERROR || "<error>".equals(elName)) { // NOI18N
            return new Problem(true, NbBundle.getMessage(FindVisitor.class, "DSC_ElementNotResolved"));
        }
        
        if ("this".equals(elName) || "super".equals(elName)) { // NOI18N
            return new Problem(true, NbBundle.getMessage(FindVisitor.class, "ERR_CannotRefactorThis", el.getSimpleName()));
        }
        
        // element is still available
        return null;
    }
}
 
Example 13
Project: incubator-netbeans   File: ElementNode.java   View source code 6 votes vote down vote up
public ElementNode getNodeForElement(ElementHandle<Element> eh) {

        if (getDescritption().elementHandle != null
                && eh.signatureEquals(getDescritption().elementHandle)) {
            return this;
        }

        Children ch = getChildren();
        if (ch instanceof ElementChilren) {
            for (Node sub : ch.getNodes()) {
                ElementNode result = ((ElementNode) sub).getNodeForElement(eh);
                if (result != null) {
                    return result;
                }
            }
        }

        return null;
    }
 
Example 14
Project: incubator-netbeans   File: GoToSupportTest.java   View source code 6 votes vote down vote up
public void testGoToTypeVariable() throws Exception {
    final boolean[] wasCalled = new boolean[1];

    performTest("package test; public class Test<TTT> {public void test() {TTT t;}}", 60, new OrigUiUtilsCaller() {
        public void open(FileObject fo, int pos) {
            assertTrue(source == fo);
            assertEquals(32, pos);
            wasCalled[0] = true;
        }
        public void beep() {
            fail("Should not be called.");
        }
        public void open(ClasspathInfo info, Element el) {
            fail("Should not be called.");
        }
    }, false);

    assertTrue(wasCalled[0]);
}
 
Example 15
Project: openjdk-jdk10   File: JavacTaskImpl.java   View source code 6 votes vote down vote up
private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) {
    for (Env<AttrContext> env: queue) {
        switch (env.tree.getTag()) {
            case CLASSDEF:
                JCClassDecl cdef = (JCClassDecl) env.tree;
                if (cdef.sym != null)
                    elems.append(cdef.sym);
                break;
            case MODULEDEF:
                JCModuleDecl mod = (JCModuleDecl) env.tree;
                if (mod.sym != null)
                    elems.append(mod.sym);
                break;
            case PACKAGEDEF:
                JCCompilationUnit unit = env.toplevel;
                if (unit.packge != null)
                    elems.append(unit.packge);
                break;
        }
    }
    genList.addAll(queue);
}
 
Example 16
Project: incubator-netbeans   File: ManyToOneImpl.java   View source code 6 votes vote down vote up
public ManyToOneImpl(final AnnotationModelHelper helper, final Element element, AnnotationMirror manyToOneAnnotation, String name, Map<String, ? extends AnnotationMirror> annByType) {
    this.name = name;
    AnnotationParser parser = AnnotationParser.create(helper);
    parser.expectClass("targetEntity", new DefaultProvider() { // NOI18N
        public Object getDefaultValue() {
            return EntityMappingsUtilities.getElementTypeName(element);
        }
    });
    parser.expectEnumConstantArray("cascade", helper.resolveType("javax.persistence.CascadeType"), new ArrayValueHandler() { // NOI18N
        public Object handleArray(List<AnnotationValue> arrayMembers) {
            return new CascadeTypeImpl(arrayMembers);
        }
    }, parser.defaultValue(new CascadeTypeImpl()));
    parser.expectEnumConstant("fetch", helper.resolveType("javax.persistence.FetchType"), parser.defaultValue("EAGER")); // NOI18N
    parser.expectPrimitive("optional", Boolean.class, parser.defaultValue(true)); // NOI18N
    parseResult = parser.parse(manyToOneAnnotation);

    joinTable = new JoinTableImpl(helper, annByType.get("javax.persistence.JoinTable")); // NOI18N
    joinColumnList = EntityMappingsUtilities.getJoinColumns(helper, annByType);
}
 
Example 17
Project: incap   File: OneToOneAP.java   View source code 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  for (TypeElement annotation : annotations) {
    System.out.println("Processing annotation:" + annotation);
  }

  if (isProcessingDone) {
    return false;
  }

  // generates a class with a constant that contains the name of all classes containing an annotation.
  Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(Annotation1.class);
  Map<String, Set<? extends Element>> mapGeneratedFileNameToOriginatingElements = processElements(annotatedElements);
  generateFiles(filer, mapGeneratedFileNameToOriginatingElements);
  isProcessingDone = true;
  return false;
}
 
Example 18
Project: openjdk-jdk10   File: AnnotationTypeRequiredMemberBuilder.java   View source code 6 votes vote down vote up
/**
 * Build the member documentation.
 *
 * @param memberDetailsTree the content tree to which the documentation will be added
 * @throws DocletException if an error occurs
 */
protected void buildAnnotationTypeMember(Content memberDetailsTree)
        throws DocletException {
    if (writer == null) {
        return;
    }
    if (hasMembersToDocument()) {
        writer.addAnnotationDetailsMarker(memberDetailsTree);
        Element lastMember = members.get((members.size() - 1));
        for (Element member : members) {
            currentMember = member;
            Content detailsTree = writer.getMemberTreeHeader();
            writer.addAnnotationDetailsTreeHeader(typeElement, detailsTree);
            Content annotationDocTree = writer.getAnnotationDocTreeHeader(
                    currentMember, detailsTree);

            buildAnnotationTypeMemberChildren(annotationDocTree);

            detailsTree.addContent(writer.getAnnotationDoc(
                    annotationDocTree, currentMember == lastMember));
            memberDetailsTree.addContent(writer.getAnnotationDetails(detailsTree));
        }
    }
}
 
Example 19
Project: incubator-netbeans   File: StaticImport.java   View source code 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    WorkingCopy copy = ctx.getWorkingCopy();
    TreePath treePath = ctx.getPath();
    TreePath mitp = treePath.getParentPath();
    if (mitp == null) {
        return;
    }
    Element e = copy.getTrees().getElement(treePath);
    if (e == null || !e.getModifiers().contains(Modifier.STATIC)) {
        return;
    }
    TreeMaker make = copy.getTreeMaker();
    copy.rewrite(treePath.getLeaf(), make.Identifier(sn));
    if (fqn == null) {
        return;
    }
    CompilationUnitTree cut = (CompilationUnitTree) copy.resolveRewriteTarget(copy.getCompilationUnit());
    CompilationUnitTree nue = GeneratorUtilities.get(copy).addImports(cut, Collections.singleton(e));
    copy.rewrite(cut, nue);
}
 
Example 20
Project: GitHub   File: Generics.java   View source code 5 votes vote down vote up
Generics(Protoclass protoclass, Element element) {
  this.parameters = computeParameters(protoclass, element);
  this.vars = computeVars(parameters);
  if (this.parameters != NO_PARAMETERS) {
    this.declaration = formatParameters(parameters, true, false);
    this.arguments = formatParameters(parameters, false, false);
    this.unknown = formatParameters(parameters, false, true);
  } else {
    this.declaration = "";
    this.arguments = "";
    this.unknown = "";
  }
}
 
Example 21
Project: EgTest   File: SelfTestMessageHandler.java   View source code 5 votes vote down vote up
private boolean addIfExpected(ExpectedBehavior expected, Element el, String message, Map<String, String> map) {
    EgSelfTest selfTest = el.getAnnotation(EgSelfTest.class);
    if (selfTest != null  &&  expected.equals(selfTest.value())) {
        map.put(JavaModelUtil.key(el), message);
        return true;
    }
    return false;
}
 
Example 22
Project: GitHub   File: Encodings.java   View source code 5 votes vote down vote up
private Naming inferNaming(Element element, EnumSet<Tag> tags, AtomicReference<StandardNaming> standardNaming) {
  Optional<NamingMirror> namingAnnotation = NamingMirror.find(element);
  if (namingAnnotation.isPresent()) {
    try {
      NamingMirror mirror = namingAnnotation.get();
      Naming naming = Naming.from(mirror.value());
      if (mirror.depluralize()) {
        tags.add(Tag.DEPLURALIZE);
      }
      standardNaming.set(mirror.standard());
      return naming;
    } catch (IllegalArgumentException ex) {
      reporter.withElement(element)
          .annotationNamed(NamingMirror.simpleName())
          .error(ex.getMessage());
    }
  }
  if (element.getKind() == ElementKind.FIELD
      || (element.getKind() == ElementKind.METHOD
      && (element.getModifiers().contains(Modifier.PRIVATE) || tags.contains(Tag.PRIVATE)))) {
    return helperNaming(element.getSimpleName());
  }
  if (tags.contains(Tag.INIT) || tags.contains(Tag.COPY)) {
    return Naming.identity();
  }
  String encodedMethodName = element.getSimpleName().toString();
  return Naming.from("*" + Naming.Usage.CAPITALIZED.apply(encodedMethodName));
}
 
Example 23
Project: openjdk-jdk10   File: Utils.java   View source code 5 votes vote down vote up
/**
 * Returns a Comparator for packages, by comparing the fully qualified names.
 *
 * @return a Comparator
 */
public Comparator<Element> makePackageComparator() {
    if (packageComparator == null) {
        packageComparator = new Utils.ElementComparator() {
            @Override
            public int compare(Element pkg1, Element pkg2) {
                return compareFullyQualifiedNames(pkg1, pkg2);
            }
        };
    }
    return packageComparator;
}
 
Example 24
Project: incubator-netbeans   File: Utilities.java   View source code 5 votes vote down vote up
private @NonNull String getVariable(@NonNull Element el) {
    String var = element2Variable.get(el);

    if (var == null) {
        element2Variable.put(el, var = "$" + currentVariableIndex++);
    }

    return var;
}
 
Example 25
Project: data-mediator   File: MediatorAnnotationProcessor.java   View source code 5 votes vote down vote up
private CodeGenerator getProxyClass(Element element) {
    //element which is annotated .
    TypeElement classElement = (TypeElement) element;
    String qualifiedName = classElement.getQualifiedName().toString();
    CodeGenerator proxyClass = mProxyClassMap.get(qualifiedName);
    if (proxyClass == null) {
        proxyClass = new CodeGenerator(mTypeUtils, mElementUtils, classElement);
        mProxyClassMap.put(qualifiedName, proxyClass);
    }
    return proxyClass;
}
 
Example 26
Project: incubator-netbeans   File: LayerGenerationException.java   View source code 5 votes vote down vote up
private static AnnotationMirror findAnnotationMirror(Element element, ProcessingEnvironment processingEnv, Class<? extends Annotation> annotation) {
    for (AnnotationMirror ann : element.getAnnotationMirrors()) {
        if (processingEnv.getElementUtils().getBinaryName((TypeElement) ann.getAnnotationType().asElement()).
                contentEquals(annotation.getName())) {
            return ann;
        }
    }
    return null;
}
 
Example 27
Project: syndesis   File: SyndesisExtensionActionProcessor.java   View source code 5 votes vote down vote up
protected void persistToFile(Element element, Properties props) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    File file = obtainResourceFile(element);
    if (file != null) {
        try (Writer writer = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) {
            props.store(writer, "Generated by Syndesis Annotation Processor");
        }
    }
}
 
Example 28
Project: incubator-netbeans   File: Utilities.java   View source code 5 votes vote down vote up
public static AnnotationMirror findAnnotation(Element element, String annotationClass){
    for (AnnotationMirror ann : element.getAnnotationMirrors()){
        if (annotationClass.equals(ann.getAnnotationType().toString())){
            return ann;
        }
    }
    
    return null;
}
 
Example 29
Project: incubator-netbeans   File: ImportClass.java   View source code 5 votes vote down vote up
private FixBase(FileObject file, String fqn, ElementHandle<Element> toImport, String sortText, boolean isValid) {
    this.isValid = isValid;
    this.file = file;
    this.fqn = fqn;
    this.toImport = toImport;
    this.sortText = sortText;
}
 
Example 30
Project: sql-first-mapper   File: SqlFirstAnnotationProcessor.java   View source code 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        return false;
    }

    Element globalConfigElement = null;
    try {
        globalConfigElement = prepareGlobalConfig(roundEnv);
        SqlFirstApcConfig globalConfig = globalConfigElement.getAnnotation(SqlFirstApcConfig.class);
        List<DaoDesc> daoDescList = processSqlSource(roundEnv, globalConfig);

        if (globalConfig != null) {
            prepareDaoClassImplementMap(daoDescList, roundEnv);
            DaoWriter daoWriter = new DaoWriter(processingEnv);
            daoWriter.write(daoDescList, globalConfig);
        }
        return !daoDescList.isEmpty();
    
    } catch (RuntimeException ex) {
        if (globalConfigElement == null) {
            roundEnv.getElementsAnnotatedWith(SqlSource.class).forEach(x ->
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ExceptionUtils.getFullStackTrace(ex), x)
            );
        } else {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ExceptionUtils.getFullStackTrace(ex), globalConfigElement);
    
        }
    }
    return false;
}
 
Example 31
Project: openjdk-jdk10   File: Utils.java   View source code 5 votes vote down vote up
private List<Element> getItems0(Element te, boolean filter, Set<ElementKind> kinds) {
    List<Element> elements = new ArrayList<>();
    for (Element e : te.getEnclosedElements()) {
        if (kinds.contains(e.getKind())) {
            if (!filter || shouldDocument(e)) {
                elements.add(e);
            }
        }
    }
    return elements;
}
 
Example 32
Project: openjdk-jdk10   File: Extern.java   View source code 5 votes vote down vote up
/**
 * Determine if a element item is externally documented.
 *
 * @param element an Element.
 * @return true if the element is externally documented
 */
public boolean isExternal(Element element) {
    if (packageToItemMap == null) {
        return false;
    }
    PackageElement pe = configuration.utils.containingPackage(element);
    if (pe.isUnnamed()) {
        return false;
    }
    return packageToItemMap.get(configuration.utils.getPackageName(pe)) != null;
}
 
Example 33
Project: GitHub   File: ButterKnifeProcessor.java   View source code 5 votes vote down vote up
private void parseResourceBool(Element element,
    Map<TypeElement, BindingSet.Builder> builderMap, Set<TypeElement> erasedTargetNames) {
  boolean hasError = false;
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

  // Verify that the target type is bool.
  if (element.asType().getKind() != TypeKind.BOOLEAN) {
    error(element, "@%s field type must be 'boolean'. (%s.%s)",
        BindBool.class.getSimpleName(), enclosingElement.getQualifiedName(),
        element.getSimpleName());
    hasError = true;
  }

  // Verify common generated code restrictions.
  hasError |= isInaccessibleViaGeneratedCode(BindBool.class, "fields", element);
  hasError |= isBindingInWrongPackage(BindBool.class, element);

  if (hasError) {
    return;
  }

  // Assemble information on the field.
  String name = element.getSimpleName().toString();
  int id = element.getAnnotation(BindBool.class).value();
  QualifiedId qualifiedId = elementToQualifiedId(element, id);
  BindingSet.Builder builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
  builder.addResource(
      new FieldResourceBinding(getId(qualifiedId), name, FieldResourceBinding.Type.BOOL));

  erasedTargetNames.add(enclosingElement);
}
 
Example 34
Project: butterknife-parent   File: ButterKnifeProcessor.java   View source code 5 votes vote down vote up
private static boolean hasAnnotationWithName(Element element, String simpleName) {
  for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
    String annotationName = mirror.getAnnotationType().asElement().getSimpleName().toString();
    if (simpleName.equals(annotationName)) {
      return true;
    }
  }
  return false;
}
 
Example 35
Project: incubator-netbeans   File: HibernateFindUsagesPlugin.java   View source code 5 votes vote down vote up
private void findJavaClassUsage(final TreePathHandle treePathHandle,
        RefactoringElementsBag refactoringElements, FileObject classFile) throws IOException {

    // Figure out the class binary name
    final String[] binaryClassName = new String[]{null};
    JavaSource javaSource = JavaSource.forFileObject(classFile);
    if (javaSource == null) {
        return;
    }

    javaSource.runUserActionTask(new Task<CompilationController>() {

        public void run(CompilationController cc) throws IOException {
            cc.toPhase(Phase.ELEMENTS_RESOLVED);
            Element element = treePathHandle.resolveElement(cc);
            if (element == null || element.getKind() != ElementKind.CLASS) {
                return;
            }
            binaryClassName[0] = ElementUtilities.getBinaryName((TypeElement) element);
        }
    }, true);

    String className = binaryClassName[0];
    if (className != null) {
        Map<FileObject, List<OccurrenceItem>> occurrences =
                HibernateRefactoringUtil.getJavaClassOccurrences(mappingFileObjs, className);

        for (FileObject mFileObj : occurrences.keySet()) {
            List<OccurrenceItem> foundPlaces = occurrences.get(mFileObj);
            for( OccurrenceItem foundPlace : foundPlaces ) {
                HibernateRefactoringElement elem = new HibernateRefactoringElement(mFileObj,
                        className,
                        foundPlace.getMatching(),
                        foundPlace.getLocation(),
                        foundPlace.getText());
                refactoringElements.add(query, elem);
            }
        }
    }
}
 
Example 36
Project: GeneratorX   File: GeneratorProcessor.java   View source code 5 votes vote down vote up
private AnnotatedClass buildAnnotatedClass(TypeElement typeElement) throws
        NoPackageNameException, IOException {

    HashMap<String, TypeMirror> variableMap = new HashMap<>();
    ArrayList<String> variableNames = new ArrayList<>();
    for (Element element : typeElement.getEnclosedElements()) {
        //过滤 字段 的Element
        if (!(element instanceof VariableElement)) {
            continue;
        }
        //过滤 static final 字段
        if (element.getModifiers().contains(STATIC) || element.getModifiers().contains(FINAL)) {
            continue;
        }
        VariableElement variableElement = (VariableElement) element;
        variableNames.add(variableElement.getSimpleName().toString());
        variableMap.put(
                variableElement.getSimpleName().toString(),
                variableElement.asType()
        );
    }

    //打印 用于测试 是否为 parcelable
    if (isParcelable(typeElement)) {
        String message = String.format("Classes %s is parceleble.", ANNOTATION);
        //messager.printMessage(Diagnostic.Kind.OTHER, message, typeElement);
    }
    return new AnnotatedClass(typeElement, variableNames, variableMap,
            isParcelable(typeElement));
}
 
Example 37
Project: GitHub   File: SwitcherModel.java   View source code 5 votes vote down vote up
private ImmutableList<SwitchOption> constructOptions() {
  ImmutableList.Builder<SwitchOption> builder = ImmutableList.builder();

  for (Element v : containedTypeElement.getEnclosedElements()) {
    if (v.getKind() == ElementKind.ENUM_CONSTANT) {
      String name = v.getSimpleName().toString();
      builder.add(new SwitchOption(name, defaultName.equals(name)));
    }
  }

  return builder.build();
}
 
Example 38
Project: react4j   File: ProcessorUtil.java   View source code 5 votes vote down vote up
@SuppressWarnings( "SameParameterValue" )
@Nonnull
static AnnotationValue getAnnotationValue( @Nonnull final Elements elements,
                                           @Nonnull final Element typeElement,
                                           @Nonnull final String annotationClassName,
                                           @Nonnull final String parameterName )
{
  final AnnotationValue value = findAnnotationValue( elements, typeElement, annotationClassName, parameterName );
  assert null != value;
  return value;
}
 
Example 39
Project: RxAndroidOrm   File: ModelEntityProxyGenerator.java   View source code 5 votes vote down vote up
public TypeSpec generate() {
    String idFieldName = Constants.FIELD_ID;
    Element idField = ProcessUtils.getIdField(element);
    if (idField != null)
        idFieldName = ProcessUtils.getObjectName(idField);

    TypeSpec.Builder builder = TypeSpec.classBuilder(ProcessUtils.getObjectName(element) + Constants.MODEL_ENTITY_PROXY)
            .addModifiers(Modifier.PUBLIC)
            .superclass(TypeName.get(element.asType()))
            .addSuperinterface(ClassName.get(Constants.DAO_PACKAGE, Constants.MODEL_ENTITY_PROXY_INTERFACE));

    if (idField == null) {
        builder.addField(TypeName.LONG, Constants.FIELD_ID);
    }

    builder.addMethod(MethodSpec.methodBuilder(Constants.MODEL_ENTITY_PROXY_GET_ID_METHOD)
            .addModifiers(Modifier.PUBLIC)
            .returns(TypeName.LONG)
            .addStatement("return $L", idFieldName)
            .build())
            .addMethod(MethodSpec.methodBuilder(Constants.MODEL_ENTITY_PROXY_SET_ID_METHOD)
                    .addModifiers(Modifier.PUBLIC)
                    .returns(TypeName.VOID)
                    .addParameter(TypeName.LONG, "id")
                    .addStatement("this.$L = id", idFieldName)
                    .build());

    return builder.build();
}
 
Example 40
Project: openjdk-jdk10   File: Messager.java   View source code 5 votes vote down vote up
private String getDiagSource(Element e) {
    if (e == null) {
        return programName;
    }
    JavacTrees trees = JavacTrees.instance(context);
    TreePath path = trees.getPath(e);
    DocSourcePositions sourcePositions = trees.getSourcePositions();
    JCTree tree = trees.getTree(e);
    CompilationUnitTree cu = path.getCompilationUnit();
    long spos = sourcePositions.getStartPosition(cu, tree);
    long lineNumber = cu.getLineMap().getLineNumber(spos);
    String fname = cu.getSourceFile().getName();
    String posString = fname + ":" + lineNumber;
    return posString;
}