Java Code Examples for javax.lang.model.element.ExecutableElement#getModifiers()

The following examples show how to use javax.lang.model.element.ExecutableElement#getModifiers() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AnnotationsAnalyzer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void checkInitializerMethod( ExecutableElement element, 
        TypeElement parent, CdiAnalysisResult result )
{
    Set<Modifier> modifiers = element.getModifiers();
    boolean isAbstract = modifiers.contains( Modifier.ABSTRACT );
    boolean isStatic = modifiers.contains( Modifier.STATIC );
    if (  isAbstract || isStatic ){
        String key = isAbstract? "ERR_AbstractInitMethod":
            "ERR_StaticInitMethod";           // NOI18N
        result.addError( element, NbBundle.getMessage(
            AnnotationsAnalyzer.class, key ));
    }    
    TypeMirror method = result.getInfo().getTypes().asMemberOf(
            (DeclaredType)parent.asType() , element);
    if ( method instanceof ExecutableType ){
        List<? extends TypeVariable> typeVariables = 
            ((ExecutableType)method).getTypeVariables();
        if ( typeVariables != null && typeVariables.size() > 0 ){
            result.addError( element, NbBundle.getMessage(
                        AnnotationsAnalyzer.class, "ERR_GenericInitMethod" ));// NOI18N
        }
    }
}
 
Example 2
Source File: EntityClassInfo.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void setStringConverter( Element typeElement ) {
    List<ExecutableElement> methods = ElementFilter.methodsIn( 
            typeElement.getEnclosedElements());
    for (ExecutableElement method : methods) {
        Set<Modifier> modifiers = method.getModifiers();
        if ( !modifiers.contains(Modifier.STATIC) || 
                !modifiers.contains(Modifier.PUBLIC))
        {
            continue;
        }
        List<? extends VariableElement> parameters = method.getParameters();
        if ( parameters.size()!= 1){
            continue;
        }
        
        if ( method.getSimpleName().contentEquals("valueOf")){
            stringConverter = StringConverter.VALUE_OF;
        }
        else if ( method.getSimpleName().contentEquals("fromString")){
            stringConverter = StringConverter.FROM_STRING;
        }
    }
}
 
Example 3
Source File: PubapiVisitor.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a String representation of a method element with everything
 * necessary to track all public aspects of it in an API.
 * @param e Element to create String for.
 * @return String representation of element.
 */
protected String makeMethodString(ExecutableElement e) {
    StringBuilder result = new StringBuilder();
    for (Modifier modifier : e.getModifiers()) {
        result.append(modifier.toString());
        result.append(" ");
    }
    result.append(e.getReturnType().toString());
    result.append(" ");
    result.append(e.toString());

    List<? extends TypeMirror> thrownTypes = e.getThrownTypes();
    if (!thrownTypes.isEmpty()) {
        result.append(" throws ");
        for (Iterator<? extends TypeMirror> iterator = thrownTypes
                .iterator(); iterator.hasNext();) {
            TypeMirror typeMirror = iterator.next();
            result.append(typeMirror.toString());
            if (iterator.hasNext()) {
                result.append(", ");
            }
        }
    }
    return result.toString();
}
 
Example 4
Source File: WebServiceVisitor.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
protected boolean shouldProcessMethod(ExecutableElement method, WebMethod webMethod) {
    builder.log("should process method: " + method.getSimpleName() + " hasWebMethods: " + hasWebMethods + " ");
    /*
    Fix for https://jax-ws.dev.java.net/issues/show_bug.cgi?id=577
    if (hasWebMethods && webMethod == null) {
        builder.log("webMethod == null");
        return false;
    }
    */
    Collection<Modifier> modifiers = method.getModifiers();
    boolean staticFinal = modifiers.contains(Modifier.STATIC) || modifiers.contains(Modifier.FINAL);
    if (staticFinal) {
        if (webMethod != null) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_METHOD_IS_STATIC_OR_FINAL(method.getEnclosingElement(),
                    method), method);
        }
        return false;
    }
    boolean result = (endpointReferencesInterface ||
            method.getEnclosingElement().equals(typeElement) ||
            (method.getEnclosingElement().getAnnotation(WebService.class) != null));
    builder.log("endpointReferencesInterface: " + endpointReferencesInterface);
    builder.log("declaring class has WebService: " + (method.getEnclosingElement().getAnnotation(WebService.class) != null));
    builder.log("returning: " + result);
    return result;
}
 
