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

The following examples show how to use javax.lang.model.element.ExecutableElement. These examples are extracted from open source projects.
Example 1
Project: jdk8u60   File: WebServiceVisitor.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected int getModeParameterCount(ExecutableElement method, WebParam.Mode mode) {
    WebParam webParam;
    int cnt = 0;
    for (VariableElement param : method.getParameters()) {
        webParam = param.getAnnotation(WebParam.class);
        if (webParam != null) {
            if (webParam.header())
                continue;
            if (isEquivalentModes(mode, webParam.mode()))
                cnt++;
        } else {
            if (isEquivalentModes(mode, WebParam.Mode.IN)) {
                cnt++;
            }
        }
    }
    return cnt;
}
 
Example 2
Project: RetroFacebook   File: RetroFacebookProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private static String formalArgsString(ExecutableElement method) {
  List<? extends VariableElement> parameters = method.getParameters();
  if (parameters.isEmpty()) {
    return "";
  } else {
    return ""
      + Joiner.on(", ").join(
      FluentIterable.from(parameters).transform(new Function<VariableElement, String>() {
        @Override
        public String apply(VariableElement element) {
          return "" + element.getSimpleName();
        }
      }))
      + "";
  }
}
 
Example 3
Project: buck   File: TreeBackedAnnotationMirrorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleElementArrayAnnotationMirrorValueWithSingleEntry() throws IOException {
  compile(
      Joiner.on('\n')
          .join(
              "@FooHelper(42)",
              "public class Foo {",
              "}",
              "@interface FooHelper {",
              "  int[] value();",
              "}"));

  AnnotationMirror a = elements.getTypeElement("Foo").getAnnotationMirrors().get(0);
  ExecutableElement keyElement = findMethod("value", elements.getTypeElement("FooHelper"));

  @SuppressWarnings("unchecked")
  List<AnnotationValue> values =
      (List<AnnotationValue>) a.getElementValues().get(keyElement).getValue();
  assertEquals(42, values.get(0).getValue());
  assertEquals(1, a.getElementValues().size());
  assertEquals(1, values.size());
}
 
Example 4
Project: doma   File: ExpressionValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testMethod_notFound() throws Exception {
  Class<?> target = ExpressionValidationDao.class;
  addCompilationUnit(target);
  addProcessor(
      new TestProcessor() {
        @Override
        protected void run() {
          ExecutableElement methodElement = createMethodElement(target, "testEmp", Emp.class);
          Map<String, TypeMirror> parameterTypeMap = createParameterTypeMap(methodElement);
          ExpressionValidator validator =
              new ExpressionValidator(ctx, methodElement, parameterTypeMap);
          ExpressionNode node = new ExpressionParser("emp.notFound(1, \"aaa\".length())").parse();
          try {
            validator.validate(node);
            fail();
          } catch (AptException expected) {
            System.out.println(expected);
            assertEquals(Message.DOMA4071, expected.getMessageResource());
          }
        }
      });
  compile();
  assertTrue(getCompiledResult());
}
 
Example 5
Project: netbeans   File: ExportNonAccessibleElement.java    License: Apache License 2.0 6 votes vote down vote up
public Boolean visitExecutable(ExecutableElement method, Void nothing) {
    if (!isVisible(method)) {
        // ok
        return false;
    }
    for (VariableElement v : method.getParameters()) {
        if (stop) {
            return false;
        }
        
        if (v.asType().accept(this, nothing)) {
            return true;
        }
    }
    return method.getReturnType().accept(this, nothing);
}
 
Example 6
Project: auto   File: MoreTypes.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Resolves a {@link VariableElement} parameter to a method or constructor based on the given
 * container, or a member of a class. For parameters to a method or constructor, the variable's
 * enclosing element must be a supertype of the container type. For example, given a
 * {@code container} of type {@code Set<String>}, and a variable corresponding to the {@code E e}
 * parameter in the {@code Set.add(E e)} method, this will return a TypeMirror for {@code String}.
 */
