Ejemplo n.º 1
0
  public boolean needToCastBundleType(TypeMirror type) throws InvalidTypeException {
    if (isPrimitive(type)) {
      return false;
    }

    if (isArrayType(type)) {
      return needToCastArrayType((ArrayType) type);
    }

    if (isArrayListType(type)) {
      return false;
    }

    if (isSparseParcelableArray(type)) {
      return needToCastSparseParcelableArray((DeclaredType) type);
    }

    if (types.isAssignable(type, bundleType)) {
      return !types.isSameType(type, bundleType);
    }

    if (isAggregateType(type)) {
      return needToCastAggregateType(type);
    }

    if (types.isAssignable(type, serializableType)) {
      return !types.isSameType(type, serializableType);
    }

    throw new InvalidTypeException(InvalidTypeException.Container.BUNDLE, type);
  }
Ejemplo n.º 2
0
  public boolean needToCastIntentType(TypeMirror type) throws InvalidTypeException {
    if (isPrimitive(type)) {
      return false;
    }

    if (isArrayType(type)) {
      return needToCastArrayType((ArrayType) type);
    }

    if (isArrayListType(type)) {
      return false;
    }

    if (types.isAssignable(type, bundleType)) {
      return !types.isSameType(type, bundleType);
    }

    if (isAggregateType(type)) {
      return needToCastAggregateType(type);
    }

    if (types.isAssignable(type, serializableType)) {
      return !types.isSameType(type, serializableType);
    }

    throw new InvalidTypeException(InvalidTypeException.Container.INTENT, type);
  }
Ejemplo n.º 3
0
  public String getBundleType(TypeMirror type) throws InvalidTypeException {
    // Primitive
    if (isPrimitive(type)) {
      return getPrimitiveType(type);
    }

    // Array
    if (isArrayType(type)) {
      return getArrayType((ArrayType) type);
    }

    // ArrayList
    if (isArrayListType(type)) {
      return getArrayListType((DeclaredType) type);
    }

    // Sparse ParcelableArray
    if (isSparseParcelableArray(type)) {
      return "SparseParcelableArray";
    }

    // Other types
    if (types.isAssignable(type, bundleType)) {
      return "Bundle";
    }

    if (isAggregateType(type)) {
      return getAggregateType(type);
    }

    if (types.isAssignable(type, serializableType)) {
      return "Serializable";
    }
    throw new InvalidTypeException(InvalidTypeException.Container.BUNDLE, type);
  }
Ejemplo n.º 4
0
  public String getIntentType(TypeMirror type) throws InvalidTypeException {
    // Primitive
    if (isPrimitive(type)) {
      return getPrimitiveType(type);
    }

    // Array
    if (isArrayType(type)) {
      return getArrayType((ArrayType) type);
    }

    // ArrayList
    if (isArrayListType(type)) {
      return getArrayListType((DeclaredType) type);
    }

    if (types.isAssignable(type, bundleType)) {
      return "Bundle";
    }

    if (isAggregateType(type)) {
      return getAggregateType(type);
    }

    if (types.isAssignable(type, serializableType)) {
      return "Serializable";
    }
    throw new InvalidTypeException(InvalidTypeException.Container.INTENT, type);
  }
Ejemplo n.º 5
0
  public TypeFactory(Elements elementUtils, Types typeUtils) {
    this.elementUtils = elementUtils;
    this.typeUtils = typeUtils;

    iterableType =
        typeUtils.erasure(elementUtils.getTypeElement(Iterable.class.getCanonicalName()).asType());
    collectionType =
        typeUtils.erasure(
            elementUtils.getTypeElement(Collection.class.getCanonicalName()).asType());
    mapType = typeUtils.erasure(elementUtils.getTypeElement(Map.class.getCanonicalName()).asType());

    implementationTypes.put(Iterable.class.getName(), getType(ArrayList.class));
    implementationTypes.put(Collection.class.getName(), getType(ArrayList.class));
    implementationTypes.put(List.class.getName(), getType(ArrayList.class));

    implementationTypes.put(Set.class.getName(), getType(HashSet.class));
    implementationTypes.put(SortedSet.class.getName(), getType(TreeSet.class));
    implementationTypes.put(NavigableSet.class.getName(), getType(TreeSet.class));

    implementationTypes.put(Map.class.getName(), getType(HashMap.class));
    implementationTypes.put(SortedMap.class.getName(), getType(TreeMap.class));
    implementationTypes.put(NavigableMap.class.getName(), getType(TreeMap.class));
    implementationTypes.put(ConcurrentMap.class.getName(), getType(ConcurrentHashMap.class));
    implementationTypes.put(
        ConcurrentNavigableMap.class.getName(), getType(ConcurrentSkipListMap.class));
  }