Example 5
Source File: DaoMetaFactory.java    From doma with Apache License 2.0 6 votes vote down vote up
private void doMethodElement(
    TypeElement interfaceElement, DaoMeta daoMeta, ExecutableElement methodElement) {
  Set<Modifier> modifiers = methodElement.getModifiers();
  if (modifiers.contains(Modifier.STATIC) || modifiers.contains(Modifier.PRIVATE)) {
    return;
  }
  validateMethod(interfaceElement, methodElement);
  QueryMeta queryMeta = createQueryMeta(daoMeta, methodElement);
  validateQueryMeta(queryMeta, methodElement);
  daoMeta.addQueryMeta(queryMeta);

  ParentDaoMeta parentDaoMeta = daoMeta.getParentDaoMeta();
  if (parentDaoMeta != null) {
    parentDaoMeta
        .getMethods()
        .removeIf(it -> ctx.getMoreElements().overrides(methodElement, it, interfaceElement));
  }
}
 
Example 6
Source File: PubapiVisitor.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a String representation of a method element with everything
 * necessary to track all public aspects of it in an API.
 * @param e Element to create String for.
 * @return String representation of element.
 */
protected String makeMethodString(ExecutableElement e) {
    StringBuilder result = new StringBuilder();
    for (Modifier modifier : e.getModifiers()) {
        result.append(modifier.toString());
        result.append(" ");
    }
    result.append(e.getReturnType().toString());
    result.append(" ");
    result.append(e.toString());

    List<? extends TypeMirror> thrownTypes = e.getThrownTypes();
    if (!thrownTypes.isEmpty()) {
        result.append(" throws ");
        for (Iterator<? extends TypeMirror> iterator = thrownTypes
                .iterator(); iterator.hasNext();) {
            TypeMirror typeMirror = iterator.next();
            result.append(typeMirror.toString());
            if (iterator.hasNext()) {
                result.append(", ");
            }
        }
    }
    return result.toString();
}
 
Example 7
Source File: SimpleMethod.java    From auto with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an appropriate string to be used in code for the access specification of the given
 * method. This will be {@code public} or {@code protected} followed by a space, or the empty
 * string for default access.
 */
static String access(ExecutableElement method) {
  Set<Modifier> mods = method.getModifiers();
  if (mods.contains(Modifier.PUBLIC)) {
    return "public ";
  } else if (mods.contains(Modifier.PROTECTED)) {
    return "protected ";
  } else {
    return "";
  }
}
 
Example 8
Source File: ModelMethodPlugin.java    From squidb with Apache License 2.0 5 votes vote down vote up
private void checkExecutableElement(ExecutableElement e, List<ExecutableElement> modelMethods,
        List<ExecutableElement> staticModelMethods, DeclaredTypeName modelClass) {
    Set<Modifier> modifiers = e.getModifiers();
    if (e.getKind() == ElementKind.CONSTRUCTOR) {
        // Don't copy constructors
        return;
    }
    if (!modifiers.contains(Modifier.STATIC)) {
        utils.getMessager().printMessage(Diagnostic.Kind.WARNING,
                "Model spec objects should never be instantiated, so non-static methods are meaningless. " +
                        "Did you mean to make this a static method?", e);
        return;
    }
    ModelMethod methodAnnotation = e.getAnnotation(ModelMethod.class);
    // Private static methods may be unannotated if they are called by a public annotated method.
    // Don't assume error if method is private
    if (methodAnnotation == null) {
        if (modifiers.contains(Modifier.PUBLIC)) {
            staticModelMethods.add(e);
        } else if (!modifiers.contains(Modifier.PRIVATE)) {
            utils.getMessager().printMessage(Diagnostic.Kind.WARNING,
                    "This method will not be added to the model definition. " +
                            "Did you mean to annotate this method with @ModelMethod?", e);
        }
    } else {
        List<? extends VariableElement> params = e.getParameters();
        if (params.size() == 0) {
            modelSpec.logError("@ModelMethod methods must have an abstract model as their first argument", e);
        } else {
            VariableElement firstParam = params.get(0);
            TypeMirror paramType = firstParam.asType();
            if (!checkFirstArgType(paramType, modelClass)) {
                modelSpec.logError("@ModelMethod methods must have an abstract model as their first argument", e);
            } else {
                modelMethods.add(e);
            }
        }
    }
}
 
