Example usage for com.google.gwt.core.ext.typeinfo JParameterizedType getRawType

List of usage examples for com.google.gwt.core.ext.typeinfo JParameterizedType getRawType

Introduction

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

Prototype

JClassType getRawType();

Source Link

Usage

From source file:com.github.ludorival.dao.gwt.rebind.EntityManagerGenerator.java

License:Apache License

private BeanMetadata create(GeneratorContext context, TreeLogger logger, String packageName, JClassType type,
        Class<?> classAdapter, IsEntity anno) throws TypeOracleException {
    String beanName = anno == null || anno.aliasName().isEmpty() ? type.getName() : anno.aliasName();
    Source implementation = null;
    JClassType implType = type;/*www .  j ava 2  s  .co m*/
    TypeOracle typeOracle = context.getTypeOracle();
    if (type.isInterface() != null) {
        implType = null;
        JClassType[] types = type.getSubtypes();
        log(logger, Type.DEBUG, "Get all sub types of %s : %s", type, Arrays.toString(types));
        if (types != null && types.length > 0) {
            for (JClassType jClassType : types) {
                if (isInstantiable(jClassType, logger)) {
                    implType = jClassType;
                    implementation = new Source(implType.getPackage().getName(), implType.getName());
                    break;
                }

            }

        }
        if (implType == null) {
            log(logger, Type.ERROR, "The type %s has not valid subtypes " + "%s !", type,
                    Arrays.toString(types));
            return null;
        }
    }
    if (!implType.isDefaultInstantiable())
        return null;
    String prefix = classAdapter.getSimpleName().replace("Adapter", "");
    boolean isEntity = anno != null;
    String className = prefix + beanName;
    if (parseOnlyInterface && implType != type)
        className += "Light";
    PrintWriter writer = context.tryCreate(logger, packageName, className);
    if (writer == null) {
        return new BeanMetadata(type, className, implementation, isEntity);
    }

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, className);
    logger.log(Type.DEBUG, "Create Entity " + factory.getCreatedClassName());

    factory.setSuperclass(classAdapter.getSimpleName() + "<" + type.getName() + ">");
    factory.addImport(RuntimeException.class.getName());
    factory.addImport(classAdapter.getName());
    factory.addImport(type.getQualifiedSourceName());
    if (isEntity) {
        factory.addImport(ArrayList.class.getName());
        factory.addImport(Collection.class.getName());
    }
    factory.addImport(HashMap.class.getName());
    factory.addImport(Property.class.getName());
    factory.addImport(Property.class.getName() + ".Kind");
    factory.addImport(Index.class.getName());
    factory.addImport(implType.getQualifiedSourceName());

    factory.addImport("javax.annotation.Generated");
    factory.addAnnotationDeclaration("@Generated(" + "value=\"" + AdapterEntity.class.getName() + "\", "
            + "date=\"" + new Date() + "\", " + "comments=\"Generated by DAO-GWT project.\")");

    SourceWriter sourceWriter = factory.createSourceWriter(context, writer);

    sourceWriter.println("//AUTO GENERATED FILE BY DAO-GWT " + getClass().getName() + ". DO NOT EDIT!\n");

    sourceWriter.println("private static HashMap<String,Property<%s,?>> PROPERTIES = "
            + "new HashMap<String,Property<%s,?>>();", type.getName(), type.getName());
    if (isEntity) {
        factory.addImport(ArrayList.class.getName());
        factory.addImport(Index.class.getName());
        sourceWriter.println("private static Collection<Index> INDEXES = " + "new ArrayList<Index>();");

    }
    sourceWriter.println("static {");
    sourceWriter.indent();
    JClassType interfaz = type != implType ? type : null;
    JMethod[] methods = parseOnlyInterface ? type.getInheritableMethods() : implType.getInheritableMethods();
    for (JMethod method : methods) {
        String name = method.getName();
        //Check if the method has a IsIgnored annotation before to continue
        IsIgnored ignored = method.getAnnotation(IsIgnored.class);
        if (ignored != null) {

            log(logger, Type.DEBUG, EXPLICITELY_IGNORED, name, implType);
            continue;
        }
        boolean startsWithGet = name.startsWith("get");
        boolean startsWithIs = name.startsWith("is");
        if (!startsWithGet && !startsWithIs) {
            log(logger, Type.DEBUG, IGNORE_METHOD, name, implType);
            continue;
        }

        //check no parameters
        if (method.getParameterTypes().length != 0) {
            log(logger, Type.WARN, NO_PARAMETER_GETTER, name, implType);
            continue;
        }
        //check return type
        JType returnType = method.getReturnType();
        if (returnType == null || returnType.getQualifiedSourceName().equals(Void.class.getName())
                || returnType.getQualifiedSourceName().equals(void.class.getName())) {
            log(logger, Type.DEBUG, VOID_GETTER, name + "" + returnType, implType);
            continue;
        }
        //change the format of the name getXyy ==> xyy
        String getterSetter = name;
        if (startsWithGet)
            getterSetter = name.substring(3);
        else if (startsWithIs)
            getterSetter = name.substring(2);
        name = getterSetter.substring(0, 1).toLowerCase() + getterSetter.substring(1);
        // check if the getter has an annotation
        IsIndexable indexable = method.getAnnotation(IsIndexable.class);
        boolean isIndexable = indexable != null;
        if (isIndexable && !isEntity)
            log(logger, Type.WARN, ONLY_ENTITY_FOR_INDEX, name, implType, IsEntity.class);

        isIndexable = isIndexable && isEntity;//only entity can defined indexable element

        String indexName = isIndexable ? indexable.aliasName() : "";
        String[] compositeIndexes = isIndexable ? indexable.compoundWith() : new String[0];
        Kind kind = null;
        JType typeOfCollection = null;
        String typeOfCollectionString = "null";

        if (!isPrimitive(returnType)) {

            //load complex properties except Key
            if (returnType.isEnum() != null) {
                kind = Kind.ENUM;
            } else {
                boolean isPrimitive = false;
                boolean isEnum = false;
                JParameterizedType pType = returnType.isParameterized();
                JType collection = typeOracle.parse(Collection.class.getName());

                if (pType != null && pType.getRawType().isAssignableTo(collection.isClassOrInterface())) {
                    JClassType[] types = pType.getTypeArgs();
                    kind = Kind.COLLECTION_OF_PRIMITIVES;
                    if (types.length > 1) {
                        log(logger, Type.DEBUG, CANNOT_PROCESS_PARAMETERIZED_TYPE, returnType, implType);
                        continue;
                    }
                    typeOfCollection = types[0];
                    typeOfCollectionString = typeOfCollection.getQualifiedSourceName() + ".class";
                    log(logger, Type.DEBUG, "The type of the collection is %s", typeOfCollectionString);
                    isPrimitive = isPrimitive(typeOfCollection);
                    isEnum = typeOfCollection.isEnum() != null;
                }
                if (!isPrimitive) {

                    if (isEnum && kind != null) {
                        kind = Kind.COLLECTION_OF_ENUMS;
                    } else {
                        JClassType classType = typeOfCollection != null ? typeOfCollection.isClassOrInterface()
                                : returnType.isClassOrInterface();
                        boolean isBean = isBean(classType);
                        if (isBean) {
                            log(logger, Type.DEBUG, "The property %s is well a type %s", name, classType);
                            if (kind == null)
                                kind = Kind.BEAN;
                            else
                                kind = Kind.COLLECTION_OF_BEANS;
                        } else {
                            log(logger, Type.DEBUG, "The property %s has not a bean type %s", name, classType);
                            continue;
                        }
                    }

                }
            }

        }
        assert kind != null;

        boolean isMemo = method.getAnnotation(IsMemo.class) != null;
        String oldName = "null";
        OldName oldNameAnno = method.getAnnotation(OldName.class);
        if (oldNameAnno != null)
            oldName = "\"" + oldNameAnno.value() + "\"";
        //create a property
        if (kind == Kind.BEAN || kind == Kind.COLLECTION_OF_BEANS)
            factory.addImport(returnType.getQualifiedSourceName());
        String valueType = "";
        JClassType classType = returnType.isClassOrInterface();
        JPrimitiveType primitiveType = returnType.isPrimitive();
        if (classType != null)
            valueType = classType.getQualifiedSourceName();
        else if (primitiveType != null) {
            valueType = primitiveType.getQualifiedBoxedSourceName();
        }

        sourceWriter.println("{ //Property %s", name);
        sourceWriter.indent();
        sourceWriter.print("Index index =");
        if (isIndexable) {
            if (indexName.isEmpty())
                indexName = name;
            sourceWriter.println("new Index(\"%s\",\"%s\",new String[]{%s});", indexName, name,
                    String.join(",", compositeIndexes));
        } else
            sourceWriter.println("null;");
        boolean useKeyAsString = anno != null ? (name.equals(anno.keyName()) ? anno.useKeyAsString() : false)
                : false;

        KeyOf keyOf = method.getAnnotation(KeyOf.class);
        if (keyOf != null) {
            IsEntity isEntity2 = keyOf.entity().getAnnotation(IsEntity.class);
            if (isEntity2 == null) {
                log(logger, Type.ERROR, AdapterEntityManager.KEY_OF_NO_ENTITY, method, keyOf, keyOf.entity(),
                        IsEntity.class);
                continue;
            }
            useKeyAsString = isEntity2.useKeyAsString();
        }
        boolean isHidden = isHidden(method, interfaz);
        sourceWriter.println(
                "Property<%s,%s> property = new Property<%s,%s>(\"%s\",%s,%s.class,%s,%s,%s,%s,index,%s){",
                type.getName(), valueType, type.getName(), valueType, name, oldName,
                returnType.getQualifiedSourceName(), typeOfCollectionString,
                kind != null ? "Kind." + kind.name() : "null", useKeyAsString + "", isMemo + "", isHidden + "");
        sourceWriter.indent();
        sourceWriter.println("@Override");
        sourceWriter.println("public %s get(%s instance){", valueType, type.getName());
        sourceWriter.indent();

        sourceWriter.println("return ((%s)instance).%s();", implType.getName(),
                startsWithGet ? "get" + getterSetter : "is" + getterSetter);
        sourceWriter.outdent();
        sourceWriter.println("}");

        sourceWriter.println("@Override");
        sourceWriter.println("public void set(%s instance, %s value){", type.getName(), valueType);
        sourceWriter.indent();

        if (getSetter(implType, getterSetter, returnType) != null)
            sourceWriter.println("((%s)instance).%s(value);", implType.getName(), "set" + getterSetter);
        else {
            logger.log(Type.WARN, " Not found setter for " + getterSetter);
            sourceWriter.println("throw new RuntimeException(\"No such setter " + getterSetter + " \");");
        }

        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.outdent();
        sourceWriter.println("};");
        sourceWriter.println("PROPERTIES.put(\"%s\",property);", name);
        if (!oldName.equals("null")) {
            sourceWriter.println("PROPERTIES.put(%s,property);", oldName);
        }
        if (isIndexable)
            sourceWriter.println("INDEXES.add(index);");
        sourceWriter.outdent();
        sourceWriter.println("}");

        log(logger, Type.DEBUG, SUCCESSFUL_ADD_PROPERTY, name + ":" + valueType, implType);

    }
    sourceWriter.outdent();
    sourceWriter.println("}");

    sourceWriter.println();
    sourceWriter.println("public %s(){", className);
    sourceWriter.indent();

    /*
     * boolean asyncReady,
       boolean autoGeneratedFlag,
       String keyName,
       boolean useKeyAsString,
       Class<T> type,Class<? extends T> implType,
       Map<String, Property<T,?>> mapAllProperties, Collection<Index> indexes) {
    super(type,implType,mapAllProperties);
     */
    if (isEntity)
        sourceWriter
                .println(String.format("super(\"%s\",%s,%s,\"%s\",%s,%s.class,%s.class,PROPERTIES,INDEXES);",
                        anno.aliasName().isEmpty() ? type.getName() : anno.aliasName(), anno.asyncReady(),
                        anno.autoGeneratedKey(), anno.keyName(), anno.useKeyAsString(), type.getName(),
                        implType.getName()));
    else {
        sourceWriter.println(
                String.format("super(%s.class,%s.class,PROPERTIES);", type.getName(), implType.getName()));

    }
    sourceWriter.outdent();
    sourceWriter.println("}");

    sourceWriter.println();
    sourceWriter.println("@Override");
    sourceWriter.println("public %s newInstance(){", type.getName());
    sourceWriter.indent();
    sourceWriter.println("return new %s();", implType.getName());
    sourceWriter.outdent();
    sourceWriter.println("}");

    sourceWriter.outdent();
    sourceWriter.println("}");
    context.commit(logger, writer);

    return new BeanMetadata(type, className, implementation, isEntity);
}

