Esempio n. 1
0
  private void parseMethod(Api api, ExecutableElement executableElement) throws IOException {

    Element actionElement =
        generator
            .getProcessingEnvironment()
            .getElementUtils()
            .getTypeElement(ApiMethodDoc.class.getName());
    TypeMirror apiMethodDocType = actionElement.asType();

    for (AnnotationMirror am : executableElement.getAnnotationMirrors()) {
      if (am.getAnnotationType().equals(apiMethodDocType)) {
        api.apiMethodDoc = Maps.newHashMap();
        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> ee :
            am.getElementValues().entrySet()) {
          api.apiMethodDoc.put(ee.getKey().getSimpleName().toString(), ee.getValue());
        }
        break;
      }
    }

    // generator.log("apiMethodDoc: " + api.apiMethodDoc);

    if (null == api.apiMethodDoc) {
      generator.log("Method miss @ApiMethodDoc. " + executableElement);
      return;
    }

    api.methodName = executableElement.getSimpleName().toString();
    api.methodMapping = executableElement.getAnnotation(RequestMapping.class);
    api.parameters = Lists.newArrayList();

    for (VariableElement var : executableElement.getParameters()) {
      api.parameters.add(var);
    }
  }
Esempio n. 2
0
  /**
   * Returns the annotation on {@code element} formatted as a Map. This returns a Map rather than an
   * instance of the annotation interface to work-around the fact that Class and Class[] fields
   * won't work at code generation time. See
   * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5089128
   */
  public static Map<String, Object> getAnnotation(Class<?> annotationType, Element element) {
    for (AnnotationMirror annotation : element.getAnnotationMirrors()) {
      if (!rawTypeToString(annotation.getAnnotationType(), '$').equals(annotationType.getName())) {
        continue;
      }

      Map<String, Object> result = new LinkedHashMap<String, Object>();
      for (Method m : annotationType.getMethods()) {
        result.put(m.getName(), m.getDefaultValue());
      }
      for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> e :
          annotation.getElementValues().entrySet()) {
        String name = e.getKey().getSimpleName().toString();
        Object value = e.getValue().accept(VALUE_EXTRACTOR, null);
        Object defaultValue = result.get(name);
        if (!lenientIsInstance(defaultValue.getClass(), value)) {
          throw new IllegalStateException(
              String.format(
                  "Value of %s.%s is a %s but expected a %s\n    value: %s",
                  annotationType,
                  name,
                  value.getClass().getName(),
                  defaultValue.getClass().getName(),
                  value instanceof Object[] ? Arrays.toString((Object[]) value) : value));
        }
        result.put(name, value);
      }
      return result;
    }
    return null; // Annotation not found.
  }
  private Set<ConstraintCheckError> checkInternal(
      Element element, AnnotationMirror annotation, TypeMirror type, String messageKey) {

    if (constraintHelper.checkConstraint(annotation.getAnnotationType(), type)
        != ConstraintCheckResult.ALLOWED) {

      return CollectionHelper.asSet(
          new ConstraintCheckError(
              element,
              annotation,
              messageKey,
              annotation.getAnnotationType().asElement().getSimpleName()));
    }

    return Collections.emptySet();
  }
 @Override
 public Set<TypeElement> scan(Element e, Set<TypeElement> p) {
   for (AnnotationMirror annotationMirror : elements.getAllAnnotationMirrors(e)) {
     Element e2 = annotationMirror.getAnnotationType().asElement();
     p.add((TypeElement) e2);
   }
   return super.scan(e, p);
 }
 private static boolean hasAnnotationWithName(Element element, String simpleName) {
   for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
     String annotationName = mirror.getAnnotationType().asElement().getSimpleName().toString();
     if (simpleName.equals(annotationName)) {
       return true;
     }
   }
   return false;
 }
    /**
     * Determines the least upper bound of a1 and a2. If a1 and a2 are both the same type of Value
     * annotation, then the LUB is the result of taking all values from both a1 and a2 and removing
     * duplicates. If a1 and a2 are not the same type of Value annotation they may still be
     * mergeable because some values can be implicitly cast as others. If a1 and a2 are both in
     * {DoubleVal, IntVal} then they will be converted upwards: IntVal &rarr; DoubleVal to arrive at
     * a common annotation type.
     *
     * @return the least upper bound of a1 and a2
     */
    @Override
    public AnnotationMirror leastUpperBound(AnnotationMirror a1, AnnotationMirror a2) {
      if (!AnnotationUtils.areSameIgnoringValues(getTopAnnotation(a1), getTopAnnotation(a2))) {
        return null;
      } else if (isSubtype(a1, a2)) {
        return a2;
      } else if (isSubtype(a2, a1)) {
        return a1;
      }
      // If both are the same type, determine the type and merge:
      else if (AnnotationUtils.areSameIgnoringValues(a1, a2)) {
        List<Object> a1Values =
            AnnotationUtils.getElementValueArray(a1, "value", Object.class, true);
        List<Object> a2Values =
            AnnotationUtils.getElementValueArray(a2, "value", Object.class, true);
        HashSet<Object> newValues = new HashSet<Object>(a1Values.size() + a2Values.size());

        newValues.addAll(a1Values);
        newValues.addAll(a2Values);

        return createAnnotation(a1.getAnnotationType().toString(), newValues);
      }
      // Annotations are in this hierarchy, but they are not the same
      else {
        // If either is UNKNOWNVAL, ARRAYLEN, STRINGVAL, or BOOLEAN then
        // the LUB is
        // UnknownVal
        if (!(AnnotationUtils.areSameByClass(a1, IntVal.class)
            || AnnotationUtils.areSameByClass(a1, DoubleVal.class)
            || AnnotationUtils.areSameByClass(a2, IntVal.class)
            || AnnotationUtils.areSameByClass(a2, DoubleVal.class))) {
          return UNKNOWNVAL;
        } else {
          // At this point one of them must be a DoubleVal and one an
          // IntVal
          AnnotationMirror doubleAnno;
          AnnotationMirror intAnno;

          if (AnnotationUtils.areSameByClass(a2, DoubleVal.class)) {
            doubleAnno = a2;
            intAnno = a1;
          } else {
            doubleAnno = a1;
            intAnno = a2;
          }
          List<Long> intVals = getIntValues(intAnno);
          List<Double> doubleVals = getDoubleValues(doubleAnno);

          for (Long n : intVals) {
            doubleVals.add(n.doubleValue());
          }

          return createDoubleValAnnotation(doubleVals);
        }
      }
    }
 private AnnotationMirror getAnnotation(Element element, String type) {
   if (element != null) {
     for (AnnotationMirror annotation : element.getAnnotationMirrors()) {
       if (type.equals(annotation.getAnnotationType().toString())) {
         return annotation;
       }
     }
   }
   return null;
 }
 private Optional<String> getPointsAnnotationValueIfAny(Element element) {
   for (AnnotationMirror am : element.getAnnotationMirrors()) {
     Name annotationName = am.getAnnotationType().asElement().getSimpleName();
     if (annotationName.contentEquals("Points")) {
       String value = getAnnotationValue(am);
       return Optional.of(value);
     }
   }
   return Optional.absent();
 }
