Example usage for com.google.gwt.core.ext.typeinfo TypeOracle parse

List of usage examples for com.google.gwt.core.ext.typeinfo TypeOracle parse

Introduction

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

Prototype


public abstract JType parse(String type) throws TypeOracleException;

Source Link

Document

Parses the string form of a type to produce the corresponding type object.

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;/*from w  w  w.ja v a 2  s  . c om*/
    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.gwtplatform.dispatch.rest.rebind.utils.JPrimitives.java

License:Apache License

public static JClassType convertToBoxed(TypeOracle typeOracle, JPrimitiveType primitive)
        throws UnableToCompleteException {
    JClassType boxedType;/*from w w  w  .j  av a2  s.c o  m*/
    try {
        String boxedSourceName = primitive.getQualifiedBoxedSourceName();
        boxedType = typeOracle.parse(boxedSourceName).isClass();
    } catch (TypeOracleException e) {
        boxedType = null;
    }

    return boxedType;
}

From source file:com.seanchenxi.resteasy.autobean.generator.ThrowableFactoryGenerator.java

License:Apache License

private HashSet<String> getAllThrowableTypes(TypeOracle oracle, TreeLogger logger) {
    HashSet<String> set = new HashSet<String>();
    try {/*from w w w.j a v  a2s  .  c om*/
        JType[] params = new JType[1];
        params[0] = oracle.parse("java.lang.String");
        JClassType[] svcTypes = oracle.getType(RESTService.class.getName()).getSubtypes();
        for (JClassType type : svcTypes) {
            for (JMethod method : type.getMethods()) {
                for (JClassType throwable : method.getThrows()) {
                    if (null != throwable.getConstructor(params))
                        set.add(throwable.getQualifiedSourceName());
                    else
                        logger.log(Type.WARN, throwable.getQualifiedSourceName()
                                + " will be ignored for serialization, it must at least have a constructor with string type message as parameter.");
                }
            }
        }
    } catch (Exception e) {
        logger.log(Type.ERROR, e.getMessage(), e);
    }
    set.addAll(THROWABLES);
    return set;
}

From source file:fr.onevu.gwt.uibinder.attributeparsers.AttributeParsers.java

License:Apache License

public AttributeParsers(TypeOracle types, FieldManager fieldManager, MortalLogger logger) {
    this.logger = logger;
    converter = new FieldReferenceConverter(fieldManager);

    try {//from www. j  a va 2 s. c  om
        BooleanAttributeParser boolParser = new BooleanAttributeParser(converter, types.parse(BOOLEAN), logger);
        addAttributeParser(BOOLEAN, boolParser);
        addAttributeParser(Boolean.class.getCanonicalName(), boolParser);

        IntAttributeParser intParser = new IntAttributeParser(converter, types.parse(INT), logger);
        addAttributeParser(INT, intParser);
        addAttributeParser(Integer.class.getCanonicalName(), intParser);

        DoubleAttributeParser doubleParser = new DoubleAttributeParser(converter, types.parse(DOUBLE), logger);
        addAttributeParser(DOUBLE, doubleParser);
        addAttributeParser(Double.class.getCanonicalName(), doubleParser);

        addAttributeParser("int,int", new IntPairAttributeParser(intParser, logger));

        addAttributeParser(HORIZ_CONSTANT,
                new HorizontalAlignmentConstantParser(converter, types.parse(HORIZ_CONSTANT), logger));
        addAttributeParser(VERT_CONSTANT,
                new VerticalAlignmentConstantParser(converter, types.parse(VERT_CONSTANT), logger));
        addAttributeParser(TEXT_ALIGN_CONSTANT,
                new TextAlignConstantParser(converter, types.parse(TEXT_ALIGN_CONSTANT), logger));

        StringAttributeParser stringParser = new StringAttributeParser(converter, types.parse(STRING));
        addAttributeParser(STRING, stringParser);

        EnumAttributeParser unitParser = new EnumAttributeParser(converter, (JEnumType) types.parse(UNIT),
                logger);
        addAttributeParser(DOUBLE + "," + UNIT, new LengthAttributeParser(doubleParser, unitParser, logger));

        SafeUriAttributeParser uriParser = new SafeUriAttributeParser(stringParser, converter,
                types.parse(SAFE_URI), logger);
        addAttributeParser(SAFE_URI, uriParser);

        safeUriInHtmlParser = new SafeUriAttributeParser(stringParser, converter, types.parse(SAFE_URI),
                types.parse(STRING), logger);
    } catch (TypeOracleException e) {
        throw new RuntimeException(e);
    }
}

From source file:fr.onevu.gwt.uibinder.elementparsers.DateLabelParser.java

License:Apache License

private JType getIntType(TypeOracle oracle) {
    try {//from ww w  .  j a va 2s  . com
        return oracle.parse("int");
    } catch (TypeOracleException e) {
        throw new RuntimeException(e);
    }
}