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

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

Introduction

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

Prototype

boolean isAnnotationPresent(Class<? extends Annotation> annotationClass);

Source Link

Document

Returns true if this item has an annotation of the specified type.

Usage

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

License:Apache License

private void printProvidedFields(JClassType baseClass, HashMap<String, JType> validBindingFieldsTypes,
        SourceWriter writer, boolean fromPool, ArrayList<JField> fields) throws UnableToCompleteException {
    for (JField f : fields) {
        if (f.isAnnotationPresent(ViewField.class)) {
            String name = f.getAnnotation(ViewField.class).name();
            if (name.isEmpty()) {
                name = f.getName();/* w  ww .  ja  v a  2  s  . c  o  m*/
            }

            if (f.getAnnotation(ViewField.class).provided()) {
                if (!fromPool) {
                    // Sanity assert
                    writer.println("assert (" + validBindingFieldsTypes.get(name).getQualifiedSourceName()
                            + ")presenter." + f.getName()
                            + " != null: \"You forgot to provide the field, make sure it is not null. Found: "
                            + baseClass + "." + name + "\";");

                    writer.println(
                            "view." + name + " = (" + validBindingFieldsTypes.get(name).getQualifiedSourceName()
                                    + ")presenter." + f.getName() + ";");
                } else {
                    writer.println("presenter." + f.getName() + " = ("
                            + validBindingFieldsTypes.get(name).getQualifiedSourceName() + ")view." + name
                            + ";");
                }
            }
        }
    }
}

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

License:Apache License

private void checkForRepetition(JClassType presenterType) throws UnableToCompleteException {

    ArrayList<JField> superFields = new ArrayList<JField>();
    collectAllFields(presenterType.getSuperclass(), superFields);
    ArrayList<String> superFieldsNames = new ArrayList<String>();
    for (JField jField : superFields) {
        superFieldsNames.add(jField.getName());
    }//from   www.  j  a va  2 s.  c o m

    for (JField f : presenterType.getFields()) {
        if (f.isAnnotationPresent(ViewField.class) || f.getName().equals("driver")) {
            if (superFieldsNames.contains(f.getName())) {
                error("The field '" + f.getName()
                        + "' is already declared on a superclass, to fix delete the field. Found: "
                        + presenterType.getQualifiedSourceName());
            }
        }
    }
}

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  .jav  a2  s .  c o  m*/
            }

            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.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   ww  w.j a  va2 s.c  om
    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:fr.onevu.gwt.uibinder.rebind.model.OwnerClass.java

License:Apache License

/**
 * Scans the owner class to find all fields annotated with @UiField, and puts
 * them in {@link #uiFields} and {@link #uiFieldTypes}.
 * // ww  w.  jav  a 2 s .com
 * @param ownerType
 *          the type of the owner class
 */
private void findUiFields(JClassType ownerType) throws UnableToCompleteException {
    JField[] fields = ownerType.getFields();
    for (JField field : fields) {
        if (field.isAnnotationPresent(UiField.class)) {
            JClassType ownerFieldType = field.getType().isClassOrInterface();

            if (ownerFieldType == null) {
                logger.die("Field type is not a class in field " + field.getName());
            }

            OwnerField ownerField = new OwnerField(field, logger, context);
            String ownerFieldName = field.getName();

            uiFields.put(ownerFieldName, ownerField);
            uiFieldTypes.put(ownerFieldType, ownerField);
        }
    }

    // Recurse to superclass
    JClassType superclass = ownerType.getSuperclass();
    if (superclass != null) {
        findUiFields(superclass);
    }
}

From source file:org.gwtportlets.portlet.rebind.WidgetFactoryHelperCreator.java

License:Open Source License

private void findDoNotSendToServerFields(JClassType t, List<String> ans) {
    JClassType sup = t.getSuperclass();/*from w w w  . j  a  v a 2s.co m*/
    if (sup != typeOracle.getJavaLangObject()) {
        findDoNotSendToServerFields(sup, ans);
    }
    for (JField f : t.getFields()) {
        if (f.isPublic() && !f.isStatic() && !f.isTransient() && !f.isFinal()
                && f.isAnnotationPresent(DoNotSendToServer.class)) {
            StringBuffer s = new StringBuffer();
            s.append("((").append(t.getQualifiedSourceName()).append(")wf).").append(f.getName()).append(" = ");
            JType ft = f.getType();
            if (ft.isPrimitive() != null) {
                if (ft == JPrimitiveType.BOOLEAN) {
                    s.append("false;");
                } else {
                    s.append("0;");
                }
            } else {
                s.append("null;");
            }
            ans.add(s.toString());
        }
    }
}

