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

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

Introduction

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

Prototype

boolean isStatic();

Source Link

Usage

From source file:cc.alcina.framework.entity.gwtsynth.ClientReflectionGenerator.java

License:Apache License

public void writeIt(List<JClassType> beanInfoTypes, List<JClassType> instantiableTypes, SourceWriter sw,
        Map<JClassType, Set<RegistryLocation>> gwtRegisteringClasses, String implName) throws Exception {
    String qualifiedImplName = this.packageName + "." + implName;
    Map<JClassType, String> initClassMethodNames = new LinkedHashMap<>();
    Map<JClassType, String> initNewInstanceNames = new LinkedHashMap<>();
    List<String> methodLines = new ArrayList<String>();
    sw.indent();/*from ww w .  jav a2  s. c om*/
    sw.println("private JavaScriptObject createLookup;");
    sw.println();
    sw.println(String.format("public %s() {", implName));
    sw.indent();
    sw.println("super();");
    sw.println("init();");
    sw.outdent();
    sw.println("}");
    sw.println();
    sw.println("@Override");
    sw.println("@UnsafeNativeLong");
    sw.println("public native <T> T newInstance0(Class<T> clazz, long objectId, long localId) /*-{");
    sw.indent();
    sw.println(String.format("var constructor = this.@%s::createLookup.get(clazz);", qualifiedImplName));
    sw.println("return constructor ? constructor() : null;");
    sw.outdent();
    sw.println("}-*/;");
    sw.println();
    sw.println();
    int methodCount = 0;
    for (JClassType jct : beanInfoTypes) {
        if (filter.omitForModule(jct, ReflectionAction.BEAN_INFO_DESCRIPTOR)) {
            continue;
        }
        String methodName = "initClass" + (methodCount++);
        initClassMethodNames.put(jct, methodName);
        sw.println(String.format("private void %s(){", methodName));
        sw.indent();
        sw.println(
                "Map<String,ClientPropertyReflector> propertyReflectors = new LinkedHashMap<String,ClientPropertyReflector>();");
        for (JMethod method : getPropertyGetters(jct)) {
            String propertyName = getPropertyNameForReadMethod(method);
            if (propertyName.equals("class") || propertyName.equals("propertyChangeListeners")) {
                continue;
            }
            if (method.isStatic()) {
                continue;
            }
            Collection<Annotation> annotations = getSuperclassAnnotationsForMethod(method);
            int aCount = 0;
            String annArray = "";
            boolean ignore = false;
            for (Annotation a : annotations) {
                if (a.annotationType() == Omit.class) {
                    ignore = true;
                }
            }
            if (ignore) {
                continue;
            }
            sw.println("{");
            sw.indent();
            for (Annotation a : annotations) {
                if (!a.annotationType().isAnnotationPresent(ClientVisible.class)
                        || a.annotationType() == RegistryLocation.class) {
                    continue;
                }
                if (aCount++ != 0) {
                    annArray += ", ";
                }
                String annImpl = getAnnImpl(a, ann2impl, aCount);
                annArray += "a" + aCount;
                sw.println(annImpl);
            }
            sw.println(String.format(
                    "ClientPropertyReflector reflector = " + "new ClientPropertyReflector(\"%s\",%s.class,"
                            + " new Annotation[]{%s}) ;",
                    propertyName, method.getReturnType().getQualifiedSourceName(), annArray));
            sw.println("propertyReflectors.put(reflector.getPropertyName(), reflector);");
            sw.outdent();
            sw.println("}");
        }
        int aCount = 0;
        String annArray = "";
        for (Annotation a : getClassAnnotations(jct, visibleAnnotationClasses, false)) {
            if (aCount++ != 0) {
                annArray += ", ";
            }
            String annImpl = getAnnImpl(a, ann2impl, aCount);
            annArray += "a" + aCount;
            sw.println(annImpl);
        }
        sw.println(String.format(
                "ClientBeanReflector beanReflector = new ClientBeanReflector("
                        + "%s.class,new Annotation[]{%s},propertyReflectors);",
                jct.getQualifiedSourceName(), annArray));
        sw.println("gwbiMap.put(beanReflector.getBeanClass(),beanReflector );");
        sw.outdent();
        sw.println("}");
        sw.println("");
    }
    Set<JClassType> allTypes = new LinkedHashSet<JClassType>();
    allTypes.addAll(instantiableTypes);
    allTypes.addAll(beanInfoTypes);
    List<JClassType> constructorTypes = CollectionFilters.filter(allTypes, new CollectionFilter<JClassType>() {
        @Override
        public boolean allow(JClassType o) {
            return o.isEnum() == null;
        }
    });
    methodCount = 0;
    for (JClassType jClassType : constructorTypes) {
        /*
         * private native void registerNewInstanceFunction0(Class clazz)/*-{
         * var closure=this;
         * this.@au.com.barnet.jade.client.test.TestClientReflector
         * ::createLookup[clazz] = function() { return
         * closure.@au.com.barnet
         * .jade.client.test.TestClientReflector::createInstance0()(); }; }-
         */;
        String registerMethodName = String.format("registerNewInstanceFunction%s", methodCount);
        String createMethodName = String.format("createInstance%s", methodCount);
        initNewInstanceNames.put(jClassType,
                String.format("%s(%s.class);", registerMethodName, jClassType.getQualifiedSourceName()));
        sw.println(String.format("private Object %s(){", createMethodName));
        sw.indent();
        sw.println(String.format("return GWT.create(%s.class);", jClassType.getQualifiedSourceName()));
        sw.outdent();
        sw.println("};");
        sw.println();
        sw.println(String.format("private native void %s(Class clazz)/*-{", registerMethodName));
        sw.indent();
        sw.println("var closure = this;");
        sw.println(String.format("var fn = function() {", qualifiedImplName));
        sw.indent();
        sw.println(String.format("return closure.@%s::%s()();", qualifiedImplName, createMethodName));
        sw.outdent();
        sw.println("};");
        sw.println(String.format("this.@%s::createLookup.set(clazz,fn);", qualifiedImplName));
        sw.outdent();
        sw.println("}-*/;");
        sw.println();
        methodCount++;
    }
    sw.println("private native void initCreateLookup0()/*-{");
    sw.indent();
    sw.println(String.format("this.@%s::createLookup = new Map();", qualifiedImplName));
    sw.outdent();
    sw.println("}-*/;");
    sw.println();
    sw.println("protected void initReflector(Class clazz) {");
    sw.indent();
    sw.println("switch(clazz.getName()){");
    sw.indent();
    initClassMethodNames.entrySet().forEach(e -> {
        sw.println("case \"%s\":", e.getKey().getQualifiedBinaryName());
        sw.indent();
        sw.println("%s();", e.getValue());
        sw.println("break;");
        sw.outdent();
    });
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");
    sw.println();
    sw.println("protected void initialiseNewInstance(Class clazz) {");
    sw.indent();
    sw.println("switch(clazz.getName()){");
    sw.indent();
    initNewInstanceNames.entrySet().forEach(e -> {
        sw.println("case \"%s\":", e.getKey().getQualifiedBinaryName());
        sw.indent();
        sw.println("%s", e.getValue());
        sw.println("break;");
        sw.outdent();
    });
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");
    sw.println();
    sw.println("private void init() {");
    sw.indent();
    sw.println("initCreateLookup0();");
    for (JClassType t : allTypes) {
        if (!filter.omitForModule(t, ReflectionAction.NEW_INSTANCE)) {
            sw.println(String.format("forNameMap.put(\"%s\",%s.class);", t.getQualifiedBinaryName(),
                    t.getQualifiedSourceName()));
        }
    }
    sw.println("");
    sw.println("//init registry");
    sw.println("");
    for (JClassType clazz : gwtRegisteringClasses.keySet()) {
        for (RegistryLocation l : gwtRegisteringClasses.get(clazz)) {
            StringBuffer sb = new StringBuffer();
            writeAnnImpl(l, ann2impl, 0, false, sb, false);
            sw.println(
                    String.format("Registry.get().register(%s.class,%s);", clazz.getQualifiedSourceName(), sb));
        }
    }
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");
}

