Search in sources :

Example 11 with TypeElement

use of javax.lang.model.element.TypeElement in project hibernate-orm by hibernate.

the class JPAMetaModelEntityProcessor method handleRootElementAnnotationMirrors.

private void handleRootElementAnnotationMirrors(final Element element) {
    List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
    for (AnnotationMirror mirror : annotationMirrors) {
        if (!ElementKind.CLASS.equals(element.getKind())) {
            continue;
        }
        String fqn = ((TypeElement) element).getQualifiedName().toString();
        MetaEntity alreadyExistingMetaEntity = tryGettingExistingEntityFromContext(mirror, fqn);
        if (alreadyExistingMetaEntity != null && alreadyExistingMetaEntity.isMetaComplete()) {
            String msg = "Skipping processing of annotations for " + fqn + " since xml configuration is metadata complete.";
            context.logMessage(Diagnostic.Kind.OTHER, msg);
            continue;
        }
        boolean requiresLazyMemberInitialization = false;
        AnnotationMetaEntity metaEntity;
        if (TypeUtils.containsAnnotation(element, Constants.EMBEDDABLE) || TypeUtils.containsAnnotation(element, Constants.MAPPED_SUPERCLASS)) {
            requiresLazyMemberInitialization = true;
        }
        metaEntity = new AnnotationMetaEntity((TypeElement) element, context, requiresLazyMemberInitialization);
        if (alreadyExistingMetaEntity != null) {
            metaEntity.mergeInMembers(alreadyExistingMetaEntity);
        }
        addMetaEntityToContext(mirror, metaEntity);
    }
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) AnnotationMetaEntity(org.hibernate.jpamodelgen.annotation.AnnotationMetaEntity) MetaEntity(org.hibernate.jpamodelgen.model.MetaEntity) AnnotationMetaEntity(org.hibernate.jpamodelgen.annotation.AnnotationMetaEntity) TypeElement(javax.lang.model.element.TypeElement)

Example 12 with TypeElement

use of javax.lang.model.element.TypeElement in project hibernate-orm by hibernate.

the class JpaDescriptorParser method determineAnnotationAccessTypes.

private void determineAnnotationAccessTypes() {
    for (EntityMappings mappings : entityMappings) {
        String fqcn;
        String packageName = mappings.getPackage();
        for (Entity entity : mappings.getEntity()) {
            String name = entity.getClazz();
            fqcn = StringUtil.determineFullyQualifiedClassName(packageName, name);
            TypeElement element = context.getTypeElementForFullyQualifiedName(fqcn);
            if (element != null) {
                TypeUtils.determineAccessTypeForHierarchy(element, context);
            }
        }
        for (org.hibernate.jpamodelgen.xml.jaxb.MappedSuperclass mappedSuperClass : mappings.getMappedSuperclass()) {
            String name = mappedSuperClass.getClazz();
            fqcn = StringUtil.determineFullyQualifiedClassName(packageName, name);
            TypeElement element = context.getTypeElementForFullyQualifiedName(fqcn);
            if (element != null) {
                TypeUtils.determineAccessTypeForHierarchy(element, context);
            }
        }
    }
}
Also used : Entity(org.hibernate.jpamodelgen.xml.jaxb.Entity) TypeElement(javax.lang.model.element.TypeElement) EntityMappings(org.hibernate.jpamodelgen.xml.jaxb.EntityMappings)

Example 13 with TypeElement

use of javax.lang.model.element.TypeElement in project DeepLinkDispatch by airbnb.

the class DeepLinkProcessor method generateDeepLinkDelegate.