From source file:org.jboss.errai.widgets.rebind.WidgetMappingsGenerator.java

License:Apache License

private void generateExtensions(GeneratorContext context, TreeLogger logger, SourceWriter sourceWriter) {
    // start constructor source generation
    sourceWriter.println("public " + className + "() { ");
    sourceWriter.println("}");

    sourceWriter.println("public void mapAll(final " + strTargetType + " widget) { ");
    sourceWriter.outdent();//from  w ww  . j  a va2  s . com

    try {
        JClassType widgetMapper = typeOracle.getType(CollectionWidgetMapper.class.getName());

        for (JField currField : targetClass.getFields()) {
            if (currField.isAnnotationPresent(WidgetMapper.class)
                    && widgetMapper.isAssignableFrom(currField.getType().isClassOrInterface())) {
                WidgetMapper mf = currField.getAnnotation(WidgetMapper.class);

                JField widgetField = targetClass.getField(mf.value());
                String varName = widgetField.getName() + "Mapper";

                JClassType binderField = currField.getType().isClassOrInterface();
                JParameterizedType pType = binderField.isParameterized();

                if (pType == null) {
                    RuntimeException e = new RuntimeException(
                            "Field '" + currField.getName() + "' must be parameterized");
                    logger.log(TreeLogger.Type.ERROR, e.getMessage(), e);
                    throw e;
                }

                // The last type arg shall always be our domain object type per this spec.
                JClassType jEntityTarget = pType.getTypeArgs()[pType.getTypeArgs().length - 1];
                String strTypeParms = generateTypeParmString(pType);

                List<JField> fieldsToMap = new LinkedList<JField>();

                /**
                 * If an EntityFields annotatio is present, then we discriminate on those fields.  Otherwise
                 * we capture all fields by default.
                 */
                if (currField.isAnnotationPresent(EntityFields.class)) {
                    EntityFields ef = currField.getAnnotation(EntityFields.class);
                    for (String fieldName : ef.value()) {
                        JField fld = jEntityTarget.getField(fieldName);
                        if (fld == null) {
                            RuntimeException e = new RuntimeException("no such field in entity class '"
                                    + jEntityTarget.getName() + "': " + fieldName);
                            logger.log(TreeLogger.Type.ERROR, e.getMessage(), e);
                            throw e;
                        }

                        fieldsToMap.add(jEntityTarget.getField(fieldName));
                    }
                } else {
                    for (JField fld : jEntityTarget.getFields()) {
                        if (fld.getEnclosingType().equals(jEntityTarget)) {
                            fieldsToMap.add(fld);
                        }
                    }
                }

                List<String> generatedInitializations = new LinkedList<String>();
                List<String> generatedBindings = new LinkedList<String>();

                FieldMapperGenerator g = getFieldMapper(widgetField.getType().getQualifiedSourceName());

                generatedInitializations.add(
                        g.init(typeOracle, widgetField, jEntityTarget, currField, null, varName, fieldsToMap));

                if (g == null) {
                    throw new RuntimeException(
                            "Cannot generateGetField mapper for widget: " + jEntityTarget.getName());
                }

                for (JField fld : fieldsToMap) {
                    String fieldName = fld.getName();

                    JField targetField = jEntityTarget.getField(fieldName);
                    if (targetField == null) {
                        throw new RuntimeException(
                                "The field '" + fieldName + "' does not correspond with a field in the class: "
                                        + jEntityTarget.getQualifiedSourceName());
                    }

                    generatedBindings.add(g.generateFieldMapperGenerator(typeOracle, widgetField, jEntityTarget,
                            null, targetField));
                }

                Map<String, Object> vars = new HashMap<String, Object>();
                vars.put("typeOracle", typeOracle);
                vars.put("variableName", varName);
                vars.put("strTypeParms", strTypeParms);
                vars.put("targetWidget", widgetField.getType().getQualifiedSourceName());
                vars.put("targetType", jEntityTarget.getQualifiedSourceName());
                vars.put("initializers", generatedInitializations);
                vars.put("bindings", generatedBindings);
                vars.put("targetFieldName", widgetField.getName());

                String s = (String) TemplateRuntime.execute(mappingsGen, vars);
                sourceWriter.print(s);

                s = "widget." + currField.getName() + " = " + varName + ";";

                sourceWriter.println(s);

            } else if (currField.isAnnotationPresent(EntityMapped.class)) {
                EntityMapped entityMappedA = currField.getAnnotation(EntityMapped.class);

                JClassType entityType = currField.getType().isClassOrInterface();
                String varName = currField.getName() + "Mapper";

                String entityFieldName = currField.getName();
                String toEntityField;

                Map<String, List<JField>> toBeMapped = new HashMap<String, List<JField>>();

                for (JField fld : targetClass.getFields()) {
                    if (fld.isAnnotationPresent(MapField.class)) {
                        MapField mapFieldA = fld.getAnnotation(MapField.class);
                        toEntityField = "".equals(mapFieldA.value()) ? entityFieldName : mapFieldA.value();

                        if (!toBeMapped.containsKey(toEntityField)) {
                            toBeMapped.put(toEntityField, new LinkedList<JField>());
                        }

                        toBeMapped.get(toEntityField).add(fld);
                    }
                }

                /**
                 * Generate the field mappings.
                 */
                for (Map.Entry<String, List<JField>> entry : toBeMapped.entrySet()) {
                    List<String> generatedInitializations = new LinkedList<String>();
                    List<String> generatedBindings = new LinkedList<String>();
                    ArrayList<String[]> fieldIndexPositions = new ArrayList<String[]>();

                    for (JField fld : entry.getValue()) {
                        JClassType classType = fld.getType().isClassOrInterface();

                        String fieldName = fld.getAnnotation(MapField.class).value();
                        if ("".equals(fieldName)) {
                            fieldName = fld.getName();
                        }

                        JField targetField = entityType.getField(fieldName);
                        if (targetField == null) {
                            throw new RuntimeException("The field '" + fieldName
                                    + "' does not correspond with a field in the class: "
                                    + entityType.getQualifiedSourceName());
                        }

                        JClassType targetFieldType = targetField.getType().isClassOrInterface();

                        FieldMapperGenerator g = getFieldMapper(classType.getQualifiedSourceName());

                        if (g == null) {
                            throw new RuntimeException(
                                    "Cannot generateGetField mapper for widget: " + classType.getName());
                        }

                        generatedInitializations
                                .add(g.init(typeOracle, fld, entityType, targetField, currField, null, null));

                        generatedBindings.add(g.generateFieldMapperGenerator(typeOracle, fld, entityType,
                                targetField, currField));

                        if (getType(typeOracle, Widget.class).isAssignableFrom(classType)) {
                            fieldIndexPositions
                                    .add(new String[] { fieldName, g.generateValueExtractorStatement(typeOracle,
                                            fld, entityType, targetField, currField) });
                        }
                    }

                    Map<String, Object> vars = new HashMap<String, Object>();
                    vars.put("typeOracle", typeOracle);
                    vars.put("variableName", varName);
                    vars.put("initializers", generatedInitializations);
                    vars.put("targetFieldName", entityFieldName);
                    vars.put("bindings", generatedBindings);
                    vars.put("fieldIndexPositions", fieldIndexPositions);
                    vars.put("entityFieldName", entityFieldName);

                    String s = (String) TemplateRuntime.execute(entityMappingGen, vars);

                    sourceWriter.print(s);
                }
            } else if (currField.isAnnotationPresent(AddAllTo.class)) {
                String copyToField = currField.getAnnotation(AddAllTo.class).value();
                String copyFromField = currField.getName();

                Map<String, Object> vars = new HashMap<String, Object>();
                vars.put("copyToField", copyToField);
                vars.put("copyFromField", copyFromField);

                String s = (String) TemplateRuntime.execute(addAllToGen, vars);

                sourceWriter.print(s);
            }
        }
    } catch (Exception e) {
        logger.log(TreeLogger.Type.ERROR, "failed to map field (does not exist)", e);
        e.printStackTrace();
    }

    // end constructor source generation
    sourceWriter.outdent();
    sourceWriter.println("}");
}