public static TypeMirror asMemberOf(Types types, DeclaredType container,
    VariableElement variable) {
  if (variable.getKind().equals(ElementKind.PARAMETER)) {
    ExecutableElement methodOrConstructor =
        MoreElements.asExecutable(variable.getEnclosingElement());
    ExecutableType resolvedMethodOrConstructor =
        MoreTypes.asExecutable(types.asMemberOf(container, methodOrConstructor));
    List<? extends VariableElement> parameters = methodOrConstructor.getParameters();
    List<? extends TypeMirror> parameterTypes = resolvedMethodOrConstructor.getParameterTypes();
    checkState(parameters.size() == parameterTypes.size());
    for (int i = 0; i < parameters.size(); i++) {
      // We need to capture the parameter type of the variable we're concerned about,
      // for later printing.  This is the only way to do it since we can't use
      // types.asMemberOf on variables of methods.
      if (parameters.get(i).equals(variable)) {
        return parameterTypes.get(i);
      }
    }
    throw new IllegalStateException("Could not find variable: " + variable);
  } else {
    return types.asMemberOf(container, variable);
  }
}
 
Example 7
Project: auto   File: AutoAnnotationProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void validateParameters(
    TypeElement annotationElement,
    ExecutableElement method,
    ImmutableMap<String, Member> members,
    ImmutableMap<String, Parameter> parameters,
    ImmutableMap<String, AnnotationValue> defaultValues) {
  boolean error = false;
  for (String memberName : members.keySet()) {
    if (!parameters.containsKey(memberName) && !defaultValues.containsKey(memberName)) {
      reportError(
          method,
          "@AutoAnnotation method needs a parameter with name '%s' and type %s"
              + " corresponding to %s.%s, which has no default value",
          memberName,
          members.get(memberName).getType(),
          annotationElement,
          memberName);
      error = true;
    }
  }
  if (error) {
    throw new AbortProcessingException();
  }
}
 
Example 8
Project: FreeBuilder   File: Analyser.java    License: Apache License 2.0 6 votes vote down vote up
/** Find a toBuilder method, if the user has provided one. */
private boolean hasToBuilderMethod(
    DeclaredType builder,
    boolean isExtensible,
    Iterable<ExecutableElement> methods) {
  for (ExecutableElement method : methods) {
    if (isToBuilderMethod(builder, method)) {
      if (!isExtensible) {
        messager.printMessage(ERROR,
            "No accessible no-args Builder constructor available to implement toBuilder",
            method);
      }
      return true;
    }
  }
  return false;
}
 
Example 9
Project: firebase-android-sdk   File: ToStringMethod.java    License: Apache License 2.0 6 votes vote down vote up
static MethodSpec generate(TypeElement element) {
  ClassName.get(element).reflectionName();
  Builder result =
      MethodSpec.methodBuilder("toString")
          .addModifiers(Modifier.PUBLIC)
          .returns(String.class)
          .addAnnotation(Override.class)
          .addCode(
              CodeBlock.builder()
                  .add(
                      "StringBuilder sb = new StringBuilder(\"@$L\");\n",
                      ClassName.get(element).reflectionName().replace('$', '.'))
                  .build());
  List<ExecutableElement> methods = ElementFilter.methodsIn(element.getEnclosedElements());
  if (!methods.isEmpty()) {
    result.addCode("sb.append('(');\n");
  }
  for (ExecutableElement method : methods) {
    result.addCode("sb.append(\"$1L=\").append($1L);\n", method.getSimpleName());
  }
  if (!methods.isEmpty()) {
    result.addCode("sb.append(')');\n");
  }
  result.addCode("return sb.toString();\n");
  return result.build();
}
 
Example 10
Project: JReFrameworker   File: MethodSpec.java    License: MIT License 6 votes vote down vote up
/**
 * Returns a new method spec builder that overrides {@code method} as a member of {@code
 * enclosing}. This will resolve type parameters: for example overriding {@link
 * Comparable#compareTo} in a type that implements {@code Comparable<Movie>}, the {@code T}
 * parameter will be resolved to {@code Movie}.
 *
 * <p>This will copy its visibility modifiers, type parameters, return type, name, parameters, and
 * throws declarations. An {@link Override} annotation will be added.
 *
 * <p>Note that in JavaPoet 1.2 through 1.7 this method retained annotations from the method and
 * parameters of the overridden method. Since JavaPoet 1.8 annotations must be added separately.
 */
