Example usage for com.google.gwt.core.ext.typeinfo JPrimitiveType getQualifiedBoxedSourceName

List of usage examples for com.google.gwt.core.ext.typeinfo JPrimitiveType getQualifiedBoxedSourceName

Introduction

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

Prototype

public String getQualifiedBoxedSourceName() 

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;/*from   www . ja  v a 2 s  .  c o  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.google.appinventor.rebind.ExtendedServiceProxyGenerator.java

License:Open Source License

/**
 * Generate the implementation of a single method.
 *
 * @param out where to print the method to
 * @param method the method//w  ww . jav  a 2 s  . com
 * @param typeName type name of the containing proxy class
 */
private void printMethod(PrintWriter out, JMethod method, String typeName) {
    // Build parameter lists
    int i = 0;
    StringBuilder actualParamsBuilder = new StringBuilder();
    StringBuilder formalParamsBuilder = new StringBuilder();
    for (JParameter param : method.getParameters()) {
        if (i != 0) {
            actualParamsBuilder.append(", ");
            formalParamsBuilder.append(", ");
        }

        String paramType = param.getType().getParameterizedQualifiedSourceName();
        String paramName = "p" + i++;
        actualParamsBuilder.append(paramName);
        formalParamsBuilder.append(paramType + " " + paramName);
    }
    String actualParams = actualParamsBuilder.toString();
    String formalParams = formalParamsBuilder.toString();

    // Information about the return type
    JType returnType = method.getReturnType();
    boolean hasReturnValue = !returnType.getSimpleSourceName().equals("void");

    JPrimitiveType primitiveReturnType = returnType.isPrimitive();
    String resultType = primitiveReturnType != null ? primitiveReturnType.getQualifiedBoxedSourceName()
            : returnType.getParameterizedQualifiedSourceName();

    String callbackType = AsyncCallback.class.getName() + "<" + resultType + ">";

    // Print method
    out.println("  public void " + method.getName() + "(" + formalParams + (formalParams.isEmpty() ? "" : ", ")
            + "final " + callbackType + " callback" + ") {");
    out.println("    fireStart(\"" + method.getName() + "\"" + (actualParams.isEmpty() ? "" : ", ")
            + actualParams + ");");
    out.println("    proxy." + method.getName() + "(" + actualParams + (actualParams.isEmpty() ? "" : ", ")
            + "new " + callbackType + "() {");
    out.println("      public void onSuccess(" + resultType + " result) {");
    out.println("        " + outcome(method, "Success", "result"));
    out.println("      }");
    out.println("      public void onFailure(Throwable caught) {");
    out.println("        " + outcome(method, "Failure", "caught"));
    out.println("      }");
    out.println("    });");
    out.println("  }");
}

From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java

License:Apache License

private void printMockMethodBody(SourceWriter sourceWriter, JMethod method, int methodNo, String newClassName) {

    JParameter[] args = method.getParameters();

    String callVar = freeVariableName("call", args);
    sourceWriter.print("Call %s = new Call(this, %s.methods[%d]", callVar, newClassName, methodNo);

    int argsCount = method.isVarArgs() ? args.length - 1 : args.length;

    for (int i = 0; i < argsCount; i++) {
        sourceWriter.print(", %s", args[i].getName());
    }/*from  w ww .  j  a v a2 s . c  o  m*/
    sourceWriter.println(");");

    if (method.isVarArgs()) {
        sourceWriter.println("%s.addVarArgument(%s);", callVar, args[args.length - 1].getName());
    }

    sourceWriter.println("try {");
    sourceWriter.indent();

    if (!isVoid(method)) {
        sourceWriter.print("return (");

        JType returnType = method.getReturnType();
        JPrimitiveType primitiveType = returnType.isPrimitive();
        if (primitiveType != null) {
            sourceWriter.print(primitiveType.getQualifiedBoxedSourceName());
        } else if (returnType.isTypeParameter() != null) {
            sourceWriter.print(returnType.isTypeParameter().getName());
        } else {
            sourceWriter.print(returnType.getQualifiedSourceName());
        }

        sourceWriter.print(") ");
    }

    sourceWriter.println("this.mocksControl.invoke(%s).answer(%s.getArguments().toArray());", callVar, callVar);
    sourceWriter.outdent();

    String exceptionVar = freeVariableName("exception", args);
    sourceWriter.println("} catch (Throwable %s) {", exceptionVar);
    sourceWriter.indent();

    String assertionError = AssertionErrorWrapper.class.getCanonicalName();
    sourceWriter.println(
            "if (%s instanceof %s) throw (AssertionError) "
                    + "((%s) %s).getAssertionError().fillInStackTrace();",
            exceptionVar, assertionError, assertionError, exceptionVar);

    for (JClassType exception : method.getThrows()) {
        printRethrowException(sourceWriter, exceptionVar, exception.getQualifiedSourceName());
    }
    printRethrowException(sourceWriter, exceptionVar, "RuntimeException");
    printRethrowException(sourceWriter, exceptionVar, "Error");
    sourceWriter.println("throw new UndeclaredThrowableException(%s);", exceptionVar);
    sourceWriter.outdent();
    sourceWriter.println("}");
}

From source file:com.gwtplatform.dispatch.rest.rebind.utils.JPrimitives.java

License:Apache License