From source file:com.github.nmorel.gwtjackson.rebind.bean.BeanProcessor.java

License:Apache License

/**
 * Look for the method to create a new instance of the bean. If none are found or the bean is abstract or an interface, we considered it
 * as non instantiable./*from  w ww .j  a  va 2 s  .co m*/
 *
 * @param typeOracle the oracle
 * @param logger logger
 * @param beanType type to look for constructor
 * @param builder current bean builder
 */
private static void determineInstanceCreator(RebindConfiguration configuration, JacksonTypeOracle typeOracle,
        TreeLogger logger, JClassType beanType, BeanInfoBuilder builder) {
    if (isObjectOrSerializable(beanType)) {
        return;
    }

    Optional<JClassType> mixinClass = configuration.getMixInAnnotations(beanType);

    List<JClassType> accessors = new ArrayList<JClassType>();
    if (mixinClass.isPresent()) {
        accessors.add(mixinClass.get());
    }
    accessors.add(beanType);

    // Look for a builder class
    Optional<Annotation> jsonDeserialize = CreatorUtils
            .getAnnotation("com.fasterxml.jackson.databind.annotation.JsonDeserialize", accessors);
    if (jsonDeserialize.isPresent()) {
        Optional<JClassType> builderClass = typeOracle.getClassFromJsonDeserializeAnnotation(logger,
                jsonDeserialize.get(), "builder");
        if (builderClass.isPresent()) {
            builder.setBuilder(builderClass.get());
            return;
        }
    }

    // we search for @JsonCreator annotation
    JConstructor creatorDefaultConstructor = null;
    JConstructor creatorConstructor = null;

    // we keep the list containing the mixin creator and the real creator
    List<? extends JAbstractMethod> creators = Collections.emptyList();

    if (null == beanType.isInterface() && !beanType.isAbstract()) {
        for (JConstructor constructor : beanType.getConstructors()) {
            if (constructor.getParameters().length == 0) {
                creatorDefaultConstructor = constructor;
                continue;
            }

            // A constructor is considered as a creator if
            // - he is annotated with JsonCreator and
            //   * all its parameters are annotated with JsonProperty
            //   * or it has only one parameter
            // - or all its parameters are annotated with JsonProperty

            List<JConstructor> constructors = new ArrayList<JConstructor>();
            if (mixinClass.isPresent() && null == mixinClass.get().isInterface()) {
                JConstructor mixinConstructor = mixinClass.get()
                        .findConstructor(constructor.getParameterTypes());
                if (null != mixinConstructor) {
                    constructors.add(mixinConstructor);
                }
            }
            constructors.add(constructor);

            Optional<JsonIgnore> jsonIgnore = getAnnotation(JsonIgnore.class, constructors);
            if (jsonIgnore.isPresent() && jsonIgnore.get().value()) {
                continue;
            }

            boolean isAllParametersAnnotatedWithJsonProperty = isAllParametersAnnotatedWith(constructors.get(0),
                    JsonProperty.class);
            if ((isAnnotationPresent(JsonCreator.class, constructors)
                    && ((isAllParametersAnnotatedWithJsonProperty)
                            || (constructor.getParameters().length == 1)))
                    || isAllParametersAnnotatedWithJsonProperty) {
                creatorConstructor = constructor;
                creators = constructors;
                break;
            }
        }
    }

    JMethod creatorFactory = null;
    if (null == creatorConstructor) {
        // searching for factory method
        for (JMethod method : beanType.getMethods()) {
            if (method.isStatic()) {

                List<JMethod> methods = new ArrayList<JMethod>();
                if (mixinClass.isPresent() && null == mixinClass.get().isInterface()) {
                    JMethod mixinMethod = mixinClass.get().findMethod(method.getName(),
                            method.getParameterTypes());
                    if (null != mixinMethod && mixinMethod.isStatic()) {
                        methods.add(mixinMethod);
                    }
                }
                methods.add(method);

                Optional<JsonIgnore> jsonIgnore = getAnnotation(JsonIgnore.class, methods);
                if (jsonIgnore.isPresent() && jsonIgnore.get().value()) {
                    continue;
                }

                if (isAnnotationPresent(JsonCreator.class, methods) && (method.getParameters().length == 1
                        || isAllParametersAnnotatedWith(methods.get(0), JsonProperty.class))) {
                    creatorFactory = method;
                    creators = methods;
                    break;
                }
            }
        }
    }

    final Optional<JAbstractMethod> creatorMethod;
    boolean defaultConstructor = false;

    if (null != creatorConstructor) {
        creatorMethod = Optional.<JAbstractMethod>of(creatorConstructor);
    } else if (null != creatorFactory) {
        creatorMethod = Optional.<JAbstractMethod>of(creatorFactory);
    } else if (null != creatorDefaultConstructor) {
        defaultConstructor = true;
        creatorMethod = Optional.<JAbstractMethod>of(creatorDefaultConstructor);
    } else {
        creatorMethod = Optional.absent();
    }

    builder.setCreatorMethod(creatorMethod);
    builder.setCreatorDefaultConstructor(defaultConstructor);

    if (creatorMethod.isPresent() && !defaultConstructor) {
        if (creatorMethod.get().getParameters().length == 1
                && !isAllParametersAnnotatedWith(creators.get(0), JsonProperty.class)) {
            // delegation constructor
            builder.setCreatorDelegation(true);
            builder.setCreatorParameters(ImmutableMap.of(BeanJsonDeserializerCreator.DELEGATION_PARAM_NAME,
                    creatorMethod.get().getParameters()[0]));
        } else {
            // we want the property name define in the mixin and the parameter defined in the real creator method
            ImmutableMap.Builder<String, JParameter> creatorParameters = ImmutableMap.builder();
            for (int i = 0; i < creatorMethod.get().getParameters().length; i++) {
                creatorParameters.put(
                        creators.get(0).getParameters()[i].getAnnotation(JsonProperty.class).value(),
                        creators.get(creators.size() - 1).getParameters()[i]);
            }
            builder.setCreatorParameters(creatorParameters.build());
        }
    }
}