public static Builder overriding(
    ExecutableElement method, DeclaredType enclosing, Types types) {
  ExecutableType executableType = (ExecutableType) types.asMemberOf(enclosing, method);
  List<? extends TypeMirror> resolvedParameterTypes = executableType.getParameterTypes();
  TypeMirror resolvedReturnType = executableType.getReturnType();

  Builder builder = overriding(method);
  builder.returns(TypeName.get(resolvedReturnType));
  for (int i = 0, size = builder.parameters.size(); i < size; i++) {
    ParameterSpec parameter = builder.parameters.get(i);
    TypeName type = TypeName.get(resolvedParameterTypes.get(i));
    builder.parameters.set(i, parameter.toBuilder(type, parameter.name).build());
  }

  return builder;
}
 
Example 11
Project: auto   File: AutoValueOrOneOfProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns a bi-map between property names and the corresponding abstract property methods. */
final ImmutableBiMap<String, ExecutableElement> propertyNameToMethodMap(
    Set<ExecutableElement> propertyMethods) {
  Map<String, ExecutableElement> map = new LinkedHashMap<>();
  Set<String> reportedDups = new HashSet<>();
  boolean allPrefixed = gettersAllPrefixed(propertyMethods);
  for (ExecutableElement method : propertyMethods) {
    String methodName = method.getSimpleName().toString();
    String name = allPrefixed ? nameWithoutPrefix(methodName) : methodName;
    ExecutableElement old = map.put(name, method);
    if (old != null) {
      List<ExecutableElement> contexts = new ArrayList<>(Arrays.asList(method));
      if (reportedDups.add(name)) {
        contexts.add(old);
      }
      // Report the error for both of the methods. If this is a third or further occurrence,
      // reportedDups prevents us from reporting more than one error for the same method.
      for (ExecutableElement context : contexts) {
        errorReporter.reportError(
            context, "More than one @%s property called %s", simpleAnnotationName, name);
      }
    }
  }
  return ImmutableBiMap.copyOf(map);
}
 
Example 12
Project: openjdk-jdk8u   File: WebServiceVisitor.java    License: GNU General Public License v2.0 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 13
Project: Mixin   File: AnnotatedMixinElementHandler.java    License: MIT License 6 votes vote down vote up
private void validateMethodVisibility(ExecutableElement method, AnnotationHandle annotation, String type, TypeHandle target,
        MethodHandle targetMethod) {
    Visibility visTarget = targetMethod.getVisibility();
    if (visTarget == null) {
        return;
    }
    
    Visibility visMethod = TypeUtils.getVisibility(method);
    String visibility = "visibility of " + visTarget + " method in " + target;
    if (visTarget.ordinal() > visMethod.ordinal()) {
        this.printMessage(Kind.WARNING, visMethod + " " + type + " method cannot reduce " + visibility, method, annotation,
                SuppressedBy.VISIBILITY);
    } else if (visTarget == Visibility.PRIVATE && visMethod.ordinal() > visTarget.ordinal()) {
        this.printMessage(Kind.WARNING, visMethod + " " + type + " method will upgrade " + visibility, method, annotation,
                SuppressedBy.VISIBILITY);
    }
}
 
Example 14
Project: netbeans   File: ResourceImplTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testSimplyAnnotatedMethod() throws Exception {
    TestUtilities.copyStringToFileObject(srcFO, "MyClass.java",
            "public class MyClass {" +
            "   @javax.annotation.Resource" +
            "   private void setMyResource(javax.sql.DataSource dataSource) {" +
            "   }" +
            "}");
    IndexingManager.getDefault().refreshIndexAndWait(srcFO.getURL(), null);
    ClasspathInfo cpi = ClasspathInfo.create(srcFO);
    final AnnotationModelHelper annotationModelHelper = AnnotationModelHelper.create(cpi);
    annotationModelHelper.runJavaSourceTask(new Runnable() {
        public void run() {
            TypeElement myClass = annotationModelHelper.getCompilationController().getElements().getTypeElement("MyClass");
            List<ExecutableElement> methods = ElementFilter.methodsIn(myClass.getEnclosedElements());
            ExecutableElement annotatedMethod = methods.get(0);
            
            ResourceImpl resource = new ResourceImpl(annotatedMethod, myClass, annotationModelHelper);
            assertEquals("myResource", resource.getName());
            assertEquals("javax.sql.DataSource", resource.getType());
            assertEquals(ResourceImpl.DEFAULT_AUTHENTICATION_TYPE, resource.getAuthenticationType());
            assertEquals(ResourceImpl.DEFAULT_SHAREABLE, resource.getShareable());
            assertEquals(ResourceImpl.DEFAULT_MAPPED_NAME, resource.getMappedName());
            assertEquals(ResourceImpl.DEFAULT_DESCRIPTION, resource.getDescription());
        }
    });
}
 