Example 9
Source File: FactoryProcessor.java    From toothpick with Apache License 2.0 5 votes vote down vote up
private boolean isValidInjectAnnotatedConstructor(ExecutableElement element) {
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

  // Verify modifiers.
  Set<Modifier> modifiers = element.getModifiers();
  if (modifiers.contains(PRIVATE)) {
    error(
        element,
        "@Inject constructors must not be private in class %s.",
        enclosingElement.getQualifiedName());
    return false;
  }

  // Verify parentScope modifiers.
  Set<Modifier> parentModifiers = enclosingElement.getModifiers();
  if (parentModifiers.contains(PRIVATE)) {
    error(
        element,
        "Class %s is private. @Inject constructors are not allowed in private classes.",
        enclosingElement.getQualifiedName());
    return false;
  }

  if (isNonStaticInnerClass(enclosingElement)) {
    return false;
  }

  for (VariableElement paramElement : element.getParameters()) {
    if (!isValidInjectedType(paramElement)) {
      return false;
    }
  }

  return true;
}
 
Example 10
Source File: JaxWsChildren.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<ExecutableElement> getPublicMethods(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 method:methods) {
        Set<Modifier> modifiers = method.getModifiers();
        if (modifiers.contains(Modifier.PUBLIC)) {
            publicMethods.add(method);
        }
    }
    return publicMethods;
}
 
Example 11
Source File: InjectMethodValidator.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
@Override
public ValidationReport<ExecutableElement> validate(ExecutableElement methodElement) {
  ValidationReport.Builder<ExecutableElement> builder =
      ValidationReport.Builder.about(methodElement);
  Set<Modifier> modifiers = methodElement.getModifiers();
  if (modifiers.contains(ABSTRACT)) {
    builder.addItem(ABSTRACT_INJECT_METHOD, methodElement);
  }

  if (modifiers.contains(PRIVATE)) {
    builder.addItem(PRIVATE_INJECT_METHOD, methodElement);
  }

  if (!methodElement.getTypeParameters().isEmpty()) {
    builder.addItem(GENERIC_INJECT_METHOD, methodElement);
  }

  for (VariableElement parameter : methodElement.getParameters()) {
    ImmutableSet<? extends AnnotationMirror> qualifiers = getQualifiers(parameter);
    if (qualifiers.size() > 1) {
      for (AnnotationMirror qualifier : qualifiers) {
        builder.addItem(MULTIPLE_QUALIFIERS, methodElement, qualifier);
      }
    }
  }

  return builder.build();
}
 
Example 12
Source File: ProducerMethodAnalyzer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void checkSpecializes(ExecutableElement element, CdiAnalysisResult result )
{
    if ( !AnnotationUtil.hasAnnotation(element, AnnotationUtil.SPECIALIZES, 
            result.getInfo() ))
    {
        return;
    }
    Set<Modifier> modifiers = element.getModifiers();
    if ( modifiers.contains( Modifier.STATIC )){
        result.addError( element,  NbBundle.getMessage(
                    ProducerMethodAnalyzer.class, 
                    "ERR_StaticSpecializesProducer"));    // NOI18N
    }
    CompilationInfo compInfo = result.getInfo();
    ExecutableElement overridenMethod = compInfo.getElementUtilities().
        getOverriddenMethod( element );
    if ( overridenMethod == null ){
        return;
    }
    TypeElement superClass = compInfo.getElementUtilities().
        enclosingTypeElement( overridenMethod );
    TypeElement containingClass = compInfo.getElementUtilities().
        enclosingTypeElement( element );
    TypeMirror typeDirectSuper = containingClass.getSuperclass();
    if ( !superClass.equals(compInfo.getTypes().asElement(typeDirectSuper)) || 
            !AnnotationUtil.hasAnnotation(overridenMethod, 
                    AnnotationUtil.PRODUCES_FQN, compInfo))
    {
        result.addError( element, NbBundle.getMessage(
                    ProducerMethodAnalyzer.class, 
                    "ERR_NoDirectSpecializedProducer"));    // NOI18N
    }
}
 