From source file:com.github.nmorel.gwtjackson.rebind.property.PropertyParser.java

License:Apache License

private static void parseMethods(TreeLogger logger, JClassType type,
        Map<String, PropertyAccessorsBuilder> propertiesMap, boolean mixin) {
    for (JMethod method : type.getMethods()) {
        if (null != method.isConstructor() || method.isStatic()
                || (type.getQualifiedSourceName().equals("java.lang.Object")
                        && method.getName().equals("getClass"))) {
            continue;
        }/*from   w  ww.j  a v  a2s.  co  m*/

        if (method.getParameters().length == 0) {
            // might be a getter
            String fieldName = extractFieldNameFromGetterSetterMethodName(method.getName());
            PropertyAccessorsBuilder property = propertiesMap.get(fieldName);
            if (null == property) {
                property = new PropertyAccessorsBuilder(fieldName);
                propertiesMap.put(fieldName, property);
            }
            property.addGetter(method, mixin);
        } else if (method.getParameters().length == 1
                || (method.getParameters().length == 2 && method.isAnnotationPresent(JsonAnySetter.class))) {
            // might be a setter
            String fieldName = extractFieldNameFromGetterSetterMethodName(method.getName());
            PropertyAccessorsBuilder property = propertiesMap.get(fieldName);
            if (null == property) {
                property = new PropertyAccessorsBuilder(fieldName);
                propertiesMap.put(fieldName, property);
            }
            property.addSetter(method, mixin);
        }
    }
}

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