Example 15
Project: immutables   File: ValueAttribute.java    License: Apache License 2.0 5 votes vote down vote up
private ImmutableSet<String> collectThrownCheckedExceptions() {
  Set<String> exceptions = new HashSet<>(2);
  Environment env = protoclass().environment();
  for (TypeMirror thrown : ((ExecutableElement) element).getThrownTypes()) {
    if (env.isCheckedException(thrown)) {
      exceptions.add(thrown.toString());
    }
  }
  return ImmutableSet.copyOf(exceptions);
}
 
Example 16
Project: netbeans   File: Utilities.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean allTypeVarsAccessible(Collection<TypeVariable> typeVars, Element target) {
    if (target == null) {
        return typeVars.isEmpty();
    }
    
    Set<TypeVariable> targetTypeVars = new HashSet<TypeVariable>();

    OUTER: while (target.getKind() != ElementKind.PACKAGE) {
        Iterable<? extends TypeParameterElement> tpes;

        switch (target.getKind()) {
            case ANNOTATION_TYPE:
            case CLASS:
            case ENUM:
            case INTERFACE:
                tpes = ((TypeElement) target).getTypeParameters();
                break;
            case METHOD:
            case CONSTRUCTOR:
                tpes = ((ExecutableElement) target).getTypeParameters();
                break;
            default:
                break OUTER;
        }

        for (TypeParameterElement tpe : tpes) {
            targetTypeVars.add((TypeVariable) tpe.asType());
        }

        if (target.getModifiers().contains(Modifier.STATIC)) {
            break;
        }

        target = target.getEnclosingElement();
    }

    return targetTypeVars.containsAll(typeVars);
}
 
Example 17
Project: openjdk-jdk9   File: WebServiceWrapperGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void processMethod(ExecutableElement method, WebMethod webMethod) {
    builder.log("WrapperGen - method: "+method);
    builder.log("method.getDeclaringType(): " + method.asType());
    if (wrapped && soapStyle.equals(SOAPStyle.DOCUMENT)) {
        generateWrappers(method, webMethod);
    }
    generateExceptionBeans(method);
}
 
Example 18
Project: netbeans   File: AddWsOperationHelper.java    License: Apache License 2.0 5 votes vote down vote up
private List<ExecutableElement> getMethods(CompilationController controller, TypeElement classElement) throws IOException {
    List<? extends Element> members = classElement.getEnclosedElements();
    List<ExecutableElement> methods = ElementFilter.methodsIn(members);
    List<ExecutableElement> publicMethods = new ArrayList<ExecutableElement>();
    for (ExecutableElement m:methods) {
        //Set<Modifier> modifiers = method.getModifiers();
        //if (modifiers.contains(Modifier.PUBLIC)) {
        publicMethods.add(m);
        //}
    }
    return publicMethods;
}
 
Example 19
Project: nalu   File: ProcessorUtils.java    License: Apache License 2.0 5 votes vote down vote up
public String createInternalEventName(ExecutableElement executableElement) {
  String internalEventname = executableElement.getSimpleName()
                                              .toString();
  for (VariableElement variableElement : executableElement.getParameters()) {
    internalEventname += ProcessorConstants.PARAMETER_DELIMITER;
    internalEventname += variableElement.asType()
                                        .toString()
                                        .replace(".",
                                                 "_");
  }
  return internalEventname;
}
 