Ejemplo n.º 6
0
  private static DeclaredType findMapTypeDeclaration(
      TypeMirror typeMirror, EnunciateJacksonContext context) {
    if (!(typeMirror instanceof DeclaredType)) {
      return null;
    }

    DeclaredType declaredType = (DeclaredType) typeMirror;
    TypeElement element = (TypeElement) declaredType.asElement();
    String fqn = element.getQualifiedName().toString();
    if (Map.class.getName().equals(fqn)) {
      return declaredType;
    }

    AdapterType adapterType = JacksonUtil.findAdapterType(element, context);
    if (adapterType != null) {
      return findMapTypeDeclaration(adapterType.getAdaptingType(), context);
    }

    DeclaredType mapType = null;
    Types typeUtils = context.getContext().getProcessingEnvironment().getTypeUtils();
    List<? extends TypeMirror> supers = typeUtils.directSupertypes(declaredType);
    for (TypeMirror superInterface : supers) {
      mapType = findMapTypeDeclaration(superInterface, context);
      if (mapType != null) {
        break;
      }
    }

    return mapType;
  }
Ejemplo n.º 7
0
 private boolean isSparseParcelableArray(TypeMirror type) {
   if (types.isAssignable(types.erasure(type), sparseArrayType) && type instanceof DeclaredType) {
     List<? extends TypeMirror> typeArguments = ((DeclaredType) type).getTypeArguments();
     if (typeArguments.size() == 1) {
       return types.isAssignable(typeArguments.get(0), parcelableType);
     }
   }
   return false;
 }
Ejemplo n.º 8
0
 @Test
 public void wildcardMirrorExtendsType() throws Exception {
   Types types = getTypes();
   Elements elements = getElements();
   TypeMirror charSequence = elements.getTypeElement(CharSequence.class.getName()).asType();
   WildcardType wildcard = types.getWildcardType(charSequence, null);
   TypeName type = TypeName.get(wildcard);
   assertThat(type.toString()).isEqualTo("? extends java.lang.CharSequence");
 }
Ejemplo n.º 9
0
 @Test
 public void wildcardMirrorSuperType() throws Exception {
   Types types = getTypes();
   Elements elements = getElements();
   TypeMirror string = elements.getTypeElement(String.class.getName()).asType();
   WildcardType wildcard = types.getWildcardType(null, string);
   TypeName type = TypeName.get(wildcard);
   assertThat(type.toString()).isEqualTo("? super java.lang.String");
 }
Ejemplo n.º 10
0
 private String getAggregateType(TypeMirror type) throws InvalidTypeException {
   if (types.isAssignable(type, stringType)) { // String is subtype of CharSequence should go first
     return "String";
   }
   if (types.isAssignable(type, charSequenceType)) {
     return "CharSequence";
   }
   if (types.isAssignable(type, parcelableType)) {
     return "Parcelable";
   }
   throw new InvalidTypeException(type);
 }