License:Apache License

/**
 * Search a static method or constructor to instantiate the mapper and return a {@link String} calling it.
 *//*from w  w  w. j  a v  a 2 s . c o  m*/
private MapperInstance getInstance(JType mappedType, JClassType classType, boolean isSerializers) {
    int nbParam = 0;
    if (null != mappedType.isGenericType() && (!isSerializers || !typeOracle.isEnumSupertype(mappedType))) {
        nbParam = mappedType.isGenericType().getTypeParameters().length;
    }

    // we first look at static method
    for (JMethod method : classType.getMethods()) {
        // method must be public static, return the instance type and take no parameters
        if (method.isStatic() && null != method.getReturnType().isClassOrInterface()
                && classType.isAssignableTo(method.getReturnType().isClassOrInterface())
                && method.getParameters().length == nbParam && method.isPublic()) {
            MapperType[] parameters = getParameters(mappedType, method, isSerializers);
            if (null == parameters) {
                continue;
            }

            return new MapperInstance(classType, method, parameters);
        }
    }

    // then we search the default constructor
    for (JConstructor constructor : classType.getConstructors()) {
        if (constructor.isPublic() && constructor.getParameters().length == nbParam) {
            MapperType[] parameters = getParameters(mappedType, constructor, isSerializers);
            if (null == parameters) {
                continue;
            }

            return new MapperInstance(classType, constructor, parameters);
        }
    }

    logger.log(Type.WARN, "Cannot instantiate the custom serializer/deserializer "
            + classType.getQualifiedSourceName() + ". It will be ignored");
    return null;
}

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