Esempio n. 9
0
 static boolean isJacksonSerializedAnnotated(Element element) {
   List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
   for (AnnotationMirror annotation : annotationMirrors) {
     TypeElement annotationElement = (TypeElement) annotation.getAnnotationType().asElement();
     if (JACKSON_MAPPING_ANNOTATION_CLASSES.contains(
         annotationElement.getQualifiedName().toString())) {
       return true;
     }
   }
   return false;
 }
Esempio n. 10
0
 static boolean isJacksonJsonTypeInfoAnnotated(Element element) {
   List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
   for (AnnotationMirror annotation : annotationMirrors) {
     TypeElement annotationElement = (TypeElement) annotation.getAnnotationType().asElement();
     if ("com.fasterxml.jackson.annotation.JsonTypeInfo"
         .equals(annotationElement.getQualifiedName().toString())) {
       return true;
     }
   }
   return false;
 }
Esempio n. 11
0
 GwtCompatibility(TypeElement type) {
   Optional<AnnotationMirror> gwtCompatibleAnnotation = Optional.absent();
   List<? extends AnnotationMirror> annotations = type.getAnnotationMirrors();
   for (AnnotationMirror annotation : annotations) {
     Name name = annotation.getAnnotationType().asElement().getSimpleName();
     if (name.contentEquals("GwtCompatible")) {
       gwtCompatibleAnnotation = Optional.of(annotation);
     }
   }
   this.gwtCompatibleAnnotation = gwtCompatibleAnnotation;
 }
Esempio n. 12
0
 /**
  * Returns an {@link AnnotationMirror} for the annotation of type {@code annotationClassName} on
  * {@code element}, or {@link Optional#absent()} if no such annotation exists.
  */
 public static Optional<AnnotationMirror> findAnnotationMirror(
     Element element, String annotationClassName) {
   for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
     TypeElement annotationTypeElement =
         (TypeElement) (annotationMirror.getAnnotationType().asElement());
     if (annotationTypeElement.getQualifiedName().contentEquals(annotationClassName)) {
       return Optional.of(annotationMirror);
     }
   }
   return Optional.absent();
 }
Esempio n. 13
0
 static Parameter forVariableElement(VariableElement variable) {
   ImmutableSet.Builder<String> qualifiers = ImmutableSet.builder();
   for (AnnotationMirror annotationMirror : variable.getAnnotationMirrors()) {
     DeclaredType annotationType = annotationMirror.getAnnotationType();
     if (annotationType.asElement().getAnnotation(Qualifier.class) != null) {
       qualifiers.add(Mirrors.getQualifiedName(annotationType).toString());
     }
   }
   return new Parameter(
       FluentIterable.from(qualifiers.build()).first(),
       variable.asType().toString(),
       variable.getSimpleName().toString());
 }
Esempio n. 14
0
  protected boolean isExplicitTypeDefinition(Element declaration) {
    if (declaration.getKind() != ElementKind.CLASS) {
      debug("%s isn't a potential JAXB type because it's not a class.", declaration);
      return false;
    }

    PackageElement pckg =
        this.context.getProcessingEnvironment().getElementUtils().getPackageOf(declaration);
    if ((pckg != null) && (pckg.getAnnotation(Ignore.class) != null)) {
      debug(
          "%s isn't a potential JAXB type because its package is annotated as to be ignored.",
          declaration);
      return false;
    }

    if (isThrowable(declaration)) {
      debug(
          "%s isn't a potential JAXB type because it's an instance of java.lang.Throwable.",
          declaration);
      return false;
    }

    List<? extends AnnotationMirror> annotationMirrors = declaration.getAnnotationMirrors();
    boolean explicitXMLTypeOrElement = false;
    for (AnnotationMirror mirror : annotationMirrors) {
      Element annotationDeclaration = mirror.getAnnotationType().asElement();
      if (annotationDeclaration != null) {
        String fqn =
            annotationDeclaration instanceof TypeElement
                ? ((TypeElement) annotationDeclaration).getQualifiedName().toString()
                : "";
        // exclude all XmlTransient types and all jaxws types.
        if (XmlTransient.class.getName().equals(fqn)
            || fqn.startsWith("javax.xml.ws")
            || fqn.startsWith("javax.ws.rs")
            || fqn.startsWith("javax.jws")) {
          debug("%s isn't a potential JAXB type because of annotation %s.", declaration, fqn);
          return false;
        } else {
          explicitXMLTypeOrElement =
              (XmlType.class.getName().equals(fqn)) || (XmlRootElement.class.getName().equals(fqn));
        }
      }

      if (explicitXMLTypeOrElement) {
        break;
      }
    }

    return explicitXMLTypeOrElement;
  }