Example 20
Project: AndServer   File: ControllerProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private Mapping getExecuteMapping(ExecutableElement execute) {
    Mapping mapping = null;
    RequestMapping requestMapping = execute.getAnnotation(RequestMapping.class);
    boolean isRest = execute.getAnnotation(ResponseBody.class) != null;
    if (requestMapping != null) {
        mapping = new Any(requestMapping, isRest);
    }

    if (mapping == null) {
        GetMapping getMapping = execute.getAnnotation(GetMapping.class);
        if (getMapping != null) {
            mapping = new Get(getMapping, isRest);
        }
    }
    if (mapping == null) {
        PostMapping postMapping = execute.getAnnotation(PostMapping.class);
        if (postMapping != null) {
            mapping = new Post(postMapping, isRest);
        }
    }
    if (mapping == null) {
        PutMapping putMapping = execute.getAnnotation(PutMapping.class);
        if (putMapping != null) {
            mapping = new Put(putMapping, isRest);
        }
    }
    if (mapping == null) {
        PatchMapping patchMapping = execute.getAnnotation(PatchMapping.class);
        if (patchMapping != null) {
            mapping = new Patch(patchMapping, isRest);
        }
    }
    if (mapping == null) {
        DeleteMapping deleteMapping = execute.getAnnotation(DeleteMapping.class);
        if (deleteMapping != null) {
            mapping = new Delete(deleteMapping, isRest);
        }
    }
    return mapping;
}
 
Example 21
Project: openjdk-8-source   File: JavahTask.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void checkMethodParameters(Set<TypeElement> classes) {
    Types types = processingEnv.getTypeUtils();
    for (TypeElement te: classes) {
        for (ExecutableElement ee: ElementFilter.methodsIn(te.getEnclosedElements())) {
            for (VariableElement ve: ee.getParameters()) {
                TypeMirror tm = ve.asType();
                checkMethodParametersVisitor.visit(tm, types);
            }
        }
    }
}
 
Example 22
Project: j2objc   File: ElementUtil.java    License: Apache License 2.0 5 votes vote down vote up
Map<? extends ExecutableElement, ? extends AnnotationValue> getElementValuesWithDefaults(
    AnnotationMirror annotation) {
  DeclaredType type = annotation.getAnnotationType();
  Map<ExecutableElement, AnnotationValue> map = new LinkedHashMap<>(
      annotation.getElementValues());
  for (ExecutableElement method : getMethods((TypeElement) type.asElement())) {
    AnnotationValue defaultValue = method.getDefaultValue();
    if (defaultValue != null && !map.containsKey(method)) {
      map.put(method, defaultValue);
    }
  }
  return map;
}
 
Example 23
Project: netbeans   File: GeneratorUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void generateConstructors(WorkingCopy wc, TreePath path, Iterable<? extends VariableElement> initFields, List<? extends ExecutableElement> inheritedConstructors, int offset) {
    ClassTree clazz = (ClassTree)path.getLeaf();
    TypeElement te = (TypeElement) wc.getTrees().getElement(path);
    GeneratorUtilities gu = GeneratorUtilities.get(wc);
    List<Tree> members = new ArrayList<>();
    for (ExecutableElement inheritedConstructor : inheritedConstructors) {
        members.add(gu.createConstructor(te, initFields, inheritedConstructor));
    }
    wc.rewrite(clazz, insertClassMembers(wc, clazz, members, offset));
}
 
Example 24
Project: buck   File: TreeBackedAnnotationFactory.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void populateValues() {
  if (valueCache == null) {
    valueCache = new HashMap<>();
    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
        TreeBackedElements.getElementValuesWithDefaultsStatic(mirror).entrySet()) {
      valueCache.put(entry.getKey().getSimpleName().toString(), entry.getValue());
    }
  }
}
 
Example 25
Project: auto   File: AutoValueOrOneOfProcessor.java    License: Apache License 2.0 5 votes vote down vote up
final ImmutableListMultimap<ExecutableElement, AnnotationMirror> propertyMethodAnnotationMap(
    TypeElement type, ImmutableSet<ExecutableElement> propertyMethods) {
  ImmutableListMultimap.Builder<ExecutableElement, AnnotationMirror> builder =
      ImmutableListMultimap.builder();
  for (ExecutableElement propertyMethod : propertyMethods) {
    builder.putAll(propertyMethod, propertyMethodAnnotations(type, propertyMethod));
  }
  return builder.build();
}
 
