Example usage for com.google.gwt.core.ext.typeinfo JClassType getFlattenedSupertypeHierarchy

List of usage examples for com.google.gwt.core.ext.typeinfo JClassType getFlattenedSupertypeHierarchy

Introduction

In this page you can find the example usage for com.google.gwt.core.ext.typeinfo JClassType getFlattenedSupertypeHierarchy.

Prototype

Set<? extends JClassType> getFlattenedSupertypeHierarchy();

Source Link

Document

Returns all of the superclasses and superinterfaces for a given type including the type itself.

Usage

From source file:cc.alcina.framework.entity.gwtsynth.ClientReflectionGenerator.java

License:Apache License

public Set<Annotation> getClassAnnotations(JClassType clazz,
        List<Class<? extends Annotation>> annotationClasses, boolean allowMultiple) {
    if (superAnnotationMap.containsKey(clazz, annotationClasses)) {
        return superAnnotationMap.get(clazz, annotationClasses);
    }//from ww  w.j av  a2 s  . co m
    Map<Class, Annotation> uniqueMap = new HashMap<Class, Annotation>();
    Set<? extends JClassType> flattenedSupertypeHierarchy = clazz.getFlattenedSupertypeHierarchy();
    // uhoh-nono
    // List<? extends JClassType> nonGeneric = flattenedSupertypeHierarchy
    // .stream().map(cl -> {
    // if (cl instanceof JParameterizedType) {
    // return ((JParameterizedType) cl).getBaseType();
    // } else {
    // return cl;
    // }
    // }).collect(Collectors.toList());
    Set values = new LinkedHashSet();// order important - lowest ordinal,
                                     // highest priority
    for (JClassType jct : flattenedSupertypeHierarchy) {
        try {
            List<Annotation> visibleAnnotations = getVisibleAnnotations(jct, annotationClasses);
            values.addAll(visibleAnnotations);
            for (Annotation a : visibleAnnotations) {
                if (!uniqueMap.containsKey(a.annotationType())) {
                    uniqueMap.put(a.annotationType(), a);
                }
            }
        } catch (Exception e) {
        }
    }
    if (!allowMultiple) {
        values = uniqueMap.values().stream().collect(Collectors.toSet());
    }
    superAnnotationMap.put(clazz, annotationClasses, values);
    return values;
}

From source file:cc.alcina.framework.entity.gwtsynth.ClientReflectionGenerator.java

License:Apache License

public Set<Annotation> getSuperclassAnnotationsForMethod(JMethod m) {
    if (superMethodAnnotationMap.containsKey(m)) {
        return superMethodAnnotationMap.get(m);
    }//from w w  w  .j  a v  a2 s  .c  o  m
    Map<Class, Annotation> uniqueMap = new HashMap<Class, Annotation>();
    JClassType c = m.getEnclosingType();
    Set<? extends JClassType> flattenedSupertypeHierarchy = c.getFlattenedSupertypeHierarchy();
    for (JClassType jct : flattenedSupertypeHierarchy) {
        try {
            JMethod m2 = jct.getMethod(m.getName(), m.getParameterTypes());
            for (Annotation a : getVisibleAnnotations(m2, visibleAnnotationClasses)) {
                if (!uniqueMap.containsKey(a.annotationType())) {
                    uniqueMap.put(a.annotationType(), a);
                }
            }
        } catch (Exception e) {
        }
    }
    HashSet values = new HashSet(uniqueMap.values());
    superMethodAnnotationMap.put(m, values);
    return values;
}

From source file:com.artemis.gwtref.gen.ReflectionCacheSourceCreator.java

License:Apache License

