Java Code Examples for javax.lang.model.util.ElementFilter

The following are top voted examples for showing how to use javax.lang.model.util.ElementFilter. 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: MatchProcessor.java   View source code 6 votes vote down vote up
private static AnnotationValue getAnnotationValue(AnnotationMirror mirror, String name) {
    ExecutableElement valueMethod = null;
    for (ExecutableElement method : ElementFilter.methodsIn(mirror.getAnnotationType().asElement().getEnclosedElements())) {
        if (method.getSimpleName().toString().equals(name)) {
            valueMethod = method;
            break;
        }
    }

    if (valueMethod == null) {
        return null;
    }

    AnnotationValue value = mirror.getElementValues().get(valueMethod);
    if (value == null) {
        value = valueMethod.getDefaultValue();
    }

    return value;
}
 
Example 2
Project: data-mediator   File: ElementHandle.java   View source code 6 votes vote down vote up
@Override 
protected ExecutableElement doGet(ProcessingEnvironment env) { 
  TypeElement typeElt = env.getElementUtils().getTypeElement(fqn.getName()); 
  if (typeElt != null) { 
    next: 
    for (ExecutableElement executableElement : ElementFilter.methodsIn(typeElt.getEnclosedElements())) {
      if (executableElement.getSimpleName().toString().equals(name)) { 
        List<? extends TypeMirror> parameterTypes = ((ExecutableType)executableElement.asType()).getParameterTypes(); 
        int len = parameterTypes.size(); 
        if (len == this.parameterTypes.size()) { 
          for (int i = 0;i < len;i++) { 
            if (!parameterTypes.get(i).toString().equals(this.parameterTypes.get(i))) { 
              continue next; 
            } 
          } 
          return executableElement; 
        } 
      } 
    } 
  } 
  return null; 
}
 
Example 3
Project: OpenJSharp   File: Gen.java   View source code 6 votes vote down vote up
/**
 * Including super classes' fields.
 */

List<VariableElement> getAllFields(TypeElement subclazz) {
    List<VariableElement> fields = new ArrayList<VariableElement>();
    TypeElement cd = null;
    Stack<TypeElement> s = new Stack<TypeElement>();

    cd = subclazz;
    while (true) {
        s.push(cd);
        TypeElement c = (TypeElement) (types.asElement(cd.getSuperclass()));
        if (c == null)
            break;
        cd = c;
    }

    while (!s.empty()) {
        cd = s.pop();
        fields.addAll(ElementFilter.fieldsIn(cd.getEnclosedElements()));
    }

    return fields;
}
 
Example 4
Project: openjdk-jdk10   File: Utils.java   View source code 6 votes vote down vote up
public ExecutableElement overriddenMethod(ExecutableElement method) {
    if (isStatic(method)) {
        return null;
    }
    final TypeElement origin = getEnclosingTypeElement(method);
    for (TypeMirror t = getSuperType(origin);
            t.getKind() == DECLARED;
            t = getSuperType(asTypeElement(t))) {
        TypeElement te = asTypeElement(t);
        if (te == null) {
            return null;
        }
        List<? extends Element> methods = te.getEnclosedElements();
        for (ExecutableElement ee : ElementFilter.methodsIn(methods)) {
            if (configuration.workArounds.overrides(method, ee, origin)) {
                return ee;
            }
        }
        if (t.equals(getObjectType()))
            return null;
    }
    return null;
}
 
Example 5
Project: auto-value-json   File: AutoValueJsonExtension.java   View source code 6 votes vote down vote up
private static boolean generateReadMethod(Context context) {
  TypeElement type = context.autoValueClass();
  //Find method with param as JSONObject and return type as autovalue class.
  for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) {
    if (method.getModifiers().contains(Modifier.STATIC) && method.getParameters().size() == 1) {
      TypeMirror rType = method.getReturnType();
      TypeName returnType = TypeName.get(rType);

      TypeMirror pType = method.getParameters().get(0).asType();
      TypeName paramType = TypeName.get(pType);
      if (returnType.equals(TypeName.get(type.asType())) && paramType.equals(
          JSON_OBJ_CLASS_NAME)) {
        return true;
      }
    }
  }
  return false;
}
 