Ejemplo n.º 11
0
 private boolean isPrimitiveWrapper(TypeMirror type) {
   Types types = context.getEnvironment().getTypeUtils();
   for (TypeKind kind : TypeKind.values()) {
     if (!kind.isPrimitive()) {
       continue;
     }
     if (ElementUtils.typeEquals(type, types.boxedClass(types.getPrimitiveType(kind)).asType())) {
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 12
0
  /**
   * Returns the Type that represents the declared Class type of the given type. For primitive
   * types, the boxed class will be used. Examples:
   *
   * <ul>
   *   <li>If type represents {@code java.lang.Integer}, it will return the type that represents
   *       {@code Class<Integer>}.
   *   <li>If type represents {@code int}, it will return the type that represents {@code
   *       Class<Integer>}.
   * </ul>
   *
   * @param type the type to return the declared class type for
   * @return the type representing {@code Class<type>}.
   */
  public Type classTypeOf(Type type) {
    TypeMirror typeToUse;
    if (type.isVoid()) {
      return null;
    } else if (type.isPrimitive()) {
      typeToUse = typeUtils.boxedClass((PrimitiveType) type.getTypeMirror()).asType();
    } else {
      typeToUse = type.getTypeMirror();
    }

    return getType(
        typeUtils.getDeclaredType(elementUtils.getTypeElement("java.lang.Class"), typeToUse));
  }
Ejemplo n.º 13
0
  public ErrorDescription[] check(JPAProblemContext ctx, AttributeWrapper attrib) {
    if (!(attrib.getModelElement() instanceof Basic)) {
      return null;
    }

    TreeUtilities treeUtils = ctx.getCompilationInfo().getTreeUtilities();
    Types types = ctx.getCompilationInfo().getTypes();
    TypeMirror attrType = attrib.getType();

    TypeMirror typeSerializable =
        treeUtils.parseType(
            "java.io.Serializable", // NOI18N
            ctx.getJavaClass());

    TypeMirror typeEnum =
        treeUtils.parseType(
            "java.lang.Enum", // NOI18N
            ctx.getJavaClass());

    TypeMirror typeCollection =
        treeUtils.parseType(
            "java.util.Collection", // NOI18N
            ctx.getJavaClass());

    if (types.isAssignable(attrType, typeSerializable)
        || types.isAssignable(attrType, typeEnum)
        || types.isAssignable(attrType, typeCollection)) {
      return null;
    }

    for (String typeName : fixedBasicTypes) {
      TypeMirror type = treeUtils.parseType(typeName, ctx.getJavaClass());

      if (type != null && types.isSameType(attrType, type)) {
        return null;
      }
    }

    if (Utilities.hasAnnotation(attrib.getJavaElement(), JPAAnnotations.ELEMENT_COLLECTION)) {
      // according to annotation it's not basic  type and need to be verified in appropriate
      // validator
      return null;
    }

    return new ErrorDescription[] {
      Rule.createProblem(
          attrib.getJavaElement(),
          ctx,
          NbBundle.getMessage(ValidBasicType.class, "MSG_ValidBasicType"))
    };
  }
Ejemplo n.º 14
0
 private boolean isArrayListType(TypeMirror type) {
   if (types.isAssignable(types.erasure(type), arrayListType)) {
     List<? extends TypeMirror> typeArguments = ((DeclaredType) type).getTypeArguments();
     if (typeArguments.size() == 1) {
       TypeMirror arg = typeArguments.get(0);
       if (types.isAssignable(arg, integerType)) {
         return true;
       }
       if (isAggregateType(arg)) {
         return true;
       }
     }
   }
   return false;
 }
 @Override
 public boolean canContain(DataModelMirror other) {
   Precondition.checkMustNotBeNull(other, "other"); // $NON-NLS-1$
   if (other instanceof ConcreteDataModelMirror) {
     ConcreteDataModelMirror that = (ConcreteDataModelMirror) other;
     return environment.getTypeUtils().isSameType(this.type, that.type);
   }
   if (other instanceof PartialDataModelMirror) {
     PartialDataModelMirror that = (PartialDataModelMirror) other;
     Types typeUtils = environment.getTypeUtils();
     return typeUtils.isSubtype(this.type, that.type.getUpperBound())
         && typeUtils.isSubtype(that.type.getLowerBound(), this.type);
   }
   return false;
 }
Ejemplo n.º 16
0
 @Override
 @DefinedBy(Api.LANGUAGE_MODEL)
 public Void visitDeclared(DeclaredType t, Types types) {
   t.asElement().getKind(); // ensure class exists
   for (TypeMirror st : types.directSupertypes(t)) visit(st, types);
   return null;
 }
Ejemplo n.º 17
0
 /** Uses both {@link Types#erasure} and string manipulation to strip any generic types. */
 private String doubleErasure(TypeMirror elementType) {
   String name = typeUtils.erasure(elementType).toString();
   int typeParamStart = name.indexOf('<');
   if (typeParamStart != -1) {
     name = name.substring(0, typeParamStart);
   }
   return name;
 }
  private Set<ConstraintCheckError> checkAnnotationValue(
      TypeElement element, AnnotationMirror annotation) {
    Set<ConstraintCheckError> errors = CollectionHelper.newHashSet();
    AnnotationValue value = annotationApiHelper.getAnnotationValue(annotation, "value");
    TypeMirror valueType = (TypeMirror) value.getValue();
    TypeElement valueElement = (TypeElement) typeUtils.asElement(valueType);

    if (valueElement.getKind().isInterface()
        || valueElement.getModifiers().contains(Modifier.ABSTRACT)) {
      errors.add(
          new ConstraintCheckError(
              element,
              annotation,
              "GROUP_SEQUENCE_PROVIDER_ANNOTATION_VALUE_MUST_BE_AN_IMPLEMENTATION_CLASS"));

    } else {
      // the TypeElement hosting the annotation is a concrete implementation of the
      // DefaultGroupSequenceProvider
      // interface. In that case, we need to check that it has a public default constructor.
      if (!hasPublicDefaultConstructor(valueElement)) {
        errors.add(
            new ConstraintCheckError(
                element,
                annotation,
                "GROUP_SEQUENCE_PROVIDER_ANNOTATION_VALUE_CLASS_MUST_HAVE_DEFAULT_CONSTRUCTOR",
                valueType));
      }
    }

    TypeMirror genericProviderType = retrieveGenericProviderType(valueType);
    if (!typeUtils.isSubtype(element.asType(), genericProviderType)) {
      errors.add(
          new ConstraintCheckError(
              element,
              annotation,
              "GROUP_SEQUENCE_PROVIDER_ANNOTATION_VALUE_DEFINED_PROVIDER_CLASS_WITH_WRONG_TYPE",
              genericProviderType,
              element.asType()));
    }

    return errors;
  }
Ejemplo n.º 19
0
 private String getArrayListType(DeclaredType type) throws InvalidTypeException {
   TypeMirror arg = type.getTypeArguments().get(0);
   if (types.isAssignable(arg, integerType)) {
     return "IntegerArrayList";
   }
   try {
     return getAggregateType(arg).concat("ArrayList");
   } catch (InvalidTypeException e) {
     throw new InvalidTypeException(type);
   }
 }
Ejemplo n.º 20
0
  /**
   * Converts any collection type, e.g. {@code List<T>} to {@code Collection<T>} and any map type,
   * e.g. {@code HashMap<K,V>} to {@code Map<K,V>}.
   *
   * @param collectionOrMap any collection or map type
   * @return the type representing {@code Collection<T>} or {@code Map<K,V>}, if the argument type
   *     is a subtype of {@code Collection<T>} or of {@code Map<K,V>} respectively.
   */
  public Type asCollectionOrMap(Type collectionOrMap) {
    List<Type> originalParameters = collectionOrMap.getTypeParameters();
    TypeMirror[] originalParameterMirrors = new TypeMirror[originalParameters.size()];
    int i = 0;
    for (Type param : originalParameters) {
      originalParameterMirrors[i++] = param.getTypeMirror();
    }

    if (collectionOrMap.isCollectionType()
        && !"java.util.Collection".equals(collectionOrMap.getFullyQualifiedName())) {
      return getType(
          typeUtils.getDeclaredType(
              elementUtils.getTypeElement("java.util.Collection"), originalParameterMirrors));
    } else if (collectionOrMap.isMapType()
        && !"java.util.Map".equals(collectionOrMap.getFullyQualifiedName())) {
      return getType(
          typeUtils.getDeclaredType(
              elementUtils.getTypeElement("java.util.Map"), originalParameterMirrors));
    }

    return collectionOrMap;
  }
 /**
  * Check shareable components for serializability.
  *
  * @param round The round environment.
  */
 private void checkShareableComponents(RoundEnvironment round) {
   Set<? extends Element> elts = round.getElementsAnnotatedWith(Shareable.class);
   note("processing %d shareable elements", elts.size());
   TypeMirror serializable = elementUtils.getTypeElement("java.io.Serializable").asType();
   for (Element elt : elts) {
     note("examining %s", elt);
     TypeMirror type = elt.asType();
     if (typeUtils.isAssignable(type, serializable)) {
       note("shareable type %s is serializable", type);
     } else {
       warning(elt, "shareable type %s is not serializable", type);
     }
   }
 }
  public ValidateDescriptor(ModelDescriptor modelDescriptor, Element field) {
    super(modelDescriptor, field);
    this.validateIf = field.getAnnotation(ValidateIf.class);
    this.validateIfValue = field.getAnnotation(ValidateIfValue.class);

    ProcessingEnvironment processingEnv = modelDescriptor.getProcessingEnvironment();
    Types typeUtils = processingEnv.getTypeUtils();
    this.isMethodValidation = getField().getKind().equals(ElementKind.METHOD);

    if (this.isMethodValidation) {
      // Make sure our method validation returns a boolean value
      if (!((ExecutableElement) this.field).getReturnType().getKind().equals(TypeKind.BOOLEAN)) {
        modelDescriptor
            .getMessager()
            .printMessage(
                Diagnostic.Kind.ERROR,
                "Methods annotated with @Validate must return a boolean value!",
                field);
      }

      methodAnnotation = getField().getAnnotation(Validate.class);
      if (this.methodAnnotation == null) {
        modelDescriptor
            .getMessager()
            .printMessage(Diagnostic.Kind.ERROR, "Could not retrieve method validation annotation");
      }
    } else {
      this.isList =
          typeUtils.isAssignable(
              field.asType(),
              typeUtils.getDeclaredType(
                  processingEnv
                      .getElementUtils()
                      .getTypeElement(ListContainer.class.getCanonicalName()),
                  typeUtils.getWildcardType(null, null)));
    }
  }
Ejemplo n.º 23
0
 private TypeMirror getPrimitiveType(Class<?> primitiveType) {
   return primitiveType == byte.class
       ? typeUtils.getPrimitiveType(TypeKind.BYTE)
       : primitiveType == short.class
           ? typeUtils.getPrimitiveType(TypeKind.SHORT)
           : primitiveType == int.class
               ? typeUtils.getPrimitiveType(TypeKind.INT)
               : primitiveType == long.class
                   ? typeUtils.getPrimitiveType(TypeKind.LONG)
                   : primitiveType == float.class
                       ? typeUtils.getPrimitiveType(TypeKind.FLOAT)
                       : primitiveType == double.class
                           ? typeUtils.getPrimitiveType(TypeKind.DOUBLE)
                           : primitiveType == boolean.class
                               ? typeUtils.getPrimitiveType(TypeKind.BOOLEAN)
                               : primitiveType == char.class
                                   ? typeUtils.getPrimitiveType(TypeKind.CHAR)
                                   : typeUtils.getPrimitiveType(TypeKind.VOID);
 }
Ejemplo n.º 24
0
 private boolean needToCastAggregateType(TypeMirror type) throws InvalidTypeException {
   if (types.isAssignable(type, charSequenceType)) {
     return !types.isSameType(type, charSequenceType);
   }
   if (types.isAssignable(type, stringType)) {
     return !types.isSameType(type, stringType);
   }
   if (types.isAssignable(type, parcelableType)) {
     return !types.isSameType(type, parcelableType);
   }
   throw new InvalidTypeException(type);
 }
  private List<MapperReference> initReferencedMappers(
      TypeElement element, MapperConfiguration mapperConfig) {
    List<MapperReference> result = new LinkedList<MapperReference>();
    List<String> variableNames = new LinkedList<String>();

    for (TypeMirror usedMapper : mapperConfig.uses()) {
      DefaultMapperReference mapperReference =
          DefaultMapperReference.getInstance(
              typeFactory.getType(usedMapper),
              MapperPrism.getInstanceOn(typeUtils.asElement(usedMapper)) != null,
              typeFactory,
              variableNames);

      result.add(mapperReference);
      variableNames.add(mapperReference.getVariableName());
    }

    return result;
  }
  /**
   * Formats an ExecutableElement as if it were contained within the container, if the container is
   * present.
   */
  public String format(ExecutableElement method, Optional<DeclaredType> container) {
    StringBuilder builder = new StringBuilder();
    TypeElement type = MoreElements.asType(method.getEnclosingElement());
    ExecutableType executableType = MoreTypes.asExecutable(method.asType());
    if (container.isPresent()) {
      executableType = MoreTypes.asExecutable(types.asMemberOf(container.get(), method));
      type = MoreElements.asType(container.get().asElement());
    }

    // TODO(cgruber): AnnotationMirror formatter.
    List<? extends AnnotationMirror> annotations = method.getAnnotationMirrors();
    if (!annotations.isEmpty()) {
      Iterator<? extends AnnotationMirror> annotationIterator = annotations.iterator();
      for (int i = 0; annotationIterator.hasNext(); i++) {
        if (i > 0) {
          builder.append(' ');
        }
        builder.append(ErrorMessages.format(annotationIterator.next()));
      }
      builder.append(' ');
    }
    builder.append(nameOfType(executableType.getReturnType()));
    builder.append(' ');
    builder.append(type.getQualifiedName());
    builder.append('.');
    builder.append(method.getSimpleName());
    builder.append('(');
    checkState(method.getParameters().size() == executableType.getParameterTypes().size());
    Iterator<? extends VariableElement> parameters = method.getParameters().iterator();
    Iterator<? extends TypeMirror> parameterTypes = executableType.getParameterTypes().iterator();
    for (int i = 0; parameters.hasNext(); i++) {
      if (i > 0) {
        builder.append(", ");
      }
      appendParameter(builder, parameters.next(), parameterTypes.next());
    }
    builder.append(')');
    return builder.toString();
  }
Ejemplo n.º 27
0
  private Type getImplementationType(TypeMirror mirror) {
    if (mirror.getKind() != TypeKind.DECLARED) {
      return null;
    }

    DeclaredType declaredType = (DeclaredType) mirror;

    Type implementationType =
        implementationTypes.get(
            ((TypeElement) declaredType.asElement()).getQualifiedName().toString());

    if (implementationType != null) {
      return new Type(
          typeUtils,
          elementUtils,
          this,
          typeUtils.getDeclaredType(
              implementationType.getTypeElement(),
              declaredType.getTypeArguments().toArray(new TypeMirror[] {})),
          implementationType.getTypeElement(),
          getTypeParameters(mirror, true),
          null,
          null,
          implementationType.getPackageName(),
          implementationType.getName(),
          implementationType.getFullyQualifiedName(),
          implementationType.isInterface(),
          implementationType.isEnumType(),
          implementationType.isIterableType(),
          implementationType.isCollectionType(),
          implementationType.isMapType(),
          isImported(implementationType.getName(), implementationType.getFullyQualifiedName()));
    }

    return null;
  }
Ejemplo n.º 28
0
 /**
  * Get the ExecutableType for given method as part of usedMapper. Possibly parameterized types in
  * method declaration will be evaluated to concrete types then.
  *
  * @param includingType the type on which's scope the method type shall be evaluated
  * @param method the method
  * @return the ExecutableType representing the method as part of usedMapper
  */
 public ExecutableType getMethodType(TypeElement includingType, ExecutableElement method) {
   DeclaredType asType =
       (DeclaredType) replaceTypeElementIfNecessary(elementUtils, includingType).asType();
   TypeMirror asMemberOf = typeUtils.asMemberOf(asType, method);
   return (ExecutableType) asMemberOf;
 }
  private Decorator getDecorator(
      TypeElement element, List<SourceMethod> methods, String implName, String implPackage) {
    DecoratedWithPrism decoratorPrism = DecoratedWithPrism.getInstanceOn(element);

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

    TypeElement decoratorElement = (TypeElement) typeUtils.asElement(decoratorPrism.value());

    if (!typeUtils.isAssignable(decoratorElement.asType(), element.asType())) {
      messager.printMessage(element, decoratorPrism.mirror, Message.DECORATOR_NO_SUBTYPE);
    }

    List<MappingMethod> mappingMethods = new ArrayList<MappingMethod>(methods.size());

    for (SourceMethod mappingMethod : methods) {
      boolean implementationRequired = true;
      for (ExecutableElement method :
          ElementFilter.methodsIn(decoratorElement.getEnclosedElements())) {
        if (elementUtils.overrides(method, mappingMethod.getExecutable(), decoratorElement)) {
          implementationRequired = false;
          break;
        }
      }
      Type declaringMapper = mappingMethod.getDeclaringMapper();
      if (implementationRequired && !(mappingMethod.isDefault() || mappingMethod.isStatic())) {
        if ((declaringMapper == null) || declaringMapper.equals(typeFactory.getType(element))) {
          mappingMethods.add(new DelegatingMethod(mappingMethod));
        }
      }
    }

    boolean hasDelegateConstructor = false;
    boolean hasDefaultConstructor = false;
    for (ExecutableElement constructor :
        ElementFilter.constructorsIn(decoratorElement.getEnclosedElements())) {
      if (constructor.getParameters().isEmpty()) {
        hasDefaultConstructor = true;
      } else if (constructor.getParameters().size() == 1) {
        if (typeUtils.isAssignable(element.asType(), first(constructor.getParameters()).asType())) {
          hasDelegateConstructor = true;
        }
      }
    }

    if (!hasDelegateConstructor && !hasDefaultConstructor) {
      messager.printMessage(element, decoratorPrism.mirror, Message.DECORATOR_CONSTRUCTOR);
    }

    Decorator decorator =
        new Decorator.Builder()
            .elementUtils(elementUtils)
            .typeFactory(typeFactory)
            .mapperElement(element)
            .decoratorPrism(decoratorPrism)
            .methods(mappingMethods)
            .hasDelegateConstructor(hasDelegateConstructor)
            .options(options)
            .versionInformation(versionInformation)
            .implName(implName)
            .implPackage(implPackage)
            .extraImports(getExtraImports(element))
            .build();

    return decorator;
  }
Ejemplo n.º 30
0
  public Type getType(TypeMirror mirror) {
    if (mirror.getKind() == TypeKind.ERROR) {
      throw new AnnotationProcessingException("Encountered erroneous type " + mirror);
    }

    Type implementationType = getImplementationType(mirror);

    boolean isIterableType = typeUtils.isSubtype(mirror, iterableType);
    boolean isCollectionType = typeUtils.isSubtype(mirror, collectionType);
    boolean isMapType = typeUtils.isSubtype(mirror, mapType);

    boolean isEnumType;
    boolean isInterface;
    String name;
    String packageName;
    String qualifiedName;
    TypeElement typeElement;
    Type componentType;

    if (mirror.getKind() == TypeKind.DECLARED) {
      DeclaredType declaredType = (DeclaredType) mirror;

      isEnumType = declaredType.asElement().getKind() == ElementKind.ENUM;
      isInterface = declaredType.asElement().getKind() == ElementKind.INTERFACE;
      name = declaredType.asElement().getSimpleName().toString();

      typeElement = (TypeElement) declaredType.asElement();

      if (typeElement != null) {
        packageName = elementUtils.getPackageOf(typeElement).getQualifiedName().toString();
        qualifiedName = typeElement.getQualifiedName().toString();
      } else {
        packageName = null;
        qualifiedName = name;
      }

      componentType = null;
    } else if (mirror.getKind() == TypeKind.ARRAY) {
      TypeMirror componentTypeMirror = getComponentType(mirror);

      if (componentTypeMirror.getKind() == TypeKind.DECLARED) {
        DeclaredType declaredType = (DeclaredType) componentTypeMirror;
        TypeElement componentTypeElement = (TypeElement) declaredType.asElement();

        name = componentTypeElement.getSimpleName().toString() + "[]";
        packageName = elementUtils.getPackageOf(componentTypeElement).getQualifiedName().toString();
        qualifiedName = componentTypeElement.getQualifiedName().toString() + "[]";
      } else {
        name = mirror.toString();
        packageName = null;
        qualifiedName = name;
      }

      isEnumType = false;
      isInterface = false;
      typeElement = null;
      componentType = getType(componentTypeMirror);
    } else {
      isEnumType = false;
      isInterface = false;
      name = mirror.toString();
      packageName = null;
      qualifiedName = name;
      typeElement = null;
      componentType = null;
    }

    return new Type(
        typeUtils,
        elementUtils,
        this,
        mirror,
        typeElement,
        getTypeParameters(mirror, false),
        implementationType,
        componentType,
        packageName,
        name,
        qualifiedName,
        isInterface,
        isEnumType,
        isIterableType,
        isCollectionType,
        isMapType,
        isImported(name, qualifiedName));
  }