private String createTypeGenerator(JType t) {
    buffer.setLength(0);/*from w ww  .  j av  a  2s.  co m*/
    String varName = "t";
    if (t instanceof JPrimitiveType)
        varName = "p";
    int id = nextId();
    typeNames2typeIds.put(t.getErasedType().getQualifiedSourceName(), id);
    pb("Type " + varName + " = new Type();");
    pb(varName + ".name = \"" + t.getErasedType().getQualifiedSourceName() + "\";");
    pb(varName + ".id = " + id + ";");
    pb(varName + ".clazz = " + t.getErasedType().getQualifiedSourceName() + ".class;");
    if (t instanceof JClassType) {
        JClassType c = (JClassType) t;
        if (isVisible(c.getSuperclass()))
            pb(varName + ".superClass = " + c.getSuperclass().getErasedType().getQualifiedSourceName()
                    + ".class;");
        if (c.getFlattenedSupertypeHierarchy() != null) {
            pb("Set<Class> " + varName + "Assignables = new HashSet<Class>();");
            for (JType i : c.getFlattenedSupertypeHierarchy()) {
                if (!isVisible(i))
                    continue;
                pb(varName + "Assignables.add(" + i.getErasedType().getQualifiedSourceName() + ".class);");
            }
            pb(varName + ".assignables = " + varName + "Assignables;");
        }
        if (c.isInterface() != null)
            pb(varName + ".isInterface = true;");
        if (c.isEnum() != null)
            pb(varName + ".isEnum = true;");
        if (c.isArray() != null)
            pb(varName + ".isArray = true;");
        if (c.isMemberType())
            pb(varName + ".isMemberClass = true;");
        pb(varName + ".isStatic = " + c.isStatic() + ";");
        pb(varName + ".isAbstract = " + c.isAbstract() + ";");

        if (c.getFields() != null) {
            pb(varName + ".fields = new Field[] {");
            for (JField f : c.getFields()) {
                String enclosingType = getType(c);
                String fieldType = getType(f.getType());
                int setter = nextId();
                int getter = nextId();
                String elementType = getElementTypes(f);
                String annotations = getAnnotations(f.getDeclaredAnnotations());

                pb("new Field(\"" + f.getName() + "\", " + enclosingType + ", " + fieldType + ", " + f.isFinal()
                        + ", " + f.isDefaultAccess() + ", " + f.isPrivate() + ", " + f.isProtected() + ", "
                        + f.isPublic() + ", " + f.isStatic() + ", " + f.isTransient() + ", " + f.isVolatile()
                        + ", " + getter + ", " + setter + ", " + elementType + ", " + annotations + "), ");

                SetterGetterStub stub = new SetterGetterStub();
                stub.name = f.getName();
                stub.enclosingType = enclosingType;
                stub.type = fieldType;
                stub.isStatic = f.isStatic();
                stub.isFinal = f.isFinal();
                if (enclosingType != null && fieldType != null) {
                    stub.getter = getter;
                    stub.setter = setter;
                }
                setterGetterStubs.add(stub);
            }
            pb("};");
        }

        printMethods(c, varName, "Method", c.getMethods());
        if (c.isPublic() && !c.isAbstract() && (c.getEnclosingType() == null || c.isStatic())) {
            printMethods(c, varName, "Constructor", c.getConstructors());
        } else {
            logger.log(Type.INFO, c.getName() + " can't be instantiated. Constructors not generated");
        }

        if (c.isArray() != null) {
            pb(varName + ".componentType = " + getType(c.isArray().getComponentType()) + ";");
        }
        if (c.isEnum() != null) {
            JEnumConstant[] enumConstants = c.isEnum().getEnumConstants();
            if (enumConstants != null) {
                pb(varName + ".enumConstants = new Object[" + enumConstants.length + "];");
                for (int i = 0; i < enumConstants.length; i++) {
                    pb(varName + ".enumConstants[" + i + "] = " + c.getErasedType().getQualifiedSourceName()
                            + "." + enumConstants[i].getName() + ";");
                }
            }
        }

        Annotation[] annotations = c.getDeclaredAnnotations();
        if (annotations != null && annotations.length > 0) {
            pb(varName + ".annotations = " + getAnnotations(annotations) + ";");
        }
    } else if (t.isAnnotation() != null) {
        pb(varName + ".isAnnotation = true;");
    } else {
        pb(varName + ".isPrimitive = true;");
    }

    pb("types.put(\"" + t.getErasedType().getQualifiedSourceName() + "\", " + varName + ");");
    return buffer.toString();
}

From source file:com.badlogic.gwtref.gen.ReflectionCacheSourceCreator.java

