Java Code Examples for javax.lang.model.element.TypeElement#getAnnotation()

The following examples show how to use javax.lang.model.element.TypeElement#getAnnotation() . 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: EmbeddableMetaFactory.java    From doma with Apache License 2.0 6 votes vote down vote up
void validateFieldAnnotation(VariableElement fieldElement, EmbeddableMeta embeddableMeta) {
  TypeElement foundAnnotationTypeElement = null;
  for (AnnotationMirror annotation : fieldElement.getAnnotationMirrors()) {
    DeclaredType declaredType = annotation.getAnnotationType();
    TypeElement typeElement = ctx.getMoreTypes().toTypeElement(declaredType);
    if (typeElement.getAnnotation(EntityField.class) != null) {
      if (foundAnnotationTypeElement != null) {
        throw new AptException(
            Message.DOMA4288,
            fieldElement,
            new Object[] {
              foundAnnotationTypeElement.getQualifiedName(), typeElement.getQualifiedName()
            });
      }
      foundAnnotationTypeElement = typeElement;
    }
  }
}
 
Example 2
Source File: AboutBoxProcessor.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected boolean handleProcess(Set<? extends TypeElement> set, RoundEnvironment env) throws LayerGenerationException {
    Elements elements = processingEnv.getElementUtils();
    for (Element element : env.getElementsAnnotatedWith(AboutBox.class)) {
        TypeElement clazz = (TypeElement) element;
        AboutBox aboutBox = clazz.getAnnotation(AboutBox.class);
        String teName = elements.getBinaryName(clazz).toString();
        File file = layer(element)
                .file("AboutBox/" + teName.replace('.', '-') + ".instance")
                .intvalue("position", aboutBox.position())
                .bundlevalue("displayName", aboutBox.displayName());
        if (!aboutBox.iconPath().isEmpty()) {
            file.bundlevalue("iconPath", aboutBox.iconPath());
        }
        file.write();
    }
    return true;
}
 
Example 3
Source File: RouterProcessor.java    From Module2Module with Apache License 2.0 6 votes vote down vote up
private void processInstaller(Set<? extends Element> mainAppElement) throws IOException {
    TypeElement typeElement = (TypeElement) mainAppElement.iterator().next();
    JavaFileObject javaFileObject = mFiler.createSourceFile(Config.ROUTER_MANAGER, typeElement);
    PrintWriter writer = new PrintWriter(javaFileObject.openWriter());

    writer.println("package " + Config.PACKAGE_NAME + ";");
    writer.println("public class " + Config.ROUTER_MANAGER + " {");
    writer.println("public static void " + Config.ROUTER_MANAGER_METHOD + "() {");

    Components componentsAnnotation = typeElement.getAnnotation(Components.class);
    String[] components = componentsAnnotation.value();
    for (String item : components) {
        writer.println(Config.FILE_PREFIX + item + ".router();");
    }

    writer.println("}");
    writer.println("}");

    writer.flush();
    writer.close();
}
 