private void generateDeepLinkDelegate(String packageName, List<TypeElement> loaderClasses) throws IOException {
    MethodSpec notifyListenerMethod = MethodSpec.methodBuilder("notifyListener").addModifiers(Modifier.PRIVATE, Modifier.STATIC).returns(void.class).addParameter(ANDROID_CONTEXT, "context").addParameter(boolean.class, "isError").addParameter(ClassName.get("android.net", "Uri"), "uri").addParameter(String.class, "errorMessage").addStatement("$T intent = new Intent()", ANDROID_INTENT).addStatement("intent.setAction($T.ACTION)", DeepLinkHandler.class).addStatement("intent.putExtra($T.EXTRA_URI, uri != null ? uri.toString() : $S)", DeepLinkHandler.class, "").addStatement("intent.putExtra($T.EXTRA_SUCCESSFUL, !isError)", DeepLinkHandler.class).beginControlFlow("if (isError)").addStatement("intent.putExtra($T.EXTRA_ERROR_MESSAGE, errorMessage)", DeepLinkHandler.class).endControlFlow().addStatement("$T.getInstance(context).sendBroadcast(intent)", ClassName.get("android.support.v4.content", "LocalBroadcastManager")).build();
    ClassName deepLinkResult = ClassName.get(DLD_PACKAGE_NAME, "DeepLinkResult");
    MethodSpec createResultAndNotifyMethod = MethodSpec.methodBuilder("createResultAndNotify").addModifiers(Modifier.PRIVATE, Modifier.STATIC).returns(deepLinkResult).addParameter(ANDROID_CONTEXT, "context").addParameter(TypeName.BOOLEAN, "successful", Modifier.FINAL).addParameter(ANDROID_URI, "uri", Modifier.FINAL).addParameter(ClassName.get(String.class), "error", Modifier.FINAL).addStatement("notifyListener(context, !successful, uri, error)").addStatement("return new $T(successful, uri != null ? uri.toString() : null, error)", deepLinkResult).build();
    FieldSpec tag = FieldSpec.builder(String.class, "TAG", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("DeepLinkDelegate.class.getSimpleName()").build();
    FieldSpec loaders = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(List.class), WildcardTypeName.subtypeOf(Parser.class)), "loaders", Modifier.PRIVATE, Modifier.FINAL).build();
    CodeBlock.Builder loadersInitializer = CodeBlock.builder().add("this.loaders = $T.asList(\n", ClassName.get(Arrays.class)).indent();
    int totalElements = loaderClasses.size();
    for (int i = 0; i < totalElements; i++) {
        loadersInitializer.add("$L$L", decapitalize(moduleNameToLoaderName(loaderClasses.get(i))), i < totalElements - 1 ? "," : "");
    }
    MethodSpec constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addParameters(FluentIterable.from(loaderClasses).transform(new Function<TypeElement, ParameterSpec>() {

        @Override
        public ParameterSpec apply(TypeElement typeElement) {
            return ParameterSpec.builder(moduleElementToLoaderClassName(typeElement), decapitalize(moduleNameToLoaderName(typeElement))).build();
        }
    }).toList()).addCode(loadersInitializer.unindent().add(");\n").build()).build();
    MethodSpec supportsUri = MethodSpec.methodBuilder("supportsUri").addModifiers(Modifier.PUBLIC).returns(TypeName.BOOLEAN).addParameter(String.class, "uriString").addStatement("return findEntry(uriString) != null").build();
    MethodSpec findEntry = MethodSpec.methodBuilder("findEntry").addModifiers(Modifier.PRIVATE).returns(CLASS_DLD_ENTRY).addParameter(String.class, "uriString").beginControlFlow("for (Parser loader : loaders)").addStatement("$T entry = loader.parseUri(uriString)", CLASS_DLD_ENTRY).beginControlFlow("if (entry != null)").addStatement("return entry").endControlFlow().endControlFlow().addStatement("return null").build();
    MethodSpec dispatchFromMethod = MethodSpec.methodBuilder("dispatchFrom").addModifiers(Modifier.PUBLIC).returns(deepLinkResult).addParameter(ANDROID_ACTIVITY, "activity").beginControlFlow("if (activity == null)").addStatement("throw new $T($S)", NullPointerException.class, "activity == null").endControlFlow().addStatement("return dispatchFrom(activity, activity.getIntent())").build();
    MethodSpec dispatchFromMethodWithIntent = MethodSpec.methodBuilder("dispatchFrom").addModifiers(Modifier.PUBLIC).returns(deepLinkResult).addParameter(ANDROID_ACTIVITY, "activity").addParameter(ANDROID_INTENT, "sourceIntent").beginControlFlow("if (activity == null)").addStatement("throw new $T($S)", NullPointerException.class, "activity == null").endControlFlow().beginControlFlow("if (sourceIntent == null)").addStatement("throw new $T($S)", NullPointerException.class, "sourceIntent == null").endControlFlow().addStatement("$T uri = sourceIntent.getData()", ANDROID_URI).beginControlFlow("if (uri == null)").addStatement("return createResultAndNotify(activity, false, null, $S)", "No Uri in given activity's intent.").endControlFlow().addStatement("String uriString = uri.toString()").addStatement("$T entry = findEntry(uriString)", CLASS_DLD_ENTRY).beginControlFlow("if (entry != null)").addStatement("$T deepLinkUri = DeepLinkUri.parse(uriString)", CLASS_DLD_URI).addStatement("$T<String, String> parameterMap = entry.getParameters(uriString)", Map.class).beginControlFlow("for (String queryParameter : deepLinkUri.queryParameterNames())").beginControlFlow("for (String queryParameterValue : deepLinkUri.queryParameterValues(queryParameter))").beginControlFlow("if (parameterMap.containsKey(queryParameter))").addStatement("$T.w(TAG, \"Duplicate parameter name in path and query param: \" + queryParameter)", ClassName.get("android.util", "Log")).endControlFlow().addStatement("parameterMap.put(queryParameter, queryParameterValue)").endControlFlow().endControlFlow().addStatement("parameterMap.put($T.URI, uri.toString())", ClassName.get(DLD_PACKAGE_NAME, "DeepLink")).addStatement("$T parameters", ANDROID_BUNDLE).beginControlFlow("if (sourceIntent.getExtras() != null)").addStatement("parameters = new Bundle(sourceIntent.getExtras())").nextControlFlow("else").addStatement("parameters = new Bundle()").endControlFlow().beginControlFlow("for (Map.Entry<String, String> parameterEntry : parameterMap.entrySet())").addStatement("parameters.putString(parameterEntry.getKey(), parameterEntry.getValue())").endControlFlow().beginControlFlow("try").addStatement("Class<?> c = entry.getActivityClass()").addStatement("$T newIntent", ANDROID_INTENT).addStatement("$T taskStackBuilder = null", TASK_STACK_BUILDER).beginControlFlow("if (entry.getType() == DeepLinkEntry.Type.CLASS)").addStatement("newIntent = new Intent(activity, c)").nextControlFlow("else").addStatement("$T method", Method.class).beginControlFlow("try").addStatement("method = c.getMethod(entry.getMethod(), $T.class)", ANDROID_CONTEXT).beginControlFlow("if (method.getReturnType().equals($T.class))", TASK_STACK_BUILDER).addStatement("taskStackBuilder = (TaskStackBuilder) method.invoke(c, activity)").beginControlFlow("if (taskStackBuilder.getIntentCount() == 0)").addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod() + \" intents length == 0\" )").endControlFlow().addStatement("newIntent = taskStackBuilder." + "editIntentAt(taskStackBuilder.getIntentCount()-1)").nextControlFlow("else").addStatement("newIntent = (Intent) method.invoke(c, activity)").endControlFlow().nextControlFlow("catch ($T exception)", NoSuchMethodException.class).addStatement("method = c.getMethod(entry.getMethod(), $T.class, $T.class)", ANDROID_CONTEXT, ANDROID_BUNDLE).beginControlFlow("if (method.getReturnType().equals($T.class))", TASK_STACK_BUILDER).addStatement("taskStackBuilder = " + "(TaskStackBuilder) method.invoke(c, activity, parameters)").beginControlFlow("if (taskStackBuilder.getIntentCount() == 0)").addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod() + \" intents length == 0\" )").endControlFlow().addStatement("newIntent = taskStackBuilder." + "editIntentAt(taskStackBuilder.getIntentCount()-1)").nextControlFlow("else").addStatement("newIntent = (Intent) method.invoke(c, activity, parameters)").endControlFlow().endControlFlow().endControlFlow().beginControlFlow("if (newIntent.getAction() == null)").addStatement("newIntent.setAction(sourceIntent.getAction())").endControlFlow().beginControlFlow("if (newIntent.getData() == null)").addStatement("newIntent.setData(sourceIntent.getData())").endControlFlow().addStatement("newIntent.putExtras(parameters)").addStatement("newIntent.putExtra(DeepLink.IS_DEEP_LINK, true)").addStatement("newIntent.putExtra(DeepLink.REFERRER_URI, uri)").beginControlFlow("if (activity.getCallingActivity() != null)").addStatement("newIntent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT)").endControlFlow().beginControlFlow("if (taskStackBuilder != null)").addStatement("taskStackBuilder.startActivities()").nextControlFlow("else").addStatement("activity.startActivity(newIntent)").endControlFlow().addStatement("return createResultAndNotify(activity, true, uri, null)").nextControlFlow("catch (NoSuchMethodException exception)").addStatement("return createResultAndNotify(activity, false, uri, \"Deep link to " + "non-existent method: \" + entry.getMethod())").nextControlFlow("catch (IllegalAccessException exception)").addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod())").nextControlFlow("catch ($T  exception)", InvocationTargetException.class).addStatement("return createResultAndNotify(activity, false, uri, \"Could not deep " + "link to method: \" + entry.getMethod())").endControlFlow().nextControlFlow("else").addStatement("return createResultAndNotify(activity, false, uri, " + "\"No registered entity to handle deep link: \" + uri.toString())").endControlFlow().build();
    TypeSpec deepLinkDelegate = TypeSpec.classBuilder("DeepLinkDelegate").addModifiers(Modifier.PUBLIC, Modifier.FINAL).addField(tag).addField(loaders).addMethod(constructor).addMethod(findEntry).addMethod(dispatchFromMethod).addMethod(dispatchFromMethodWithIntent).addMethod(createResultAndNotifyMethod).addMethod(notifyListenerMethod).addMethod(supportsUri).build();
    JavaFile.builder(packageName, deepLinkDelegate).build().writeTo(filer);
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) ParameterSpec(com.squareup.javapoet.ParameterSpec) TypeElement(javax.lang.model.element.TypeElement) CodeBlock(com.squareup.javapoet.CodeBlock) Method(java.lang.reflect.Method) FieldSpec(com.squareup.javapoet.FieldSpec) ClassName(com.squareup.javapoet.ClassName) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 14 with TypeElement

