Example usage for com.google.gwt.core.ext.typeinfo JField isPublic

List of usage examples for com.google.gwt.core.ext.typeinfo JField isPublic

Introduction

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

Prototype

boolean isPublic();

Source Link

Usage

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

License:Apache License

private String createTypeGenerator(JType t) {
    buffer.setLength(0);/*w  w  w. j a v a2s  . c o  m*/
    String varName = "t";
    if (t instanceof JPrimitiveType)
        varName = "p";
    int id = nextId();
    typeNames2typeIds.put(t.getErasedType().getQualifiedSourceName(), id);
    pb("Type " + varName + " = new Type();");
    pb(varName + ".name = \"" + t.getErasedType().getQualifiedSourceName() + "\";");
    pb(varName + ".id = " + id + ";");
    pb(varName + ".clazz = " + t.getErasedType().getQualifiedSourceName() + ".class;");
    if (t instanceof JClassType) {
        JClassType c = (JClassType) t;
        if (isVisible(c.getSuperclass()))
            pb(varName + ".superClass = " + c.getSuperclass().getErasedType().getQualifiedSourceName()
                    + ".class;");
        if (c.getFlattenedSupertypeHierarchy() != null) {
            pb("Set<Class> " + varName + "Assignables = new HashSet<Class>();");
            for (JType i : c.getFlattenedSupertypeHierarchy()) {
                if (!isVisible(i))
                    continue;
                pb(varName + "Assignables.add(" + i.getErasedType().getQualifiedSourceName() + ".class);");
            }
            pb(varName + ".assignables = " + varName + "Assignables;");
        }
        if (c.isInterface() != null)
            pb(varName + ".isInterface = true;");
        if (c.isEnum() != null)
            pb(varName + ".isEnum = true;");
        if (c.isArray() != null)
            pb(varName + ".isArray = true;");
        if (c.isMemberType())
            pb(varName + ".isMemberClass = true;");
        pb(varName + ".isStatic = " + c.isStatic() + ";");
        pb(varName + ".isAbstract = " + c.isAbstract() + ";");

        if (c.getFields() != null) {
            pb(varName + ".fields = new Field[] {");
            for (JField f : c.getFields()) {
                String enclosingType = getType(c);
                String fieldType = getType(f.getType());
                int setter = nextId();
                int getter = nextId();
                String elementType = getElementTypes(f);
                String annotations = getAnnotations(f.getDeclaredAnnotations());

                pb("new Field(\"" + f.getName() + "\", " + enclosingType + ", " + fieldType + ", " + f.isFinal()
                        + ", " + f.isDefaultAccess() + ", " + f.isPrivate() + ", " + f.isProtected() + ", "
                        + f.isPublic() + ", " + f.isStatic() + ", " + f.isTransient() + ", " + f.isVolatile()
                        + ", " + getter + ", " + setter + ", " + elementType + ", " + annotations + "), ");

                SetterGetterStub stub = new SetterGetterStub();
                stub.name = f.getName();
                stub.enclosingType = enclosingType;
                stub.type = fieldType;
                stub.isStatic = f.isStatic();
                stub.isFinal = f.isFinal();
                if (enclosingType != null && fieldType != null) {
                    stub.getter = getter;
                    stub.setter = setter;
                }
                setterGetterStubs.add(stub);
            }
            pb("};");
        }

        printMethods(c, varName, "Method", c.getMethods());
        if (c.isPublic() && !c.isAbstract() && (c.getEnclosingType() == null || c.isStatic())) {
            printMethods(c, varName, "Constructor", c.getConstructors());
        } else {
            logger.log(Type.INFO, c.getName() + " can't be instantiated. Constructors not generated");
        }

        if (c.isArray() != null) {
            pb(varName + ".componentType = " + getType(c.isArray().getComponentType()) + ";");
        }
        if (c.isEnum() != null) {
            JEnumConstant[] enumConstants = c.isEnum().getEnumConstants();
            if (enumConstants != null) {
                pb(varName + ".enumConstants = new Object[" + enumConstants.length + "];");
                for (int i = 0; i < enumConstants.length; i++) {
                    pb(varName + ".enumConstants[" + i + "] = " + c.getErasedType().getQualifiedSourceName()
                            + "." + enumConstants[i].getName() + ";");
                }
            }
        }

        Annotation[] annotations = c.getDeclaredAnnotations();
        if (annotations != null && annotations.length > 0) {
            pb(varName + ".annotations = " + getAnnotations(annotations) + ";");
        }
    } else if (t.isAnnotation() != null) {
        pb(varName + ".isAnnotation = true;");
    } else {
        pb(varName + ".isPrimitive = true;");
    }

    pb("types.put(\"" + t.getErasedType().getQualifiedSourceName() + "\", " + varName + ");");
    return buffer.toString();
}

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

License:Apache License