Example 4
Source File: ImplementsPlugin.java    From squidb with Apache License 2.0 5 votes vote down vote up
private void parseInterfaces() {
    TypeElement modelSpecElement = modelSpec.getModelSpecElement();
    if (modelSpecElement.getAnnotation(Implements.class) != null) {
        List<DeclaredTypeName> typeNames = utils.getTypeNamesFromAnnotationValue(
                utils.getAnnotationValue(modelSpecElement, Implements.class, "interfaceClasses"));
        if (!AptUtils.isEmpty(typeNames)) {
            interfaces.addAll(typeNames);
        }

        AnnotationValue value = utils
                .getAnnotationValue(modelSpecElement, Implements.class, "interfaceDefinitions");
        List<AnnotationMirror> interfaceSpecs = utils.getValuesFromAnnotationValue(value,
                AnnotationMirror.class);

        for (AnnotationMirror spec : interfaceSpecs) {
            AnnotationValue interfaceClassValue = utils.getAnnotationValueFromMirror(spec, "interfaceClass");
            List<DeclaredTypeName> interfaceClassList = utils.getTypeNamesFromAnnotationValue(interfaceClassValue);
            if (!AptUtils.isEmpty(interfaceClassList)) {
                DeclaredTypeName interfaceClass = interfaceClassList.get(0);

                AnnotationValue interfaceTypeArgsValue = utils
                        .getAnnotationValueFromMirror(spec, "interfaceTypeArgs");
                List<DeclaredTypeName> typeArgs = utils.getTypeNamesFromAnnotationValue(interfaceTypeArgsValue);
                if (AptUtils.isEmpty(typeArgs)) {
                    List<String> typeArgNames = utils.getValuesFromAnnotationValue(
                            utils.getAnnotationValueFromMirror(spec, "interfaceTypeArgNames"), String.class);
                    for (String typeArgName : typeArgNames) {
                        typeArgs.add(new DeclaredTypeName(typeArgName));
                    }
                }
                interfaceClass.setTypeArgs(typeArgs);
                interfaces.add(interfaceClass);
            }
        }
    }
}
 
Example 5
Source File: WebServiceVisitor.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private boolean isStateful(TypeElement classElement) {
    try {
        // We don't want dependency on rt-ha module as its not integrated in JDK
        return classElement.getAnnotation((Class<? extends Annotation>) Class.forName("com.sun.xml.internal.ws.developer.Stateful")) != null;
    } catch (ClassNotFoundException e) {
        //ignore
    }
    return false;
}
 
Example 6
Source File: WebServiceVisitor.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
protected void preProcessWebService(WebService webService, TypeElement element) {
    processedMethods = new HashSet<String>();
    seiContext = context.getSeiContext(element);
    String targetNamespace = null;
    if (webService != null)
        targetNamespace = webService.targetNamespace();
    PackageElement packageElement = builder.getProcessingEnvironment().getElementUtils().getPackageOf(element);
    if (targetNamespace == null || targetNamespace.length() == 0) {
        String packageName = packageElement.getQualifiedName().toString();
        if (packageName == null || packageName.length() == 0) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_NO_PACKAGE_CLASS_MUST_HAVE_TARGETNAMESPACE(
                    element.getQualifiedName()), element);
        }
        targetNamespace = RuntimeModeler.getNamespace(packageName);
    }
    seiContext.setNamespaceUri(targetNamespace);
    if (serviceImplName == null)
        serviceImplName = seiContext.getSeiImplName();
    if (serviceImplName != null) {
        seiContext.setSeiImplName(serviceImplName);
        context.addSeiContext(serviceImplName, seiContext);
    }
    portName = ClassNameInfo.getName(element.getSimpleName().toString().replace('$', '_'));
    packageName = packageElement.getQualifiedName();
    portName = webService != null && webService.name() != null && webService.name().length() > 0 ?
            webService.name() : portName;
    serviceName = ClassNameInfo.getName(element.getQualifiedName().toString()) + WebServiceConstants.SERVICE.getValue();
    serviceName = webService != null && webService.serviceName() != null && webService.serviceName().length() > 0 ?
            webService.serviceName() : serviceName;
    wsdlNamespace = seiContext.getNamespaceUri();
    typeNamespace = wsdlNamespace;

    SOAPBinding soapBinding = element.getAnnotation(SOAPBinding.class);
    if (soapBinding != null) {
        pushedSoapBinding = pushSoapBinding(soapBinding, element, element);
    } else if (element.equals(typeElement)) {
        pushedSoapBinding = pushSoapBinding(new MySoapBinding(), element, element);
    }
}
 
Example 7
Source File: RetroFacebookProcessor.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
private boolean ancestorIsRetroFacebook(TypeElement type) {
  while (true) {
    TypeMirror parentMirror = type.getSuperclass();
    if (parentMirror.getKind() == TypeKind.NONE) {
      return false;
    }
    Types typeUtils = processingEnv.getTypeUtils();
    TypeElement parentElement = (TypeElement) typeUtils.asElement(parentMirror);
    if (parentElement.getAnnotation(RetroFacebook.class) != null) {
      return true;
    }
    type = parentElement;
  }
}
 