use of javax.lang.model.element.TypeElement in project epoxy by airbnb.

the class EpoxyProcessor method generateDefaultMethodImplementations.

/**
   * Generates default implementations of certain model methods if the model is abstract and doesn't
   * implement them.
   */
private Iterable<MethodSpec> generateDefaultMethodImplementations(ClassToGenerateInfo info) {
    List<MethodSpec> methods = new ArrayList<>();
    TypeElement originalClassElement = info.getOriginalClassElement();
    addCreateHolderMethodIfNeeded(originalClassElement, methods);
    addDefaultLayoutMethodIfNeeded(originalClassElement, methods);
    return methods;
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) ArrayList(java.util.ArrayList)

Example 15 with TypeElement

use of javax.lang.model.element.TypeElement in project epoxy by airbnb.

the class EpoxyProcessor method updateClassesForInheritance.

/**
   * Check each model for super classes that also have attributes. For each super class with
   * attributes we add those attributes to the attributes of the generated class, so that a
   * generated class contains all the attributes of its super classes combined.
   * <p>
   * One caveat is that if a sub class is in a different package than its super class we can't
   * include attributes that are package private, otherwise the generated class won't compile.
   */
private void updateClassesForInheritance(Map<TypeElement, ClassToGenerateInfo> helperClassMap) {
    for (Entry<TypeElement, ClassToGenerateInfo> entry : helperClassMap.entrySet()) {
        TypeElement thisClass = entry.getKey();
        Map<TypeElement, ClassToGenerateInfo> otherClasses = new LinkedHashMap<>(helperClassMap);
        otherClasses.remove(thisClass);
        for (Entry<TypeElement, ClassToGenerateInfo> otherEntry : otherClasses.entrySet()) {
            TypeElement otherClass = otherEntry.getKey();
            if (!isSubtype(thisClass, otherClass)) {
                continue;
            }
            Set<AttributeInfo> otherAttributes = otherEntry.getValue().getAttributeInfo();
            if (belongToTheSamePackage(thisClass, otherClass)) {
                entry.getValue().addAttributes(otherAttributes);
            } else {
                for (AttributeInfo attribute : otherAttributes) {
                    if (!attribute.isPackagePrivate()) {
                        entry.getValue().addAttribute(attribute);
                    }
                }
            }
        }
    }
}
Also used : TypeElement(javax.lang.model.element.TypeElement) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

TypeElement (javax.lang.model.element.TypeElement)1564 ExecutableElement (javax.lang.model.element.ExecutableElement)517 Element (javax.lang.model.element.Element)504 TypeMirror (javax.lang.model.type.TypeMirror)421 VariableElement (javax.lang.model.element.VariableElement)333 DeclaredType (javax.lang.model.type.DeclaredType)202 ArrayList (java.util.ArrayList)177 PackageElement (javax.lang.model.element.PackageElement)159 AnnotationMirror (javax.lang.model.element.AnnotationMirror)151 Test (org.junit.Test)136 HashMap (java.util.HashMap)118 HashSet (java.util.HashSet)109 Elements (javax.lang.model.util.Elements)101 Map (java.util.Map)98 IOException (java.io.IOException)97 List (java.util.List)97 ClassName (com.squareup.javapoet.ClassName)88 Test (org.junit.jupiter.api.Test)80 MethodSpec (com.squareup.javapoet.MethodSpec)72 TypeSpec (com.squareup.javapoet.TypeSpec)63