From source file:com.totsp.gwittir.rebind.beans.IntrospectorGenerator.java

License:Open Source License

private JType resolveType(final JType type) {
    JType ret = type;//w w  w. j  a  v a  2s .c  o  m
    JParameterizedType pt = type.isParameterized();

    if (pt != null) {
        ret = pt.getRawType();
    }

    JTypeParameter tp = ret.isTypeParameter();

    if (tp != null) {
        ret = tp.getBaseType();
    }

    return ret;
}

From source file:com.totsp.gwt.freezedry.rebind.SerializableTypeOracleBuilder.java

License:Apache License

/**
 * Checks that a type which qualifies as either automatically serializable or
 * manually serializable actually is.// w  w w  . jav a  2s.  c om
 */
private void checkType(TreeLogger logger, JType type, boolean checkSubtypes) {
    if (type == null || type.isPrimitive() != null) {
        return;
    }

    logger = logger.branch(TreeLogger.DEBUG, type.getParameterizedQualifiedSourceName(), null);

    MetaTypeInfo mti = getMetaTypeInfo(type);
    TypeState state = mti.getState();

    if (state == SerializableTypeOracleBuilder.CHECK_FAILED) {
        logReasonsForUnserializability(logger, type);
        return;
    } else if (state == SerializableTypeOracleBuilder.CHECK_IN_PROGRESS) {
        logger.branch(TreeLogger.DEBUG,
                "'" + type.getParameterizedQualifiedSourceName() + "' is being analyzed; skipping", null);
        return;
    } else if (state == SerializableTypeOracleBuilder.CHECK_SUCCEEDED) {
        if (!mti.needToRecheck(checkSubtypes, inManualSerializationContext())) {
            logger.branch(TreeLogger.DEBUG, "Type has already been analyzed", null);
            return;
        }
    }

    mti.setState(SerializableTypeOracleBuilder.CHECK_IN_PROGRESS);

    if (type.isParameterized() != null) {
        JParameterizedType parameterized = type.isParameterized();
        checkType(logger.branch(TreeLogger.DEBUG, "Analyzing raw type", null), parameterized.getRawType(),
                true);

        checkTypes(logger.branch(TreeLogger.DEBUG, "Analyzing type args", null), parameterized.getTypeArgs());
    } else if (type.isArray() != null) {
        checkArray(logger, type.isArray());
    } else if (type.isClassOrInterface() != null) {
        checkClassOrInterface(logger, type.isClassOrInterface(), checkSubtypes);
    }

    if (mti.getState() != SerializableTypeOracleBuilder.CHECK_FAILED) {
        mti.setState(SerializableTypeOracleBuilder.CHECK_SUCCEEDED);
    }

    mti.setCheckedSubtypes(checkSubtypes);
    mti.setCheckedInManualContext(inManualSerializationContext());
}