Example 26
Project: openjdk-8   File: Mangle.java    License: GNU General Public License v2.0 5 votes vote down vote up
public String mangleMethod(ExecutableElement method, TypeElement clazz,
                                  int mtype) throws TypeSignature.SignatureException {
    StringBuilder result = new StringBuilder(100);
    result.append("Java_");

    if (mtype == Mangle.Type.METHOD_JDK_1) {
        result.append(mangle(clazz.getQualifiedName(), Mangle.Type.CLASS));
        result.append('_');
        result.append(mangle(method.getSimpleName(),
                             Mangle.Type.FIELD));
        result.append("_stub");
        return result.toString();
    }

    /* JNI */
    result.append(mangle(getInnerQualifiedName(clazz), Mangle.Type.JNI));
    result.append('_');
    result.append(mangle(method.getSimpleName(),
                         Mangle.Type.JNI));
    if (mtype == Mangle.Type.METHOD_JNI_LONG) {
        result.append("__");
        String typesig = signature(method);
        TypeSignature newTypeSig = new TypeSignature(elems);
        String sig = newTypeSig.getTypeSignature(typesig,  method.getReturnType());
        sig = sig.substring(1);
        sig = sig.substring(0, sig.lastIndexOf(')'));
        sig = sig.replace('/', '.');
        result.append(mangle(sig, Mangle.Type.JNI));
    }

    return result.toString();
}
 
Example 27
Project: netbeans   File: WebBeansModelProviderImpl.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isObservesParameter( VariableElement element,
        ExecutableElement method , List<? extends AnnotationMirror> annotations ) 
    throws org.netbeans.modules.web.beans.api.model.InjectionPointDefinitionError
{
    List<? extends VariableElement> parameters = method.getParameters();
    boolean observesFound = false;
    for (VariableElement variableElement : parameters) {
        if (  AnnotationObjectProvider.hasAnnotation(variableElement, 
                OBSERVES_ANNOTATION, getModel().getHelper()))
        {
            if ( observesFound ){
                throw new org.netbeans.modules.web.beans.api.model.
                    InjectionPointDefinitionError(method, 
                        NbBundle.getMessage(WebBeansModelImplementation.class, 
                                "ERR_MultipleObserves" , method.getSimpleName()));
            }
            observesFound = true;
        }
    }
    if ( !observesFound ){
        return false;
    }
    
    String badAnnotation = checkInjectProducers(annotations);
    if ( badAnnotation != null ){
        throw new org.netbeans.modules.web.beans.api.model.
            InjectionPointDefinitionError( method, 
                NbBundle.getMessage(WebBeansModelImplementation.class, 
                        "ERR_ObserverHasInjectOrProduces" , method.getSimpleName(),
                        badAnnotation ));
    }
    return observesFound;
}
 
Example 28
Project: openjdk-jdk9   File: VisibleMemberMap.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Filter the annotation type members and return either the required
 * members or the optional members, depending on the value of the
 * required parameter.
 *
 * @param typeElement The annotation type to process.
 * @param required
 * @return the annotation type members and return either the required
 * members or the optional members, depending on the value of the
 * required parameter.
 */
private List<Element> filterAnnotations(TypeElement typeElement, boolean required) {
    List<Element> members = utils.getAnnotationMethods(typeElement);
    List<Element> targetMembers = new ArrayList<>();
    for (Element member : members) {
        ExecutableElement ee = (ExecutableElement)member;
        if ((required && ee.getDefaultValue() == null)
                || ((!required) && ee.getDefaultValue() != null)) {
            targetMembers.add(member);
        }
    }
    return targetMembers;
}
 
Example 29
Project: immutables   File: ThrowForInvalidImmutableState.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean hasStringArrayConstructor(TypeElement element) {
  for (ExecutableElement e : ElementFilter.constructorsIn(element.getEnclosedElements())) {
    if (e.getModifiers().contains(Modifier.PUBLIC) && e.getParameters().size() == 1) {
      if (isArrayOfStrings(e.getParameters().get(0).asType())) {
        return true;
      }
    }
  }
  return false;
}
 