Example 6
Project: incubator-netbeans   File: SourceUtilsTest.java   View source code 6 votes vote down vote up
public void testIsDeprecated2() throws Exception {
    prepareTest();
    
    TypeElement test = info.getElements().getTypeElement("sourceutils.TestIsDeprecated2");
    
    assertNotNull(test);
    
    ExecutableElement methodDeprecated = findElementBySimpleName("methodDeprecated", ElementFilter.methodsIn(test.getEnclosedElements()));
    ExecutableElement methodNotDeprecated = findElementBySimpleName("methodNotDeprecated", ElementFilter.methodsIn(test.getEnclosedElements()));
    VariableElement fieldDeprecated = findElementBySimpleName("fieldDeprecated", ElementFilter.fieldsIn(test.getEnclosedElements()));
    VariableElement fieldNotDeprecated = findElementBySimpleName("fieldNotDeprecated", ElementFilter.fieldsIn(test.getEnclosedElements()));
    TypeElement classDeprecated = findElementBySimpleName("classDeprecated", ElementFilter.typesIn(test.getEnclosedElements()));
    TypeElement classNotDeprecated = findElementBySimpleName("classNotDeprecated", ElementFilter.typesIn(test.getEnclosedElements()));
    
    assertFalse(info.getElements().isDeprecated(methodNotDeprecated));
    assertFalse(info.getElements().isDeprecated(fieldNotDeprecated));
    assertFalse(info.getElements().isDeprecated(classNotDeprecated));

    assertTrue(info.getElements().isDeprecated(methodDeprecated));
    assertTrue(info.getElements().isDeprecated(fieldDeprecated));
    assertTrue(info.getElements().isDeprecated(classDeprecated));
}
 
Example 7
Project: incubator-netbeans   File: GeneratorUtilitiesTest.java   View source code 6 votes vote down vote up
public void validate(CompilationInfo info) {
    TypeElement test = info.getElements().getTypeElement("test.Test");

    boolean foundRunMethod = false;

    for (ExecutableElement ee : ElementFilter.methodsIn(test.getEnclosedElements())) {
        if ("run".equals(ee.getSimpleName().toString())) {
            if (ee.getParameters().isEmpty()) {
                assertFalse(foundRunMethod);
                foundRunMethod = true;
            }
        }
    }

    assertTrue(foundRunMethod);
}
 
Example 8
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);
    ArrayList<ExecutableElement> methods = new ArrayList<ExecutableElement>(2);
    TypeElement object = copy.getElements().getTypeElement("java.lang.Object");
    assertNotNull(object);
    for (ExecutableElement method : ElementFilter.methodsIn(object.getEnclosedElements())) {
        if (method.getSimpleName().contentEquals("clone"))
            methods.add(method);
        else if (method.getSimpleName().contentEquals("toString"))
            methods.add(method);
    }
    GeneratorUtilities utilities = GeneratorUtilities.get(copy);
    assertNotNull(utilities);
    ClassTree newCt = utilities.insertClassMembers(ct, utilities.createOverridingMethods(te, methods));
    copy.rewrite(ct, newCt);
}
 
Example 9
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);
    ArrayList<ExecutableElement> methods = new ArrayList<ExecutableElement>(1);
    TypeElement sup = (TypeElement)((DeclaredType)te.getSuperclass()).asElement();
    assertNotNull(sup);
    for (ExecutableElement method : ElementFilter.methodsIn(sup.getEnclosedElements())) {
        if (method.getSimpleName().contentEquals("test"))
            methods.add(method);
    }
    GeneratorUtilities utilities = GeneratorUtilities.get(copy);
    assertNotNull(utilities);
    ClassTree newCt = utilities.insertClassMembers(ct, utilities.createOverridingMethods(te, methods));
    copy.rewrite(ct, newCt);
}
 