private String createTypeGenerator(JType t) {
    buffer.setLength(0);//from  w w  w  .  j a  v  a 2  s. c  o m
    int id = nextTypeId++;
    typeNames2typeIds.put(t.getErasedType().getQualifiedSourceName(), id);
    JClassType c = t.isClass();

    String name = t.getErasedType().getQualifiedSourceName();
    String superClass = null;
    if (c != null && (isVisible(c.getSuperclass())))
        superClass = c.getSuperclass().getErasedType().getQualifiedSourceName() + ".class";
    String assignables = null;
    String interfaces = null;

    if (c != null && c.getFlattenedSupertypeHierarchy() != null) {
        assignables = "new HashSet<Class>(Arrays.asList(";
        boolean used = false;
        for (JType i : c.getFlattenedSupertypeHierarchy()) {
            if (!isVisible(i) || i.equals(t)
                    || "java.lang.Object".equals(i.getErasedType().getQualifiedSourceName()))
                continue;
            if (used)
                assignables += ", ";
            assignables += i.getErasedType().getQualifiedSourceName() + ".class";
            used = true;
        }
        if (used)
            assignables += "))";
        else
            assignables = null;
    }

    if (c == null) {
        // if it's not a class, it may be an interface instead
        c = t.isInterface();
    }

    if (c != null && c.getImplementedInterfaces() != null) {
        interfaces = "new HashSet<Class>(Arrays.asList(";
        boolean used = false;
        for (JType i : c.getImplementedInterfaces()) {
            if (!isVisible(i) || i.equals(t))
                continue;
            if (used)
                interfaces += ", ";
            interfaces += i.getErasedType().getQualifiedSourceName() + ".class";
            used = true;
        }
        if (used)
            interfaces += "))";
        else
            interfaces = null;
    }

    String varName = "c" + id;
    pb("private static Type " + varName + ";");
    pb("private static Type " + varName + "() {");
    pb("if(" + varName + "!=null) return " + varName + ";");
    pb(varName + " = new Type(\"" + name + "\", " + id + ", " + name + ".class, " + superClass + ", "
            + assignables + ", " + interfaces + ");");

    if (c != null) {
        if (c.isEnum() != null)
            pb(varName + ".isEnum = true;");
        if (c.isArray() != null)
            pb(varName + ".isArray = true;");
        if (c.isMemberType())
            pb(varName + ".isMemberClass = true;");
        if (c.isInterface() != null) {
            pb(varName + ".isInterface = true;");
        } else {
            pb(varName + ".isStatic = " + c.isStatic() + ";");
            pb(varName + ".isAbstract = " + c.isAbstract() + ";");
        }

        if (c.getFields() != null && c.getFields().length > 0) {
            pb(varName + ".fields = new Field[] {");
            for (JField f : c.getFields()) {
                String enclosingType = getType(c);
                String fieldType = getType(f.getType());
                int setterGetter = nextSetterGetterId++;
                String elementType = getElementTypes(f);
                String annotations = getAnnotations(f.getDeclaredAnnotations());

                pb("    new Field(\"" + f.getName() + "\", " + enclosingType + ", " + fieldType + ", "
                        + f.isFinal() + ", " + f.isDefaultAccess() + ", " + f.isPrivate() + ", "
                        + f.isProtected() + ", " + f.isPublic() + ", " + f.isStatic() + ", " + f.isTransient()
                        + ", " + f.isVolatile() + ", " + setterGetter + ", " + setterGetter + ", " + elementType
                        + ", " + annotations + "), ");

                SetterGetterStub stub = new SetterGetterStub();
                stub.name = f.getName();
                stub.enclosingType = enclosingType;
                stub.type = fieldType;
                stub.isStatic = f.isStatic();
                stub.isFinal = f.isFinal();
                if (enclosingType != null && fieldType != null) {
                    stub.getter = setterGetter;
                    stub.setter = setterGetter;
                }
                setterGetterStubs.add(stub);
            }
            pb("};");
        }

        createTypeInvokables(c, varName, "Method", c.getMethods());
        if (c.isPublic() && !c.isAbstract() && (c.getEnclosingType() == null || c.isStatic())) {
            createTypeInvokables(c, varName, "Constructor", c.getConstructors());
        } else {
            logger.log(Type.INFO, c.getName() + " can't be instantiated. Constructors not generated");
        }

        if (c.isArray() != null) {
            pb(varName + ".componentType = " + getType(c.isArray().getComponentType()) + ";");
        }
        if (c.isEnum() != null) {
            JEnumConstant[] enumConstants = c.isEnum().getEnumConstants();
            if (enumConstants != null) {
                pb(varName + ".enumConstants = new Object[" + enumConstants.length + "];");
                for (int i = 0; i < enumConstants.length; i++) {
                    pb(varName + ".enumConstants[" + i + "] = " + c.getErasedType().getQualifiedSourceName()
                            + "." + enumConstants[i].getName() + ";");
                }
            }
        }

        Annotation[] annotations = c.getDeclaredAnnotations();
        if (annotations != null && annotations.length > 0) {
            pb(varName + ".annotations = " + getAnnotations(annotations) + ";");
        }
    } else if (t.isAnnotation() != null) {
        pb(varName + ".isAnnotation = true;");
    } else {
        pb(varName + ".isPrimitive = true;");
    }

    pb("return " + varName + ";");
    pb("}");
    return buffer.toString();
}

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

License:Apache License

private static boolean isFieldAutoDetected(RebindConfiguration configuration,
        PropertyAccessors propertyAccessors, BeanInfo info) {
    if (!propertyAccessors.getField().isPresent()) {
        return false;
    }//from  w w w. j  a v a  2 s.com

    for (Class<? extends Annotation> annotation : AUTO_DISCOVERY_ANNOTATIONS) {
        if (propertyAccessors.isAnnotationPresentOnField(annotation)) {
            return true;
        }
    }

    JField field = propertyAccessors.getField().get();

    JsonAutoDetect.Visibility visibility = info.getFieldVisibility();
    if (Visibility.DEFAULT == visibility) {
        visibility = configuration.getDefaultFieldVisibility();
    }
    return isAutoDetected(visibility, field.isPrivate(), field.isProtected(), field.isPublic(),
            field.isDefaultAccess());
}

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