From source file:com.totsp.gwt.freezedry.rebind.SerializableTypeOracleImpl.java

License:Apache License

public String getSerializedTypeName(JType type) {
    JPrimitiveType primitiveType = type.isPrimitive();
    if (primitiveType != null) {
        return primitiveType.getJNISignature();
    }/*from  w ww. j  ava  2s  .c o m*/

    JArrayType arrayType = type.isArray();
    if (arrayType != null) {
        JType component = arrayType.getComponentType();
        if (component.isClassOrInterface() != null) {
            return "[L" + getSerializedTypeName(arrayType.getComponentType()) + ";";
        } else {
            return "[" + getSerializedTypeName(arrayType.getComponentType());
        }
    }

    JParameterizedType parameterizedType = type.isParameterized();
    if (parameterizedType != null) {
        return getSerializedTypeName(parameterizedType.getRawType());
    }

    JClassType classType = type.isClassOrInterface();
    assert (classType != null);

    JClassType enclosingType = classType.getEnclosingType();
    if (enclosingType != null) {
        return getSerializedTypeName(enclosingType) + "$" + classType.getSimpleSourceName();
    }

    return classType.getQualifiedSourceName();
}

From source file:com.totsp.gwt.freezedry.rebind.SerializableTypeOracleImpl.java

