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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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;
}
 
Example 41
Project: GitHub   File: Metaservices.java   Source Code and License 5 votes vote down vote up
ListMultimap<String, String> allMetaservices() {
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();

  for (Element element : round().getElementsAnnotatedWith(Metainf.Service.class)) {
    @Nullable TypeElement typeElement = validated(element);
    if (typeElement == null) {
      continue;
    }
    Set<String> interfaceNames = extractServiceInterfaceNames(typeElement);
    String binaryName = processing().getElementUtils().getBinaryName(typeElement).toString();
    builder.putAll(binaryName, interfaceNames);
  }

  return builder.build();
}
 
Example 42
Project: incubator-netbeans   File: ConvertToLambdaPreconditionChecker.java   Source Code and License 5 votes vote down vote up
private List<TypeMirror> getTypesFromElements(List<? extends VariableElement> elements) {
    List<TypeMirror> elementTypes = new ArrayList<TypeMirror>();
    for (Element e : elements) {
        elementTypes.add(e.asType());
    }
    return elementTypes;
}
 
Example 43
Project: incubator-netbeans   File: JavadocGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * computes name of throws clause to work around
 * <a href="http://www.netbeans.org/issues/show_bug.cgi?id=160414">issue 160414</a>.
 */
private static String resolveThrowsName(Element el, String fqn, ExpressionTree throwTree) {
    boolean nestedClass = ElementKind.CLASS == el.getKind()
            && NestingKind.TOP_LEVEL != ((TypeElement) el).getNestingKind();
    String insertName = nestedClass ? fqn : throwTree.toString();
    return insertName;
}
 
Example 44
Project: incubator-netbeans   File: ConvertToLambdaPreconditionChecker.java   Source Code and License 5 votes vote down vote up
private ExecutableElement getElementFromInvokingTree(TreePath treePath) {
    Tree invokingTree = treePath.getLeaf();
    Element result;
    if (invokingTree.getKind() == Tree.Kind.METHOD_INVOCATION) {
        MethodInvocationTree invokingMethTree = ((MethodInvocationTree) invokingTree);
        TreePath methodTreePath = new TreePath(treePath, invokingMethTree);
        result = getElementFromTreePath(methodTreePath);
    } else {
        result = getElementFromTreePath(treePath);
    }
    if (result != null && (result.getKind() == ElementKind.CONSTRUCTOR || result.getKind() == ElementKind.METHOD)) {
        return (ExecutableElement) result;
    }
    return null;
}
 
Example 45
Project: incubator-netbeans   File: ArrayStringConversions.java   Source Code and License 5 votes vote down vote up
/**
 * Determines whether the array can contain other arrays. Checks if the component type is an array type.
 * Otherwise, checks whether the component type is a declared one, and that it is an Object. Other declared
 * types cannot hold array references.
 * 
 * @param ci context
 * @param tp path to the array expression
 * @return true, if the expression (assuming array type) can hold other arrays as members
 */
static boolean canContainArrays(CompilationInfo ci, TreePath tp) {
    TypeMirror tm = ci.getTrees().getTypeMirror(tp);
    if (!Utilities.isValidType(tm)) {
        return false;
    }
    tm = ci.getTypes().erasure(tm);
    if (tm == null || tm.getKind() != TypeKind.ARRAY) {
        return false;
    }
    ArrayType arrayType = (ArrayType)tm;
    TypeMirror ct = arrayType.getComponentType();
    boolean enableDeep = false;
    
    if (ct.getKind() == TypeKind.ARRAY) {
        // if the component kind is known to be an array, enable deepHash
        enableDeep = true;
    } else if (ct.getKind() == TypeKind.DECLARED) {
        Element obj = ci.getElements().getTypeElement("java.lang.Object"); // NOI18N
        if (obj == null) {
            return false;
        }
        // other ref types than Object cannot hold array instances, deepHash is a nonsense
        enableDeep = ci.getTypes().isSameType(obj.asType(), ct);
    }
    return enableDeep;
}
 
Example 46
Project: Java-9-Programming-By-Example   File: Aptools.java   Source Code and License 5 votes vote down vote up
/**
 * Get the list of the methods from the element.
 * 
 * @return list of the method elements in form of ExecutableElements
 */
@Transition(from = "ElementTool", end = true)
public List<ExecutableElement> getMethods() {
  List<ExecutableElement> methodElements = new LinkedList<>();
  for (Element methodElement : element.getEnclosedElements()) {
    if (methodElement.getKind().equals(ElementKind.METHOD)) {
      methodElements.add((ExecutableElement) methodElement);
    }
  }
  return methodElements;
}
 