Example 10
Project: incubator-netbeans   File: GeneratorUtilitiesTest.java   View source code 6 votes vote down vote up
public void validate(CompilationInfo info) {
    TypeElement test = info.getElements().getTypeElement("test.Test");

    boolean foundCloneMethod = false;
    boolean foundToStringMethod = false;

    for (ExecutableElement ee : ElementFilter.methodsIn(test.getEnclosedElements())) {
        if (ee.getSimpleName().contentEquals("clone")) {
            if (ee.getParameters().isEmpty()) {
                assertFalse(foundCloneMethod);
                foundCloneMethod = true;
            }
        } else if (ee.getSimpleName().contentEquals("toString")) {
            if (ee.getParameters().isEmpty()) {
                assertFalse(foundToStringMethod);
                foundToStringMethod = true;
            }
        }
    }

    assertTrue(foundCloneMethod);
    assertTrue(foundToStringMethod);
}
 
Example 11
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 12
Project: incubator-netbeans   File: JavaSourceHelper.java   View source code 6 votes vote down vote up
public static List<VariableTree> getAllFields(JavaSource source) {
    final List<VariableTree> allFields = new ArrayList<VariableTree>();

    try {
        source.runUserActionTask(new AbstractTask<CompilationController>() {

            public void run(CompilationController controller) throws IOException {
                controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                TypeElement classElement = getTopLevelClassElement(controller);
                List<VariableElement> fields = ElementFilter.fieldsIn(classElement.getEnclosedElements());

                for (VariableElement field : fields) {
                    allFields.add((VariableTree) controller.getTrees().getTree(field));
                }
            }
        }, true);
    } catch (IOException ex) {
    }
    return allFields;
}
 
Example 13
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());
    assertEquals(1, vars.size());
    GeneratorUtilities utilities = GeneratorUtilities.get(copy);
    assertNotNull(utilities);
    ClassTree newCt = utilities.insertClassMember(ct, getter
            ? utilities.createGetter(te, vars.get(0))
            : utilities.createSetter(te, vars.get(0)));
    copy.rewrite(ct, newCt);
}
 
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: auto-value-step-builder   File: TypeSimplifier.java   View source code 6 votes vote down vote up
/**
 * Finds all types that are declared with non private visibility by the given {@code TypeMirror},
 * any class in its superclass chain, or any interface it implements.
 */
private static Set<TypeMirror> nonPrivateDeclaredTypes(Types typeUtils, TypeMirror type) {
  if (type == null) {
    return new TypeMirrorSet();
  } else {
    Set<TypeMirror> declared = new TypeMirrorSet();
    declared.add(type);
    List<TypeElement> nestedTypes =
        ElementFilter.typesIn(typeUtils.asElement(type).getEnclosedElements());
    for (TypeElement nestedType : nestedTypes) {
      if (!nestedType.getModifiers().contains(PRIVATE)) {
        declared.add(nestedType.asType());
      }
    }
    for (TypeMirror supertype : typeUtils.directSupertypes(type)) {
      declared.addAll(nonPrivateDeclaredTypes(typeUtils, supertype));
    }
    return declared;
  }
}
 
Example 16
Project: openjdk-jdk10   File: ElementsTable.java   View source code 6 votes vote down vote up
/**
 * Returns the "requires" modules for the target module.
 * @param mdle the target module element
 * @param onlyTransitive true gets all the requires transitive, otherwise
 *                 gets all the non-transitive requires
 *
 * @return a set of modules
 */
private Set<ModuleElement> getModuleRequires(ModuleElement mdle, boolean onlyTransitive) throws ToolException {
    Set<ModuleElement> result = new HashSet<>();
    for (RequiresDirective rd : ElementFilter.requiresIn(mdle.getDirectives())) {
        ModuleElement dep = rd.getDependency();
        if (result.contains(dep))
            continue;
        if (!isMandated(mdle, rd) && onlyTransitive == rd.isTransitive()) {
            if (!haveModuleSources(dep)) {
                messager.printWarning(dep, "main.module_not_found", dep.getSimpleName());
            }
            result.add(dep);
        } else if (isMandated(mdle, rd) && haveModuleSources(dep)) {
            result.add(dep);
        }
    }
    return result;
}
 