Example 8
Source File: DataBeanModel.java    From PowerfulRecyclerViewAdapter with Apache License 2.0 5 votes vote down vote up
@Override
public BeanInfo visitType(TypeElement element, Void aVoid) {
    //check element type
    if (!VALIDATED_CLASS_NAME.equals(getQualifiedName(element)))
        checkElementType(element, VALIDATED_CLASS_NAME);
    TypeMirror typeMirror = null;
    BeanInfo beanInfo = new BeanInfo();
    //get annotated Element info.
    String annotatedElementPackage = getPackageName(element);
    beanInfo.holderName = getSimpleName(element);
    beanInfo.holderPackage = annotatedElementPackage;
    //get annotation info
    try {
        DataBean dataBean = element.getAnnotation(DataBean.class);
        beanInfo.dataBeanName = dataBean.beanName();
        beanInfo.dataBeanPackage = annotatedElementPackage + ".databean";
        beanInfo.layoutId = dataBean.layout();
        //Get type of Data,may throw exception
        dataBean.data();
    } catch (MirroredTypeException mte) {
        typeMirror = mte.getTypeMirror();
    }
    if (typeMirror != null) {
        if (typeMirror.getKind() == TypeKind.DECLARED) {
            DeclaredType declaredType = (DeclaredType) typeMirror;
            TypeElement dataBeanElement = (TypeElement) declaredType.asElement();
            beanInfo.dataPackage = getPackageName(dataBeanElement);
            beanInfo.dataName = getSimpleName(dataBeanElement);
        }
    }
    //log
    logger.log(Diagnostic.Kind.NOTE,
            beanInfo.toString());
    return beanInfo;
}
 
Example 9
Source File: WebServiceVisitor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected void checkForInvalidSeiAnnotation(TypeElement element, Class annotationClass) {
    Object annotation = element.getAnnotation(annotationClass);
    if (annotation != null) {
        builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_SEI_ANNOTATION(
                annotationClass.getName(), element.getQualifiedName()), element);
    }
}
 
Example 10
Source File: InlineAnnotationReaderImpl.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public boolean hasClassAnnotation(TypeElement clazz, Class<? extends Annotation> annotationType) {
    return clazz.getAnnotation(annotationType)!=null;
}
 
Example 11
Source File: OperatorProcessor.java    From java with Apache License 2.0 4 votes vote down vote up
private void collectOpMethods(
    Multimap<String, MethodSpec> groupedMethods, TypeElement opClass, TypeElement annotation) {
  boolean opClassDeprecated = opClass.getAnnotation(Deprecated.class) != null;
  AnnotationMirror operatorAnnot = getAnnotationMirror(opClass, annotation.getQualifiedName());
  if (operatorAnnot == null) {
    throw new IllegalArgumentException(
        "Annotation "
            + annotation.getSimpleName()
            + " not present on element "
            + opClass.getSimpleName());
  }
  String opGroup = getAnnotationElementValueAsString("group", operatorAnnot);
  String opName = getAnnotationElementValueAsString("name", operatorAnnot);
  if (Strings.isNullOrEmpty(opName)) {
    opName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, ClassName.get(opClass).simpleName());
  }
  // Build an endpoint for each method annotated with @Endpoint, which takes in parameter a scope
  // and, optionally, a list of arguments
  for (ExecutableElement opMethod : ElementFilter.methodsIn(opClass.getEnclosedElements())) {
    AnnotationMirror endpointAnnot =
        getAnnotationMirror(opMethod, elements.getName(T_ENDPOINT.toString()));
    if (endpointAnnot != null) {
      if (!opMethod.getModifiers().containsAll(Arrays.asList(Modifier.STATIC, Modifier.PUBLIC))) {
        throw new IllegalArgumentException(
            "Endpoint " + opMethod + " of class " + opClass + " must be static and public");
      }
      if (opMethod.getParameters().isEmpty() ||
          !((TypeElement)types.asElement(opMethod.getParameters().get(0).asType())).getQualifiedName()
              .equals(elements.getName(T_SCOPE.toString()))) {
        throw new IllegalArgumentException(
            "Endpoint " + opMethod + " of class " + opClass + " must take an instance of " + T_SCOPE
                + " as its first parameter");
      }
      String endpointGroup = getAnnotationElementValueAsString("group", endpointAnnot);
      if (endpointGroup.isEmpty()) {
        endpointGroup = opGroup;
      }
      String endpointName = getAnnotationElementValueAsString("name", endpointAnnot);
      if (endpointName.isEmpty()) {
        endpointName = opName;
      }
      boolean describeByClass =
          getAnnotationElementValueAsBoolean("describeByClass", endpointAnnot, false);
      boolean deprecated = opMethod.getAnnotation(Deprecated.class) != null || opClassDeprecated;
      MethodSpec method = buildOpMethod(endpointName, opClass, opMethod, describeByClass, deprecated);
      groupedMethods.put(endpointGroup, method);
    }
  }
}
 
