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

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

Introduction

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

Prototype

boolean isAssignableFrom(JClassType possibleSubtype);

Source Link

Document

Returns true if this JClassType is assignable from the specified JClassType parameter.

Usage

From source file:com.colinalworth.xmlview.rebind.XmlValidatorGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    // validate the interface, annotations
    TypeOracle oracle = context.getTypeOracle();
    JClassType toGenerate = oracle.findType(typeName).isInterface();
    if (toGenerate == null) {
        logger.log(Type.ERROR, typeName + " is not an interface type");
        throw new UnableToCompleteException();
    }//from  w  w w  .j a v a  2  s  . c o m
    JClassType schema = oracle.findType(Name.getSourceNameForClass(Schema.class)).isInterface();
    if (!schema.isAssignableFrom(toGenerate)) {
        // this shouldn't be possible unless the generator is deliberately invoked
        logger.log(Type.ERROR, "Declared interface must be assignable from XmlValidator");
        throw new UnableToCompleteException();
    }

    SchemaURL urlAnnotation = toGenerate.getAnnotation(SchemaURL.class);
    SchemaPath pathAnnotation = toGenerate.getAnnotation(SchemaPath.class);
    // get a handle on the file that has the schema
    final Sources sources = new Sources();
    if (urlAnnotation != null) {
        for (String url : urlAnnotation.value()) {
            try {
                sources.urls.add(new URL(url));
            } catch (MalformedURLException e) {
                logger.log(Type.ERROR, "Problem with @SchemaURL(\"" + url + "\")", e);
                throw new UnableToCompleteException();
            }
        }
    }
    if (pathAnnotation != null) {
        for (String file : pathAnnotation.value()) {
            sources.files.add(new File(file));
        }
    }
    if (urlAnnotation == null && pathAnnotation == null) {
        assert urlAnnotation == null && pathAnnotation == null;
        logger.log(Type.ERROR, "A Path or URL must be defined");
        throw new UnableToCompleteException();
    }

    // make the impl class
    String packageName = toGenerate.getPackage().getName();
    String simpleSourceName = toGenerate.getName().replace('.', '_') + "_Impl";
    PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName);
    if (pw == null) {
        return packageName + "." + simpleSourceName;
    }

    //public class X implements X {
    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.setSuperclass(Name.getSourceNameForClass(AbstractSchemaImpl.class));
    factory.addImplementedInterface(typeName);

    //factory.addImport(Name.getSourceNameForClass(GWT.class));
    factory.addImport(Name.getSourceNameForClass(Node.class));
    factory.addImport(Name.getSourceNameForClass(Element.class));
    factory.addImport(Name.getSourceNameForClass(Attr.class));
    factory.addImport(Name.getSourceNameForClass(CharacterData.class));
    factory.addImport(Name.getSourceNameForClass(JsArray.class));

    SourceWriter sw = factory.createSourceWriter(context, pw);

    // generate the class
    ValidatorCreator c = new ValidatorCreator(simpleSourceName, sources, context, logger, sw);

    c.generateCtor();
    c.generateMethods();

    sw.commit(logger);
    return packageName + "." + simpleSourceName;
}

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();//  w  w w  . j  a  v a  2  s.  c  o  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.autobean.gwt.rebind.model.AutoBeanFactoryModel.java

License:Apache License