Example 17
Project: openjdk-jdk10   File: WebServiceVisitor.java   View source code 6 votes vote down vote up
protected boolean hasWebMethods(TypeElement element) {
    if (element.getQualifiedName().toString().equals(Object.class.getName()))
        return false;
    WebMethod webMethod;
    for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
        webMethod = method.getAnnotation(WebMethod.class);
        if (webMethod != null) {
            if (webMethod.exclude()) {
                if (webMethod.operationName().length() > 0)
                    builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_WEBMETHOD_ELEMENT_WITH_EXCLUDE(
                            "operationName", element.getQualifiedName(), method.toString()), method);
                if (webMethod.action().length() > 0)
                    builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_WEBMETHOD_ELEMENT_WITH_EXCLUDE(
                            "action", element.getQualifiedName(), method.toString()), method);
            } else {
                return true;
            }
        }
    }
    return false;//hasWebMethods(d.getSuperclass().getDeclaration());
}
 
Example 18
Project: openjdk-jdk10   File: AbstractVerifier.java   View source code 6 votes vote down vote up
protected static AnnotationValue findAnnotationValue(AnnotationMirror mirror, String name) {
    ExecutableElement valueMethod = null;
    for (ExecutableElement method : ElementFilter.methodsIn(mirror.getAnnotationType().asElement().getEnclosedElements())) {
        if (method.getSimpleName().toString().equals(name)) {
            valueMethod = method;
            break;
        }
    }

    if (valueMethod == null) {
        return null;
    }

    AnnotationValue value = mirror.getElementValues().get(valueMethod);
    if (value == null) {
        value = valueMethod.getDefaultValue();
    }

    return value;
}
 
Example 19
Project: incubator-netbeans   File: EqualsHashCodeGenerator.java   View source code 6 votes vote down vote up
@Override
public boolean accept(CompilationInfo info, TypeMirror tm) {
    if (minimalVersion != null && minimalVersion.compareTo(info.getSourceVersion()) > 0) {
        return false;
    }
    
    TypeElement clazz = info.getElements().getTypeElement(fqn);

    if (clazz == null) {
        return false;
    }

    for (ExecutableElement m : ElementFilter.methodsIn(clazz.getEnclosedElements())) {
        if (m.getSimpleName().contentEquals(methodName)) {
            return true;
        }
    }

    return false;
}
 
Example 20
Project: OpenJSharp   File: JavahTask.java   View source code 6 votes vote down vote up
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {
        Set<TypeElement> classes = getAllClasses(ElementFilter.typesIn(roundEnv.getRootElements()));
        if (classes.size() > 0) {
            checkMethodParameters(classes);
            g.setProcessingEnvironment(processingEnv);
            g.setClasses(classes);
            g.run();
        }
    } catch (CompletionFailure cf) {
        messager.printMessage(ERROR, getMessage("class.not.found", cf.sym.getQualifiedName().toString()));
    } catch (ClassNotFoundException cnfe) {
        messager.printMessage(ERROR, getMessage("class.not.found", cnfe.getMessage()));
    } catch (IOException ioe) {
        messager.printMessage(ERROR, getMessage("io.exception", ioe.getMessage()));
    } catch (Util.Exit e) {
        exit = e;
    }

    return true;
}
 