License:Apache License

private String createTypeGenerator(JType t) {
    buffer.setLength(0);//from  ww  w  .j av  a  2 s  .c  om
    int id = nextTypeId++;
    typeNames2typeIds.put(t.getErasedType().getQualifiedSourceName(), id);
    JClassType c = t.isClass();

    String name = t.getErasedType().getQualifiedSourceName();
    String superClass = null;
    if (c != null && (isVisible(c.getSuperclass())))
        superClass = c.getSuperclass().getErasedType().getQualifiedSourceName() + ".class";
    String assignables = null;
    String interfaces = null;

    if (c != null && c.getFlattenedSupertypeHierarchy() != null) {
        assignables = "new HashSet<Class>(Arrays.asList(";
        boolean used = false;
        for (JType i : c.getFlattenedSupertypeHierarchy()) {
            if (!isVisible(i) || i.equals(t)
                    || "java.lang.Object".equals(i.getErasedType().getQualifiedSourceName()))
                continue;
            if (used)
                assignables += ", ";
            assignables += i.getErasedType().getQualifiedSourceName() + ".class";
            used = true;
        }
        if (used)
            assignables += "))";
        else
            assignables = null;
    }

    if (c == null) {
        // if it's not a class, it may be an interface instead
        c = t.isInterface();
    }

    if (c != null && c.getImplementedInterfaces() != null) {
        interfaces = "new HashSet<Class>(Arrays.asList(";
        boolean used = false;
        for (JType i : c.getImplementedInterfaces()) {
            if (!isVisible(i) || i.equals(t))
                continue;
            if (used)
                interfaces += ", ";
            interfaces += i.getErasedType().getQualifiedSourceName() + ".class";
            used = true;
        }
        if (used)
            interfaces += "))";
        else
            interfaces = null;
    }

    String varName = "c" + id;
    pb("private static Type " + varName + ";");
    pb("private static Type " + varName + "() {");
    pb("if(" + varName + "!=null) return " + varName + ";");
    pb(varName + " = new Type(\"" + name + "\", " + id + ", " + name + ".class, " + superClass + ", "
            + assignables + ", " + interfaces + ");");

    if (c != null) {
        if (c.isEnum() != null)
            pb(varName + ".isEnum = true;");
        if (c.isArray() != null)
            pb(varName + ".isArray = true;");
        if (c.isMemberType())
            pb(varName + ".isMemberClass = true;");
        if (c.isInterface() != null) {
            pb(varName + ".isInterface = true;");
        } else {
            pb(varName + ".isStatic = " + c.isStatic() + ";");
            pb(varName + ".isAbstract = " + c.isAbstract() + ";");
        }

        if (c.getFields() != null && c.getFields().length > 0) {
            pb(varName + ".fields = new Field[] {");
            for (JField f : c.getFields()) {
                String enclosingType = getType(c);
                String fieldType = getType(f.getType());
                int setterGetter = nextSetterGetterId++;
                String elementType = getElementTypes(f);
                String annotations = getAnnotations(f.getDeclaredAnnotations());

                pb("    new Field(\"" + f.getName() + "\", " + enclosingType + ", " + fieldType + ", "
                        + f.isFinal() + ", " + f.isDefaultAccess() + ", " + f.isPrivate() + ", "
                        + f.isProtected() + ", " + f.isPublic() + ", " + f.isStatic() + ", " + f.isTransient()
                        + ", " + f.isVolatile() + ", " + setterGetter + ", " + setterGetter + ", " + elementType
                        + ", " + annotations + "), ");

                SetterGetterStub stub = new SetterGetterStub();
                stub.name = f.getName();
                stub.enclosingType = enclosingType;
                stub.type = fieldType;
                stub.isStatic = f.isStatic();
                stub.isFinal = f.isFinal();
                if (enclosingType != null && fieldType != null) {
                    stub.getter = setterGetter;
                    stub.setter = setterGetter;
                }
                setterGetterStubs.add(stub);
            }
            pb("};");
        }

        createTypeInvokables(c, varName, "Method", c.getMethods());
        if (c.isPublic() && !c.isAbstract() && (c.getEnclosingType() == null || c.isStatic())) {
            createTypeInvokables(c, varName, "Constructor", c.getConstructors());
        } else {
            logger.log(Type.INFO, c.getName() + " can't be instantiated. Constructors not generated");
        }

        if (c.isArray() != null) {
            pb(varName + ".componentType = " + getType(c.isArray().getComponentType()) + ";");
        }
        if (c.isEnum() != null) {
            JEnumConstant[] enumConstants = c.isEnum().getEnumConstants();
            if (enumConstants != null) {
                pb(varName + ".enumConstants = new Object[" + enumConstants.length + "];");
                for (int i = 0; i < enumConstants.length; i++) {
                    pb(varName + ".enumConstants[" + i + "] = " + c.getErasedType().getQualifiedSourceName()
                            + "." + enumConstants[i].getName() + ";");
                }
            }
        }

        Annotation[] annotations = c.getDeclaredAnnotations();
        if (annotations != null && annotations.length > 0) {
            pb(varName + ".annotations = " + getAnnotations(annotations) + ";");
        }
    } else if (t.isAnnotation() != null) {
        pb(varName + ".isAnnotation = true;");
    } else {
        pb(varName + ".isPrimitive = true;");
    }

    pb("return " + varName + ";");
    pb("}");
    return buffer.toString();
}