Esempio n. 15
0
    public static MetaAnnotated from(AnnotationMirror mirror) {
      TypeElement element = (TypeElement) mirror.getAnnotationType().asElement();
      String name = element.getQualifiedName().toString();

      @Nullable MetaAnnotated metaAnnotated = cache.get(element);
      if (metaAnnotated == null) {
        metaAnnotated = ImmutableProto.MetaAnnotated.of(element);
        @Nullable MetaAnnotated existing = cache.putIfAbsent(name, metaAnnotated);
        if (existing != null) {
          metaAnnotated = existing;
        }
      }

      return metaAnnotated;
    }
Esempio n. 16
0
  private static String wrapText(Element element, AnnotationMirror mirror, String text) {
    StringBuilder b = new StringBuilder();
    if (element != null) {
      b.append("Element " + element.toString());
    }
    if (mirror != null) {
      b.append(" at annotation @" + Utils.getSimpleName(mirror.getAnnotationType()));
    }

    if (b.length() > 0) {
      b.append(" is erroneous: ").append(text);
      return b.toString();
    } else {
      return text;
    }
  }
Esempio n. 17
0
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   for (TypeElement te : ElementFilter.typesIn(roundEnv.getRootElements())) {
     if (isSimpleName(te, "InvalidSource")) {
       for (Element c : te.getEnclosedElements()) {
         for (AnnotationMirror am : c.getAnnotationMirrors()) {
           Element ate = am.getAnnotationType().asElement();
           if (isSimpleName(ate, "ExpectInterfaces")) {
             checkInterfaces((TypeElement) c, getValue(am));
           } else if (isSimpleName(ate, "ExpectSupertype")) {
             checkSupertype((TypeElement) c, getValue(am));
           }
         }
       }
     }
   }
   return true;
 }
Esempio n. 18
0
 String gwtCompatibleAnnotationString() {
   if (gwtCompatibleAnnotation.isPresent()) {
     AnnotationMirror annotation = gwtCompatibleAnnotation.get();
     TypeElement annotationElement = (TypeElement) annotation.getAnnotationType().asElement();
     String annotationArguments;
     if (annotation.getElementValues().isEmpty()) {
       annotationArguments = "";
     } else {
       List<String> elements = Lists.newArrayList();
       for (Map.Entry<ExecutableElement, AnnotationValue> entry :
           Collections.unmodifiableMap(annotation.getElementValues()).entrySet()) {
         elements.add(entry.getKey().getSimpleName() + " = " + entry.getValue());
       }
       annotationArguments = "(" + Joiner.on(", ").join(elements) + ")";
     }
     return "@" + annotationElement.getQualifiedName() + annotationArguments;
   } else {
     return "";
   }
 }
Esempio n. 19
0
 private static VariableElement getAutoTypeParameter(
     ExecutableElement method, VariableElement target_parameter) {
   for (VariableElement param : method.getParameters()) {
     AnnotationMirror auto_annotation = Utils.getParameterAutoAnnotation(param);
     if (auto_annotation != null) {
       Class annotation_type =
           NativeTypeTranslator.getClassFromType(auto_annotation.getAnnotationType());
       String parameter_name;
       if (annotation_type.equals(AutoType.class)) {
         parameter_name = param.getAnnotation(AutoType.class).value();
       } else if (annotation_type.equals(AutoSize.class)) {
         parameter_name = param.getAnnotation(AutoSize.class).value();
       } else {
         throw new RuntimeException("Unknown annotation type " + annotation_type);
       }
       if (target_parameter.getSimpleName().toString().equals(parameter_name)) {
         return param;
       }
     }
   }
   return null;
 }
  /** Returns whether the field {@code f} is unused, given the annotations on the receiver. */
  private boolean isUnused(
      VariableTree field, Collection<? extends AnnotationMirror> receiverAnnos) {
    if (receiverAnnos.isEmpty()) {
      return false;
    }

    AnnotationMirror unused =
        getDeclAnnotation(TreeUtils.elementFromDeclaration(field), Unused.class);
    if (unused == null) {
      return false;
    }

    Name when = AnnotationUtils.getElementValueClassName(unused, "when", false);
    for (AnnotationMirror anno : receiverAnnos) {
      Name annoName = ((TypeElement) anno.getAnnotationType().asElement()).getQualifiedName();
      if (annoName.contentEquals(when)) {
        return true;
      }
    }

    return false;
  }
  /**
   * INTERNAL: The pre-processing stages requires some knowledge of the annotation values (e.g.
   * targetEntity) so we will visit the annotation values and build complete MetadataAnnotation from
   * the mirrors.
   */
  protected void buildMetadataAnnotations(
      MetadataAnnotatedElement annotatedElement,
      List<? extends AnnotationMirror> annotationMirrors) {
    AnnotationValueVisitor<Object, Object> visitor = new AnnotationValueVisitor<Object, Object>();

    for (AnnotationMirror annotationMirror : annotationMirrors) {
      String annotation = annotationMirror.getAnnotationType().toString();

      // Only add annotations that we care about. Be nice to have API
      // that we could call into with the annotation mirror to the
      // processor to see if it is a supported annotation. That is, it
      // would tie into the  @SupportedAnnotationTypes({"javax.persistence.*",
      // "org.eclipse.persistence.annotations.*"})
      // declaration from CanonicalModelProcessor, but I couldn't find a
      // way to do this. For now we'll check the strings (similar to what
      // is done with our ASM factory).
      if (annotation.contains(JPA_PERSISTENCE_PACKAGE_PREFIX)
          || annotation.contains(ECLIPSELINK_PERSISTENCE_PACKAGE_PREFIX)) {
        annotatedElement.addAnnotation(
            (MetadataAnnotation) visitor.visitAnnotation(annotationMirror, null));
      }
    }
  }
