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

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

Introduction

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

Prototype

JClassType getEnclosingType();

Source Link

Usage

From source file:com.ait.ext4j.rebind.TemplateGenerator.java

License:Apache License

/**
 * Given a TemplateResource interface, return the path to its .html file,
 * suitable for any classloader to find it as a resource. If the .html does
 * not exist or is empty see if the template was declared inline. If no
 * content is found we throw an exception.
 *//* w w  w  .j a va2  s .  c o  m*/
private String getTemplateContent(GeneratorContext context, TreeLogger logger, JClassType interfaceType)
        throws UnableToCompleteException {
    String templateHtmlFile = null;

    TemplateResource annotation = interfaceType.getAnnotation(TemplateResource.class);
    if (annotation == null) {
        // if the interface is defined as a nested class, use the name of
        // the
        // enclosing type
        if (interfaceType.getEnclosingType() != null) {
            interfaceType = interfaceType.getEnclosingType();
        }
        templateHtmlFile = slashify(interfaceType.getQualifiedBinaryName()) + TEMPLATE_SUFFIX;
        logger.log(TreeLogger.INFO, "Template : " + templateHtmlFile);

        InputStream stream = getTemplateResource(context, logger, templateHtmlFile);
        if (stream == null) {
            logger.log(Type.ERROR, "No data could be loaded - no data at path "
                    + interfaceType.getQualifiedBinaryName() + TEMPLATE_SUFFIX);
            throw new UnableToCompleteException();
        }
        return sanitize(Util.readStreamAsString(stream));

    } else {
        // first we look at the HTML File
        templateHtmlFile = annotation.source();

        if (templateHtmlFile.length() > 0) {

            if (!templateHtmlFile.endsWith(TEMPLATE_SUFFIX)) {
                logger.log(TreeLogger.ERROR, "Template file name must end with " + TEMPLATE_SUFFIX);
                throw new UnableToCompleteException();
            }

            if (annotation.value().length() != 0) {
                logger.log(Type.WARN, "Found both source file and inline template, using source file");
            }

            templateHtmlFile = slashify(interfaceType.getPackage().getName()) + "/" + templateHtmlFile;
            InputStream stream = getTemplateResource(context, logger, templateHtmlFile);
            return sanitize(Util.readStreamAsString(stream));

        } else if (annotation.value().length() > 0) {
            return annotation.value();
        } else {
            logger.log(Type.ERROR,
                    "Template annotation found with no contents, cannot generate method , this may cause other failures.");
        }

    }
    return null;
}

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

License:Apache License

private String createTypeGenerator(JType t) {
    buffer.setLength(0);/*from w  w w .  jav a 2  s.  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   www . ja v a 2s  .com
    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.didactilab.gwt.phprpc.rebind.phpgen.PhpClass.java

License:Apache License

@Override
protected void getContents(TreeLogger logger, StringBuffer buffer) throws UnableToCompleteException {
    JClassType type = getJavaType();
    buffer.append("/**\n");
    buffer.append(" * @gwtname ").append(type.getQualifiedBinaryName()).append("\n");
    if (type.getEnclosingType() != null) {
        buffer.append(" * @enclosing ").append(type.getEnclosingType().getQualifiedBinaryName()).append("\n");
    }/*www  .j av a 2  s.co  m*/
    buffer.append(" */\n");
    buffer.append("class ").append(PhpTools.typeToString(type, true));
    JClassType superClass = type.getSuperclass();
    if ((superClass != null) && (!superClass.getQualifiedBinaryName().equals("java.lang.Object"))) {
        buffer.append(" extends ").append(PhpTools.typeToString(superClass, true));
    }
    buffer.append(" implements IsSerializable {\n");
    if (serializable) {
        for (JField field : type.getFields()) {
            if (field.isStatic())
                continue;
            if (field.isTransient())
                continue;
            buffer.append("\t/** @var ").append(PhpTools.typeToString(field.getType(), false)).append(" */\n");
            buffer.append("\tpublic $").append(field.getName()).append(";\n\n");
        }
    }
    buffer.append("}\n");
}

From source file:com.didactilab.gwt.phprpc.rebind.phpgen.PhpException.java

License:Apache License