License:Apache License

/**
 * Search a static method or constructor to instantiate the key mapper and return a {@link String} calling it.
 *///  ww w  .  j a v  a2s.c om
private MapperInstance getKeyInstance(JType mappedType, JClassType classType, boolean isSerializers) {
    int nbParam = 0;
    if (!isSerializers && typeOracle.isEnumSupertype(mappedType)) {
        nbParam = 1;
    }

    // we first look at static method
    for (JMethod method : classType.getMethods()) {
        // method must be public static, return the instance type and take no parameters
        if (method.isStatic() && null != method.getReturnType().isClassOrInterface()
                && classType.isAssignableTo(method.getReturnType().isClassOrInterface())
                && method.getParameters().length == nbParam && method.isPublic()) {
            MapperType[] parameters = getParameters(mappedType, method, isSerializers);
            if (null == parameters) {
                continue;
            }

            return new MapperInstance(classType, method, parameters);
        }
    }

    // then we search the default constructor
    for (JConstructor constructor : classType.getConstructors()) {
        if (constructor.isPublic() && constructor.getParameters().length == nbParam) {
            MapperType[] parameters = getParameters(mappedType, constructor, isSerializers);
            if (null == parameters) {
                continue;
            }

            return new MapperInstance(classType, constructor, parameters);
        }
    }

    logger.log(Type.WARN, "Cannot instantiate the custom key serializer/deserializer "
            + classType.getQualifiedSourceName() + ". It will be ignored");
    return null;
}

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

License:Apache License

/**
 * Find <code>Object __intercept(AutoBean&lt;?> bean, Object value);</code> in
 * the category types.//from w w w.  j a v a  2 s  . c o  m
 */
private JMethod findInterceptor(JClassType beanType) {
    if (categoryTypes == null) {
        return null;
    }
    for (JClassType category : categoryTypes) {
        for (JMethod method : category.getOverloads("__intercept")) {
            // Ignore non-static, non-public methods
            // TODO: Implement visibleFrom() to allow package-protected categories
            if (!method.isStatic() || !method.isPublic()) {
                continue;
            }

            JParameter[] params = method.getParameters();
            if (params.length != 2) {
                continue;
            }
            if (!methodAcceptsAutoBeanAsFirstParam(beanType, method)) {
                continue;
            }
            JClassType value = params[1].getType().isClassOrInterface();
            if (value == null) {
                continue;
            }
            if (!oracle.getJavaLangObject().isAssignableTo(value)) {
                continue;
            }
            return method;
        }
    }
    return null;
}

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

License:Apache License

/**
 * Search the category types for a static implementation of an interface
 * method. Given the interface method declaration:
 * //from w  w w.  jav  a 2  s.  com
 * <pre>
 * Foo bar(Baz baz);
 * </pre>
 * 
 * this will search the types in {@link #categoryTypes} for the following
 * method:
 * 
 * <pre>
 * public static Foo bar(AutoBean&lt;Intf> bean, Baz baz) {}
 * </pre>
 */