Example 12
Source File: M2MEntity.java    From kripton with Apache License 2.0 4 votes vote down vote up
/**
 * Works with @BindDaoMany2Many and @BindDao to extract entity name.
 * @param schema 
 *
 * @param daoElement the dao element
 * @return the m 2 M entity
 */
public static M2MEntity extractEntityManagedByDAO(TypeElement daoElement) {
	ClassName entity1 = null;
	ClassName entity2 = null;
	String prefixId = null;
	String tableName = null;
	String entityName = null;
	PackageElement pkg = null;
	String packageName = null;
	boolean needToCreate = true;
	boolean generatedMethods=true;
	boolean immutable=true;
	
	
	if (daoElement.getAnnotation(BindDaoMany2Many.class) != null) {
		entity1 = TypeUtility.className(AnnotationUtility.extractAsClassName(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.ENTITY_1));
		entity2 = TypeUtility.className(AnnotationUtility.extractAsClassName(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.ENTITY_2));
		prefixId = AnnotationUtility.extractAsString(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.ID_NAME);
		tableName = AnnotationUtility.extractAsString(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.TABLE_NAME);
		tableName = AnnotationUtility.extractAsString(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.TABLE_NAME);
		immutable = AnnotationUtility.extractAsBoolean(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.IMMUTABLE);
		
		generatedMethods=AnnotationUtility.extractAsBoolean(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.METHODS);
		
		entityName = entity1.simpleName() + entity2.simpleName();
		pkg = BaseProcessor.elementUtils.getPackageOf(daoElement);
		packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();
	}

	if (daoElement.getAnnotation(BindDao.class) != null) {
		// we have @BindDao
		String derived = AnnotationUtility.extractAsClassName(daoElement, BindDao.class, AnnotationAttributeType.VALUE);
		ClassName clazz = TypeUtility.className(derived);

		packageName = clazz.packageName();
		entityName = clazz.simpleName();

		String tableTemp = AnnotationUtility.extractAsClassName(daoElement, BindDao.class, AnnotationAttributeType.TABLE_NAME);
		if (StringUtils.hasText(tableTemp)) {
			tableName = tableTemp;
		}

		needToCreate = false;
	}

	M2MEntity entity = new M2MEntity(daoElement, packageName, entityName, TypeUtility.className(daoElement.asType().toString()), entity1, entity2, prefixId, tableName, needToCreate, generatedMethods, immutable);

	return entity;
}
 