License:Apache License

private void generateSerializationSignature(JType type, CRC32 crc) {
    JParameterizedType parameterizedType = type.isParameterized();
    if (parameterizedType != null) {
        generateSerializationSignature(parameterizedType.getRawType(), crc);

        return;//  www.j av a2  s.co m
    }

    String serializedTypeName = getSerializedTypeName(type);
    crc.update(serializedTypeName.getBytes());

    if (excludeImplementationFromSerializationSignature(type)) {
        return;
    }

    JClassType customSerializer = hasCustomFieldSerializer(type);
    if (customSerializer != null) {
        generateSerializationSignature(customSerializer, crc);
    } else if (type.isArray() != null) {
        JArrayType isArray = type.isArray();
        generateSerializationSignature(isArray.getComponentType(), crc);
    } else if (type.isClassOrInterface() != null) {
        JClassType isClassOrInterface = type.isClassOrInterface();
        JField[] fields = getSerializableFields(isClassOrInterface);
        for (int i = 0; i < fields.length; ++i) {
            JField field = fields[i];
            assert (field != null);

            crc.update(field.getName().getBytes());
            crc.update(getSerializedTypeName(field.getType()).getBytes());
        }

        JClassType superClass = isClassOrInterface.getSuperclass();
        if (superClass != null) {
            generateSerializationSignature(superClass, crc);
        }
    }
}

