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

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

Introduction

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

Prototype

JClassType getEnclosingType();

Source Link

Document

Gets the type in which this method or constructor was declared.

Usage

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 va  2 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.cgxlib.xq.rebind.JsonBuilderGenerator.java

License:Apache License

public void generateMethod(SourceWriter sw, JMethod method, String name, TreeLogger logger)
        throws UnableToCompleteException {
    String ifaceName = method.getEnclosingType().getQualifiedSourceName();

    String retType = method.getReturnType().getParameterizedQualifiedSourceName();
    sw.print("public final " + retType + " " + method.getName());
    JParameter[] params = method.getParameters();
    if (params.length == 0) {
        JArrayType arr = method.getReturnType().isArray();
        JParameterizedType list = method.getReturnType().isParameterized();

        sw.println("() {");
        sw.indent();//from  www  . ja va 2s.c  o m
        if (retType.matches("(java.lang.Boolean|boolean)")) {
            sw.println("return p.getBoolean(\"" + name + "\");");
        } else if (retType.matches("java.util.Date")) {
            sw.println("return new Date(java.lang.Long.parseLong(p.getStr(\"" + name + "\")));");
        } else if (method.getReturnType().isPrimitive() != null) {
            sw.println("return (" + retType + ")p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Character")) {
            sw.println("return (char) p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Byte")) {
            sw.println("return (byte) p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Integer")) {
            sw.println("return (int) p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Float")) {
            sw.println("return p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Double")) {
            sw.println("return (double) p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Long")) {
            sw.println("return (long) p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Byte")) {
            sw.println("return (byte) p.getFloat(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), stringType)) {
            sw.println("return p.getStr(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), jsonBuilderType)) {
            String q = method.getReturnType().getQualifiedSourceName();
            sw.println("return " + "((" + q + ")GWT.create(" + q + ".class))" + ".load(getPropertiesBase(\""
                    + name + "\"));");
        } else if (isTypeAssignableTo(method.getReturnType(), settingsType)) {
            String q = method.getReturnType().getQualifiedSourceName();
            sw.println("return " + "((" + q + ")getPropertiesBase(\"" + name + "\"));");
        } else if (retType.equals(Properties.class.getName())) {
            sw.println("return getPropertiesBase(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), jsType)) {
            sw.println("return p.getJavaScriptObject(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), functionType)) {
            sw.println("return p.getFunction(\"" + name + "\");");
        } else if (arr != null || list != null) {
            JType type = arr != null ? arr.getComponentType() : list.getTypeArgs()[0];
            boolean buildType = isTypeAssignableTo(type, jsonBuilderType);
            String t = type.getQualifiedSourceName();
            sw.println("JsArrayMixed a = p.getArray(\"" + name + "\");");
            sw.println("int l = a == null ? 0 : a.length();");
            String ret;
            if (buildType) {
                sw.println(t + "[] r = new " + t + "[l];");
                sw.println("JsObjectArray<?> a1 = p.getArray(\"" + name + "\").cast();");
                sw.println("int l1 = r.length;");
                sw.println("for (int i = 0 ; i < l1 ; i++) {");
                sw.println("  Object w = a1.get(i);");
                sw.println("  " + t + " instance = GWT.create(" + t + ".class);");
                sw.println("  r[i] = instance.load(w);");
                sw.println("}");
                ret = "r";
            } else {
                ret = "getArrayBase(\"" + name + "\", new " + t + "[l], " + t + ".class)";
            }
            if (arr != null) {
                sw.println("return " + ret + ";");
            } else {
                sw.println("return Arrays.asList(" + ret + ");");
            }
        } else if (method.getReturnType().isEnum() != null) {
            sw.println("return " + method.getReturnType().getQualifiedSourceName() + ".valueOf(p.getStr(\""
                    + name + "\"));");
        } else {
            sw.println("System.err.println(\"JsonBuilderGenerator WARN: unknown return type " + retType + " "
                    + ifaceName + "." + name + "()\"); ");
            // We return the object because probably the user knows how to handle it
            sw.println("return p.get(\"" + name + "\");");
        }
        sw.outdent();
        sw.println("}");
    } else if (params.length == 1) {
        JType type = params[0].getType();
        JArrayType arr = type.isArray();
        JParameterizedType list = type.isParameterized();

        sw.print("(" + type.getParameterizedQualifiedSourceName() + " a)");
        sw.println("{");
        sw.indent();
        if (arr != null || list != null) {
            String a = "a";
            if (list != null) {
                a = "a.toArray(new " + list.getTypeArgs()[0].getQualifiedSourceName() + "[0])";
            }
            sw.println("setArrayBase(\"" + name + "\", " + a + ");");
        } else if (type.getParameterizedQualifiedSourceName().matches("java.util.Date")) {
            sw.println("p.setNumber(\"" + name + "\", a.getTime());");
        } else if (type.getParameterizedQualifiedSourceName().matches(
                "(java.lang.(Character|Long|Double|Integer|Float|Byte)|(char|long|double|int|float|byte))")) {
            sw.println("p.setNumber(\"" + name + "\", a);");
        } else if (type.getParameterizedQualifiedSourceName().matches("(java.lang.Boolean|boolean)")) {
            sw.println("p.setBoolean(\"" + name + "\", a);");
        } else if (type.getParameterizedQualifiedSourceName().matches("com.cgxlib.xq.client.Function")) {
            sw.println("p.setFunction(\"" + name + "\", a);");
        } else if (type.isEnum() != null) {
            sw.println("p.set(\"" + name + "\", a.name());");
        } else {
            sw.println("set(\"" + name + "\", a);");
        }
        if (!"void".equals(retType)) {
            if (isTypeAssignableTo(method.getReturnType(), method.getEnclosingType())) {
                sw.println("return this;");
            } else {
                sw.println("return null;");
            }
        }
        sw.outdent();
        sw.println("}");
    }
}

From source file:com.cgxlib.xq.rebind.XmlBuilderGenerator.java

License:Apache License

public void generateMethod(SourceWriter sw, JMethod method, TreeLogger logger)
        throws UnableToCompleteException {
    Name nameAnnotation = method.getAnnotation(Name.class);
    String name = nameAnnotation != null ? nameAnnotation.value()
            : method.getName().replaceFirst("^(get|set)", "");

    if (nameAnnotation == null) {
        name = name.substring(0, 1).toLowerCase() + name.substring(1);
    }/*from w  w  w.  j a  va2 s .c o  m*/

    String retType = method.getReturnType().getParameterizedQualifiedSourceName();

    sw.print("public final " + retType + " " + method.getName());
    JParameter[] params = method.getParameters();
    if (params.length == 0) {
        JArrayType arr = method.getReturnType().isArray();
        sw.println("() {");
        sw.indent();
        if (retType.matches("(java.lang.Boolean|boolean)")) {
            sw.println("return getBooleanBase(\"" + name + "\");");
        } else if (method.getReturnType().isPrimitive() != null) {
            sw.println("return (" + retType + ")getFloatBase(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), stringType)) {
            sw.println("return getStrBase(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), xmlBuilderType)) {
            String q = method.getReturnType().getQualifiedSourceName();
            sw.println("Element e = getElementBase(\"" + name + "\");");
            sw.println(
                    "return e == null ? null : (" + q + ")((" + q + ")GWT.create(" + q + ".class)).load(e);");
        } else if (retType.equals(Properties.class.getName())) {
            sw.println("return getPropertiesBase(\"" + name + "\");");
        } else if (arr != null) {
            String q = arr.getComponentType().getQualifiedSourceName();
            sw.println("ArrayList<" + q + "> l = new ArrayList<" + q + ">();");
            sw.println("for (Element e: getElementsBase(\"" + name + "\")) {");
            sw.println("  " + q + " c = GWT.create(" + q + ".class);");
            sw.println("  c.load(e);");
            sw.println("  l.add(c);");
            sw.println("}");
            sw.println("return l.toArray(new " + q + "[0]);");
        } else {
            sw.println("return null; // Unsupported return type: " + retType);
        }
        sw.outdent();
        sw.println("}");
    } else if (params.length == 1) {
        JType type = params[0].getType();
        JArrayType arr = type.isArray();
        String qname = type.getParameterizedQualifiedSourceName();
        sw.print("(" + qname + " a)");
        sw.println("{");
        sw.indent();
        if (arr != null) {
            sw.println("setArrayBase(\"" + name + "\", a);");
        } else {
            sw.println("setBase(\"" + name + "\", a);");
        }
        if (!"void".equals(retType)) {
            if (isTypeAssignableTo(method.getReturnType(), method.getEnclosingType())) {
                sw.println("return this;");
            } else {
                sw.println("return null;");
            }
        }
        sw.outdent();
        sw.println("}");
    }
}

From source file:com.colinalworth.gwt.websockets.rebind.ServerCreator.java

License:Apache License

/**
 * Checks to see if the given method can be called over the wire.
 *
 *
 * @param m method to check/*from w w w  .j av a2  s .c om*/
 * @param superClass either {@link Server} or {@link Client}, indicating which direction the call will be made
 * @return
 */
private boolean isRemoteMethod(JMethod m, Class<?> superClass) {
    assert superClass == Server.class || superClass == Client.class;
    return !m.getEnclosingType().getQualifiedSourceName().equals(superClass.getName());
}

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

License:Apache License

/**
 * Generates the concrete MocksControl implementation of the {@code typeName} interface and 
 * delegates generation of mock classes to
 * {@link com.google.gwt.testing.easygwtmock.rebind.MocksGenerator}
 *//*from  ww  w.  ja  v  a  2 s . com*/
@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {

    TypeOracle typeOracle = context.getTypeOracle();
    JClassType mockControlInterface = typeOracle.findType(typeName);

    if (mockControlInterface == null) {
        logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null);
        throw new UnableToCompleteException();
    }

    if (mockControlInterface.isInterface() == null) {
        logger.log(TreeLogger.ERROR, mockControlInterface.getQualifiedSourceName() + " is not an interface",
                null);
        throw new UnableToCompleteException();
    }

    JPackage interfacePackage = mockControlInterface.getPackage();
    String packageName = interfacePackage == null ? "" : interfacePackage.getName();
    String newClassName = mockControlInterface.getName().replace(".", "_") + "Impl";
    String fullNewClassName = packageName + "." + newClassName;

    PrintWriter printWriter = context.tryCreate(logger, packageName, newClassName);
    if (printWriter == null) {
        // We generated this before.
        return fullNewClassName;
    }

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, newClassName);
    composer.setSuperclass(MocksControlBase.class.getCanonicalName());
    composer.addImplementedInterface(mockControlInterface.getQualifiedSourceName());

    SourceWriter writer = composer.createSourceWriter(context, printWriter);
    writer.println();

    MocksGenerator mocksGenerator = new MocksGenerator(context, logger);
    JClassType markerInterface = typeOracle.findType(MocksControl.class.getCanonicalName());

    Set<String> reservedNames = getMethodNames(composer.getSuperclassName(), logger, typeOracle);

    // Report one error per method in the control interface. They are likely to be independent,
    // so it's a bit nicer for the user.
    boolean failed = false;
    for (JMethod method : mockControlInterface.getOverridableMethods()) {
        if (method.getEnclosingType().equals(markerInterface)) {
            // Method is implemented in MocksControlBase
            continue;
        }

        if (reservedNames.contains(method.getName())) {
            // Method name is already used in base class and method should not be overwritten!
            logger.log(TreeLogger.ERROR,
                    method.getName()
                            + " is a reserved name. Do not use it in the extended MocksControl interface",
                    null);
            failed = true;
            continue;
        }

        JClassType typeToMock = method.getReturnType().isClassOrInterface();

        if (typeToMock == null) {
            logger.log(TreeLogger.ERROR,
                    method.getReturnType().getQualifiedSourceName() + " is not an interface or a class", null);
            failed = true;
            continue;
        }

        if (typeToMock.isInterface() != null) {

            if (method.getParameterTypes().length != 0) {
                String methodName = mockControlInterface.getSimpleSourceName() + "." + method.getName();
                logger.log(TreeLogger.ERROR,
                        "This method should not have parameters because it creates Ua mock of an interface: "
                                + methodName,
                        null);
                failed = true;
                continue;
            }

        } else {

            JConstructor constructorToCall = typeToMock.findConstructor(method.getParameterTypes());
            if (constructorToCall == null) {
                String methodName = mockControlInterface.getSimpleSourceName() + "." + method.getName();
                logger.log(TreeLogger.ERROR, "Cannot find matching constructor to call for " + methodName,
                        null);
                failed = true;
                continue;
            }
        }

        String mockClassName = mocksGenerator.generateMock(typeToMock);

        printFactoryMethod(writer, method, mockControlInterface, mockClassName);
    }

    if (failed) {
        throw new UnableToCompleteException();
    }

    writer.commit(logger);
    return fullNewClassName;
}

From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java

License:Apache License

/**
 * For interfaces that consist of nothing more than getters and setters,
 * create a map-based implementation that will allow the AutoBean's internal
 * state to be easily consumed./*from  w ww.j  a va2 s.  c  om*/
 */
private void writeCreateSimpleBean(SourceWriter sw, AutoBeanType type) {
    sw.println("@Override protected %s createSimplePeer() {", type.getPeerType().getQualifiedSourceName());
    sw.indent();
    // return new FooIntf() {
    sw.println("return new %s() {", type.getPeerType().getQualifiedSourceName());
    sw.indent();
    sw.println("private final %s data = %s.this.data;", Splittable.class.getCanonicalName(),
            type.getQualifiedSourceName());
    for (AutoBeanMethod method : type.getMethods()) {
        JMethod jmethod = method.getMethod();
        JType returnType = jmethod.getReturnType();
        sw.println("public %s {", getBaseMethodDeclaration(jmethod));
        sw.indent();
        switch (method.getAction()) {
        case GET: {
            String castType;
            if (returnType.isPrimitive() != null) {
                castType = returnType.isPrimitive().getQualifiedBoxedSourceName();
                // Boolean toReturn = Other.this.getOrReify("foo");
                sw.println("%s toReturn = %s.this.getOrReify(\"%s\");", castType, type.getSimpleSourceName(),
                        method.getPropertyName());
                // return toReturn == null ? false : toReturn;
                sw.println("return toReturn == null ? %s : toReturn;",
                        returnType.isPrimitive().getUninitializedFieldExpression());
            } else if (returnType
                    .equals(context.getTypeOracle().findType(Splittable.class.getCanonicalName()))) {
                sw.println("return data.isNull(\"%1$s\") ? null : data.get(\"%1$s\");",
                        method.getPropertyName());
            } else {
                // return (ReturnType) Outer.this.getOrReify(\"foo\");
                castType = ModelUtils.getQualifiedBaseSourceName(returnType);
                sw.println("return (%s) %s.this.getOrReify(\"%s\");", castType, type.getSimpleSourceName(),
                        method.getPropertyName());
            }
        }
            break;
        case SET:
        case SET_BUILDER: {
            JParameter param = jmethod.getParameters()[0];
            // Other.this.setProperty("foo", parameter);
            sw.println("%s.this.setProperty(\"%s\", %s);", type.getSimpleSourceName(), method.getPropertyName(),
                    param.getName());
            if (JBeanMethod.SET_BUILDER.equals(method.getAction())) {
                sw.println("return this;");
            }
            break;
        }
        case CALL:
            // return com.example.Owner.staticMethod(Outer.this, param,
            // param);
            JMethod staticImpl = method.getStaticImpl();
            if (!returnType.equals(JPrimitiveType.VOID)) {
                sw.print("return ");
            }
            sw.print("%s.%s(%s.this", staticImpl.getEnclosingType().getQualifiedSourceName(),
                    staticImpl.getName(), type.getSimpleSourceName());
            for (JParameter param : jmethod.getParameters()) {
                sw.print(", %s", param.getName());
            }
            sw.println(");");
            break;
        default:
            throw new RuntimeException();
        }
        sw.outdent();
        sw.println("}");
    }
    sw.outdent();
    sw.println("};");
    sw.outdent();
    sw.println("}");
}

From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java

License:Apache License

private void writeReturnWrapper(SourceWriter sw, AutoBeanType type, AutoBeanMethod method)
        throws UnableToCompleteException {
    if (!method.isValueType() && !method.isNoWrap()) {
        JMethod jmethod = method.getMethod();
        JClassType returnClass = jmethod.getReturnType().isClassOrInterface();
        AutoBeanType peer = model.getPeer(returnClass);

        sw.println("if (toReturn != null) {");
        sw.indent();//from  w  ww.  j a  v  a 2  s  .c  o m
        sw.println("if (%s.this.isWrapped(toReturn)) {", type.getSimpleSourceName());
        sw.indentln("toReturn = %s.this.getFromWrapper(toReturn);", type.getSimpleSourceName());
        sw.println("} else {");
        sw.indent();
        if (peer != null) {
            // toReturn = new FooAutoBean(getFactory(), toReturn).as();
            sw.println("toReturn = new %s(getFactory(), toReturn).as();", peer.getQualifiedSourceName());
        }
        sw.outdent();
        sw.println("}");

        sw.outdent();
        sw.println("}");
    }
    // Allow return values to be intercepted
    JMethod interceptor = type.getInterceptor();
    if (interceptor != null) {
        // toReturn = FooCategory.__intercept(FooAutoBean.this, toReturn);
        sw.println("toReturn = %s.%s(%s.this, toReturn);",
                interceptor.getEnclosingType().getQualifiedSourceName(), interceptor.getName(),
                type.getSimpleSourceName());
    }
}

From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java

License:Apache License

/**
 * Generate traversal logic.//from   w w  w . ja v  a  2 s  .  c om
 */
private void writeTraversal(SourceWriter sw, AutoBeanType type) {
    List<AutoBeanMethod> referencedSetters = new ArrayList<AutoBeanMethod>();
    sw.println("@Override protected void traverseProperties(%s visitor, %s ctx) {",
            AutoBeanVisitor.class.getCanonicalName(), OneShotContext.class.getCanonicalName());
    sw.indent();
    sw.println("%s bean;", AbstractAutoBean.class.getCanonicalName());
    sw.println("Object value;");
    sw.println("%s propertyContext;", ClientPropertyContext.class.getCanonicalName());
    // Local variable ref cleans up emitted js
    sw.println("%1$s as = as();", type.getPeerType().getQualifiedSourceName());

    for (AutoBeanMethod method : type.getMethods()) {
        if (!method.getAction().equals(JBeanMethod.GET)) {
            continue;
        }

        AutoBeanMethod setter = null;
        // If it's not a simple bean type, try to find a real setter method
        if (!type.isSimpleBean()) {
            for (AutoBeanMethod maybeSetter : type.getMethods()) {
                boolean isASetter = maybeSetter.getAction().equals(JBeanMethod.SET)
                        || maybeSetter.getAction().equals(JBeanMethod.SET_BUILDER);
                if (isASetter && maybeSetter.getPropertyName().equals(method.getPropertyName())) {
                    setter = maybeSetter;
                    break;
                }
            }
        }

        // The type of property influences the visitation
        String valueExpression = String.format("bean = (%1$s) %2$s.getAutoBean(as.%3$s());",
                AbstractAutoBean.class.getCanonicalName(), AutoBeanUtils.class.getCanonicalName(),
                method.getMethod().getName());
        String visitMethod;
        String visitVariable = "bean";
        if (method.isCollection()) {
            visitMethod = "Collection";
        } else if (method.isMap()) {
            visitMethod = "Map";
        } else if (method.isValueType()) {
            valueExpression = String.format("value = as.%s();", method.getMethod().getName());
            visitMethod = "Value";
            visitVariable = "value";
        } else {
            visitMethod = "Reference";
        }
        sw.println(valueExpression);

        // Map<List<Foo>, Bar> --> Map, List, Foo, Bar
        List<JType> typeList = new ArrayList<JType>();
        createTypeList(typeList, method.getMethod().getReturnType());
        assert typeList.size() > 0;

        /*
         * Make the PropertyContext that lets us call the setter. We allow
         * multiple methods to be bound to the same property (e.g. to allow JSON
         * payloads to be interpreted as different types). The leading underscore
         * allows purely numeric property names, which are valid JSON map keys.
         */
        // propertyContext = new CPContext(.....);
        sw.println("propertyContext = new %s(", ClientPropertyContext.class.getCanonicalName());
        sw.indent();
        // The instance on which the context is nominally operating
        sw.println("as,");
        // Produce a JSNI reference to a setter function to call
        {
            if (setter != null) {
                // Call a method that returns a JSNI reference to the method to call
                // setFooMethodReference(),
                sw.println("%sMethodReference(as),", setter.getMethod().getName());
                referencedSetters.add(setter);
            } else {
                // Create a function that will update the values map
                // CPContext.beanSetter(FooBeanImpl.this, "foo");
                sw.println("%s.beanSetter(%s.this, \"%s\"),",
                        ClientPropertyContext.Setter.class.getCanonicalName(), type.getSimpleSourceName(),
                        method.getPropertyName());
            }
        }
        if (typeList.size() == 1) {
            sw.println("%s.class", ModelUtils.ensureBaseType(typeList.get(0)).getQualifiedSourceName());
        } else {
            // Produce the array of parameter types
            sw.print("new Class<?>[] {");
            boolean first = true;
            for (JType lit : typeList) {
                if (first) {
                    first = false;
                } else {
                    sw.print(", ");
                }
                sw.print("%s.class", ModelUtils.ensureBaseType(lit).getQualifiedSourceName());
            }
            sw.println("},");

            // Produce the array of parameter counts
            sw.print("new int[] {");
            first = true;
            for (JType lit : typeList) {
                if (first) {
                    first = false;
                } else {
                    sw.print(", ");
                }
                JParameterizedType hasParam = lit.isParameterized();
                if (hasParam == null) {
                    sw.print("0");
                } else {
                    sw.print(String.valueOf(hasParam.getTypeArgs().length));
                }
            }
            sw.println("}");
        }
        sw.outdent();
        sw.println(");");

        // if (visitor.visitReferenceProperty("foo", value, ctx))
        sw.println("if (visitor.visit%sProperty(\"%s\", %s, propertyContext)) {", visitMethod,
                method.getPropertyName(), visitVariable);
        if (!method.isValueType()) {
            // Cycle-detection in AbstractAutoBean.traverse
            sw.indentln("if (bean != null) { bean.traverse(visitor, ctx); }");
        }
        sw.println("}");
        // visitor.endVisitorReferenceProperty("foo", value, ctx);
        sw.println("visitor.endVisit%sProperty(\"%s\", %s, propertyContext);", visitMethod,
                method.getPropertyName(), visitVariable);
    }
    sw.outdent();
    sw.println("}");

    for (AutoBeanMethod method : referencedSetters) {
        JMethod jmethod = method.getMethod();
        assert jmethod.getParameters().length == 1;

        /*-
         * Setter setFooMethodReference(Object instance) {
         *   return instance.@com.example.Blah::setFoo(Lcom/example/Foo;);
         * }
         */
        sw.println("public static native %s %sMethodReference(Object instance) /*-{",
                ClientPropertyContext.Setter.class.getCanonicalName(), jmethod.getName());
        sw.indentln("return instance.@%s::%s(%s);", jmethod.getEnclosingType().getQualifiedSourceName(),
                jmethod.getName(), jmethod.getParameters()[0].getType().getJNISignature());
        sw.println("}-*/;");
    }
}

From source file:com.google.web.bindery.autobean.gwt.rebind.model.AutoBeanFactoryModel.java

License:Apache License

public AutoBeanFactoryModel(TreeLogger logger, JClassType factoryType) throws UnableToCompleteException {
    this.logger = logger;
    oracle = factoryType.getOracle();/*ww w. j  ava2  s. co  m*/
    autoBeanInterface = oracle.findType(AutoBean.class.getCanonicalName()).isGenericType();
    autoBeanFactoryInterface = oracle.findType(AutoBeanFactory.class.getCanonicalName()).isInterface();

    /*
     * We want to allow the user to override some of the useful Object methods,
     * so we'll extract them here.
     */
    JClassType objectType = oracle.getJavaLangObject();
    objectMethods = Arrays.asList(objectType.findMethod("equals", new JType[] { objectType }),
            objectType.findMethod("hashCode", EMPTY_JTYPE), objectType.findMethod("toString", EMPTY_JTYPE));

    // Process annotations
    {
        Category categoryAnnotation = factoryType.getAnnotation(Category.class);
        if (categoryAnnotation != null) {
            categoryTypes = new ArrayList<JClassType>(categoryAnnotation.value().length);
            processClassArrayAnnotation(categoryAnnotation.value(), categoryTypes);
        } else {
            categoryTypes = null;
        }

        noWrapTypes = new ArrayList<JClassType>();
        noWrapTypes.add(oracle.findType(AutoBean.class.getCanonicalName()));
        NoWrap noWrapAnnotation = factoryType.getAnnotation(NoWrap.class);
        if (noWrapAnnotation != null) {
            processClassArrayAnnotation(noWrapAnnotation.value(), noWrapTypes);
        }

        ExtraEnums extraEnumsAnnotation = factoryType.getAnnotation(ExtraEnums.class);
        if (extraEnumsAnnotation != null) {
            for (Class<?> clazz : extraEnumsAnnotation.value()) {
                JEnumType asEnum = oracle.findType(clazz.getCanonicalName()).isEnum();
                assert asEnum != null;
                for (JEnumConstant value : asEnum.getEnumConstants()) {
                    allEnumConstants.put(value, AutoBeanMethod.getEnumName(value));
                }
            }
        }
    }

    for (JMethod method : factoryType.getOverridableMethods()) {
        if (method.getEnclosingType().equals(autoBeanFactoryInterface)) {
            // Ignore methods in AutoBeanFactory
            continue;
        }

        JClassType returnType = method.getReturnType().isInterface();
        if (returnType == null) {
            poison("The return type of method %s is a primitive type", method.getName());
            continue;
        }

        // AutoBean<FooIntf> blah() --> beanType = FooIntf
        JClassType beanType = ModelUtils.findParameterizationOf(autoBeanInterface, returnType)[0];
        if (beanType.isInterface() == null) {
            poison("The %s parameterization is not an interface", beanType.getQualifiedSourceName());
            continue;
        }

        // AutoBean<FooIntf> blah(FooIntfSub foo) --> toWrap = FooIntfSub
        JClassType toWrap;
        if (method.getParameters().length == 0) {
            toWrap = null;
        } else if (method.getParameters().length == 1) {
            toWrap = method.getParameters()[0].getType().isClassOrInterface();
            if (!beanType.isAssignableFrom(toWrap)) {
                poison("The %s parameterization %s is not assignable from the delegate" + " type %s",
                        autoBeanInterface.getSimpleSourceName(), toWrap.getQualifiedSourceName());
                continue;
            }
        } else {
            poison("Unexpecetd parameters in method %s", method.getName());
            continue;
        }

        AutoBeanType autoBeanType = getAutoBeanType(beanType);

        // Must wrap things that aren't simple interfaces
        if (!autoBeanType.isSimpleBean() && toWrap == null) {
            if (categoryTypes != null) {
                poison("The %s parameterization is not simple and the following"
                        + " methods did not have static implementations:", beanType.getQualifiedSourceName());
                for (AutoBeanMethod missing : autoBeanType.getMethods()) {
                    if (missing.getAction().equals(JBeanMethod.CALL) && missing.getStaticImpl() == null) {
                        poison(missing.getMethod().getReadableDeclaration());
                    }
                }
            } else {
                poison("The %s parameterization is not simple, but the %s method"
                        + " does not provide a delegate", beanType.getQualifiedSourceName(), method.getName());
            }
            continue;
        }

        AutoBeanFactoryMethod.Builder builder = new AutoBeanFactoryMethod.Builder();
        builder.setAutoBeanType(autoBeanType);
        builder.setMethod(method);
        methods.add(builder.build());
    }

    while (!toCalculate.isEmpty()) {
        Set<JClassType> examine = toCalculate;
        toCalculate = new LinkedHashSet<JClassType>();
        for (JClassType beanType : examine) {
            getAutoBeanType(beanType);
        }
    }

    if (poisoned) {
        die("Unable to complete due to previous errors");
    }
}

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

License:Apache License

public RequestFactoryModel(TreeLogger logger, JClassType factoryType) throws UnableToCompleteException {
    this.logger = logger;
    this.factoryType = factoryType;
    this.oracle = factoryType.getOracle();
    collectionInterface = oracle.findType(Collection.class.getCanonicalName());
    entityProxyInterface = oracle.findType(EntityProxy.class.getCanonicalName());
    instanceRequestInterface = oracle.findType(InstanceRequest.class.getCanonicalName());
    listInterface = oracle.findType(List.class.getCanonicalName());
    mapInterface = oracle.findType(Map.class.getCanonicalName());
    requestContextInterface = oracle.findType(RequestContext.class.getCanonicalName());
    requestFactoryInterface = oracle.findType(RequestFactory.class.getCanonicalName());
    requestInterface = oracle.findType(Request.class.getCanonicalName());
    setInterface = oracle.findType(Set.class.getCanonicalName());
    splittableType = oracle.findType(Splittable.class.getCanonicalName());
    valueProxyInterface = oracle.findType(ValueProxy.class.getCanonicalName());

    extraTypes = checkExtraTypes(factoryType, false);
    for (JMethod method : factoryType.getOverridableMethods()) {
        if (method.getEnclosingType().equals(requestFactoryInterface)) {
            // Ignore methods defined an RequestFactory itself
            continue;
        }//from  w w w .  j a  v  a2s. c  om

        if (method.getParameters().length > 0) {
            poison("Unexpected parameter on method %s", method.getName());
            continue;
        }

        JClassType contextType = method.getReturnType().isInterface();
        if (contextType == null || !requestContextInterface.isAssignableFrom(contextType)) {
            poison("Unexpected return type %s on method %s is not" + " an interface assignable to %s",
                    method.getReturnType().getQualifiedSourceName(), method.getName(),
                    requestContextInterface.getSimpleSourceName());
            continue;
        }

        ContextMethod.Builder builder = new ContextMethod.Builder();
        builder.setDeclaredMethod(method);
        buildContextMethod(builder, contextType);
        contextMethods.add(builder.build());
    }

    if (poisoned) {
        die(poisonedMessage());
    }
}