Example 13
Source File: JaxWsChildren.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<ExecutableElement> getPublicMethods(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 method:methods) {
        Set<Modifier> modifiers = method.getModifiers();
        if (modifiers.contains(Modifier.PUBLIC)) {
            publicMethods.add(method);
        }
    }
    return publicMethods;
}
 
Example 14
Source File: ModelSourceLinker.java    From ngAndroid with Apache License 2.0 4 votes vote down vote up
private NgModelSourceLink getSourceLink(Element element) {

        TypeMirror fieldType = element.asType();
        TypeElement typeElement = typeUtils.asTypeElement(fieldType);
        Option<String> packageName = elementUtils.getPackageName(typeElement);
        String fullName = elementUtils.getFullName(typeElement);

        List<SourceField> fields = new ArrayList<>();

        String modelName = elementUtils.stripClassName(fieldType);

        List<? extends Element> enclosedElements = typeElement.getEnclosedElements();
        boolean isInterface = typeElement.getKind().isInterface();

        if(isInterface) {
            messageUtils.error(Option.of(typeElement), "Model must be a class");
        }

        Set<String> duplicateCheck = new HashSet<>();

        for(int index = 0; index < enclosedElements.size(); index++){
            Element enclosedElement = enclosedElements.get(index);
            if(elementUtils.isSetter(enclosedElement)) {
                ExecutableElement setter = (ExecutableElement) enclosedElement;
                if (!elementUtils.returnsVoid(setter)) {
                    messageUtils.error(Option.of(element), "Setter '%s' must not return a value", element.toString());
                    continue;
                }
                Set<Modifier> modifiers = setter.getModifiers();
                if(modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.PROTECTED)){
                    messageUtils.error(Option.of(setter), "Unable to access field '%s' from scope '%s'. Must have default or public access", element.toString(), element.getEnclosingElement().toString());
                    continue;
                }
                String fName = setter.getSimpleName().toString().substring(3).toLowerCase();

                if(duplicateCheck.contains(fName)){
                    messageUtils.error(Option.of(setter), "Field '%s' in model '%s' is a duplicate.", setter.getSimpleName().toString().substring(3), fullName);
                    continue;
                }
                duplicateCheck.add(fName);

                TypeMirror typeMirror = setter.getParameters().get(0).asType();
                String type = typeMirror.toString();
                SourceField sourceField = new SourceField(fName, type, primitiveUtils);
                sourceField.setSetter(setter.getSimpleName().toString());
                // TODO O(n^2) is the best
                boolean getterFound = false;
                for(Element possGetter : enclosedElements) {
                    if(elementUtils.isGetterForField(possGetter, fName, typeMirror.getKind())){
                        sourceField.setGetter(possGetter.getSimpleName().toString());
                        getterFound = true;
                        break;
                    }
                }
                if(!getterFound) {
                    messageUtils.error(Option.of(setter), "Field '%s' is missing a corresponding getter", fName);
                }
                fields.add(sourceField);
            }
        }
        return new NgModelSourceLink(modelName, packageName, fullName, isInterface, fields, element);
    }
 