From source file:com.google.web.bindery.requestfactory.gwt.rebind.model.RequestFactoryModel.java

License:Apache License

/**
 * Checks type and its supertypes for {@link ExtraTypes} annotations.
 * /*from   w  ww. ja  v  a  2  s .  c o m*/
 * @param type the type to examine
 * @param addModelExtraTypes if {@code true} the contents of the
 *          {@link #extraTypes} field will be added to the returned list.
 */
private List<EntityProxyModel> checkExtraTypes(JClassType type, boolean addModelExtraTypes)
        throws UnableToCompleteException {
    Set<EntityProxyModel> toReturn = new LinkedHashSet<EntityProxyModel>();
    if (addModelExtraTypes && extraTypes != null) {
        toReturn.addAll(extraTypes);
    }
    for (JClassType toExamine : type.getFlattenedSupertypeHierarchy()) {
        ExtraTypes proxyExtraTypes = toExamine.getAnnotation(ExtraTypes.class);
        if (proxyExtraTypes != null) {
            for (Class<? extends BaseProxy> clazz : proxyExtraTypes.value()) {
                JClassType proxy = oracle.findType(clazz.getCanonicalName());
                if (proxy == null) {
                    poison("Unknown class %s in @%s", clazz.getCanonicalName(),
                            ExtraTypes.class.getSimpleName());
                } else {
                    toReturn.add(getEntityProxyType(proxy));
                }
            }
        }
    }
    if (toReturn.isEmpty()) {
        return Collections.emptyList();
    }
    return new ArrayList<EntityProxyModel>(toReturn);
}

From source file:com.google.web.bindery.requestfactory.gwt.rebind.model.RequestFactoryModel.java

License:Apache License

private EntityProxyModel getEntityProxyType(JClassType entityProxyType) throws UnableToCompleteException {
    entityProxyType = ModelUtils.ensureBaseType(entityProxyType);
    EntityProxyModel toReturn = peers.get(entityProxyType);
    if (toReturn == null) {
        EntityProxyModel.Builder inProgress = peerBuilders.get(entityProxyType);
        if (inProgress != null) {
            toReturn = inProgress.peek();
        }//ww  w  . j av  a2 s . c  om
    }
    if (toReturn == null) {
        EntityProxyModel.Builder builder = new EntityProxyModel.Builder();
        peerBuilders.put(entityProxyType, builder);

        // Validate possible super-proxy types first
        for (JClassType supertype : entityProxyType.getFlattenedSupertypeHierarchy()) {
            List<EntityProxyModel> superTypes = new ArrayList<EntityProxyModel>();
            if (supertype != entityProxyType && shouldAttemptProxyValidation(supertype)) {
                superTypes.add(getEntityProxyType(supertype));
            }
            builder.setSuperProxyTypes(superTypes);
        }

        builder.setQualifiedBinaryName(ModelUtils.getQualifiedBaseBinaryName(entityProxyType));
        builder.setQualifiedSourceName(ModelUtils.getQualifiedBaseSourceName(entityProxyType));
        if (entityProxyInterface.isAssignableFrom(entityProxyType)) {
            builder.setType(Type.ENTITY);
        } else if (valueProxyInterface.isAssignableFrom(entityProxyType)) {
            builder.setType(Type.VALUE);
        } else {
            poison("The type %s is not assignable to either %s or %s",
                    entityProxyInterface.getQualifiedSourceName(),
                    valueProxyInterface.getQualifiedSourceName());
            // Cannot continue, since knowing the behavior is crucial
            die(poisonedMessage());
        }

        // Get the server domain object type
        ProxyFor proxyFor = entityProxyType.getAnnotation(ProxyFor.class);
        ProxyForName proxyForName = entityProxyType.getAnnotation(ProxyForName.class);
        JsonRpcProxy jsonRpcProxy = entityProxyType.getAnnotation(JsonRpcProxy.class);
        if (proxyFor == null && proxyForName == null && jsonRpcProxy == null) {
            poison("The %s type does not have a @%s, @%s, or @%s annotation",
                    entityProxyType.getQualifiedSourceName(), ProxyFor.class.getSimpleName(),
                    ProxyForName.class.getSimpleName(), JsonRpcProxy.class.getSimpleName());
        }

        // Look at the methods declared on the EntityProxy
        List<RequestMethod> requestMethods = new ArrayList<RequestMethod>();
        Map<String, JMethod> duplicatePropertyGetters = new HashMap<String, JMethod>();
        for (JMethod method : entityProxyType.getInheritableMethods()) {
            if (method.getEnclosingType().equals(entityProxyInterface)) {
                // Ignore methods on EntityProxy
                continue;
            }
            RequestMethod.Builder methodBuilder = new RequestMethod.Builder();
            methodBuilder.setDeclarationMethod(entityProxyType, method);

            JType transportedType;
            String name = method.getName();
            if (JBeanMethod.GET.matches(method)) {
                transportedType = method.getReturnType();
                String propertyName = JBeanMethod.GET.inferName(method);
                JMethod previouslySeen = duplicatePropertyGetters.get(propertyName);
                if (previouslySeen == null) {
                    duplicatePropertyGetters.put(propertyName, method);
                } else {
                    poison("Duplicate accessors for property %s: %s() and %s()", propertyName,
                            previouslySeen.getName(), method.getName());
                }

            } else if (JBeanMethod.SET.matches(method) || JBeanMethod.SET_BUILDER.matches(method)) {
                transportedType = method.getParameters()[0].getType();

            } else if (name.equals("stableId") && method.getParameters().length == 0) {
                // Ignore any overload of stableId
                continue;
            } else {
                poison("The method %s is neither a getter nor a setter", method.getReadableDeclaration());
                continue;
            }
            validateTransportableType(methodBuilder, transportedType, false);
            RequestMethod requestMethod = methodBuilder.build();
            requestMethods.add(requestMethod);
        }
        builder.setExtraTypes(checkExtraTypes(entityProxyType, false)).setRequestMethods(requestMethods);

        toReturn = builder.build();
        peers.put(entityProxyType, toReturn);
        peerBuilders.remove(entityProxyType);
    }
    return toReturn;
}

From source file:com.gwtent.gen.reflection.GeneratorHelper.java

License:Apache License

/**
 * private interface ClassTypeOfA extends ClassType<ClassA>{
 * <p>/*from  www  .  j  a va2s.  c  o  m*/
 * <p>   }
 * 
 * <p> find a Parameterized class/interface in super classs/interfaces,
 * this class should a sub class of ClassType class and will point out what's the class need generate reflection information
 * 
 * <p> if can NOT found, give a error, user should correct this before final compile
 * @param classType
 * @return
 */