private JMethod findStaticImpl(JClassType beanType, JMethod method) {
    if (categoryTypes == null) {
        return null;
    }

    for (JClassType category : categoryTypes) {
        // One extra argument for the AutoBean
        JParameter[] methodParams = method.getParameters();
        int requiredArgs = methodParams.length + 1;
        overload: for (JMethod overload : category.getOverloads(method.getName())) {
            if (!overload.isStatic() || !overload.isPublic()) {
                // Ignore non-static, non-public methods
                continue;
            }

            JParameter[] overloadParams = overload.getParameters();
            if (overloadParams.length != requiredArgs) {
                continue;
            }

            if (!methodAcceptsAutoBeanAsFirstParam(beanType, overload)) {
                // Ignore if the first parameter is a primitive or not assignable
                continue;
            }

            // Match the rest of the parameters
            for (int i = 1; i < requiredArgs; i++) {
                JType methodType = methodParams[i - 1].getType();
                JType overloadType = overloadParams[i].getType();
                if (methodType.equals(overloadType)) {
                    // Match; exact, the usual case
                } else if (methodType.isClassOrInterface() != null && overloadType.isClassOrInterface() != null
                        && methodType.isClassOrInterface().isAssignableTo(overloadType.isClassOrInterface())) {
                    // Match; assignment-compatible
                } else {
                    // No match, keep looking
                    continue overload;
                }
            }
            return overload;
        }
    }
    return null;
}

From source file:com.googlecode.gwtx.rebind.PropertyDescriptorsGenerator.java

License:Apache License

/**
 * Lookup any public method in the type to match JavaBeans accessor convention
 * @param type/*from  ww  w.  j  ava  2s  . c  o m*/
 * @return Collection of javabean properties
 */
protected Collection<Property> lookupJavaBeanPropertyAccessors(TreeLogger logger, JClassType type) {
    Map<String, Property> properties = new HashMap<String, Property>();

    JMethod[] methods = type.getMethods();
    for (JMethod method : methods) {
        if (!method.isPublic() || method.isStatic()) {
            continue;
        }
        if (method.getName().startsWith("set") && method.getParameters().length == 1) {
            String name = Introspector.decapitalize(method.getName().substring(3));
            String propertyType = null;
            JParameter[] parameters = method.getParameters();
            if (parameters.length == 1) {
                JParameter parameter = parameters[0];
                propertyType = parameter.getType().getErasedType().getQualifiedSourceName();
            } else {
                logger.log(Type.WARN, "Property '" + name + "' has " + parameters.length + " parameters: "
                        + parameters + "!");
                continue;
            }
            Property property = properties.get(name);
            if (property == null) {
                property = new Property(name);
                properties.put(name, property);
            }
            property.setter = method;
            if (property.propertyType == null) {
                property.propertyType = propertyType;
            } else if (!property.propertyType.equals(propertyType)) {
                logger.log(Type.WARN, "Property '" + name + "' has an invalid setter: " + propertyType
                        + " was expected, " + property.propertyType + " found!");
                continue;
            }
        } else if (method.getName().startsWith("get") && method.getParameters().length == 0) {
            String name = Introspector.decapitalize(method.getName().substring(3));
            String propertyType = method.getReturnType().getErasedType().getQualifiedSourceName();
            Property property = properties.get(name);
            if (property == null) {
                property = new Property(name);
                properties.put(name, property);
            }
            property.getter = method;
            if (property.propertyType == null) {
                property.propertyType = propertyType;
            } else if (!property.propertyType.equals(propertyType)) {
                logger.log(Type.WARN, "Property '" + name + "' has an invalid getter: " + propertyType
                        + " was expected, " + property.propertyType + " found!");
                continue;
            }
        } else if (method.getName().startsWith("is") && method.getParameters().length == 0) {
            String name = Introspector.decapitalize(method.getName().substring(2));
            String propertyType = method.getReturnType().getErasedType().getQualifiedSourceName();
            Property property = properties.get(name);
            if (property == null) {
                property = new Property(name);
                properties.put(name, property);
            }
            property.getter = method;
            if (property.propertyType == null) {
                property.propertyType = propertyType;
            } else if (!property.propertyType.equals(propertyType)) {
                logger.log(Type.WARN, "Property '" + name + "' has an invalid 'is' getter: " + propertyType
                        + " was expected, " + property.propertyType + " found!");
                continue;
            }
        }
    }
    return properties.values();
}

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