From source file:com.totsp.gwt.freezedry.rebind.Shared.java

License:Apache License

/**
 * Gets the suffix needed to make a call for a particular type. For example,
 * the <code>int</code> class needs methods named "readInt" and "writeInt".
 * //ww w.  j  av  a2  s .c o  m
 * @param type the type in question
 * @return the suffix of the method to call
 */
static String getCallSuffix(JType type) {
    JParameterizedType isParameterized = type.isParameterized();
    if (isParameterized != null) {
        return getCallSuffix(isParameterized.getRawType());
    } else if (type.isPrimitive() != null) {
        if (type == JPrimitiveType.BOOLEAN) {
            return "Boolean";
        } else if (type == JPrimitiveType.BYTE) {
            return "Byte";
        } else if (type == JPrimitiveType.CHAR) {
            return "Char";
        } else if (type == JPrimitiveType.DOUBLE) {
            return "Double";
        } else if (type == JPrimitiveType.FLOAT) {
            return "Float";
        } else if (type == JPrimitiveType.INT) {
            return "Int";
        } else if (type == JPrimitiveType.LONG) {
            return "Long";
        } else if (type == JPrimitiveType.SHORT) {
            return "Short";
        } else {
            return null;
        }
    } else if (type.getQualifiedSourceName().equals("java.lang.String")) {
        return "String";
    } else {
        return "Object";
    }
}

From source file:fr.onevu.gwt.uibinder.rebind.model.OwnerClass.java

License:Apache License

/**
 * Scans the owner class to find all methods annotated with @UiFactory, and
 * puts them in {@link #uiFactories}./*from www . jav  a2  s .  c  om*/
 * 
 * @param ownerType
 *          the type of the owner class
 * @throws UnableToCompleteException
 */
private void findUiFactories(JClassType ownerType) throws UnableToCompleteException {
    JMethod[] methods = ownerType.getMethods();
    for (JMethod method : methods) {
        if (method.isAnnotationPresent(UiFactory.class)) {
            JClassType factoryType = method.getReturnType().isClassOrInterface();

            if (factoryType == null) {
                logger.die("Factory return type is not a class in method " + method.getName());
            }

            JParameterizedType paramType = factoryType.isParameterized();
            if (paramType != null) {
                factoryType = paramType.getRawType();
            }

            if (uiFactories.containsKey(factoryType)) {
                logger.die("Duplicate factory in class " + method.getEnclosingType().getName() + " for type "
                        + factoryType.getName());
            }

            uiFactories.put(factoryType, method);
        }
    }

    // Recurse to superclass
    JClassType superclass = ownerType.getSuperclass();
    if (superclass != null) {
        findUiFactories(superclass);
    }
}

From source file:fr.onevu.gwt.uibinder.rebind.UiBinderWriter.java

License:Apache License

public boolean isElementAssignableTo(XMLElement elem, JClassType possibleSupertype)
        throws UnableToCompleteException {
    /*//from w  ww . j  a v  a2s  .co m
     * Things like <W extends IsWidget & IsPlaid>
     */
    JTypeParameter typeParameter = possibleSupertype.isTypeParameter();
    if (typeParameter != null) {
        JClassType[] bounds = typeParameter.getBounds();
        for (JClassType bound : bounds) {
            if (!isElementAssignableTo(elem, bound)) {
                return false;
            }
        }
        return true;
    }

    /*
     * Binder fields are always declared raw, so we're cheating if the user is
     * playing with parameterized types. We're happy enough if the raw types
     * match, and rely on them to make sure the specific types really do work.
     */
    JParameterizedType parameterized = possibleSupertype.isParameterized();
    if (parameterized != null) {
        return isElementAssignableTo(elem, parameterized.getRawType());
    }

    JClassType fieldtype = findFieldType(elem);
    if (fieldtype == null) {
        return false;
    }
    return fieldtype.isAssignableTo(possibleSupertype);
}

From source file:fr.putnami.pwt.core.model.rebind.ModelCreator.java

License:Open Source License

private void addImport(JType type) {
    JParameterizedType parametrizedType = type.isParameterized();
    if (parametrizedType != null) {
        this.imports.add(parametrizedType.getRawType());
        this.imports.addAll(Lists.newArrayList(parametrizedType.getTypeArgs()));
    } else {/*from  w w w .j  av  a  2 s . c  o m*/
        this.imports.add(type);
    }
}