public static JClassType getReflectionClassType(TypeOracle oracle, JClassType classType) {
    JClassType classClassType;
    try {
        classClassType = oracle.getType(ClassType.class.getCanonicalName());
    } catch (NotFoundException e) {
        throw new RuntimeException(
                "Can not found reflection class, forgot include module xml file?" + e.getMessage());
    }

    ReflectionTarget target = classType.getAnnotation(ReflectionTarget.class);
    if (target != null) {
        if (target.value() != null && target.value().length() > 0) {
            try {
                return oracle.getType(target.value());
            } catch (NotFoundException e) {

            }
        }
    }

    for (JClassType supClass : classType.getFlattenedSupertypeHierarchy()) {
        if (supClass.isParameterized() != null && supClass.isAssignableTo(classClassType)) {
            if (supClass.isParameterized().getTypeArgs().length == 1) {
                return supClass.isParameterized().getTypeArgs()[0];
            } else {
                throw new RuntimeException(
                        "ClassType should have only one Parameterized type, please see document of ClassType interface. Current processing type: "
                                + classType.getQualifiedSourceName() + ", Current parameterized type count:"
                                + classType.isParameterized().getTypeArgs().length);
            }
        }
    }

    throw new RuntimeException(
            "ClassType should have at least one Parameterized type or annotated by @ReflectionTarget, please see document of ClassType interface. Current processing type: "
                    + classType.getQualifiedSourceName());
}