Example 30
Project: reflection-no-reflection   File: Processor.java    License: Apache License 2.0 5 votes vote down vote up
private void addMethodOrConstructorToAnnotationDatabase(ExecutableElement methodOrConstructorElement, int level) {
    String methodOrConstructorName = methodOrConstructorElement.getSimpleName().toString();
    //System.out.printf("Type: %s, injection: %s \n",typeElementName, methodOrConstructorName);
    if (methodOrConstructorName.startsWith("<init>")) {
        addConstructor(methodOrConstructorElement, level);
    } else {
        addMethod(methodOrConstructorElement, level);
    }
}
 
Example 31
Project: openjdk-jdk8u-backup   File: WebServiceVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected boolean processedMethod(ExecutableElement method) {
    String id = method.toString();
    if (processedMethods.contains(id))
        return true;
    processedMethods.add(id);
    return false;
}
 
Example 32
Project: TencentKona-8   File: TestSymtabItems.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitExecutable(ExecutableElement e, Void p) {
    show("executable", e);
    indent(+1);
    super.visitExecutable(e, p);
    indent(-1);
    return null;
}
 
Example 33
Project: netbeans   File: NbBundleProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void warnUndocumented(int i, Element e, String key) {
    AnnotationMirror mirror = null;
    AnnotationValue value = null;
    if (e != null) {
        for (AnnotationMirror _mirror : e.getAnnotationMirrors()) {
            if (_mirror.getAnnotationType().toString().equals(NbBundle.Messages.class.getCanonicalName())) {
                mirror = _mirror;
                for (Map.Entry<? extends ExecutableElement,? extends AnnotationValue> entry : mirror.getElementValues().entrySet()) {
                    if (entry.getKey().getSimpleName().contentEquals("value")) {
                        // SimpleAnnotationValueVisitor6 unusable here since we need to determine the AnnotationValue in scope when visitString is called:
                        Object v = entry.getValue().getValue();
                        if (v instanceof String) {
                            if (((String) v).startsWith(key + "=")) {
                                value = entry.getValue();
                            }
                        } else {
                            for (AnnotationValue subentry : NbCollections.checkedListByCopy((List<?>) v, AnnotationValue.class, true)) {
                                v = subentry.getValue();
                                if (v instanceof String) {
                                    if (((String) v).startsWith(key + "=")) {
                                        value = subentry;
                                        break;
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }
    }
    processingEnv.getMessager().printMessage(Kind.WARNING, "Undocumented format parameter {" + i + "}", e, mirror, value);
}
 
Example 34
Project: netbeans   File: FieldInjectionPointLogic.java    License: Apache License 2.0 5 votes vote down vote up
private boolean collectSpecializes( Element productionElement,
        ExecutableElement element, WebBeansModelImplementation model,
        Set<Element> probableSpecializes, Set<Element> specializeElements )
{
    ElementUtilities elementUtilities =
        model.getHelper().getCompilationController().getElementUtilities();
    if ( !elementUtilities.overridesMethod(element)){
        return false;
    }
    ExecutableElement overriddenMethod = elementUtilities.
        getOverriddenMethod( element);
    if ( overriddenMethod == null ){
        return false;
    }
    if (!AnnotationObjectProvider.hasSpecializes(element,  model.getHelper())){
        return false;
    }
    probableSpecializes.add( element);
    if( overriddenMethod.equals( productionElement ) ||
            specializeElements.contains( productionElement))
    {
        return true;
    }
    else {
        return collectSpecializes(productionElement, overriddenMethod, model,
                probableSpecializes, specializeElements);
    }
}
 
Example 35
Project: openjdk-8   File: WebServiceVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void verifyImplAnnotations(TypeElement d) {
    for (ExecutableElement method : ElementFilter.methodsIn(d.getEnclosedElements())) {
        checkForInvalidImplAnnotation(method, WebMethod.class);
        checkForInvalidImplAnnotation(method, Oneway.class);
        checkForInvalidImplAnnotation(method, WebResult.class);
        for (VariableElement param : method.getParameters()) {
            checkForInvalidImplAnnotation(param, WebParam.class);
        }
    }
}
 
Example 36
Project: buck   File: TreeBackedAnnotationValueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiElementAnnotationMirrorValue() throws IOException {
  compile(
      Joiner.on('\n')
          .join(
              "public @interface Foo {",
              "  FooHelper value() default @FooHelper(number=42, string=\"42\");",
              "}",
              "@interface FooHelper {",
              "  int number();",
              "  String string();",
              "}"));

  ExecutableElement method = findMethod("value", elements.getTypeElement("Foo"));
  AnnotationValue defaultValue = method.getDefaultValue();
  defaultValue.accept(
      new TestVisitor() {
        @Override
        public Void visitAnnotation(AnnotationMirror a, Void aVoid) {
          AnnotationMirror annotationMirrorValue = (AnnotationMirror) defaultValue.getValue();
          ExecutableElement numberKeyElement =
              findMethod("number", elements.getTypeElement("FooHelper"));
          ExecutableElement stringKeyElement =
              findMethod("string", elements.getTypeElement("FooHelper"));

          assertEquals(2, annotationMirrorValue.getElementValues().size());
          assertEquals(
              42, annotationMirrorValue.getElementValues().get(numberKeyElement).getValue());
          assertEquals(
              "42", annotationMirrorValue.getElementValues().get(stringKeyElement).getValue());
          return null;
        }
      },
      null);
  assertEquals("@FooHelper(number=42, string=\"42\")", defaultValue.toString());
}
 
Example 37
Project: openjdk-jdk8u-backup   File: ApNavigator.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean hasDefaultConstructor(TypeElement t) {
    if (t == null || !t.getKind().equals(ElementKind.CLASS))
        return false;

    for (ExecutableElement init : ElementFilter.constructorsIn(env.getElementUtils().getAllMembers(t))) {
        if (init.getParameters().isEmpty())
            return true;
    }
    return false;
}
 
Example 38
Project: netbeans   File: CreateElementUtilities.java    License: Apache License 2.0 5 votes vote down vote up
private static List<? extends TypeMirror> computeNewClass(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    NewClassTree nct = (NewClassTree) parent.getLeaf();
    boolean errorInRealArguments = false;
    
    for (Tree param : nct.getArguments()) {
        errorInRealArguments |= param == error;
    }
    
    if (errorInRealArguments) {
        List<TypeMirror> proposedTypes = new ArrayList<TypeMirror>();
        int[] proposedIndex = new int[1];
        List<ExecutableElement> ee = fuzzyResolveMethodInvocation(info, parent, proposedTypes, proposedIndex);
        
        if (ee.isEmpty()) { //cannot be resolved
            return null;
        }
        
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return proposedTypes;
    }

    Tree id = nct.getIdentifier();

    if (id.getKind() == Kind.PARAMETERIZED_TYPE) {
        id = ((ParameterizedTypeTree) id).getType();
    }

    if (id == error) {
        return resolveType(EnumSet.noneOf(ElementKind.class), info, parent.getParentPath(), nct, offset, null, null);
    }
    
    return null;
}
 
Example 39
Project: j2objc   File: MethodTranslator.java    License: Apache License 2.0 5 votes vote down vote up
private ExecutableElement findMethod(String name, TypeMirror type, MethodReference methodDef) {
  TypeElement typeElement = (TypeElement) parserEnv.typeUtilities().asElement(type);
  String signature = methodDef.getSignature();
  String erasedSignature = methodDef.getErasedSignature();
  for (Element e : typeElement.getEnclosedElements()) {
    if (e.getKind() == ElementKind.METHOD && e.getSimpleName().contentEquals(name)) {
      String sig = typeUtil.getReferenceSignature((ExecutableElement) e);
      if (sig.equals(signature) || sig.equals(erasedSignature)) {
        return (ExecutableElement) e;
      }
    }
  }
  throw new AssertionError("failed method lookup: " + type + " " + name + signature);
}
 
Example 40
Project: netbeans   File: DelegateMethodGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
private String dump(ExecutableElement ee) {
    StringBuilder result = new StringBuilder();
    
    for (Modifier m : ee.getModifiers()) {
        result.append(m.toString());
        result.append(' ');
    }
    
    result.append(ee.getReturnType().toString() + " " + ee.toString());
    
    return result.toString();
}