Example 13
Source File: WebServiceWrapperGenerator.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private boolean generateExceptionBean(TypeElement thrownDecl, String beanPackage) {
    if (!builder.isServiceException(thrownDecl.asType()))
        return false;

    String exceptionName = ClassNameInfo.getName(thrownDecl.getQualifiedName().toString());
    if (processedExceptions.contains(exceptionName))
        return false;
    processedExceptions.add(exceptionName);
    WebFault webFault = thrownDecl.getAnnotation(WebFault.class);
    String className = beanPackage+ exceptionName + BEAN.getValue();

    Collection<MemberInfo> members = ap_generator.collectExceptionBeanMembers(thrownDecl);
    boolean isWSDLException = isWSDLException(members, thrownDecl);
    String namespace = typeNamespace;
    String name = exceptionName;
    FaultInfo faultInfo;
    if (isWSDLException) {
        TypeMirror beanType =  getFaultInfoMember(members).getParamType();
        faultInfo = new FaultInfo(TypeMonikerFactory.getTypeMoniker(beanType), true);
        namespace = webFault.targetNamespace().length()>0 ?
                           webFault.targetNamespace() : namespace;
        name = webFault.name().length()>0 ?
                      webFault.name() : name;
        faultInfo.setElementName(new QName(namespace, name));
        seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
        return false;
    }
    if (webFault != null) {
        namespace = webFault.targetNamespace().length()>0 ?
                    webFault.targetNamespace() : namespace;
        name = webFault.name().length()>0 ?
               webFault.name() : name;
        className = webFault.faultBean().length()>0 ?
                    webFault.faultBean() : className;

    }
    JDefinedClass cls = getCMClass(className, CLASS);
    faultInfo = new FaultInfo(className, false);

    if (duplicateName(className)) {
        builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_EXCEPTION_BEAN_NAME_NOT_UNIQUE(
                typeElement.getQualifiedName(), thrownDecl.getQualifiedName()));
    }

    boolean canOverWriteBean = builder.canOverWriteClass(className);
    if (!canOverWriteBean) {
        builder.log("Class " + className + " exists. Not overwriting.");
        seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
        return false;
    }
    if (seiContext.getExceptionBeanName(thrownDecl.getQualifiedName()) != null)
        return false;

    //write class comment - JAXWS warning
    JDocComment comment = cls.javadoc();
    for (String doc : GeneratorBase.getJAXWSClassComment(ToolVersion.VERSION.MAJOR_VERSION)) {
        comment.add(doc);
    }

    // XmlElement Declarations
    writeXmlElementDeclaration(cls, name, namespace);

    // XmlType Declaration
    //members = sortMembers(members);
    XmlType xmlType = thrownDecl.getAnnotation(XmlType.class);
    String xmlTypeName = (xmlType != null && !xmlType.name().equals("##default")) ? xmlType.name() : exceptionName;
    String xmlTypeNamespace = (xmlType != null && !xmlType.namespace().equals("##default")) ? xmlType.namespace() : typeNamespace;
    writeXmlTypeDeclaration(cls, xmlTypeName, xmlTypeNamespace, members);

    writeMembers(cls, members);

    seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
    return true;
}
 
Example 14
Source File: JsonAnnotationProcessor.java    From ig-json-parser with MIT License 4 votes vote down vote up
/**
 * This processes a single class that is annotated with {@link JsonType}. It verifies that the
 * class is public and creates an {@link ProcessorClassData} for it.
 */