Esempio n. 22
0
  private void verifyExclusiveMethodAnnotation(Template template, Class<?>... annotationTypes) {
    List<ExecutableElement> methods =
        ElementFilter.methodsIn(template.getTemplateType().getEnclosedElements());
    for (ExecutableElement method : methods) {
      List<AnnotationMirror> foundAnnotations = new ArrayList<>();
      for (int i = 0; i < annotationTypes.length; i++) {
        Class<?> annotationType = annotationTypes[i];
        AnnotationMirror mirror =
            ElementUtils.findAnnotationMirror(context.getEnvironment(), method, annotationType);
        if (mirror != null) {
          foundAnnotations.add(mirror);
        }
      }
      if (foundAnnotations.size() > 1) {
        List<String> annotationNames = new ArrayList<>();
        for (AnnotationMirror mirror : foundAnnotations) {
          annotationNames.add("@" + ElementUtils.getSimpleName(mirror.getAnnotationType()));
        }

        template.addError("Non exclusive usage of annotations %s.", annotationNames);
      }
    }
  }
Esempio n. 23
0
  /**
   * Inject extra bound fields into a classInfo.
   *
   * @param extraBoundFields a list that represents the extra fields defined inside a @{@link
   *     BoundBox} annotation.
   * @param classInfo representation of the class whose BoundBox will receive the extra fields.
   */
  private void injectExtraBoundFields(
      List<? extends AnnotationValue> extraBoundFields, ClassInfo classInfo) {
    if (extraBoundFields == null || extraBoundFields.isEmpty()) {
      return;
    }

    List<FieldInfo> listFieldInfos = classInfo.getListFieldInfos();
    TypeMirror fieldClass = null;
    String fieldName = null;
    for (AnnotationValue annotationValue : extraBoundFields) {
      AnnotationMirror annotationMirror = (AnnotationMirror) annotationValue.getValue();
      log.info("mirror " + annotationMirror.getAnnotationType());

      Map<? extends ExecutableElement, ? extends AnnotationValue>
          mapExecutableElementToAnnotationValue = annotationMirror.getElementValues();
      for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
          mapExecutableElementToAnnotationValue.entrySet()) {
        if (BOUNDBOX_ANNOTATION_PARAMETER_EXTRA_BOUND_FIELDS_FIELD_NAME.equals(
            entry.getKey().getSimpleName().toString())) {
          fieldName = getAnnotationValueAsString(entry.getValue());
          // TODO shoot an error if its null or not a valid field name in java
        }
        if (BOUNDBOX_ANNOTATION_PARAMETER_EXTRA_BOUND_FIELDS_FIELD_CLASS.equals(
            entry.getKey().getSimpleName().toString())) {
          fieldClass = (TypeMirror) entry.getValue().getValue();
        }
      }
      FieldInfo fieldInfo = new FieldInfo(fieldName, fieldClass);

      // TODO we should add a warning to the developer here.
      // TODO there can even be an error if a field of the same name but with a different type
      // exists.
      if (!listFieldInfos.contains(fieldInfo)) {
        listFieldInfos.add(fieldInfo);
      }
    }
  }
Esempio n. 24
0
  private void processLabels(TypeElement resourcesType, List<LabelTemplateMethod> methods) {
    for (Element element : resourcesType.getEnclosedElements()) {
      if (element.getKind() != ElementKind.METHOD) {
        continue;
      }
      final ExecutableElement method = (ExecutableElement) element;
      Message labelAnnotation = element.getAnnotation(Message.class);
      final TemplateParam returnType = new TemplateParam(method.getReturnType().toString());
      final boolean deprecated = method.getAnnotation(Deprecated.class) != null;
      final LabelTemplateMethod labelMethod;
      try {
        labelMethod =
            new LabelTemplateMethod(
                method.getSimpleName().toString(),
                deprecated,
                returnType,
                labelAnnotation.value(),
                labelAnnotation.mobile());
      } catch (Throwable t) {
        processingEnv.getMessager().printMessage(Kind.WARNING, t.getMessage(), resourcesType);
        continue;
      }

      for (VariableElement variable : method.getParameters()) {
        final String paramName = variable.getSimpleName().toString();
        final String paramType = variable.asType().toString();

        List<TemplateAnnotation> annotations = new ArrayList<TemplateAnnotation>();
        for (AnnotationMirror annotationMirrors : variable.getAnnotationMirrors()) {
          annotations.add(new TemplateAnnotation(annotationMirrors.getAnnotationType().toString()));
        }

        labelMethod.getParams().add(new TemplateParam(paramType, paramName, annotations));
      }
      methods.add(labelMethod);
    }
  }
 @Override
 public Void visitAnnotation(AnnotationMirror annotation, AnnotationValue unused) {
   // By explicitly adding annotations rather than relying on AnnotationMirror.toString(),
   // we can import the types and make the code (hopefully) more readable.
   code.add("@%s", QualifiedName.of(asElement(annotation.getAnnotationType())));
   if (annotation.getElementValues().isEmpty()) {
     return null;
   }
   code.add("(");
   if (hasSingleValueWithDefaultKey(annotation)) {
     AnnotationValue value = getOnlyElement(annotation.getElementValues().values());
     visit(value, value);
   } else {
     String separator = "";
     for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
         annotation.getElementValues().entrySet()) {
       code.add("%s%s = ", separator, entry.getKey().getSimpleName());
       visit(entry.getValue(), entry.getValue());
       separator = ", ";
     }
   }
   code.add(")");
   return null;
 }