Example 47
Project: openjdk-jdk10   File: ApNavigator.java   Source Code and License 5 votes vote down vote up
private Location getLocation(Element element) {
    Trees trees = Trees.instance(env);
    return getLocation(
            ((TypeElement) element.getEnclosingElement()).getQualifiedName() + "." + element.getSimpleName(),
            trees.getPath(element)
    );
}
 
Example 48
Project: incubator-netbeans   File: NbBundleProcessor.java   Source Code and License 5 votes vote down vote up
private void addToAnnotatedElements(Collection<? extends Element> unscannedElements, Set<Element> annotatedElements) {
    for (Element e : unscannedElements) {
        if (e.getAnnotation(NbBundle.Messages.class) != null) {
            annotatedElements.add(e);
        }
        if (e.getKind() != ElementKind.PACKAGE) {
            addToAnnotatedElements(e.getEnclosedElements(), annotatedElements);
        }
    }
}
 
Example 49
Project: CustomAnnotation   File: ProxyToolProcessor.java   Source Code and License 5 votes vote down vote up
/**
 * 注解是否有效
 * @author leibing
 * @createTime 2017/3/2
 * @lastModify 2017/3/2
 * @param annotationClass
 * @param targetThing
 * @param element 元素
 * @return
 */
private boolean isValid(Class<? extends Annotation> annotationClass, String targetThing, Element element) {
    boolean isVaild = true;
    // 获取变量的所在的父元素,肯能是类、接口、枚举
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
    // 父元素的全限定名
    String qualifiedName = enclosingElement.getQualifiedName().toString();
    // 所在的类不能是private或static修饰
    Set<Modifier> modifiers = element.getModifiers();
    if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) {
        error(element, "@%s %s must not be private or static. (%s.%s)",
                annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(),
                element.getSimpleName());
        isVaild = false;
    }
    // 父元素必须是类,而不能是接口或枚举
    if (enclosingElement.getKind() != ElementKind.CLASS) {
        error(enclosingElement, "@%s %s may only be contained in classes. (%s.%s)",
                annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(),
                element.getSimpleName());
        isVaild = false;
    }
    // 不能在Android框架层注解
    if (qualifiedName.startsWith("android.")) {
        error(element, "@%s-annotated class incorrectly in Android framework package. (%s)",
                annotationClass.getSimpleName(), qualifiedName);
        return false;
    }
    // 不能在java框架层注解
    if (qualifiedName.startsWith("java.")) {
        error(element, "@%s-annotated class incorrectly in Java framework package. (%s)",
                annotationClass.getSimpleName(), qualifiedName);
        return false;
    }

    return isVaild;
}
 
Example 50
Project: auto   File: EnrichedTypeElement.java   Source Code and License 5 votes vote down vote up
private List<Element> getEnclosingElements() {
  List<Element> elements = new ArrayList<>();
  Element enclosing = type.getEnclosingElement();

  while (enclosing != null && !(enclosing instanceof PackageElement)) {
    elements.add(enclosing);
    enclosing = enclosing.getEnclosingElement();
  }

  return elements;
}
 
Example 51
Project: incubator-netbeans   File: ConvertAnonymousToInner.java   Source Code and License 5 votes vote down vote up
@Override
public Void visitIdentifier(IdentifierTree node, Set<VariableElement> p) {
    Element el = info.getTrees().getElement(getCurrentPath());
    TreePath elPath = el != null ? info.getTrees().getPath(el) : null;
    
    if (el != null && elPath != null && VARIABLES.contains(el.getKind()) && !isParent(newClassToConvert, elPath)) {
        p.add((VariableElement) el);
    }
    
    return super.visitIdentifier(node, p);
}
 
Example 52
Project: Spyglass   File: TestGetValueMethodGenerator.java   Source Code and License 5 votes vote down vote up
@Test
public void testGenerateFor_EnumOrdinalHandlerAnnotationSupplied() {
	final Element element = avatarRule.getElementWithUniqueId("enum ordinal");
	final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, EnumOrdinalHandler.class);

	final MethodSpec generatedMethod = generator.generateFor(mirror);

	checkSignature(generatedMethod, ClassName.get(Number.class));
	checkCompiles(generatedMethod);
}
 