private void processClassAnnotation(Element element) {
  boolean abstractClass = false;
  TypeElement typeElement = (TypeElement) element;

  // The annotation should be validated for an interface, but no code should be generated.
  JsonType annotation = element.getAnnotation(JsonType.class);
  if (element.getKind() == INTERFACE) {
    return;
  }

  boolean isKotlin = false;
  try {
    Class<? extends Annotation> metaDataClass =
        Class.forName("kotlin.Metadata").asSubclass(Annotation.class);
    isKotlin = element.getAnnotation(metaDataClass) != null;
  } catch (ClassNotFoundException e) {
    // not kotlin
  }

  // Verify containing class visibility is not private.
  if (element.getModifiers().contains(PRIVATE)) {
    error(
        element,
        "@%s %s may not be applied to private classes. (%s.%s)",
        JsonType.class.getSimpleName(),
        typeElement.getQualifiedName(),
        element.getSimpleName());
    return;
  }
  if (element.getModifiers().contains(ABSTRACT)) {
    abstractClass = true;
  }

  JsonParserClassData injector = mState.mClassElementToInjectorMap.get(typeElement);
  if (injector == null) {

    String parentGeneratedClassName = null;

    if (!mOmitSomeMethodBodies) {
      // Superclass info is only needed if we're generating method bodies.
      TypeMirror superclass = typeElement.getSuperclass();
      // walk up the superclass hierarchy until we find another class we know about.
      while (superclass.getKind() != TypeKind.NONE) {
        TypeElement superclassElement = (TypeElement) mTypes.asElement(superclass);

        if (superclassElement.getAnnotation(JsonType.class) != null) {
          String superclassPackageName = mTypeUtils.getPackageName(mElements, superclassElement);
          parentGeneratedClassName =
              superclassPackageName
                  + "."
                  + mTypeUtils.getPrefixForGeneratedClass(
                      superclassElement, superclassPackageName)
                  + JsonAnnotationProcessorConstants.HELPER_CLASS_SUFFIX;

          break;
        }

        superclass = superclassElement.getSuperclass();
      }
    }

    boolean generateSerializer =
        annotation.generateSerializer() == JsonType.TriState.DEFAULT
            ? mGenerateSerializers
            : annotation.generateSerializer() == JsonType.TriState.YES;

    String packageName = mTypeUtils.getPackageName(mElements, typeElement);
    injector =
        new JsonParserClassData(
            packageName,
            typeElement.getQualifiedName().toString(),
            mTypeUtils.getClassName(typeElement, packageName),
            mTypeUtils.getPrefixForGeneratedClass(typeElement, packageName)
                + JsonAnnotationProcessorConstants.HELPER_CLASS_SUFFIX,
            new ProcessorClassData.AnnotationRecordFactory<String, TypeData>() {

              @Override
              public TypeData createAnnotationRecord(String key) {
                return new TypeData();
              }
            },
            abstractClass,
            generateSerializer,
            mOmitSomeMethodBodies,
            parentGeneratedClassName,
            annotation,
            isKotlin);
    mState.mClassElementToInjectorMap.put(typeElement, injector);
  }
}
 
Example 15
Source File: WebServiceWrapperGenerator.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
protected boolean isWSDLException(Collection<MemberInfo> members, TypeElement thrownDecl) {
    WebFault webFault = thrownDecl.getAnnotation(WebFault.class);
    return webFault != null && members.size() == 2 && getFaultInfoMember(members) != null;
}
 
Example 16
Source File: JsonAnnotationProcessor.java    From ig-json-parser with MIT License 4 votes vote down vote up
/**
 * This processes a single field annotated with {@link JsonField}. It locates the enclosing class
 * and then gathers data on the declared type of the field.
 */