Example 21
Project: incubator-netbeans   File: ChangeParametersPlugin.java   View source code 6 votes vote down vote up
Problem duplicateConstructor(Problem p, ParameterInfo[] paramTable, final ExecutableElement method, TypeElement enclosingTypeElement, List<? extends Element> allMembers) {
    List<ExecutableElement> constructors = ElementFilter.constructorsIn(allMembers);
    for (ExecutableElement constructor : constructors) {
        if(!constructor.equals(method)) {
            if(constructor.getParameters().size() == paramTable.length) {
                boolean sameParameters = true;
                for (int j = 0; j < constructor.getParameters().size(); j++) {
                    TypeMirror exType = ((VariableElement)constructor.getParameters().get(j)).asType();
                    String type = paramTable[j].getType();
                    TypeMirror paramType = javac.getTreeUtilities().parseType(type, enclosingTypeElement);
                    if(!javac.getTypes().isSameType(exType, paramType)) {
                        sameParameters = false;
                    }
                }
                if(sameParameters) {
                    p = createProblem(p, false, NbBundle.getMessage(ChangeParametersPlugin.class, "ERR_existingConstructor", constructor.toString(), enclosingTypeElement.getQualifiedName())); // NOI18N
                }
            }
        }
    }
    return p;
}
 
Example 22
Project: openjdk-jdk10   File: MethodsDroppedBetweenRounds.java   View source code 6 votes vote down vote up
public boolean process(Set<? extends TypeElement> annos,RoundEnvironment rEnv) {
    if (keptMethod != null) {
        //force GC:
        List<byte[]> hold = new ArrayList<>();
        try {
            while (true)
                hold.add(new byte[1024 * 1024 * 1024]);
        } catch (OutOfMemoryError err) { }
        hold.clear();
        if (keptMethod.get() != null) {
            throw new IllegalStateException("Holds method across rounds.");
        }
    }

    TypeElement currentClass = elements.getTypeElement("MethodsDroppedBetweenRounds");

    if (currentClassSymbol != null && currentClassSymbol != currentClass) {
        throw new IllegalStateException("Different ClassSymbols across rounds");
    }

    ExecutableElement method = ElementFilter.methodsIn(currentClass.getEnclosedElements()).get(0);

    keptMethod = new WeakReference<>(method);

    return true;
}
 
Example 23
Project: openjdk-jdk10   File: T4994049.java   View source code 6 votes vote down vote up
public boolean run(DocletEnvironment root) {
    DocTrees trees = root.getDocTrees();

    SourcePositions sourcePositions = trees.getSourcePositions();
    for (TypeElement klass : ElementFilter.typesIn(root.getIncludedElements())) {
        for (ExecutableElement method : getMethods(klass)) {
            if (method.getSimpleName().toString().equals("tabbedMethod")) {
                TreePath path = trees.getPath(method);
                CompilationUnitTree cu = path.getCompilationUnit();
                long pos = sourcePositions.getStartPosition(cu, path.getLeaf());
                LineMap lineMap = cu.getLineMap();
                long columnNumber = lineMap.getColumnNumber(pos);
                if (columnNumber == 9) {
                    System.out.println(columnNumber + ": OK!");
                    return true;
                } else {
                    System.err.println(columnNumber + ": wrong tab expansion");
                    return false;
                }
            }
        }
    }
    return false;
}
 
Example 24
Project: android-auto-mapper   File: AutoMappperProcessor.java   View source code 6 votes vote down vote up
/**
 * This method returns a list of all non private fields. If any <code>private</code> fields is
 * found, the method errors out
 *
 * @param type element
 * @return list of all non-<code>private</code> fields
 */
private List<VariableElement> getParcelableFieldsOrError(TypeElement type) {
    List<VariableElement> allFields = ElementFilter.fieldsIn(type.getEnclosedElements());
    List<VariableElement> nonPrivateFields = new ArrayList<>();

    for (VariableElement field : allFields) {
        if (!field.getModifiers().contains(PRIVATE)) {
            nonPrivateFields.add(field);
        } else {
            // return error, PRIVATE fields are not allowed
            mErrorReporter.abortWithError("getFieldsError error, PRIVATE fields not allowed", type);
        }
    }

    return nonPrivateFields;
}
 
Example 25
Project: data-mediator   File: ImplInfoDelegate.java   View source code 6 votes vote down vote up
/**
 * parse impl info for current element
 * @param te the current type element
 * @param out the out infos
 * @return true if parse without error.
 */