Example 53
Project: incubator-netbeans   File: MoveBase.java   Source Code and License 5 votes vote down vote up
void performMove(FileObject source, final int[] position, final String target, final Visibility visibility, Problem... expectedProblems) throws IOException, IllegalArgumentException, InterruptedException {
    final MoveRefactoring[] r = new MoveRefactoring[1];
    final JavaMoveMembersProperties[] properties = new JavaMoveMembersProperties[1];
    JavaSource.forFileObject(source).runUserActionTask(new Task<CompilationController>() {

        @Override
        public void run(CompilationController info) throws Exception {
            info.toPhase(JavaSource.Phase.RESOLVED);
            CompilationUnitTree cut = info.getCompilationUnit();
            final ClassTree classTree = (ClassTree) cut.getTypeDecls().get(0);
            final TreePath classPath = info.getTrees().getPath(cut, classTree);
            TypeElement classEl = (TypeElement) info.getTrees().getElement(classPath);
            List<? extends Element> allMembers = classEl.getEnclosedElements();
            TreePathHandle[] handles = new TreePathHandle[position.length];
            for (int i = 0; i < position.length; i++) {
                handles[i] = TreePathHandle.create(allMembers.get(position[i]), info);
            }
            r[0] = new MoveRefactoring(Lookups.fixed((Object[]) handles));
            properties[0] = new JavaMoveMembersProperties(handles);
            
            TypeElement typeElement = info.getElements().getTypeElement(target);
            r[0].setTarget(Lookups.singleton(TreePathHandle.create(typeElement, info)));
        }
    }, true);
    properties[0].setVisibility(visibility);
    r[0].getContext().add(properties[0]);

    RefactoringSession rs = RefactoringSession.create("Session");
    List<Problem> problems = new LinkedList<Problem>();
    addAllProblems(problems, r[0].preCheck());
    if (!problemIsFatal(problems)) {
        addAllProblems(problems, r[0].prepare(rs));
    }
    if (!problemIsFatal(problems)) {
        addAllProblems(problems, rs.doRefactoring(true));
    }
    assertProblems(Arrays.asList(expectedProblems), problems);
}
 
Example 54
Project: LifecycleAware   File: ModifierRule.java   Source Code and License 5 votes vote down vote up
@Override
public boolean apply(Element element) {
    Set<Modifier> modifiers = element.getModifiers();
    boolean invalidModifiers = modifiers.contains(Modifier.PRIVATE)
            || modifiers.contains(Modifier.PROTECTED)
            || modifiers.contains(Modifier.FINAL);
    return !invalidModifiers;
}
 
Example 55
Project: incubator-netbeans   File: ElementScanningTask.java   Source Code and License 5 votes vote down vote up
@Override
public Context visitVariable(VariableTree node, Void p) {
    Element e = this.trees.getElement(this.getCurrentPath());
    if (e != null) {
        long pos = this.sourcePositions.getStartPosition(cu, node);
        ctx.pos.put(e, pos);
    }
    return null;
}
 
Example 56
Project: incubator-netbeans   File: UiUtils.java   Source Code and License 5 votes vote down vote up
/**
    * Opens given {@link Element}.
    * 
    * @param cpInfo fileobject whose {@link ClasspathInfo} will be used
    * @param el    declaration to open
    * @return true if and only if the declaration was correctly opened,
    *                false otherwise
    * @deprecated Use {@link org.netbeans.api.java.source.ui.ElementOpen#open(org.netbeans.api.java.source.ClasspathInfo, org.netbeans.api.java.source.ElementHandle) }
    *             of the org.netbeans.modules.java.sourceui module
    */
   @Deprecated
   public static boolean open(final ClasspathInfo cpInfo, final Element el) {
Object[] openInfo = getOpenInfo (cpInfo, el);
if (openInfo != null) {
    assert openInfo[0] instanceof FileObject;
    assert openInfo[1] instanceof Integer;
    return doOpen((FileObject)openInfo[0],(Integer)openInfo[1]);
}
return false;
   }
 
Example 57
Project: GitHub   File: ProxyProcessor.java   Source Code and License 5 votes vote down vote up
@Override
public Iterable<? extends Completion> getCompletions(
    Element element,
    AnnotationMirror annotation,
    ExecutableElement member,
    String userText) {
  return delegate.getCompletions(element, annotation, member, userText);
}
 
Example 58
Project: openjdk-jdk10   File: Utils.java   Source Code and License 5 votes vote down vote up
public boolean isExecutableElement(Element e) {
    ElementKind kind = e.getKind();
    switch (kind) {
        case CONSTRUCTOR: case METHOD: case INSTANCE_INIT:
            return true;
        default:
            return false;
    }
}
 
Example 59
Project: android-auto-mapper   File: MoreTypes.java   Source Code and License 4 votes vote down vote up
@Override
public Element visitError(ErrorType t, Void p) {
    return t.asElement();
}
 
Example 60
Project: openjdk-jdk10   File: CommentUtils.java   Source Code and License 4 votes vote down vote up
public DocCommentDuo getSyntheticCommentDuo(Element e) {
    return dcTreesMap.get(e);
}