Esempio n. 26
0
  public boolean hasErrors(final TypeElement typeElement) {

    isClass(typeElement);
    isNotNested(typeElement);

    final MethodValidator methodValidator = new MethodValidator(this.messager);

    for (final ExecutableElement executableElement :
        ElementFilter.methodsIn(typeElement.getEnclosedElements())) {

      boolean symbol = false;
      for (final AnnotationMirror annotationMirror : executableElement.getAnnotationMirrors()) {
        if (annotationMirror
            .getAnnotationType()
            .asElement()
            .getSimpleName()
            .toString()
            .equals(Symbol.class.getSimpleName())) {
          symbol = true;
          break;
        }
      }

      // validate as C symbol
      if (symbol) {
        methodValidator.validateSymbol(executableElement);
      } else {
        // validate as C method
        methodValidator.validateIfNative(executableElement);
      }
    }

    this.error |= methodValidator.errorRaised();

    return this.error;
  }
Esempio n. 27
0
  @Override
  public StringBuffer generate(
      final String packageName,
      final PackageElement packageElement,
      final String className,
      final Element element,
      final ProcessingEnvironment processingEnvironment)
      throws GenerationException {

    final Messager messager = processingEnvironment.getMessager();
    messager.printMessage(Kind.NOTE, "Starting code generation for [" + className + "]");

    final Elements elementUtils = processingEnvironment.getElementUtils();

    // Extract required information
    final TypeElement classElement = (TypeElement) element;
    final String annotationName = ClientAPIModule.getWorkbenchScreenClass();

    String identifier = null;
    Integer preferredHeight = null;
    Integer preferredWidth = null;

    for (final AnnotationMirror am : classElement.getAnnotationMirrors()) {
      if (annotationName.equals(am.getAnnotationType().toString())) {
        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
            am.getElementValues().entrySet()) {
          AnnotationValue aval = entry.getValue();
          if ("identifier".equals(entry.getKey().getSimpleName().toString())) {
            identifier = aval.getValue().toString();
          } else if ("preferredHeight".equals(entry.getKey().getSimpleName().toString())) {
            final int _preferredHeight = (Integer) aval.getValue();
            if (_preferredHeight > 0) {
              preferredHeight = _preferredHeight;
            }
          } else if ("preferredWidth".equals(entry.getKey().getSimpleName().toString())) {
            final int _preferredWidth = (Integer) aval.getValue();
            if (_preferredWidth > 0) {
              preferredWidth = _preferredWidth;
            }
          }
        }
        break;
      }
    }

    final String owningPlace =
        GeneratorUtils.getOwningPerspectivePlaceRequest(classElement, processingEnvironment);

    final String beanActivatorClass =
        GeneratorUtils.getBeanActivatorClassName(classElement, processingEnvironment);

    final ExecutableElement onStartupMethod =
        GeneratorUtils.getOnStartupMethodForNonEditors(classElement, processingEnvironment);

    final String onStartup0ParameterMethodName;
    final String onStartup1ParameterMethodName;
    if (onStartupMethod == null) {
      onStartup0ParameterMethodName = null;
      onStartup1ParameterMethodName = null;
    } else if (onStartupMethod.getParameters().isEmpty()) {
      onStartup0ParameterMethodName = onStartupMethod.getSimpleName().toString();
      onStartup1ParameterMethodName = null;
    } else {
      onStartup0ParameterMethodName = null;
      onStartup1ParameterMethodName = onStartupMethod.getSimpleName().toString();
    }

    final String onMayCloseMethodName =
        GeneratorUtils.getOnMayCloseMethodName(classElement, processingEnvironment);
    final String onCloseMethodName =
        GeneratorUtils.getOnCloseMethodName(classElement, processingEnvironment);
    final String onShutdownMethodName =
        GeneratorUtils.getOnShutdownMethodName(classElement, processingEnvironment);
    final String onOpenMethodName =
        GeneratorUtils.getOnOpenMethodName(classElement, processingEnvironment);
    final String onLostFocusMethodName =
        GeneratorUtils.getOnLostFocusMethodName(classElement, processingEnvironment);
    final String onFocusMethodName =
        GeneratorUtils.getOnFocusMethodName(classElement, processingEnvironment);
    final String getDefaultPositionMethodName =
        GeneratorUtils.getDefaultPositionMethodName(classElement, processingEnvironment);
    final String getTitleMethodName =
        GeneratorUtils.getTitleMethodName(classElement, processingEnvironment);
    final String getContextIdMethodName =
        GeneratorUtils.getContextIdMethodName(classElement, processingEnvironment);
    final ExecutableElement getTitleWidgetMethod =
        GeneratorUtils.getTitleWidgetMethodName(classElement, processingEnvironment);
    final String getTitleWidgetMethodName =
        getTitleWidgetMethod == null ? null : getTitleWidgetMethod.getSimpleName().toString();
    final ExecutableElement getWidgetMethod =
        GeneratorUtils.getWidgetMethodName(classElement, processingEnvironment);
    final String getWidgetMethodName =
        getWidgetMethod == null ? null : getWidgetMethod.getSimpleName().toString();
    final boolean hasUberView =
        GeneratorUtils.hasUberViewReference(classElement, processingEnvironment, getWidgetMethod);

    final boolean isWidget = GeneratorUtils.getIsWidget(classElement, processingEnvironment);
    final String getMenuBarMethodName =
        GeneratorUtils.getMenuBarMethodName(classElement, processingEnvironment);
    final String getToolBarMethodName =
        GeneratorUtils.getToolBarMethodName(classElement, processingEnvironment);
    final String securityTraitList =
        GeneratorUtils.getSecurityTraitList(elementUtils, classElement);
    final String rolesList = GeneratorUtils.getRoleList(elementUtils, classElement);

    if (GeneratorUtils.debugLoggingEnabled()) {
      messager.printMessage(Kind.NOTE, "Package name: " + packageName);
      messager.printMessage(Kind.NOTE, "Class name: " + className);
      messager.printMessage(Kind.NOTE, "Identifier: " + identifier);
      messager.printMessage(Kind.NOTE, "Owning Perspective Identifier: " + owningPlace);
      messager.printMessage(Kind.NOTE, "Preferred Height: " + preferredHeight);
      messager.printMessage(Kind.NOTE, "Preferred Width: " + preferredWidth);
      messager.printMessage(Kind.NOTE, "getContextIdMethodName: " + getContextIdMethodName);
      messager.printMessage(
          Kind.NOTE, "onStartup0ParameterMethodName: " + onStartup0ParameterMethodName);
      messager.printMessage(
          Kind.NOTE, "onStartup1ParameterMethodName: " + onStartup1ParameterMethodName);
      messager.printMessage(Kind.NOTE, "onMayCloseMethodName: " + onMayCloseMethodName);
      messager.printMessage(Kind.NOTE, "onCloseMethodName: " + onCloseMethodName);
      messager.printMessage(Kind.NOTE, "onShutdownMethodName: " + onShutdownMethodName);
      messager.printMessage(Kind.NOTE, "onOpenMethodName: " + onOpenMethodName);
      messager.printMessage(Kind.NOTE, "onLostFocusMethodName: " + onLostFocusMethodName);
      messager.printMessage(Kind.NOTE, "onFocusMethodName: " + onFocusMethodName);
      messager.printMessage(
          Kind.NOTE, "getDefaultPositionMethodName: " + getDefaultPositionMethodName);
      messager.printMessage(Kind.NOTE, "getTitleMethodName: " + getTitleMethodName);
      messager.printMessage(Kind.NOTE, "getTitleWidgetMethodName: " + getTitleWidgetMethodName);
      messager.printMessage(Kind.NOTE, "getWidgetMethodName: " + getWidgetMethodName);
      messager.printMessage(Kind.NOTE, "isWidget: " + Boolean.toString(isWidget));
      messager.printMessage(Kind.NOTE, "hasUberView: " + Boolean.toString(hasUberView));
      messager.printMessage(Kind.NOTE, "getMenuBarMethodName: " + getMenuBarMethodName);
      messager.printMessage(Kind.NOTE, "getToolBarMethodName: " + getToolBarMethodName);
      messager.printMessage(Kind.NOTE, "securityTraitList: " + securityTraitList);
      messager.printMessage(Kind.NOTE, "rolesList: " + rolesList);
    }

    // Validate getWidgetMethodName and isWidget
    if (!isWidget && getWidgetMethodName == null) {
      throw new GenerationException(
          "The WorkbenchScreen must either extend IsWidget or provide a @WorkbenchPartView annotated method to return a com.google.gwt.user.client.ui.IsWidget.",
          packageName + "." + className);
    }
    if (isWidget && getWidgetMethodName != null) {
      final String msg =
          "The WorkbenchScreen both extends com.google.gwt.user.client.ui.IsWidget and provides a @WorkbenchPartView annotated method. The annotated method will take precedence.";
      messager.printMessage(Kind.WARNING, msg, classElement);
    }

    // Validate getTitleMethodName and getTitleWidgetMethodName
    if (getTitleMethodName == null) {
      throw new GenerationException(
          "The WorkbenchScreen must provide a @WorkbenchPartTitle annotated method to return a java.lang.String.",
          packageName + "." + className);
    }

    // Setup data for template sub-system
    Map<String, Object> root = new HashMap<String, Object>();
    root.put("packageName", packageName);
    root.put("className", className);
    root.put("identifier", identifier);
    root.put("owningPlace", owningPlace);
    root.put("preferredHeight", preferredHeight);
    root.put("preferredWidth", preferredWidth);
    root.put("getContextIdMethodName", getContextIdMethodName);
    root.put("realClassName", classElement.getSimpleName().toString());
    root.put("beanActivatorClass", beanActivatorClass);
    root.put("onStartup0ParameterMethodName", onStartup0ParameterMethodName);
    root.put("onStartup1ParameterMethodName", onStartup1ParameterMethodName);
    root.put("onMayCloseMethodName", onMayCloseMethodName);
    root.put("onCloseMethodName", onCloseMethodName);
    root.put("onShutdownMethodName", onShutdownMethodName);
    root.put("onOpenMethodName", onOpenMethodName);
    root.put("onLostFocusMethodName", onLostFocusMethodName);
    root.put("onFocusMethodName", onFocusMethodName);
    root.put("getDefaultPositionMethodName", getDefaultPositionMethodName);
    root.put("getTitleMethodName", getTitleMethodName);
    root.put("getTitleWidgetMethodName", getTitleWidgetMethodName);
    root.put("getWidgetMethodName", getWidgetMethodName);
    root.put("isWidget", isWidget);
    root.put("hasUberView", hasUberView);
    root.put("getMenuBarMethodName", getMenuBarMethodName);
    root.put("getToolBarMethodName", getToolBarMethodName);
    root.put("securityTraitList", securityTraitList);
    root.put("rolesList", rolesList);

    // Generate code
    final StringWriter sw = new StringWriter();
    final BufferedWriter bw = new BufferedWriter(sw);
    try {
      final Template template = config.getTemplate("activityScreen.ftl");
      template.process(root, bw);
    } catch (IOException ioe) {
      throw new GenerationException(ioe);
    } catch (TemplateException te) {
      throw new GenerationException(te);
    } finally {
      try {
        bw.close();
        sw.close();
      } catch (IOException ioe) {
        throw new GenerationException(ioe);
      }
    }
    messager.printMessage(Kind.NOTE, "Successfully generated code for [" + className + "]");

    return sw.getBuffer();
  }