private boolean parseImplInfo(TypeElement te, ImplInfo[] out) {
    //handle @ImplClass
    AnnotationMirror am_impl = null;
    for (AnnotationMirror am : te.getAnnotationMirrors()) {
        TypeElement e1 = (TypeElement) am.getAnnotationType().asElement();
        if ( e1.getQualifiedName().toString().equals(ImplClass.class.getName())) {
            am_impl = am;
            break;
        }
    }
    ImplInfo info = new ImplInfo();
    if (am_impl != null) {
        if(!parseImplClass(types, pp, am_impl, info)){
            return false;
        }
    }
    //handle @ImplMethod. note: may only have @ImplMethod.
    List<? extends Element> elements = ElementFilter.methodsIn(te.getEnclosedElements());
    parseImplMethods(types, pp, elements, info);
    if(info.isValid()) {
        out[0] = info;
    }
    return true;
}
 
Example 26
Project: OpenJSharp   File: ApNavigator.java   View source code 5 votes vote down vote up
public VariableElement getDeclaredField(TypeElement clazz, String fieldName) {
    for (VariableElement fd : ElementFilter.fieldsIn(clazz.getEnclosedElements())) {
        if (fd.getSimpleName().toString().equals(fieldName))
            return fd;
    }
    return null;
}
 
Example 27
Project: openjdk-jdk10   File: ElementsTable.java   View source code 5 votes vote down vote up
private Set<PackageElement> computeModulePackages() throws ToolException {
    AccessKind accessValue = accessFilter.getAccessValue(ElementKind.PACKAGE);
    final boolean documentAllModulePackages = (accessValue == AccessKind.PACKAGE ||
            accessValue == AccessKind.PRIVATE);

    accessValue = accessFilter.getAccessValue(ElementKind.MODULE);
    final boolean moduleDetailedMode = (accessValue == AccessKind.PACKAGE ||
            accessValue == AccessKind.PRIVATE);
    Set<PackageElement> expandedModulePackages = new LinkedHashSet<>();

    for (ModuleElement mdle : specifiedModuleElements) {
        if (documentAllModulePackages) { // include all packages
            List<PackageElement> packages = ElementFilter.packagesIn(mdle.getEnclosedElements());
            expandedModulePackages.addAll(packages);
            expandedModulePackages.addAll(getAllModulePackages(mdle));
        } else { // selectively include required packages
            List<ExportsDirective> exports = ElementFilter.exportsIn(mdle.getDirectives());
            for (ExportsDirective export : exports) {
                // add if fully exported or add qualified exports only if desired
                if (export.getTargetModules() == null
                        || documentAllModulePackages || moduleDetailedMode) {
                    expandedModulePackages.add(export.getPackage());
                }
            }
        }

        // add all packages specified on the command line
        // belonging to this module
        if (!cmdLinePackages.isEmpty()) {
            for (ModulePackage modpkg : cmdLinePackages) {
                PackageElement pkg = toolEnv.elements.getPackageElement(mdle,
                        modpkg.packageName);
                if (pkg != null) {
                    expandedModulePackages.add(pkg);
                }
            }
        }
    }
    return expandedModulePackages;
}
 
Example 28
Project: GitHub   File: Processor.java   View source code 5 votes vote down vote up
private void processTemplates(Set<? extends Element> templates) {
  for (TypeElement templateType : ElementFilter.typesIn(templates)) {
    try {
      generateTemplateType(templateType);
    } catch (Exception ex) {
      processingEnv.getMessager()
          .printMessage(Diagnostic.Kind.ERROR,
              ex.getMessage() + "\n\n" + Throwables.getStackTraceAsString(ex),
              templateType);
    }
  }
}
 
Example 29
Project: GitHub   File: ValueType.java   View source code 5 votes vote down vote up
private Long findSerialVersionUID() {
  for (VariableElement field : ElementFilter.fieldsIn(element.getEnclosedElements())) {
    if (field.getSimpleName().contentEquals(SERIAL_VERSION_FIELD_NAME)
        && field.asType().getKind() == TypeKind.LONG) {
      return (Long) field.getConstantValue();
    }
  }
  return null;
}
 