private List<AutoBeanMethod> computeMethods(JClassType beanType) {
    List<JMethod> toExamine = new ArrayList<JMethod>();
    toExamine.addAll(Arrays.asList(beanType.getInheritableMethods()));
    toExamine.addAll(objectMethods);/*from   ww w  .  j av  a  2  s  .c  o m*/
    List<AutoBeanMethod> toReturn = new ArrayList<AutoBeanMethod>(toExamine.size());
    for (JMethod method : toExamine) {
        if (method.isPrivate()) {
            // Ignore private methods
            continue;
        }
        AutoBeanMethod.Builder builder = new AutoBeanMethod.Builder();
        builder.setMethod(method);

        // See if this method shouldn't have its return type wrapped
        // TODO: Allow class return types?
        JClassType classReturn = method.getReturnType().isInterface();
        if (classReturn != null) {
            maybeCalculate(classReturn);
            if (noWrapTypes != null) {
                for (JClassType noWrap : noWrapTypes) {
                    if (noWrap.isAssignableFrom(classReturn)) {
                        builder.setNoWrap(true);
                        break;
                    }
                }
            }
        }

        // GET, SET, or CALL
        JBeanMethod action = JBeanMethod.which(method);
        builder.setAction(action);
        if (JBeanMethod.CALL.equals(action)) {
            JMethod staticImpl = findStaticImpl(beanType, method);
            if (staticImpl == null && objectMethods.contains(method)) {
                // Don't complain about lack of implementation for Object methods
                continue;
            }
            builder.setStaticImp(staticImpl);
        }

        AutoBeanMethod toAdd = builder.build();

        // Collect referenced enums
        if (toAdd.hasEnumMap()) {
            allEnumConstants.putAll(toAdd.getEnumMap());
        }

        // See if parameterizations will pull in more types
        if (toAdd.isCollection()) {
            maybeCalculate(toAdd.getElementType());
        } else if (toAdd.isMap()) {
            maybeCalculate(toAdd.getKeyType());
            maybeCalculate(toAdd.getValueType());
        }

        toReturn.add(toAdd);
    }
    return toReturn;
}

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

License:Apache License

private AutoBeanType getAutoBeanType(JClassType beanType) {
    beanType = ModelUtils.ensureBaseType(beanType);
    AutoBeanType toReturn = peers.get(beanType);
    if (toReturn == null) {
        AutoBeanType.Builder builder = new AutoBeanType.Builder();
        builder.setOwnerFactory(this);
        builder.setPeerType(beanType);/*ww  w. ja v  a2s  . c  o  m*/
        builder.setMethods(computeMethods(beanType));
        builder.setInterceptor(findInterceptor(beanType));
        if (noWrapTypes != null) {
            for (JClassType noWrap : noWrapTypes) {
                if (noWrap.isAssignableFrom(beanType)) {
                    builder.setNoWrap(true);
                    break;
                }
            }
        }
        toReturn = builder.build();
        peers.put(beanType, toReturn);
    }
    return toReturn;
}

From source file:com.guit.rebind.binder.GuitBinderGenerator.java

License:Apache License