@Override
protected void getContents(TreeLogger logger, StringBuffer buffer) throws UnableToCompleteException {
    JClassType type = getJavaType();
    buffer.append("/**\n");
    buffer.append(" * @gwtname ").append(type.getQualifiedBinaryName()).append("\n");
    if (type.getEnclosingType() != null) {
        buffer.append(" * @enclosing ").append(type.getEnclosingType().getQualifiedBinaryName()).append("\n");
    }/*from   w  w w . j av  a2s .  c  o m*/
    buffer.append(" */\n");
    buffer.append("class ").append(PhpTools.typeToString(type, true)).append(" extends Exception {\n\n");
    buffer.append("}\n");
}

From source file:com.didactilab.gwt.phprpc.rebind.PhpTools.java

License:Apache License

public static String typeToString(JType type, boolean phpCompatible) {
    String name = "";
    JArrayType arrayType = type.isArray();
    if (arrayType != null) {
        if (phpCompatible)
            name = "array";
        else/*ww  w  .ja v a  2 s .c o  m*/
            name = typeToString(arrayType.getComponentType(), phpCompatible) + "[]";
    } else {
        JClassType classType = type.isClassOrInterface();
        if ((classType != null) && (classType.getEnclosingType() != null))
            name = typeToString(classType.getEnclosingType(), phpCompatible) + "_";
        name += filterType(type.getSimpleSourceName());
        if (!phpCompatible) {
            JParameterizedType params = type.isParameterized();
            if (params != null) {
                JClassType[] args = params.getTypeArgs();
                name += "<";
                for (int i = 0, c = args.length; i < c; i++) {
                    name += typeToString(args[i], phpCompatible);
                    if (i < c - 1)
                        name += ", ";
                }
                name += ">";
            }
        }
    }
    return name;
}

From source file:com.dom_distiller.client.JsTestEntryGenerator.java

License:Open Source License

public static List<TestCase> getTestCases(TreeLogger logger, GeneratorContext context)
        throws UnableToCompleteException {
    if (DEBUG)// ww w  .  j  ava  2s .  com
        logger = logger.branch(TreeLogger.WARN, "Getting test cases", null, null);
    TypeOracle oracle = context.getTypeOracle();
    JClassType jsTestCaseClass = oracle.findType(JsTestCase.class.getName());

    List<TestCase> testCases = new ArrayList<TestCase>();

    for (JClassType classType : oracle.getTypes()) {
        if (classType.equals(jsTestCaseClass) || !classType.isAssignableTo(jsTestCaseClass)) {
            continue;
        }

        if (classType.getEnclosingType() != null) {
            if (DEBUG)
                logger.log(TreeLogger.WARN, "Skipping nested class: " + classType.getEnclosingType().getName()
                        + "." + classType.getName());
            continue;
        }

        if (DEBUG)
            logger.log(TreeLogger.WARN, "Found class: " + classType.getName());
        testCases.add(new TestCase(classType, findTests(logger, context, classType)));
    }
    return testCases;
}

From source file:com.github.nmorel.gwtjackson.rebind.AbstractCreator.java

License:Apache License

/**
 * Returns the mapper information for the given type. The result is cached.
 *
 * @param beanType the type/*from  w  ww .j av a2s  . c  o  m*/
 *
 * @return the mapper information
 * @throws UnableToCompleteException if an exception occured while processing the type
 */