Example 30
Project: OpenJSharp   File: WebServiceVisitor.java   View source code 5 votes vote down vote up
private static List<ExecutableElement> getClassMethods(TypeElement classElement) {
    if (classElement.getQualifiedName().toString().equals(Object.class.getName())) // we don't need Object's methods
        return null;
    TypeElement superclassElement = (TypeElement) ((DeclaredType) classElement.getSuperclass()).asElement();
    List<ExecutableElement> superclassesMethods = getClassMethods(superclassElement);
    List<ExecutableElement> classMethods = ElementFilter.methodsIn(classElement.getEnclosedElements());
    if (superclassesMethods == null)
        return classMethods;
    else
        superclassesMethods.addAll(classMethods);
    return superclassesMethods;
}
 
Example 31
Project: GitHub   File: ValueType.java   View source code 5 votes vote down vote up
public Set<String> getNonAttributeAbstractMethodSignatures() {
  if (element.getKind().isClass() || element.getKind().isInterface()) {
    Set<String> signatures = new LinkedHashSet<>();

    List<? extends Element> members = constitution.protoclass()
        .environment()
        .processing()
        .getElementUtils()
        .getAllMembers(CachingElements.getDelegate((TypeElement) element));

    for (ExecutableElement m : ElementFilter.methodsIn(members)) {
      if (!m.getParameters().isEmpty()
          || m.getSimpleName().contentEquals(AccessorAttributesCollector.HASH_CODE_METHOD)
          || m.getSimpleName().contentEquals(AccessorAttributesCollector.TO_STRING_METHOD)) {

        if (m.getModifiers().contains(Modifier.ABSTRACT)) {
          TypeMirror returnType = m.getReturnType();
          if (!AccessorAttributesCollector.isEclipseImplementation(m)) {
            returnType = AccessorAttributesCollector.asInheritedMemberReturnType(
                constitution.protoclass().processing(),
                CachingElements.getDelegate((TypeElement) element),
                m);
          }
          signatures.add(toSignature(m, returnType));
        }
      }
    }

    return signatures;
  }
  return Collections.emptySet();
}
 
Example 32
Project: openjdk-jdk10   File: BreakIteratorWarning.java   View source code 5 votes vote down vote up
public boolean run(DocletEnvironment root) {
    TypeElement cd = ElementFilter.typesIn(root.getIncludedElements()).iterator().next();
    VariableElement fd = getFields(cd).get(0);
    DocTrees docTrees = root.getDocTrees();
    DocCommentTree docCommentTree = docTrees.getDocCommentTree(fd);
    List<? extends DocTree> firstSentence = docCommentTree.getFirstSentence();
    return true;
}
 
Example 33
Project: incubator-netbeans   File: ModelUtils.java   View source code 5 votes vote down vote up
public static VariableElement getField(TypeElement clazz, String fieldName) {
    for (VariableElement field : ElementFilter.fieldsIn(clazz.getEnclosedElements())) {
        if (field.getSimpleName().contentEquals(fieldName)) {
            return field;
        }
    }

    return null;
}
 
Example 34
Project: openjdk-jdk10   File: ModuleTestBase.java   View source code 5 votes vote down vote up
void addEnclosedElements(DocletEnvironment docenv, Set<Element> result, Element e) {
    List<Element> elems = e.getEnclosedElements().stream()
            .filter(el -> docenv.isIncluded(el))
            .collect(Collectors.toList());
    result.addAll(elems);
    for (TypeElement t : ElementFilter.typesIn(elems)) {
        addEnclosedElements(docenv, result, t);
    }
}
 
Example 35
Project: incubator-netbeans   File: EntityManagerGenerationStrategySupport.java   View source code 5 votes vote down vote up
/**
 * Gets the element representing an annotation of the given type. Searches annotations
 *  declared on class, fields and methods (in that order).
 * @param annotationTypeFqn the fully qualified name of the annotation's type.
 * @return the element or null if no matching annotation was found.
 */