public static boolean isBoxed(JType type) {
    String name = type.getQualifiedSourceName();

    for (JPrimitiveType primitive : JPrimitiveType.values()) {
        if (name.equals(primitive.getQualifiedBoxedSourceName())) {
            return true;
        }/*  w  w w  . j  av  a2s  .  com*/
    }

    return false;
}

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 www.j a v a2s  .co  m
    try {
        String boxedSourceName = primitive.getQualifiedBoxedSourceName();
        boxedType = typeOracle.parse(boxedSourceName).isClass();
    } catch (TypeOracleException e) {
        boxedType = null;
    }

    return boxedType;
}

From source file:com.seanchenxi.gwt.storage.rebind.TypeXmlFinder.java

License:Apache License

private void parsePrimitiveTypes(Set<JType> serializables, boolean autoArrayType) {
    logger.branch(TreeLogger.Type.DEBUG, "Adding all primitive types");
    // All primitive types and its array types will be considered as serializable
    for (JPrimitiveType jpt : JPrimitiveType.values()) {
        if (JPrimitiveType.VOID.equals(jpt)) {
            continue;
        }/*from w  w  w .j  a  va2  s.co m*/
        JClassType jBoxedType = typeOracle.findType(jpt.getQualifiedBoxedSourceName());
        boolean added = false;
        if (autoArrayType) {
            if (addIfIsValidType(serializables, typeOracle.getArrayType(jpt), logger))
                added = addIfIsValidType(serializables, typeOracle.getArrayType(jBoxedType), logger);
        } else {
            if (addIfIsValidType(serializables, jpt, logger))
                added = addIfIsValidType(serializables, jBoxedType, logger);
        }
        if (added)
            logger.branch(TreeLogger.Type.TRACE, "Added " + jpt.getQualifiedSourceName());
    }
}

From source file:com.vaadin.server.widgetsetutils.ConnectorBundleLoaderFactory.java

License:Apache License

private void writeJsniInvoker(TreeLogger logger, SplittingSourceWriter w, JClassType type, JMethod method)
        throws UnableToCompleteException {
    w.println("new JsniInvoker() {");
    w.indent();/*w  w w.ja va2 s.  c o m*/

    w.println("protected native Object jsniInvoke(Object target, %s<Object> params) /*-{ ",
            JsArrayObject.class.getName());
    w.indent();

    JType returnType = method.getReturnType();
    boolean hasReturnType = !"void".equals(returnType.getQualifiedSourceName());

    // Note that void is also a primitive type
    boolean hasPrimitiveReturnType = hasReturnType && returnType.isPrimitive() != null;

    if (hasReturnType) {
        w.print("return ");

        if (hasPrimitiveReturnType) {
            // Integer.valueOf(expression);
            w.print("@%s::valueOf(%s)(", returnType.isPrimitive().getQualifiedBoxedSourceName(),
                    returnType.getJNISignature());

            // Implementation tested briefly, but I don't dare leave it
            // enabled since we are not using it in the framework and we
            // have not tests for it.
            logger.log(Type.ERROR,
                    "JSNI invocation is not yet supported for methods with "
                            + "primitive return types. Change your method "
                            + "to public to be able to use conventional" + " Java invoking instead.");
            throw new UnableToCompleteException();
        }
    }

    JType[] parameterTypes = method.getParameterTypes();

    w.print("target.@%s::" + method.getName() + "(*)(", method.getEnclosingType().getQualifiedSourceName());
    for (int i = 0; i < parameterTypes.length; i++) {
        if (i != 0) {
            w.print(", ");
        }

        w.print("params[" + i + "]");

        JPrimitiveType primitive = parameterTypes[i].isPrimitive();
        if (primitive != null) {
            // param.intValue();
            w.print(".@%s::%sValue()()", primitive.getQualifiedBoxedSourceName(),
                    primitive.getQualifiedSourceName());
        }
    }

    if (hasPrimitiveReturnType) {
        assert hasReturnType;
        w.print(")");
    }

    w.println(");");

    if (!hasReturnType) {
        w.println("return null;");
    }

    w.outdent();
    w.println("}-*/;");

    w.outdent();
    w.print("}");
}

From source file:com.vaadin.server.widgetsetutils.metadata.Property.java

License:Apache License

public String getUnboxedPropertyTypeName() {
    JType propertyType = getPropertyType();
    JPrimitiveType primitive = propertyType.isPrimitive();
    if (primitive != null) {
        return primitive.getQualifiedBoxedSourceName();
    } else {/* w w w  .  j  a  v  a 2s . c  o m*/
        return propertyType.getQualifiedSourceName();
    }
}

From source file:com.vaadin.server.widgetsetutils.metadata.Property.java

License:Apache License

public String boxValue(String codeSnippet) {
    JPrimitiveType primitive = propertyType.isPrimitive();
    if (primitive == null) {
        return codeSnippet;
    } else {//  w w w. j a v a 2  s  .  co  m
        return String.format("@%s::valueOf(%s)(%s)", primitive.getQualifiedBoxedSourceName(),
                propertyType.getJNISignature(), codeSnippet);
    }
}

From source file:com.vaadin.server.widgetsetutils.metadata.Property.java

License:Apache License

public String unboxValue(String codeSnippet) {
    JPrimitiveType primitive = propertyType.isPrimitive();
    if (primitive == null) {
        return codeSnippet;
    } else {/* w w w.ja v a  2  s  . com*/
        return String.format("%s.@%s::%sValue()()", codeSnippet, primitive.getQualifiedBoxedSourceName(),
                primitive.getSimpleSourceName());
    }
}