Example 15
Source File: ProvidesMethodValidator.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
@Override
public ValidationReport<ExecutableElement> validate(ExecutableElement providesMethodElement) {
  ValidationReport.Builder<ExecutableElement> builder =
      ValidationReport.Builder.about(providesMethodElement);

  Provides providesAnnotation = providesMethodElement.getAnnotation(Provides.class);
  checkArgument(providesAnnotation != null);

  Element enclosingElement = providesMethodElement.getEnclosingElement();
  if (!isAnnotationPresent(enclosingElement, Module.class)) {
    builder.addItem(formatModuleErrorMessage(BINDING_METHOD_NOT_IN_MODULE),
        providesMethodElement);
  }
  
  if (!providesMethodElement.getTypeParameters().isEmpty()) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_TYPE_PARAMETER),
        providesMethodElement);
  }

  Set<Modifier> modifiers = providesMethodElement.getModifiers();
  if (modifiers.contains(PRIVATE)) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_PRIVATE),
        providesMethodElement);
  }
  if (modifiers.contains(STATIC)) {
    // TODO(gak): why not?
    builder.addItem(formatErrorMessage(BINDING_METHOD_STATIC), providesMethodElement);
  }
  if (modifiers.contains(ABSTRACT)) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_ABSTRACT), providesMethodElement);
  }

  TypeMirror returnType = providesMethodElement.getReturnType();
  TypeKind returnTypeKind = returnType.getKind();
  if (returnTypeKind.equals(VOID)) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_MUST_RETURN_A_VALUE),
        providesMethodElement);
  }

  // check mapkey is right
  if (!providesAnnotation.type().equals(Provides.Type.MAP) 
      && (getMapKeys(providesMethodElement) != null
          && getMapKeys(providesMethodElement).size() > 0)) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_NOT_MAP_HAS_MAP_KEY),
        providesMethodElement);
  }

  validateMethodQualifiers(builder, providesMethodElement);

  switch (providesAnnotation.type()) {
    case UNIQUE: // fall through
    case SET:
      validateKeyType(builder, returnType);
      break;
    case MAP:
      validateKeyType(builder, returnType);
      ImmutableSet<? extends AnnotationMirror> annotationMirrors =
          getMapKeys(providesMethodElement);
      switch (annotationMirrors.size()) {
        case 0:
          builder.addItem(formatErrorMessage(BINDING_METHOD_WITH_NO_MAP_KEY),
              providesMethodElement);
          break;
        case 1:
          break;
        default:
          builder.addItem(formatErrorMessage(BINDING_METHOD_WITH_MULTIPLE_MAP_KEY),
              providesMethodElement);
          break;
      }
      break;
    case SET_VALUES:
      if (!returnTypeKind.equals(DECLARED)) {
        builder.addItem(PROVIDES_METHOD_SET_VALUES_RETURN_SET, providesMethodElement);
      } else {
        DeclaredType declaredReturnType = (DeclaredType) returnType;
        // TODO(gak): should we allow "covariant return" for set values?
        if (!declaredReturnType.asElement().equals(getSetElement())) {
          builder.addItem(PROVIDES_METHOD_SET_VALUES_RETURN_SET, providesMethodElement);
        } else if (declaredReturnType.getTypeArguments().isEmpty()) {
          builder.addItem(formatErrorMessage(BINDING_METHOD_SET_VALUES_RAW_SET),
              providesMethodElement);
        } else {
          validateKeyType(builder,
              Iterables.getOnlyElement(declaredReturnType.getTypeArguments()));
        }
      }
      break;
    default:
      throw new AssertionError();
  }

  return builder.build();
}
 
Example 16
Source File: ProducesMethodValidator.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
@Override
public ValidationReport<ExecutableElement> validate(ExecutableElement producesMethodElement) {
  ValidationReport.Builder<ExecutableElement> builder =
      ValidationReport.Builder.about(producesMethodElement);

  Produces producesAnnotation = producesMethodElement.getAnnotation(Produces.class);
  checkArgument(producesAnnotation != null);

  Element enclosingElement = producesMethodElement.getEnclosingElement();
  if (!isAnnotationPresent(enclosingElement, ProducerModule.class)) {
    builder.addItem(formatModuleErrorMessage(BINDING_METHOD_NOT_IN_MODULE),
        producesMethodElement);
  }

  if (!producesMethodElement.getTypeParameters().isEmpty()) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_TYPE_PARAMETER), producesMethodElement);
  }

  Set<Modifier> modifiers = producesMethodElement.getModifiers();
  if (modifiers.contains(PRIVATE)) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_PRIVATE), producesMethodElement);
  }
  if (modifiers.contains(STATIC)) {
    // TODO(gak): why not?
    builder.addItem(formatErrorMessage(BINDING_METHOD_STATIC), producesMethodElement);
  }
  if (modifiers.contains(ABSTRACT)) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_ABSTRACT), producesMethodElement);
  }

  TypeMirror returnType = producesMethodElement.getReturnType();
  TypeKind returnTypeKind = returnType.getKind();
  if (returnTypeKind.equals(VOID)) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_MUST_RETURN_A_VALUE),
        producesMethodElement);
  }

  // check mapkey is right
  if (!producesAnnotation.type().equals(Produces.Type.MAP)
      && (getMapKeys(producesMethodElement) != null
          && !getMapKeys(producesMethodElement).isEmpty())) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_NOT_MAP_HAS_MAP_KEY),
        producesMethodElement);
  }

  ProvidesMethodValidator.validateMethodQualifiers(builder, producesMethodElement);

  switch (producesAnnotation.type()) {
    case UNIQUE: // fall through
    case SET:
      validateSingleReturnType(builder, returnType);
      break;
    case MAP:
      validateSingleReturnType(builder, returnType);
      ImmutableSet<? extends AnnotationMirror> annotationMirrors =
          getMapKeys(producesMethodElement);
      switch (annotationMirrors.size()) {
        case 0:
          builder.addItem(formatErrorMessage(BINDING_METHOD_WITH_NO_MAP_KEY),
              producesMethodElement);
          break;
        case 1:
          break;
        default:
          builder.addItem(formatErrorMessage(BINDING_METHOD_WITH_MULTIPLE_MAP_KEY),
              producesMethodElement);
          break;
      }
      break;
    case SET_VALUES:
      if (returnTypeKind.equals(DECLARED)
          && MoreTypes.isTypeOf(ListenableFuture.class, returnType)) {
        DeclaredType declaredReturnType = MoreTypes.asDeclared(returnType);
        if (!declaredReturnType.getTypeArguments().isEmpty()) {
          validateSetType(builder, Iterables.getOnlyElement(
              declaredReturnType.getTypeArguments()));
        }
      } else {
        validateSetType(builder, returnType);
      }
      break;
    default:
      throw new AssertionError();
  }

  return builder.build();
}
 