License:Apache License

protected void validateHandler(JMethod m, String name, String presenterName) throws UnableToCompleteException {
    if (m.isStatic()) {
        error("All event handlers must not be static. Found: %s.%s", presenterName, name);
    }//from  w w  w.  j a  va 2s.c  o m

    if (m.isPrivate()) {
        error("All event handlers must not be private. Found: %s.%s", presenterName, name);
    }

    JPrimitiveType returnTypePrimitive = m.getReturnType().isPrimitive();
    if (returnTypePrimitive == null || !returnTypePrimitive.equals(JPrimitiveType.VOID)) {
        error("All event handlers should return void. Found: %s.%s", presenterName, name);
    }
}

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

License:Apache License

public void init(JMethod method) throws UnableToCompleteException {

    functionName = method.getName();/* w ww .  j  ava2s  . c  o m*/
    isStatic = method.isStatic();

    JClassType classReturnType = method.getReturnType().isClassOrInterface();
    if (classReturnType != null && classReturnType == classCollection.stringClass) {
        returnString = true;
    } else {
        returnString = false;

        JPrimitiveType primitiveReturnType = method.getReturnType().isPrimitive();
        if (primitiveReturnType == null || primitiveReturnType != JPrimitiveType.VOID) {
            logger.log(TreeLogger.WARN,
                    "In presenter " + presenterInspector.getPresenterClassName() + ", method " + functionName
                            + " annotated with @" + TitleFunction.class.getSimpleName()
                            + " returns something else than void or String. "
                            + "Return value will be ignored and void will be assumed.");
        }
    }

    int i = 0;
    for (JParameter parameter : method.getParameters()) {
        JClassType parameterType = parameter.getType().isClassOrInterface();
        if (parameterType.isAssignableFrom(ginjectorInspector.getGinjectorClass())
                && gingectorParamIndex == -1) {
            gingectorParamIndex = i;
        } else if (parameterType.isAssignableFrom(classCollection.placeRequestClass)
                && placeRequestParamIndex == -1) {
            placeRequestParamIndex = i;
        } else if (parameterType.isAssignableFrom(classCollection.setPlaceTitleHandlerClass)
                && setPlaceTitleHandlerParamIndex == -1) {
            setPlaceTitleHandlerParamIndex = i;
        } else {
            logger.log(TreeLogger.ERROR, "In presenter " + presenterInspector.getPresenterClassName()
                    + ", in method " + functionName + " annotated with @" + TitleFunction.class.getSimpleName()
                    + ", parameter " + i + " is invalid. Method can have at most one parameter of type "
                    + ginjectorInspector.getGinjectorClassName() + ", " + ClassCollection.placeRequestClassName
                    + " or " + ClassCollection.setPlaceTitleHandlerClassName);
            throw new UnableToCompleteException();
        }
        i++;
    }

    if (returnString && setPlaceTitleHandlerParamIndex != -1) {
        logger.log(TreeLogger.ERROR,
                "In presenter " + presenterInspector.getPresenterClassName() + ", the method " + functionName
                        + " annotated with @" + TitleFunction.class.getSimpleName()
                        + " returns a string and accepts a " + ClassCollection.setPlaceTitleHandlerClassName
                        + " parameter. This is not supported, you can have only one or the other.");
        throw new UnableToCompleteException();
    }

    if (!returnString && setPlaceTitleHandlerParamIndex == -1) {
        logger.log(TreeLogger.ERROR, "In presenter " + presenterInspector.getPresenterClassName()
                + ", the method " + functionName + " annotated with @" + TitleFunction.class.getSimpleName()
                + " doesn't return a string and doesn't accept a "
                + ClassCollection.setPlaceTitleHandlerClassName + " parameter. You need one or the other.");
        throw new UnableToCompleteException();
    }
}