Esempio n. 28
0
  private static boolean printMethodCallArgument(
      PrintWriter writer,
      ExecutableElement method,
      VariableElement param,
      Map<VariableElement, TypeInfo> typeinfos_instance,
      Mode mode,
      boolean first_parameter,
      TypeMap type_map) {
    if (!first_parameter) {
      writer.print(", ");
    }

    AnnotationMirror auto_annotation = Utils.getParameterAutoAnnotation(param);
    Constant constant_annotation = param.getAnnotation(Constant.class);
    if (constant_annotation != null) {
      writer.print(constant_annotation.value());
    } else if (auto_annotation != null && mode == Mode.NORMAL) {
      Class param_type = NativeTypeTranslator.getClassFromType(auto_annotation.getAnnotationType());
      if (AutoType.class.equals(param_type)) {
        final AutoType auto_type_annotation = param.getAnnotation(AutoType.class);
        final VariableElement auto_parameter =
            Utils.findParameter(method, auto_type_annotation.value());
        final String auto_type = typeinfos_instance.get(auto_parameter).getAutoType();
        if (auto_type == null) {
          throw new RuntimeException(
              "No auto type for parameter " + param.getSimpleName() + " in method " + method);
        }
        writer.print(auto_type);
      } else if (AutoSize.class.equals(param_type)) {
        final AutoSize auto_size_annotation = param.getAnnotation(AutoSize.class);
        if (!auto_size_annotation.useExpression()) {
          final String auto_parameter_name = auto_size_annotation.value();
          final VariableElement auto_target_param =
              Utils.findParameter(method, auto_parameter_name);
          final TypeInfo auto_target_type_info = typeinfos_instance.get(auto_target_param);
          final boolean shift_remaining =
              !hasAnyParameterAutoTypeAnnotation(method, auto_target_param)
                  && Utils.isParameterMultiTyped(auto_target_param);
          int shifting = 0;
          if (shift_remaining) {
            shifting = getBufferElementSizeExponent(auto_target_type_info.getType());
            if (shifting > 0) {
              writer.print("(");
            }
          }
          if (auto_size_annotation.canBeNull()) {
            writer.print(
                "("
                    + auto_parameter_name
                    + " == null ? 0 : "
                    + auto_parameter_name
                    + ".remaining())");
          } else {
            writer.print(auto_parameter_name + ".remaining()");
          }
          // Shift the remaining if the target parameter is multityped and there's no AutoType to
          // track type
          if (shift_remaining && shifting > 0) {
            writer.print(" << " + shifting);
            writer.print(")");
          }
        }
        writer.print(auto_size_annotation.expression());
      } else {
        throw new RuntimeException("Unknown auto annotation " + param_type);
      }
    } else {
      if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) {
        writer.print(param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX);
      } else {
        Class type = typeinfos_instance.get(param).getType();
        Check check_annotation = param.getAnnotation(Check.class);
        boolean hide_buffer = mode == Mode.AUTOS && getAutoTypeParameter(method, param) != null;
        if (hide_buffer) {
          writer.print("0L");
        } else {
          if (type == CharSequence.class || type == CharSequence[].class) {
            final String offset = Utils.getStringOffset(method, param);

            writer.print("APIUtil.getBuffer");
            if (param.getAnnotation(NullTerminated.class) != null) {
              writer.print("NT");
            }
            writer.print('(');
            writer.print(type_map.getAPIUtilParam(true));
            writer.print(param.getSimpleName());
            if (offset != null) {
              writer.print(", " + offset);
            }
            writer.print(")");
          } else {
            final AutoSize auto_size_annotation = param.getAnnotation(AutoSize.class);
            if (auto_size_annotation != null) {
              writer.print(auto_size_annotation.value() + "_");
            }

            final Class buffer_type = Utils.getNIOBufferType(param.asType());
            if (buffer_type == null) {
              writer.print(param.getSimpleName());
            } else {
              writer.print("MemoryUtil.getAddress");
              if (check_annotation != null && check_annotation.canBeNull()) {
                writer.print("Safe");
              }
              writer.print("(");
              writer.print(param.getSimpleName());
              writer.print(")");
            }
          }
        }
        if (type != long.class) {
          PointerWrapper pointer_annotation = param.getAnnotation(PointerWrapper.class);
          if (pointer_annotation != null) {
            if (pointer_annotation.canBeNull()) {
              writer.print(" == null ? 0 : " + param.getSimpleName());
            }
            writer.print(".getPointer()");
          }
        }
      }
    }
    return false;
  }