private void printViewFieldBindings(SourceWriter writer, JClassType presenterType, String viewTypeName,
        HashMap<String, JType> validBindingFieldsType, ArrayList<JField> fields)
        throws UnableToCompleteException {

    Set<String> validBindingFields = validBindingFieldsType.keySet();

    JClassType viewAccesorType = getType(ViewAccesor.class.getCanonicalName());

    ArrayList<JField> superFields = new ArrayList<JField>();
    collectAllFields(presenterType.getSuperclass(), superFields);

    JClassType elementDomType = getType(com.guit.client.dom.Element.class.getCanonicalName());

    for (JField f : fields) {
        if (f.isAnnotationPresent(ViewField.class)) {
            // Check for repetided fields
            if (f.getType().isClassOrInterface().isAssignableTo(elementDomType)) {
                if (superFields.contains(f)) {

                }// w  ww.  ja va  2  s.  c om
            }

            String name = f.getName();
            ViewField viewField = f.getAnnotation(ViewField.class);
            String viewName = viewField.name();
            if (viewName.isEmpty()) {
                viewName = name;
            }
            if (!validBindingFields.contains(viewName)) {
                error("The field '%s' do not exists. Found: %s.%s", viewName,
                        presenterType.getQualifiedSourceName(), name);
            }

            JClassType type = f.getType().isClassOrInterface();
            // if (type.isInterface() == null && !viewField.provided()) {
            // error("A ViewField must be an interface. Found: %s.%s", presenterType
            // .getQualifiedSourceName(), name);
            // }

            if (type.isAssignableTo(viewAccesorType)) {
                writer.println("{");
                writer.indent();
                if (!type.isAnnotationPresent(Implementation.class)) {
                    writer.println(type.getQualifiedSourceName() + " accesor = "
                            + GinOracle.getProvidedInstance(type.getQualifiedSourceName()) + ".get();");
                } else {

                    JClassType implementation = getType(
                            type.getAnnotation(Implementation.class).value().getCanonicalName());

                    // If they are parameterized look for the base type
                    JParameterizedType implementationParameterized = implementation.isParameterized();
                    if (implementationParameterized != null) {
                        implementation = implementationParameterized.getBaseType();
                    }
                    JParameterizedType typeParameterized = type.isParameterized();
                    if (typeParameterized != null) {
                        type = typeParameterized.getBaseType();
                    }

                    // Verify that they are assignable
                    if (!implementation.isAssignableTo(type)) {
                        error("An implementation of a ViewAccesor must implement the ViewAccesor interface. Found: %s",
                                implementation.getQualifiedSourceName());
                    }
                    writer.println(type.getQualifiedSourceName() + " accesor = new "
                            + implementation.getQualifiedSourceName() + "();");
                }

                writer.println("accesor.setTarget(view." + viewName + ");");
                writer.println("presenter." + name + " = accesor;");
                writer.outdent();
                writer.print("}");
                writer.println();
            } else if (type == null
                    || type.isAssignableFrom(validBindingFieldsType.get(viewName).isClassOrInterface())
                    || type.getQualifiedSourceName().startsWith("elemental.")) {
                String qualifiedSourceName = f.getType().getQualifiedSourceName();
                writer.println("presenter." + name + " = (" + qualifiedSourceName + ") view." + viewName + ";");
                writer.println();
            } else {
                // Interface emulation (without exceptions)
                writer.println(
                        "presenter." + name + " = new " + type.getParameterizedQualifiedSourceName() + "() {");
                writer.indent();

                ArrayList<JMethod> methods = new ArrayList<JMethod>();
                findAllMethods(type, methods);
                for (JMethod m : methods) {
                    writer.print(m.getReadableDeclaration(false, true, true, true, true));
                    writer.println("{");
                    writer.indent();

                    // Find the parameters
                    StringBuilder callParameters = new StringBuilder();
                    for (JParameter p : m.getParameters()) {
                        if (callParameters.length() > 0) {
                            callParameters.append(", ");
                        }
                        if (p.isAnnotationPresent(ImplicitCast.class)) {
                            callParameters.append("(");
                            callParameters
                                    .append(p.getAnnotation(ImplicitCast.class).value().getCanonicalName());
                            callParameters.append(") ");
                        }
                        callParameters.append(p.getName());
                    }

                    JType returnType = m.getReturnType();
                    if (!returnType.equals(JPrimitiveType.VOID)) {
                        writer.print("return ");

                        // Implicit cast
                        writer.print("(" + returnType.getParameterizedQualifiedSourceName() + ")");
                    }

                    writer.indent();
                    writer.println(createdClassName + ".this.view." + viewName + "." + m.getName() + "("
                            + callParameters.toString() + ");");
                    writer.outdent();

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

                // Get .equals working on emulated interfaces for
                // event.getSource() comparations
                writer.println("@Override");
                writer.println("public boolean equals(Object obj) {");
                writer.indent();
                writer.println("return view." + viewName + ".equals(obj);");
                writer.outdent();
                writer.println("}");
                writer.println();

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

From source file:com.gwtplatform.mvp.rebind.ClassInspector.java

License:Apache License

/**
 * Inspects the methods to find one that return the specified type. The method can be either in
 * the inspected class or any of its parent classes. It can be static or not.
 *
 * @param returnType The type that should be returned by the method.
 * @return The method returning {@code returnType}, or {@code null} if not found.
 * @throws UnableToCompleteException If more than one matching method is found.
 *//*from   w  w w  .j  a va2  s .c  om*/
public JMethod findMethodWithoutParamsReturning(JClassType returnType) throws UnableToCompleteException {
    JMethod result = null;
    for (JClassType classType : inspectedClass.getFlattenedSupertypeHierarchy()) {
        for (JMethod method : classType.getMethods()) {
            JClassType actualReturnType = method.getReturnType().isClassOrInterface();
            if (method.getParameters().length == 0 && actualReturnType != null
                    && returnType.isAssignableFrom(actualReturnType)) {
                if (result != null) {
                    logger.log(TreeLogger.ERROR,
                            "The class '" + inspectedClass.getName() + "' has more than one method returning "
                                    + returnType.getName() + " and taking no parameter. This is not allowed.",
                            null);
                    throw new UnableToCompleteException();
                }
                result = method;
            }
        }
    }
    return result;
}

From source file:com.gwtplatform.mvp.rebind.ClassInspector.java

License:Apache License

/**
 * Inspects the methods to find one that return the specified parameterized type with the
 * specified type as a parameter. The method can be either in the inspected class or any of its
 * parent classes. It can be static or not.
 *
 * @param returnType          The parameterized type that should be returned by the method.
 * @param returnTypeParameter The type parameter of {@code returnType}.
 * @return The method returning {@code returnType<returnTypeParameter>}, or {@code null} if not
 *         found./*from   w w  w.  j  ava 2  s. c o m*/
 * @throws UnableToCompleteException If more than one matching method is found.
 */
public JMethod findMethodWithoutParamsReturning(JGenericType returnType, JClassType returnTypeParameter)
        throws UnableToCompleteException {
    JMethod result = null;
    for (JClassType classType : inspectedClass.getFlattenedSupertypeHierarchy()) {
        for (JMethod method : classType.getMethods()) {
            JParameterizedType actualReturnType = method.getReturnType().isParameterized();
            if (method.getParameters().length == 0 && actualReturnType != null
                    && returnType.isAssignableFrom(actualReturnType)
                    && returnTypeParameter.isAssignableFrom(actualReturnType.getTypeArgs()[0])) {
                if (result != null) {
                    logger.log(TreeLogger.ERROR,
                            "The class '" + inspectedClass.getName() + "' has more than one method returning "
                                    + returnType.getName() + "<" + returnTypeParameter.getName()
                                    + "> and taking no parameter. " + "This is not allowed.",
                            null);
                    throw new UnableToCompleteException();
                }
                result = method;
            }
        }
    }
    return result;
}

From source file:com.gwtplatform.mvp.rebind.ClassInspector.java

License:Apache License

/**
 * Inspects the methods to find one that return the specified type and is annotated with the
 * specified annotation. The method can be either in the inspected class or any of its parent
 * classes. It can be static or not./*from   w w w  . j a va  2s  . c  o m*/
 *
 * @param returnType The type that should be returned by the method.
 * @param annotation The annotation that should be present on the method.
 * @param failIfAnnotationIsFoundOnWrongMethod
 *                   If {@code true}, the call will throw an
 *                   {@link UnableToCompleteException} and log an error if the annotation is found on the
 *                   wrong method.
 * @return The method returning {@code returnType} and annotated with {@code annotation}, or
 *         {@code null} if not found.
 * @throws UnableToCompleteException If more than one matching method is found, or if the
 *                                   annotation is found on another method and {@code
 *                                   failIfAnnotationIsFoundOnWrongMethod}
 *                                   is {@code true}.
 */
public JMethod findAnnotatedMethodWithoutParamsReturning(JClassType returnType,
        Class<? extends Annotation> annotation, boolean failIfAnnotationIsFoundOnWrongMethod)
        throws UnableToCompleteException {
    JMethod result = null;
    for (JClassType classType : inspectedClass.getFlattenedSupertypeHierarchy()) {
        for (JMethod method : classType.getMethods()) {
            JClassType actualReturnType = method.getReturnType().isClassOrInterface();
            if (method.getAnnotation(annotation) != null) {
                if (method.getParameters().length == 0 && actualReturnType != null
                        && returnType.isAssignableFrom(actualReturnType)) {
                    if (result != null) {
                        logger.log(TreeLogger.ERROR,
                                "The class '" + inspectedClass.getName()
                                        + "' has more than one method returning " + returnType.getName()
                                        + " annotated with '" + annotation.getSimpleName() + "' "
                                        + " and taking no parameter. This is not allowed.",
                                null);
                        throw new UnableToCompleteException();
                    }
                    result = method;
                } else if (failIfAnnotationIsFoundOnWrongMethod) {
                    logger.log(TreeLogger.ERROR, "The class '" + inspectedClass.getName() + "' has method '"
                            + method.getName() + "' annotated with '" + annotation.getSimpleName()
                            + "', but the method has the wrong "
                            + "signature. It must take 0 parameter and return '" + returnType.getName() + "'.",
                            null);
                    throw new UnableToCompleteException();
                }
            }
        }
    }
    return result;
}

From source file:com.gwtplatform.mvp.rebind.ClassInspector.java

License:Apache License

/**
 * Inspects the class for a method with the given name and taking exactly one parameter of the
 * specified type, or of a subtype of that type.
 *
 * @param methodName    The name of the method to look for.
 * @param parameterType The type of the unique parameter accepted by that method.
 * @return The method, or {@code null} if not found.
 *///from w  w w  .  j  a  va2 s  .c  o  m
public JMethod findMethod(String methodName, JClassType parameterType) {
    for (JClassType classType : inspectedClass.getFlattenedSupertypeHierarchy()) {
        for (JMethod method : classType.getMethods()) {
            if (methodName.equals(method.getName())) {
                JType[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 1) {
                    JClassType actualParameterType = parameterTypes[0].isClassOrInterface();
                    if (actualParameterType != null && parameterType.isAssignableFrom(actualParameterType)) {
                        return method;
                    }
                }
            }
        }
    }
    return null;
}

From source file:com.gwtplatform.mvp.rebind.ClassInspector.java

License:Apache License

/**
 * Inspects the fields to collect the ones of the specified parameterized type with the specified
 * type as a parameter annotated with the specified annotation. The field can be either in the
 * inspected class or any of its parent classes. Only static fields are collected.
 *
 * @param type          The parameterized type of the desired fields.
 * @param typeParameter The type parameter of {@code type}.
 * @param annotation    The annotation that should be present on the field.
 * @param collection    The list in which to collect matching fields.
 * @throws UnableToCompleteException If a field annotated with {@code annotation} is found that
 *                                   does not respect the other criteria of the search.
 *//*w w  w .  ja va 2  s .  c  o m*/
public void collectStaticAnnotatedFields(JClassType type, JClassType typeParameter,
        Class<? extends Annotation> annotation, List<JField> collection) throws UnableToCompleteException {
    for (JClassType classType : inspectedClass.getFlattenedSupertypeHierarchy()) {
        for (JField field : classType.getFields()) {
            if (field.getAnnotation(annotation) != null) {
                JParameterizedType parameterizedType = field.getType().isParameterized();
                if (!field.isStatic() || parameterizedType == null || !type.isAssignableFrom(parameterizedType)
                        || !typeParameter.isAssignableFrom(parameterizedType.getTypeArgs()[0])) {
                    logger.log(TreeLogger.ERROR,
                            "Found the annotation @" + annotation.getSimpleName() + " on the invalid field '"
                                    + classType.getName() + "." + field.getName()
                                    + "'. Field must be static and its type must be " + type.getName() + "<"
                                    + typeParameter.getName() + ">.",
                            null);
                    throw new UnableToCompleteException();
                }
                collection.add(field);
            }
        }
    }
}