protected Element getAnnotation(final String annotationTypeFqn){
    
    Parameters.notEmpty("annotationTypeFqn", annotationTypeFqn); //NOI18N
    
    TypeElement annotationType = asTypeElement(annotationTypeFqn);
    TypeElement classElement = getClassElement();
    List<Element> elements = new ArrayList<Element>();
    elements.add(classElement);
    elements.addAll(ElementFilter.fieldsIn(classElement.getEnclosedElements()));
    elements.addAll(ElementFilter.methodsIn(classElement.getEnclosedElements()));
    
    
    return checkElementsForAnnotationType(elements, annotationType);
}
 
Example 36
Project: incubator-netbeans   File: Utils.java   View source code 5 votes vote down vote up
public static VariableElement getField(TypeElement clazz, String fieldName) {
    for (VariableElement field : ElementFilter.fieldsIn(clazz.getEnclosedElements())) {
        if (field.getSimpleName().contentEquals(fieldName)) {
            return field;
        }
    }

    return null;
}
 
Example 37
Project: incubator-netbeans   File: Utils.java   View source code 5 votes vote down vote up
public static ExecutableElement[] getMethod(TypeElement clazz, String methodName) {
    List<ExecutableElement> methods = new ArrayList<ExecutableElement>();

    for (ExecutableElement method : ElementFilter.methodsIn(clazz.getEnclosedElements())) {
        if (method.getSimpleName().contentEquals(methodName)) {
            methods.add(method);
        }
    }

    return methods.toArray(new ExecutableElement[methods.size()]);
}
 
Example 38
Project: incubator-netbeans   File: JpaControllerUtil.java   View source code 5 votes vote down vote up
public static VariableElement guessField(ExecutableElement getter) {
    String name = getter.getSimpleName().toString().substring(3);
    String guessFieldName = name.substring(0,1).toLowerCase() + name.substring(1);
    TypeElement typeElement = (TypeElement) getter.getEnclosingElement();
    for (VariableElement variableElement : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) {
        if (variableElement.getSimpleName().contentEquals(guessFieldName)) {
            return variableElement;
        }
    }
    Logger.getLogger(JpaControllerUtil.class.getName()).log(Level.WARNING, "Cannot detect the field associated with property: {0}", guessFieldName);
    return null;
}
 
Example 39
Project: incubator-netbeans   File: TestMethodNameGenerator.java   View source code 5 votes vote down vote up
/**
 * Collects names of accessible no-argument methods that are present
 * in the given class and its superclasses. Methods inherited from the
 * class's superclasses are taken into account, too.
 * 
 * @param  clazz  class whose methods' names should be collected
 * @param  reservedMethodNames  collection to which the method names
 *                              should be added
 */
private void collectExistingMethodNames(TypeElement clazz,
                                        Collection<String> reservedMethodNames) {
    final Elements elements = workingCopy.getElements();
    List<? extends Element> allMembers = elements.getAllMembers(clazz);
    List<? extends ExecutableElement> methods = ElementFilter.methodsIn(allMembers);
    if (!methods.isEmpty()) {
        for (ExecutableElement method : methods) {
            if (method.getParameters().isEmpty()) {
                reservedMethodNames.add(method.getSimpleName().toString());
            }
        }
    }
}
 
Example 40
Project: incubator-netbeans   File: TestMethodNameGenerator.java   View source code 5 votes vote down vote up
/**
 * Returns a list of methods contained directly in the given class.
 * 
 * @param  classElem  class whose methods should be returned
 * @return  list of methods in the given class
 */
private static List<ExecutableElement> getExistingMethods(
                                final TypeElement classElem) {
    List<? extends Element> elements = classElem.getEnclosedElements();
    if (elements.isEmpty()) {
        return Collections.<ExecutableElement>emptyList();
    }

    List<ExecutableElement> methods = ElementFilter.methodsIn(elements);
    return !methods.isEmpty() ? methods
                              : Collections.<ExecutableElement>emptyList();
}