Esempio n. 29
0
  @Override
  public boolean process(
      final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) {
    // Get all classes that has the annotation
    Set<? extends Element> classElements =
        roundEnvironment.getElementsAnnotatedWith(BoundBox.class);
    // For each class that has the annotation
    for (final Element classElement : classElements) {

      // Get the annotation information
      TypeElement boundClass = null;
      String maxSuperClass = null;
      String[] prefixes = null;
      String boundBoxPackageName = null;

      List<? extends AnnotationValue> extraBoundFields = null;
      List<? extends AnnotationMirror> listAnnotationMirrors = classElement.getAnnotationMirrors();
      if (listAnnotationMirrors == null) {
        messager.printMessage(Kind.WARNING, "listAnnotationMirrors is null", classElement);
        return true;
      }

      StringBuilder message = new StringBuilder();
      for (AnnotationMirror annotationMirror : listAnnotationMirrors) {
        log.info("mirror " + annotationMirror.getAnnotationType());
        Map<? extends ExecutableElement, ? extends AnnotationValue> map =
            annotationMirror.getElementValues();
        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
            map.entrySet()) {
          message.append(entry.getKey().getSimpleName().toString());
          message.append("\n");
          message.append(entry.getValue().toString());
          if (BOUNDBOX_ANNOTATION_PARAMETER_BOUND_CLASS.equals(
              entry.getKey().getSimpleName().toString())) {
            boundClass = getAnnotationValueAsTypeElement(entry.getValue());
          }
          if (BOUNDBOX_ANNOTATION_PARAMETER_MAX_SUPER_CLASS.equals(
              entry.getKey().getSimpleName().toString())) {
            maxSuperClass = getAnnotationValueAsTypeElement(entry.getValue()).asType().toString();
          }
          if (BOUNDBOX_ANNOTATION_PARAMETER_EXTRA_BOUND_FIELDS.equals(
              entry.getKey().getSimpleName().toString())) {
            extraBoundFields = getAnnotationValueAsAnnotationValueList(entry.getValue());
          }
          if (BOUNDBOX_ANNOTATION_PARAMETER_PREFIXES.equals(
              entry.getKey().getSimpleName().toString())) {
            List<? extends AnnotationValue> listPrefixes =
                getAnnotationValueAsAnnotationValueList(entry.getValue());
            prefixes = new String[listPrefixes.size()];
            for (int indexAnnotation = 0;
                indexAnnotation < listPrefixes.size();
                indexAnnotation++) {
              prefixes[indexAnnotation] =
                  getAnnotationValueAsString(listPrefixes.get(indexAnnotation));
            }
          }
          if (BOUNDBOX_ANNOTATION_PARAMETER_PACKAGE.equals(
              entry.getKey().getSimpleName().toString())) {
            boundBoxPackageName = getAnnotationValueAsString(entry.getValue());
          }
        }
      }

      if (boundClass == null) {
        messager.printMessage(Kind.WARNING, "BoundClass is null : " + message, classElement);
        return true;
      }

      if (maxSuperClass != null) {
        boundClassVisitor.setMaxSuperClassName(maxSuperClass);
      }

      if (prefixes != null && prefixes.length != 2 && prefixes.length != 1) {
        error(
            classElement,
            "You must provide 1 or 2 prefixes. The first one for class names, the second one for methods.");
        return true;
      }
      if (prefixes != null && prefixes.length == 1) {
        String[] newPrefixes = new String[] {prefixes[0], prefixes[0].toLowerCase(Locale.US)};
        prefixes = newPrefixes;
      }
      boundboxWriter.setPrefixes(prefixes);

      if (boundBoxPackageName == null) {
        String boundClassFQN = boundClass.getQualifiedName().toString();
        if (boundClassFQN.contains(PACKAGE_SEPARATOR)) {
          boundBoxPackageName = StringUtils.substringBeforeLast(boundClassFQN, PACKAGE_SEPARATOR);
        } else {
          boundBoxPackageName = StringUtils.EMPTY;
        }
      }
      boundClassVisitor.setBoundBoxPackageName(boundBoxPackageName);
      boundboxWriter.setBoundBoxPackageName(boundBoxPackageName);

      ClassInfo classInfo = boundClassVisitor.scan(boundClass);

      injectExtraBoundFields(extraBoundFields, classInfo);

      listClassInfo.add(classInfo);

      // perform some computations on meta model
      inheritanceComputer.computeInheritanceAndHidingFields(classInfo.getListFieldInfos());
      inheritanceComputer.computeInheritanceAndOverridingMethods(
          classInfo.getListMethodInfos(), boundClass, elements);
      inheritanceComputer.computeInheritanceAndHidingInnerClasses(
          classInfo.getListInnerClassInfo());
      inheritanceComputer.computeInheritanceInInnerClasses(classInfo, elements);

      // write meta model to java class file
      Writer sourceWriter = null;
      try {
        String boundBoxClassName =
            boundboxWriter.getNamingGenerator().createBoundBoxName(classInfo);
        String boundBoxClassFQN =
            boundBoxPackageName.isEmpty()
                ? boundBoxClassName
                : boundBoxPackageName + PACKAGE_SEPARATOR + boundBoxClassName;
        JavaFileObject sourceFile = filer.createSourceFile(boundBoxClassFQN, (Element[]) null);
        sourceWriter = sourceFile.openWriter();

        boundboxWriter.writeBoundBox(classInfo, sourceWriter);
      } catch (IOException e) {
        e.printStackTrace();
        error(classElement, e.getMessage());
      } finally {
        if (sourceWriter != null) {
          IOUtils.closeQuietly(sourceWriter);
        }
      }
    }

    return true;
  }