Example 17
Source File: ToothpickProcessor.java    From toothpick with Apache License 2.0 4 votes vote down vote up
protected boolean isValidInjectAnnotatedMethod(ExecutableElement methodElement) {
  TypeElement enclosingElement = (TypeElement) methodElement.getEnclosingElement();

  // Verify modifiers.
  Set<Modifier> modifiers = methodElement.getModifiers();
  if (modifiers.contains(PRIVATE)) {
    error(
        methodElement,
        "@Inject annotated methods must not be private : %s#%s",
        enclosingElement.getQualifiedName(),
        methodElement.getSimpleName());
    return false;
  }

  // Verify parentScope modifiers.
  Set<Modifier> parentModifiers = enclosingElement.getModifiers();
  if (parentModifiers.contains(PRIVATE)) {
    error(
        methodElement,
        "@Injected fields in class %s. The class must be non private.",
        enclosingElement.getSimpleName());
    return false;
  }

  for (VariableElement paramElement : methodElement.getParameters()) {
    if (!isValidInjectedType(paramElement)) {
      return false;
    }
  }

  if (modifiers.contains(PUBLIC) || modifiers.contains(PROTECTED)) {
    if (!hasWarningSuppressed(methodElement, SUPPRESS_WARNING_ANNOTATION_VISIBLE_VALUE)) {
      crashOrWarnWhenMethodIsNotPackageVisible(
          methodElement,
          format(
              "@Inject annotated methods should have package visibility: %s#%s", //
              enclosingElement.getQualifiedName(), methodElement.getSimpleName()));
    }
  }
  return true;
}
 
Example 18
Source File: InterceptedBeanAnalyzer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void analyze( TypeElement element, TypeElement parent,
        WebBeansModel model, AtomicBoolean cancel,
        Result result )
{
    if ( AnnotationUtil.hasAnnotation(element, AnnotationUtil.INTERCEPTOR, 
            model.getCompilationController() ))
    {
        result.requireCdiEnabled(element, model);
        // rule should not be applied to interceptor 
        return ;
    }
    boolean hasIBindings = hasInterceptorBindings(element, model);
    if ( hasIBindings ){
        result.requireCdiEnabled(element, model);
        EditorAnnotationsHelper helper = EditorAnnotationsHelper.getInstance(result);
        ElementHandle<TypeElement> handle = ElementHandle.create(element);
        if ( helper != null ){
            helper.addInterceptedBean( result , 
                    handle.resolve( result.getInfo()));
        }
    }
    
    
    Set<Modifier> modifiers = element.getModifiers();
    boolean isFinal = modifiers.contains(Modifier.FINAL);
    List<ExecutableElement> methods = ElementFilter.methodsIn(
            element.getEnclosedElements());
    ExecutableElement badMethod = null;
    for (ExecutableElement method : methods) {
        if ( cancel.get() ){
            return;
        }
        modifiers = method.getModifiers();
        if ( !modifiers.contains( Modifier.FINAL )){
            continue;
        }
        if ( modifiers.contains( Modifier.STATIC ) || 
                modifiers.contains( Modifier.PRIVATE))
        {
            continue;
        }
        badMethod = method;
        break;
    }
    if ( badMethod == null && !isFinal ){
        return;
    }
    if ( cancel.get() ){
        return;
    }
    if (hasIBindings && isFinal) {
        result.addError(element, model, 
                        NbBundle.getMessage(
                        InterceptedBeanAnalyzer.class,
                        "ERR_FinalInterceptedBean")); // NOI18N
    }
    if (hasIBindings && badMethod != null) {
        result.addError(element, model,   
                        NbBundle.getMessage(
                        InterceptedBeanAnalyzer.class,
                        "ERR_InterceptedBeanHasFinalMethod", badMethod
                                .getSimpleName().toString())); // NOI18N
    }
}
 