From source file:com.gwtmobile.persistence.rebind.GenUtils.java

License:Apache License

public boolean isSubclassOf(JType type, String superClass) {
    JClassType classType = type.isInterface();
    if (classType == null) {
        classType = type.isClass();//w  w w  .j a  v a 2  s.  c  o  m
    }
    if (classType == null) {
        return false;
    }
    Set<? extends JClassType> superTypes = classType.getFlattenedSupertypeHierarchy();
    for (JClassType superType : superTypes) {
        if (superType.getSimpleSourceName().equals(superClass)) {
            return true;
        }
    }
    return false;
}

From source file:com.sencha.gxt.core.rebind.FormatCollector.java

License:sencha.com license

public FormatCollector(GeneratorContext context, TreeLogger l, JClassType toGenerate)
        throws UnableToCompleteException {
    this.logger = l.branch(Type.DEBUG, "Collecting formatters for " + toGenerate.getName());
    this.context = context;

    // Collect factories first
    List<FormatterFactory> foundFactories = new ArrayList<XTemplates.FormatterFactory>();
    for (JClassType type : toGenerate.getFlattenedSupertypeHierarchy()) {
        if (type.isAnnotationPresent(FormatterFactories.class)) {
            foundFactories.addAll(Arrays.asList(type.getAnnotation(FormatterFactories.class).value()));
        }/*w w w.  ja v a  2 s .  co  m*/
    }
    for (FormatterFactory f : foundFactories) {
        if (!f.name().equals("")) {
            registerFactory(f.name(), f.factory(), "getFormat", "", f.acceptsNull());
        } else if (f.methods().length != 0) {
            for (FormatterFactoryMethod method : f.methods()) {
                registerFactory(method.name(), f.factory(), method.method(), method.defaultArgs(),
                        f.acceptsNull());
            }
        } else {
            logger.log(Type.ERROR,
                    "Formatter factory defined, but no way to access it (no name, no methods declared): "
                            + f.factory());
            throw new UnableToCompleteException();
        }
    }
}

From source file:com.sencha.gxt.core.rebind.MethodCollector.java

License:sencha.com license

public MethodCollector(GeneratorContext context, TreeLogger logger, JClassType template) {
    // this.ctx = context;
    this.logger = logger.branch(Type.DEBUG, "Collecting methods in " + template.getName());

    for (JClassType type : template.getFlattenedSupertypeHierarchy()) {
        if (type.isAnnotationPresent(TemplateCondition.class)) {
            addMethod(type.getAnnotation(TemplateCondition.class));
        }/*from   www.j  a  v a 2s .  c o m*/
        if (type.isAnnotationPresent(TemplateConditions.class)) {
            for (TemplateCondition c : type.getAnnotation(TemplateConditions.class).value()) {
                addMethod(c);
            }
        }
    }
}