protected final BeanJsonMapperInfo getMapperInfo(JClassType beanType) throws UnableToCompleteException {
    BeanJsonMapperInfo mapperInfo = typeOracle.getBeanJsonMapperInfo(beanType);
    if (null != mapperInfo) {
        return mapperInfo;
    }

    boolean samePackage = true;
    String packageName = beanType.getPackage().getName();
    // We can't create classes in the java package so we prefix it.
    if (packageName.startsWith("java.")) {
        packageName = "gwtjackson." + packageName;
        samePackage = false;
    }

    // Retrieve the informations on the beans and its properties.
    BeanInfo beanInfo = BeanProcessor.processBean(logger, typeOracle, configuration, beanType);
    PropertiesContainer properties = PropertyProcessor.findAllProperties(configuration, logger, typeOracle,
            beanInfo, samePackage);
    beanInfo = BeanProcessor.processProperties(configuration, logger, typeOracle, beanInfo, properties);

    // We concatenate the name of all the enclosing classes.
    StringBuilder builder = new StringBuilder(beanType.getSimpleSourceName());
    JClassType enclosingType = beanType.getEnclosingType();
    while (null != enclosingType) {
        builder.insert(0, enclosingType.getSimpleSourceName() + "_");
        enclosingType = enclosingType.getEnclosingType();
    }

    // If the type is specific to the mapper, we concatenate the name and hash of the mapper to it.
    boolean isSpecificToMapper = configuration.isSpecificToMapper(beanType);
    if (isSpecificToMapper) {
        JClassType rootMapperClass = configuration.getRootMapperClass();
        builder.insert(0, '_').insert(0, configuration.getRootMapperHash()).insert(0, '_').insert(0,
                rootMapperClass.getSimpleSourceName());
    }

    String simpleSerializerClassName = builder.toString() + "BeanJsonSerializerImpl";
    String simpleDeserializerClassName = builder.toString() + "BeanJsonDeserializerImpl";

    mapperInfo = new BeanJsonMapperInfo(beanType, packageName, samePackage, simpleSerializerClassName,
            simpleDeserializerClassName, beanInfo, properties.getProperties());

    typeOracle.addBeanJsonMapperInfo(beanType, mapperInfo);

    return mapperInfo;
}

From source file:com.github.nmorel.gwtjackson.rebind.ObjectMapperCreator.java

License:Apache License

/**
 * Creates the implementation of the interface denoted by interfaceClass and extending {@link ObjectMapper}
 *
 * @param interfaceClass the interface to generate an implementation
 *
 * @return the fully qualified name of the created class
 * @throws UnableToCompleteException//from ww w .j  a v a 2  s  .  co m
 */
public String create(JClassType interfaceClass) throws UnableToCompleteException {
    // We concatenate the name of all the enclosing class.
    StringBuilder builder = new StringBuilder(interfaceClass.getSimpleSourceName() + "Impl");
    JClassType enclosingType = interfaceClass.getEnclosingType();
    while (null != enclosingType) {
        builder.insert(0, enclosingType.getSimpleSourceName() + "_");
        enclosingType = enclosingType.getEnclosingType();
    }

    String mapperClassSimpleName = builder.toString();
    String packageName = interfaceClass.getPackage().getName();
    String qualifiedMapperClassName = packageName + "." + mapperClassSimpleName;

    PrintWriter printWriter = getPrintWriter(packageName, mapperClassSimpleName);
    // The class already exists, no need to continue.
    if (printWriter == null) {
        return qualifiedMapperClassName;
    }

    try {
        // Extract the type of the object to map.
        JClassType mappedTypeClass = extractMappedType(interfaceClass);

        boolean reader = typeOracle.isObjectReader(interfaceClass);
        boolean writer = typeOracle.isObjectWriter(interfaceClass);
        Class<?> abstractClass;
        if (reader) {
            if (writer) {
                abstractClass = AbstractObjectMapper.class;
            } else {
                abstractClass = AbstractObjectReader.class;
            }
        } else {
            abstractClass = AbstractObjectWriter.class;
        }

        TypeSpec.Builder mapperBuilder = TypeSpec.classBuilder(mapperClassSimpleName)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addSuperinterface(typeName(interfaceClass))
                .superclass(parameterizedName(abstractClass, mappedTypeClass))
                .addMethod(buildConstructor(mappedTypeClass));

        if (reader) {
            mapperBuilder.addMethod(buildNewDeserializerMethod(mappedTypeClass));
        }

        if (writer) {
            mapperBuilder.addMethod(buildNewSerializerMethod(mappedTypeClass));
        }

        write(packageName, mapperBuilder.build(), printWriter);
    } finally {
        printWriter.close();
    }

    return qualifiedMapperClassName;
}

From source file:com.googlecode.gwt.test.internal.rewrite.RewriteSingleJsoImplDispatches.java

License:Apache License

private String getResourceName(JClassType type) {
    if (type.getEnclosingType() != null) {
        return getResourceName(type.getEnclosingType()) + "$" + type.getSimpleSourceName();
    }/*from   w w  w.j av  a  2s.c om*/
    return type.getQualifiedSourceName().replace('.', '/');
}