Example 19
Source File: EjbFacadeGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void modifyEntityManager( List<GenerationOptions> methodOptions ,
        FileObject fileObject)  throws IOException 
{
    final Set<String> methodNames = new HashSet<String>();
    for( GenerationOptions opt : methodOptions ){
        methodNames.add( opt.getMethodName());
    }
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        
        @Override
        public void run(WorkingCopy workingCopy) throws Exception {
            
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            
            for (Tree typeDeclaration : cut.getTypeDecls()){
                if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDeclaration
                        .getKind()))
                {
                    ClassTree clazz = (ClassTree) typeDeclaration;
                    TreePath path = workingCopy.getTrees().getPath(cut,
                            clazz);
                    Element element = workingCopy.getTrees().getElement(
                            path);
                    List<ExecutableElement> methods = ElementFilter
                            .methodsIn(element.getEnclosedElements());
                    for (ExecutableElement method : methods) {
                        if ( methodNames.contains(method.getSimpleName().
                                toString()) )
                        {
                            MethodTree methodTree = workingCopy.getTrees().
                                getTree( method );
                            Set<Modifier> modifiers = method.getModifiers();
                            AnnotationTree annotation = make.Annotation(
                                    make.QualIdent(Override.class.getCanonicalName()),
                                    Collections.<ExpressionTree>emptyList());
                            ModifiersTree newModifs = make.Modifiers(
                                    modifiers, 
                                    Collections.singletonList(annotation));
                            workingCopy.rewrite(methodTree.getModifiers(), 
                                    newModifs);
                        }
                    }
                }
            }
        }
    };
    
    JavaSource.forFileObject(fileObject).runModificationTask(task).commit();
}
 
Example 20
Source File: EntityClassInfo.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected void extractFieldsFromMethods(DeclaredType originalEntity, 
        TypeElement typeElement, CompilationController controller) 
{
    List<ExecutableElement> methods = ElementFilter.methodsIn(typeElement.getEnclosedElements());

    for (ExecutableElement method : methods) {
        Set<Modifier> modifiers = method.getModifiers();
        if (modifiers.contains(Modifier.STATIC) || modifiers.contains(Modifier.PRIVATE)) {
            continue;
        }

        FieldInfo fieldInfo = new FieldInfo();

        fieldInfo.parseAnnotations(method.getAnnotationMirrors());

        if (!fieldInfo.isPersistent() || !fieldInfo.hasPersistenceAnnotation()) {
            continue;
        }

        fieldInfos.add(fieldInfo);
        String name = method.getSimpleName().toString();
        if (name.startsWith("get")) {       //NOI18N
            name = name.substring(3);
            name = Util.lowerFirstChar(name);
        }

        fieldInfo.setName(name);
        TypeMirror methodType = controller.getTypes().asMemberOf(
                originalEntity, method);
        fieldInfo.setType(((ExecutableType)methodType).getReturnType(), controller);

        if (fieldInfo.isId()) {
            idFieldInfo = fieldInfo;
        }
    }
    TypeElement superClass = getJPASuperClass(typeElement, controller);
    if ( superClass == null ){
        return;
    }
    extractFieldsFromMethods( originalEntity , superClass , controller );
}