License:Apache License

/**
 * Finds the valid methods and check all the conventions.
 *//*  w w  w .j a v  a 2 s .  c  o m*/
protected void printEventBusBindingMethods(SourceWriter writer, JClassType presenterType)
        throws UnableToCompleteException {
    JPackage contextEventsPackage = getPackage(presenterType.getPackage().getName() + ".event");
    for (JMethod m : presenterType.getMethods()) {
        if (m.isAnnotationPresent(EventBusHandler.class)) {

            EventBusHandler eventBusHandler = m.getAnnotation(EventBusHandler.class);

            String name = m.getName();
            String presenterName = presenterType.getQualifiedSourceName();

            validateHandler(m, name, presenterName);

            // Find the event type
            JParameter[] parameters = m.getParameters();

            if (!name.startsWith("$") && !name.startsWith("eventBus$")) {
                error("Bad method name: %s on class: %s, the method should start with '$' or 'eventBus$'", name,
                        presenterName);
            }

            // Clean the name
            if (name.startsWith("$")) {
                name = name.substring(1); // Cut off the $
            } else {
                name = name.substring(9); // Cut off the eventBus$
            }

            JClassType eventType = getType(eventBusHandler.value().getCanonicalName());
            if (eventType.equals(gwtEventType)) {
                eventType = getEventByName(name, contextEventsPackage);
                if (eventType == null) {
                    error("There is no context, dom or shared event with the name '%s'. Binding method: '%s' in class: '%s'",
                            name, m.getName(), presenterType.getQualifiedSourceName());
                }
            }

            StringBuilder bindingParameters = new StringBuilder();
            ArrayList<String> parameterStrings = new ArrayList<String>();
            for (JParameter p : parameters) {
                String parameter = p.getName();

                if (bindingParameters.length() > 0) {
                    bindingParameters.append(", ");
                }

                int initlenght = bindingParameters.length();

                // Implicit cast
                bindingParameters
                        .append("(" + p.getType().getErasedType().getParameterizedQualifiedSourceName() + ")");

                String getter = "get";

                // Check if it is a boolean then the getter is 'is' not
                // 'get'
                JPrimitiveType parameterTypeIsPrimitive = p.getType().isPrimitive();
                if (parameterTypeIsPrimitive != null
                        && parameterTypeIsPrimitive.equals(JPrimitiveType.BOOLEAN)) {
                    getter = "is";
                }

                // Event getter binding
                if (parameter.indexOf("$") == -1) {
                    // Event binding
                    bindingParameters.append("event.");
                    bindingParameters.append(getter);
                    bindingParameters.append(capitalize(parameter));
                    bindingParameters.append("()");
                } else {
                    // Event binding nested binding
                    String[] parameterParts = parameter.split("[$]");

                    bindingParameters.append("event");
                    for (int n = 0; n < parameterParts.length - 1; n++) {
                        bindingParameters.append(".get");
                        bindingParameters.append(capitalize(parameterParts[n]));
                        bindingParameters.append("()");
                    }

                    bindingParameters.append(".");
                    bindingParameters.append(getter);
                    bindingParameters.append(capitalize(parameterParts[parameterParts.length - 1]));
                    bindingParameters.append("()");
                }

                parameterStrings.add(bindingParameters.substring(initlenght, bindingParameters.length()));
            }

            // Find the event name
            String simpleName = eventType.getSimpleSourceName();
            if (!simpleName.endsWith("Event")) {
                error("The event %s does not use the event convention. It should end with 'Event'",
                        eventType.getQualifiedSourceName());
            }
            String eventName = eventClassNameToEventName(simpleName);

            // Check that the name of the event correspond to the method
            // name convention
            if (!eventName.equals(name)) {
                error("The method %s on class %s does not use the event bus handler method convention. "
                        + "It should start with '$' or 'eventBus$' "
                        + "and end with the event name. i.e ValueChangeEvent -> $valueChange. Solve it renaming it to '$%s'",
                        m.getName(), presenterName, eventName);
            }

            // Get event handler name
            JClassType handlerType = getHandlerForEvent(eventType);
            if (handlerType == null) {
                error("Parameter '%s' is not an event (subclass of GwtEvent).", eventType.getName());
            }

            // Retrieves the single method (usually 'onSomething') related
            // to all
            // handlers. Ex: onClick in ClickHandler, onBlur in BlurHandler
            // ...
            JMethod[] methods = handlerType.getMethods();
            if (methods.length != 1) {
                error("'%s' has more than one method defined.", handlerType.getName());
            }

            // 'onSomething' method
            JMethod handlerOnMethod = methods[0];

            // Checks if the method has an Event as parameter. Ex:
            // ClickEvent in onClick, BlurEvent in onBlur ...
            parameters = handlerOnMethod.getParameters();
            if (parameters.length != 1) {
                error("Method '%s' needs '%s' as parameter", handlerOnMethod.getName(), eventType.getName());
            }

            writer.println("eventBusBindings.add(eventBus.addHandler(");

            writer.println(eventType.getQualifiedSourceName() + ".");

            // getType or TYPE ?
            JField typeField = eventType.getField("TYPE");
            if (typeField != null && typeField.isStatic() && typeField.isPublic()) {
                writer.println("TYPE");
            } else {
                writer.println("getType()");
            }
            writer.println(", ");

            writer.println("new " + handlerType.getQualifiedSourceName() + "() {");
            writer.indent();
            writer.println("public void " + handlerOnMethod.getName() + "(final "
                    + eventType.getQualifiedSourceName() + " event) {");
            writer.indent();

            // Process contributors
            String bindingParametersString = bindingParameters.toString();
            BinderContextImpl binderContext = processMethodContributors(presenterType, null, null, null, m,
                    eventType, parameterStrings.toArray(new String[parameterStrings.size()]));

            StringSourceWriter handlerWriter = new StringSourceWriter();

            handlerWriter
                    .println("if (" + LogConfiguration.class.getCanonicalName() + ".loggingIsEnabled()) {");
            handlerWriter.println(Logger.class.getCanonicalName() + ".getLogger(\"Binder\").info(\""
                    + binderContext.getLog() + "\");");
            handlerWriter.println("}");

            handlerWriter.println("presenter." + m.getName() + "(" + bindingParametersString + ");");

            writer.println(binderContext.build(handlerWriter));

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

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

License:Apache License

private void printViewBindingMethods(SourceWriter writer, JClassType presenterType, String viewTypeName,
        HashMap<String, JType> validBindingFieldsTypes) throws UnableToCompleteException {

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

    JPackage contextEventsPackage = getPackage(presenterType.getPackage().getName() + ".event");

    ArrayList<JMethod> methods = new ArrayList<JMethod>();
    findAllMethods(presenterType, methods);

    for (JMethod m : methods) {
        String name = m.getName();
        if (m.isAnnotationPresent(ViewHandler.class)) {
            validateHandler(m, name, presenterType.getQualifiedSourceName());

            String eventName;/*from  w  ww  .  j av  a2 s . c o  m*/
            ViewHandler viewHandlerAnnotation = m.getAnnotation(ViewHandler.class);
            JClassType eventType = getType(viewHandlerAnnotation.event().getCanonicalName());

            boolean fieldsAreElements = false;
            Set<String> bindingFields = null;
            boolean addHandlerToView = false;
            if (viewHandlerAnnotation.fields().length == 0) {
                if (name.startsWith("$")) {
                    // Direct view binding
                    eventName = name.substring(1);

                    addHandlerToView = true;
                } else {
                    // View fields binding
                    String[] nameParts = name.split("[$]");

                    // Check the name format
                    if (nameParts.length < 2) {
                        error("The method %s on the class %s have a bad binding format. It should be: "
                                + "'{viewField}${eventName}' or for binding multiple fields: '{viewField1}${viewField2}${eventName}'",
                                name, presenterType.getQualifiedSourceName());
                    }

                    // Check that the binding fields are valid
                    bindingFields = new HashSet<String>();
                    for (int n = 0; n < nameParts.length - 1; n++) {
                        if (!validBindingFields.contains(nameParts[n])) {
                            error("The field %s on the class %s is not a valid binding field. It must be public or protected and not static",
                                    nameParts[n], presenterType);
                        }
                        bindingFields.add(nameParts[n]);
                    }

                    eventName = nameParts[nameParts.length - 1]; // last
                    // token
                }

                // Check the event type and name convention
                if (eventType.equals(gwtEventType)) {
                    eventType = getEventByName(eventName, contextEventsPackage);
                    if (eventType == null) {
                        error("There is no context, dom or shared event with the name '%s'. Binding method: '%s' in class: '%s'",
                                eventName, name, presenterType.getQualifiedSourceName());
                    }
                } else {
                    // Check that the method name correspond to the event
                    // type
                    String eventNameToEventClassName = eventNameToEventClassName(eventName);
                    if (!eventNameToEventClassName.equals(eventType.getSimpleSourceName())) {
                        error("The method '%s' in the class '%s' have a typo in the name. The last token should be : ..$%s() {.. ",
                                name, presenterType.getQualifiedSourceName(), eventName);
                    }
                }
            } else {
                String[] fields = viewHandlerAnnotation.fields();
                bindingFields = new HashSet<String>();
                for (String f : fields) {
                    if (f.isEmpty()) {
                        addHandlerToView = true;
                    } else {
                        if (!validBindingFields.contains(f)) {
                            error("The field %s on the class %s is not a valid binding field. It must be public or protected and not static",
                                    f, presenterType);
                        }
                        bindingFields.add(f);
                    }
                }

                if (eventType.equals(gwtEventType)) {
                    error("When using ViewFields you must specify the event class in the Handler annotation. Found: %s.%s",
                            presenterType.getQualifiedSourceName(), name);
                }

                eventName = eventClassNameToEventName(eventType.getSimpleSourceName());
            }

            // If any field is an element all of them should be otherwise none
            // of them
            int widgetCount = 0;
            JClassType widgetJType = getType(Widget.class.getCanonicalName());
            JClassType isWidgetJType = getType(IsWidget.class.getCanonicalName());
            for (String f : bindingFields) {
                JClassType classOrInterface = validBindingFieldsTypes.get(f).isClassOrInterface();
                if (classOrInterface.isAssignableTo(widgetJType)
                        || classOrInterface.isAssignableTo(isWidgetJType)) {
                    widgetCount++;
                }
            }

            if (widgetCount != bindingFields.size() && widgetCount != 0) {
                error("Not all fields on the class %s.%s are either all elements or all widgets. You cannot bind elements and widgets on the same handler",
                        presenterType, name);
            }
            fieldsAreElements = widgetCount == 0;

            /**
             * Find parameters bindings. The binding can be with the event(cannot have anidation of
             * getters):'getter'->'getGetter()' or with the view:'$getter'->'view.getGetter()' or with a
             * view field '{viewField$getter}'->'view.viewField.getGetter();', this last two ones will
             * support anidation: '{viewField$getter$another}'->'view.viewField.getGetter().getAnother (
             * ) ; '
             **/
            StringBuilder bindingParameters = new StringBuilder();
            JParameter[] parameters = m.getParameters();
            ArrayList<String> parameterStrings = new ArrayList<String>();
            for (JParameter p : parameters) {
                String parameter = p.getName();
                JType parameterType = p.getType();
                if (bindingParameters.length() > 0) {
                    bindingParameters.append(", ");
                }

                int initlenght = bindingParameters.length();

                // Implicit cast
                bindingParameters.append(
                        "(" + parameterType.getErasedType().getParameterizedQualifiedSourceName() + ")");

                String getter = "get";

                // Check if it is a boolean then the getter is 'is' not
                // 'get'
                JPrimitiveType parameterTypeIsPrimitive = parameterType.isPrimitive();
                if (parameterTypeIsPrimitive != null
                        && parameterTypeIsPrimitive.equals(JPrimitiveType.BOOLEAN)) {
                    getter = "is";
                }

                if (p.getName().equals("event")) {
                    bindingParameters.append("event");
                } else if (p.isAnnotationPresent(Attribute.class)) {
                    // Only valid for domEvents
                    if (!eventType.isAssignableTo(hasNativeEventType)) {
                        error("Attributes binding are only valid for DomEvents. Found: %s.%s in parameter: %s",
                                presenterType.getQualifiedSourceName(), name, parameter);
                    }

                    String parameterTypeQualifiedSourceName = parameterType.getQualifiedSourceName();
                    boolean isString = parameterTypeQualifiedSourceName.equals(STRINGCANONICALNAME);
                    if (!isString) {
                        bindingParameters.append(parameterTypeQualifiedSourceName + ".valueOf(");
                    }
                    bindingParameters.append("((" + Element.class.getCanonicalName()
                            + ")event.getNativeEvent().getEventTarget().cast()).getAttribute(\"" + parameter
                            + "\")");
                    if (!isString) {
                        bindingParameters.append(")");
                    }
                } else if (parameter.indexOf("$") == -1) {
                    // Event binding
                    bindingParameters.append("event.");
                    bindingParameters.append(getter);
                    bindingParameters.append(capitalize(parameter));
                    bindingParameters.append("()");
                } else {
                    // Event binding nested binding
                    String[] parameterParts = parameter.split("[$]");

                    bindingParameters.append("event");
                    for (int n = 0; n < parameterParts.length - 1; n++) {
                        bindingParameters.append(".get");
                        bindingParameters.append(capitalize(parameterParts[n]));
                        bindingParameters.append("()");
                    }

                    bindingParameters.append(".");
                    bindingParameters.append(getter);
                    bindingParameters.append(capitalize(parameterParts[parameterParts.length - 1]));
                    bindingParameters.append("()");
                }

                parameterStrings.add(bindingParameters.substring(initlenght, bindingParameters.length()));
            }

            // Get event handler name
            JClassType handlerType = getHandlerForEvent(eventType);
            if (handlerType == null) {
                error("Parameter '%s' is not an event (subclass of GwtEvent).", eventType.getName());
            }

            // Retrieves the single method (usually 'onSomething') related
            // to all
            // handlers. Ex: onClick in ClickHandler, onBlur in BlurHandler
            // ...
            JMethod[] handlerMethods = handlerType.getMethods();
            if (handlerMethods.length != 1) {
                error("'%s' has more than one method defined.", handlerType.getName());
            }

            // 'onSomething' method
            JMethod handlerOnMethod = handlerMethods[0];

            String methodName = name;
            String handlerTypeName = handlerType.getQualifiedSourceName();

            GwtPresenter presenterAnnotation = presenterType.getAnnotation(GwtPresenter.class);
            boolean isElemental = presenterAnnotation != null && presenterAnnotation.elemental();

            // Write handler
            SourceWriter eventHandlerWriter = new StringSourceWriter();
            if (!fieldsAreElements) {
                eventHandlerWriter.println("new " + handlerTypeName + "() {");
                eventHandlerWriter.indent();
                eventHandlerWriter.println("public void " + handlerOnMethod.getName() + "(final "
                        + eventType.getQualifiedSourceName() + " event) {");
                eventHandlerWriter.indent();
            } else if (isElemental) {
                eventHandlerWriter.println("new elemental.events.EventListener() {");
                eventHandlerWriter.println("  @Override");
                eventHandlerWriter.println("  public void handleEvent(elemental.events.Event event) {");
            } else {
                eventHandlerWriter
                        .println("new " + com.guit.client.dom.EventHandler.class.getCanonicalName() + "() {");
                eventHandlerWriter.indent();
                eventHandlerWriter
                        .println("public void onEvent(" + Event.class.getCanonicalName() + " event_) {");
                eventHandlerWriter.println("  " + EventImpl.class.getCanonicalName() + " event = ("
                        + EventImpl.class.getCanonicalName() + ") event_;");
                eventHandlerWriter.indent();
            }

            String bindingParametersString = bindingParameters.toString();

            // Process contributors
            BinderContextImpl binderContext = processMethodContributors(presenterType, null, null, viewTypeName,
                    m, eventType, parameterStrings.toArray(new String[parameterStrings.size()]));

            StringSourceWriter handlerWriter = new StringSourceWriter();

            handlerWriter
                    .println("if (" + LogConfiguration.class.getCanonicalName() + ".loggingIsEnabled()) {");
            handlerWriter.println(Logger.class.getCanonicalName() + ".getLogger(\"Binder\").info(\""
                    + binderContext.getLog() + "\");");
            handlerWriter.println("}");

            handlerWriter.print("presenter." + methodName + "(");
            handlerWriter.print(bindingParametersString);
            handlerWriter.println(");");

            eventHandlerWriter.println(binderContext.build(handlerWriter));

            eventHandlerWriter.outdent();
            eventHandlerWriter.println("}");
            eventHandlerWriter.outdent();
            eventHandlerWriter.print("}");

            if (fieldsAreElements) {
                if (bindingFields != null) {
                    writer.print("final "
                            + (isElemental ? EventListener.class.getCanonicalName()
                                    : com.guit.client.dom.EventHandler.class.getCanonicalName())
                            + " " + methodName + "$" + eventName + " =");
                    writer.print(eventHandlerWriter.toString());
                    writer.println(";");

                    for (String f : bindingFields) {
                        String eventNameLower = eventName.toLowerCase();
                        boolean isTouchStart = eventNameLower.equals("touchstart");
                        boolean isTouchEnd = eventNameLower.equals("touchend");
                        if (isTouchStart || isTouchEnd) {
                            writer.println("if (com.google.gwt.event.dom.client.TouchEvent.isSupported()) {");
                        }
                        if (isElemental) {
                            writer.println("presenter." + f + ".setOn" + eventNameLower + "(" + methodName + "$"
                                    + eventName + ");");
                        } else {
                            writer.println("bindings.add(new " + ElementImpl.class.getCanonicalName() + "(view."
                                    + f + ")." + eventNameLower + "(" + methodName + "$" + eventName + "));");
                        }
                        if (isTouchStart || isTouchEnd) {
                            writer.println("} else {");

                            if (isElemental) {
                                writer.println("presenter." + f + ".setOnmouse" + (isTouchStart ? "down" : "up")
                                        + "(" + methodName + "$" + eventName + ");");
                            } else {
                                writer.println("bindings.add(new " + ElementImpl.class.getCanonicalName()
                                        + "(view." + f + ")." + (isTouchStart ? "mousedown" : "mouseup") + "("
                                        + methodName + "$" + eventName + "));");
                            }

                            writer.print("}");
                        }
                    }
                }
            } else if (viewHandlerAnnotation.force()) {
                String addMethodName = "addDomHandler";
                String eventTypeGetter = eventType.getQualifiedSourceName() + ".";
                JField typeField = eventType.getField("TYPE");
                if (typeField != null && typeField.isStatic() && typeField.isPublic()) {
                    eventTypeGetter += "TYPE";
                } else {
                    eventTypeGetter += "getType()";
                }
                if (bindingFields != null) {
                    writer.print("final " + handlerTypeName + " " + methodName + " =");
                    writer.print(eventHandlerWriter.toString());
                    writer.println(";");

                    for (String f : bindingFields) {
                        writer.println("bindings.add(view." + f + "." + addMethodName + "(" + methodName + ", "
                                + eventTypeGetter + "));");
                    }
                }

                if (addHandlerToView) {
                    writer.print("bindings.add(view." + addMethodName + "(" + eventHandlerWriter.toString()
                            + ", " + eventTypeGetter + "));");
                }
            } else {
                String addMethodName = "add" + eventName.substring(0, 1).toUpperCase() + eventName.substring(1)
                        + "Handler";
                if (bindingFields != null) {
                    writer.print("final " + handlerTypeName + " " + methodName + " =");
                    writer.print(eventHandlerWriter.toString());
                    writer.println(";");

                    for (String f : bindingFields) {

                        // Small patch for touch events
                        if (addMethodName.equals("addTouchStartHandler") && parameters.length == 0) {
                            writer.println("if (!com.google.gwt.event.dom.client.TouchEvent.isSupported()) {");
                            writer.println("bindings.add(view." + f + ".addMouseDownHandler(new "
                                    + MouseDownHandler.class.getCanonicalName() + "(){public void onMouseDown("
                                    + MouseDownEvent.class.getCanonicalName() + " event){presenter."
                                    + methodName + "();} }" + "));");
                            writer.println("}");
                        }

                        if (addMethodName.equals("addTouchEndHandler") && parameters.length == 0) {
                            writer.println("if (!com.google.gwt.event.dom.client.TouchEvent.isSupported()) {");
                            writer.println("bindings.add(view." + f + ".addMouseUpHandler(new "
                                    + MouseUpHandler.class.getCanonicalName() + "(){public void onMouseUp("
                                    + MouseUpEvent.class.getCanonicalName() + " event){presenter." + methodName
                                    + "();} }" + "));");
                            writer.println("}");
                        }
                        writer.println(
                                "bindings.add(view." + f + "." + addMethodName + "(" + methodName + "));");
                    }
                }

                if (addHandlerToView) {
                    writer.print(
                            "bindings.add(view." + addMethodName + "(" + eventHandlerWriter.toString() + "));");
                }
            }
        } else {
            for (Annotation a : m.getAnnotations()) {
                Class<? extends Annotation> annotationType = a.annotationType();
                if (annotationType.isAnnotationPresent(Plugin.class)) {
                    String[] nameParts = name.split("[$]");

                    // Check that the binding fields are valid
                    StringBuilder fields = new StringBuilder();
                    for (int n = 0; n < nameParts.length - 1; n++) {
                        if (!validBindingFields.contains(nameParts[n])) {
                            error("The field %s on the class %s is not a valid binding field. It must be public or protected and not static",
                                    nameParts[n], presenterType);
                        }
                        if (fields.length() > 0) {
                            fields.append(",");
                        }
                        fields.append("view." + nameParts[n]);
                    }

                    Class<?> handler = annotationType.getAnnotation(Plugin.class).value();
                    writer.println("new " + handler.getCanonicalName()
                            + "().install(new com.google.gwt.user.client.Command() {");
                    writer.println("@Override");
                    writer.println("public void execute() {");
                    writer.println("  presenter." + m.getName() + "();");
                    writer.println("}");
                    writer.println("}, new Object[]{");
                    writer.println(fields.toString() + "});");
                }
            }
        }
    }
}

From source file:com.hiramchirino.restygwt.rebind.JsonEncoderDecoderClassCreator.java

License:Apache License

public void generate() throws UnableToCompleteException {

    locator = new JsonEncoderDecoderInstanceLocator(context, logger);

    JClassType soruceClazz = source.isClass();
    if (soruceClazz == null) {
        error("Type is not a class");
    }/*from  w w  w. j  a  va 2 s  .  co m*/
    if (!soruceClazz.isDefaultInstantiable()) {
        error("No default constuctor");
    }

    Json jsonAnnotation = source.getAnnotation(Json.class);
    final Style classStyle = jsonAnnotation != null ? jsonAnnotation.style() : Style.DEFAULT;

    p();
    p("public static final " + shortName + " INSTANCE = new " + shortName + "();");
    p();

    p("public " + JSON_VALUE_CLASS + " encode(" + source.getParameterizedQualifiedSourceName() + " value) {")
            .i(1);
    {
        p(JSON_OBJECT_CLASS + " rc = new " + JSON_OBJECT_CLASS + "();");

        for (final JField field : getFields(source)) {

            final String getterName = getGetterName(field);

            // If can ignore some fields right off the back..
            if (getterName == null && (field.isStatic() || field.isFinal() || field.isTransient())) {
                continue;
            }

            branch("Processing field: " + field.getName(), new Branch<Void>() {
                public Void execute() throws UnableToCompleteException {
                    // TODO: try to get the field with a setter or JSNI
                    if (getterName != null || field.isDefaultAccess() || field.isProtected()
                            || field.isPublic()) {

                        String name = field.getName();

                        String fieldExpr = "value." + name;
                        if (getterName != null) {
                            fieldExpr = "value." + getterName + "()";
                        }

                        Json jsonAnnotation = field.getAnnotation(Json.class);
                        Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;

                        String expression = locator.encodeExpression(field.getType(), fieldExpr, style);

                        p("{").i(1);
                        {
                            p(JSON_VALUE_CLASS + " v=" + expression + ";");
                            p("if( v!=null ) {").i(1);
                            {
                                if (field.isAnnotationPresent(ExcludeNull.class))
                                    p("if (v != " + JSONNull.class.getCanonicalName() + ".getInstance())");
                                p("rc.put(" + wrap(name) + ", v);");
                            }
                            i(-1).p("}");
                        }
                        i(-1).p("}");

                    } else {
                        error("field must not be private: " + field.getEnclosingType().getQualifiedSourceName()
                                + "." + field.getName());
                    }
                    return null;
                }
            });

        }

        p("return rc;");
    }
    i(-1).p("}");
    p();
    p("public " + source.getName() + " decode(" + JSON_VALUE_CLASS + " value) {").i(1);
    {
        p(JSON_OBJECT_CLASS + " object = toObject(value);");
        p("" + source.getParameterizedQualifiedSourceName() + " rc = new "
                + source.getParameterizedQualifiedSourceName() + "();");
        for (final JField field : getFields(source)) {

            final String setterName = getSetterName(field);

            // If can ignore some fields right off the back..
            if (setterName == null && (field.isStatic() || field.isFinal() || field.isTransient())) {
                continue;
            }

            branch("Processing field: " + field.getName(), new Branch<Void>() {
                public Void execute() throws UnableToCompleteException {

                    // TODO: try to set the field with a setter or JSNI
                    if (setterName != null || field.isDefaultAccess() || field.isProtected()
                            || field.isPublic()) {

                        Json jsonAnnotation = field.getAnnotation(Json.class);
                        Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;

                        String name = field.getName();
                        String expression = locator.decodeExpression(field.getType(),
                                "object.get(" + wrap(name) + ")", style);

                        if (setterName != null) {
                            p("rc." + setterName + "(" + expression + ");");
                        } else {
                            p("rc." + name + "=" + expression + ";");
                        }

                    } else {
                        error("field must not be private.");
                    }
                    return null;
                }
            });
        }

        p("return rc;");
    }
    i(-1).p("}");
    p();
}

From source file:com.sencha.gxt.core.rebind.Context.java

License:sencha.com license

public Context(Context parent, String childDeref, JType childType) {
    this.parent = parent;
    this.knownValues = new HashMap<String, JType>();
    setCountVar(parent.countVar);/*from   w ww.  jav  a 2 s. c  om*/

    scopedVarDeref = childDeref;
    scopedVarType = childType;
    if (childType.isClassOrInterface() != null) {
        for (JMethod m : childType.isClassOrInterface().getInheritableMethods()) {
            if (m.getParameters().length != 0) {
                continue;
            }
            knownValues.put(m.getName(), m.getReturnType());
            final String prop;
            if (m.getName().startsWith("get") && m.getName().length() > "get".length()) {
                prop = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4);
            } else if (m.getName().startsWith("is") && m.getName().length() > "is".length()) {
                prop = m.getName().substring(2, 3).toLowerCase() + m.getName().substring(3);
            } else if (m.getName().startsWith("has") && m.getName().length() > "has".length()) {
                prop = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4);
            } else {
                continue;
            }
            knownValues.put(prop, m.getReturnType());
        }
        for (JClassType superType : childType.isClassOrInterface().getFlattenedSupertypeHierarchy()) {
            for (JField field : superType.isClassOrInterface().getFields()) {
                // only public fields
                if (!field.isPublic()) {
                    continue;
                }
                // let existing getters/setters declared above (and earlier fields) override (later) fields
                if (knownValues.containsKey(field.getName())) {
                    continue;
                }
                knownValues.put(field.getName(), field.getType());
            }
        }
    }

    localNames = null; // only global names for now
}

From source file:com.sencha.gxt.core.rebind.Context.java

License:sencha.com license

/**
 * Gets the type of content available at this path, within the current
 * context.//from w w w  .  j a  v  a 2 s .c  o m
 * 
 * @param localName the name of the content
 * @return the type of the content
 * @throws UnableToCompleteException if the type cannot be returned
 */
public JType getType(String localName) throws UnableToCompleteException {
    // magic vars (\\.|\\.\\.|#), illegal in other contexts
    if (localName.matches("^#$")) {// row number
        return getContext().getTypeOracle().findType("java.lang.Integer");
    } else if (localName.matches("^\\.\\.$")) {// parent
        return parent.getType(".");
    } else if (localName.matches("^\\.$")) {// this
        return scopedVarType;
    }

    // formats .*\\:(<format-name>?:(:(<format-params>))?)
    if (FORMAT_PATTERN.matcher(localName).matches()) {
        return getContext().getTypeOracle().findType("java.lang.String");
    }

    // look in local context
    String[] localPath = localName.split("\\.");
    if (knownValues.containsKey(localPath[0])) {
        // if we have the key, then run with it -
        JType type = knownValues.get(localPath[0]);
        for (int i = 1; i < localPath.length; i++) {
            JType nextType = null;
            JMethod[] possibleGetters = type.isClassOrInterface().getInheritableMethods();
            for (JMethod possible : possibleGetters) {
                // TODO this is wrong, if we intend to support getProperty() and
                // property(), and evaluate to the most specific method
                if (isMatchingGetter(possible, localPath[i])) {
                    nextType = possible.getReturnType();
                    break;
                }
            }

            if (nextType == null) {
                for (JClassType superType : type.isClassOrInterface().getFlattenedSupertypeHierarchy()) {
                    JField field = superType.isClassOrInterface().findField(localPath[i]);
                    if (field != null && field.isPublic()) {
                        nextType = field.getType();
                        break;
                    }
                }
            }
            type = nextType;
            if (type == null) {
                return null;
            }
        }
        return type;
    }

    // ask parent, if any
    if (!isRoot()) {
        JType possibleType = parent.getType(localName);
        if (possibleType != null) {
            return possibleType;
        }
    }

    // magic vars, only replace if they don't have other meaning
    if (localName.startsWith("parent") && !isRoot()) {
        if (localName.length() == "parent".length()) {
            return parent.getType(".");
        }
        if (localName.startsWith("parent.")) {
            return parent.getType(localName.substring("parent.".length()));
        }
    }
    if (localName.endsWith("count")) {
        return getContext().getTypeOracle().findType("java.lang.Integer");
    }

    // fail
    // TODO find a better way to end this recursive call - only fail locally
    return null;
}

From source file:com.sencha.gxt.data.rebind.ValueProviderCreator.java

License:sencha.com license

private JField getField(JClassType type, String p) {
    for (JClassType superType : type.getFlattenedSupertypeHierarchy()) {
        JField field = superType.findField(p);
        if (field != null && field.isPublic()) {
            return field;
        }/*from ww w . j a v  a 2  s. com*/
    }
    return null;
}

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

License:Apache License

private static List<JField> getPublicFields(JClassType type) {
    Set<String> names = new HashSet<String>();
    ArrayList<JField> fields = new ArrayList<JField>();
    for (JClassType subType : type.getFlattenedSupertypeHierarchy()) {
        JField[] subFields = subType.getFields();
        for (JField field : subFields) {
            if (field.isPublic() && !field.isStatic() && names.add(field.getName())) {
                fields.add(field);//  w w w  .  java 2  s  .  co  m
            }
        }
    }
    return fields;
}