private void processFieldAnnotation(Element element) {
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

  // Verify common generated code restrictions.
  if (!isFieldAnnotationValid(JsonField.class, element)) {
    return;
  }

  TypeMirror type = element.asType();

  JsonParserClassData injector = mState.mClassElementToInjectorMap.get(enclosingElement);

  TypeData data = injector.getOrCreateRecord(element.getSimpleName().toString());

  JsonField annotation = element.getAnnotation(JsonField.class);

  data.setFieldName(annotation.fieldName());
  data.setAlternateFieldNames(annotation.alternateFieldNames());
  data.setMapping(annotation.mapping());
  data.setValueExtractFormatter(VALUE_EXTRACT.forString(annotation.valueExtractFormatter()));
  data.setAssignmentFormatter(FIELD_ASSIGNMENT.forString(annotation.fieldAssignmentFormatter()));
  data.setSerializeCodeFormatter(
      FIELD_CODE_SERIALIZATION.forString(annotation.serializeCodeFormatter()));
  TypeUtils.CollectionType collectionType = mTypeUtils.getCollectionType(type);
  data.setCollectionType(collectionType);

  if (collectionType != TypeUtils.CollectionType.NOT_A_COLLECTION) {
    // inspect the inner type.
    type = mTypeUtils.getCollectionParameterizedType(type);
  }

  data.setParseType(mTypeUtils.getParseType(type, JsonType.class));

  boolean skipEnumValidationCheck = setJsonAdapterIfApplicable(type, injector, data, annotation);

  if (data.getParseType() == TypeUtils.ParseType.PARSABLE_OBJECT) {
    TypeMirror erasedType = mTypes.erasure(type);
    DeclaredType declaredType = (DeclaredType) erasedType;
    TypeElement typeElement = (TypeElement) declaredType.asElement();

    String packageName = mTypeUtils.getPackageName(mElements, typeElement);

    data.setPackageName(packageName);
    data.setParsableType(mTypeUtils.getClassName(typeElement, packageName));
    data.setParsableTypeParserClass(
        mTypeUtils.getPrefixForGeneratedClass(typeElement, packageName));

    JsonType typeAnnotation = typeElement.getAnnotation(JsonType.class);
    // Use the parsable object's value extract formatter if existing one is empty
    data.setValueExtractFormatter(
        data.getValueExtractFormatter()
            .orIfEmpty(VALUE_EXTRACT.forString(typeAnnotation.valueExtractFormatter())));

    CodeFormatter.Factory serializeCodeType =
        typeElement.getKind() == INTERFACE
            ? CodeFormatter.CLASS_CODE_SERIALIZATION
            : CodeFormatter.INTERFACE_CODE_SERIALIZATION;
    data.setSerializeCodeFormatter(
        data.getSerializeCodeFormatter()
            .orIfEmpty(serializeCodeType.forString(typeAnnotation.serializeCodeFormatter())));

    data.setIsInterface(typeElement.getKind() == INTERFACE);
    data.setFormatterImports(typeAnnotation.typeFormatterImports());
  } else if (data.getParseType() == TypeUtils.ParseType.ENUM_OBJECT) {
    // verify that we have value extract and serializer formatters.
    if (!skipEnumValidationCheck
        && (StringUtil.isNullOrEmpty(annotation.valueExtractFormatter())
            || (injector.generateSerializer()
                && StringUtil.isNullOrEmpty(annotation.serializeCodeFormatter())))) {
      error(
          element,
          "%s: Annotate the enum with @%s (see annotation docs for details). "
              + "If that is undesirable you must have a value extract formatter, "
              + "and a serialize code formatter if serialization generation is enabled",
          enclosingElement,
          JsonAdapter.class.getSimpleName());
    }
    data.setEnumType(type.toString());
  }
}
 
Example 17
Source File: SerializerBuilder.java    From domino-jackson with Apache License 2.0 4 votes vote down vote up
private JsonInclude getJsonInclude(DeclaredType enclosingType) {
    TypeElement enclosingElement = ((TypeElement) enclosingType.asElement());
    return enclosingElement.getAnnotation(JsonInclude.class);
}
 
Example 18
Source File: InlineAnnotationReaderImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public boolean hasClassAnnotation(TypeElement clazz, Class<? extends Annotation> annotationType) {
    return clazz.getAnnotation(annotationType)!=null;
}
 
Example 19
Source File: WebServiceWrapperGenerator.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
protected boolean isWSDLException(Collection<MemberInfo> members, TypeElement thrownDecl) {
    WebFault webFault = thrownDecl.getAnnotation(WebFault.class);
    return webFault != null && members.size() == 2 && getFaultInfoMember(members) != null;
}
 
Example 20
Source File: WebServiceWrapperGenerator.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
protected boolean isWSDLException(Collection<MemberInfo> members, TypeElement thrownDecl) {
    WebFault webFault = thrownDecl.getAnnotation(WebFault.class);
    return webFault != null && members.size() == 2 && getFaultInfoMember(members) != null;
}