List of usage examples for com.google.gwt.core.ext.typeinfo JType isPrimitive
JPrimitiveType isPrimitive();
From source file:com.ekuefler.supereventbus.rebind.EventRegistrationWriter.java
License:Apache License
private String getFirstParameterType(JMethod method) { // If the parameter type is primitive, box it JType type = method.getParameterTypes()[0]; if (type.isPrimitive() != null) { if (type.isPrimitive() == JPrimitiveType.BOOLEAN) { return Boolean.class.getName(); } else if (type.isPrimitive() == JPrimitiveType.BYTE) { return Byte.class.getName(); } else if (type.isPrimitive() == JPrimitiveType.CHAR) { return Character.class.getName(); } else if (type.isPrimitive() == JPrimitiveType.DOUBLE) { return Double.class.getName(); } else if (type.isPrimitive() == JPrimitiveType.FLOAT) { return Float.class.getName(); } else if (type.isPrimitive() == JPrimitiveType.INT) { return Integer.class.getName(); } else if (type.isPrimitive() == JPrimitiveType.LONG) { return Long.class.getName(); } else if (type.isPrimitive() == JPrimitiveType.SHORT) { return Short.class.getName(); }// www .java2s . co m } // Otherwise return the fully-qualified type name return type.getQualifiedSourceName(); }
From source file:com.github.ludorival.dao.gwt.rebind.EntityManagerGenerator.java
License:Apache License
private BeanMetadata create(GeneratorContext context, TreeLogger logger, String packageName, JClassType type, Class<?> classAdapter, IsEntity anno) throws TypeOracleException { String beanName = anno == null || anno.aliasName().isEmpty() ? type.getName() : anno.aliasName(); Source implementation = null; JClassType implType = type;//w w w . j a v a 2 s.c om TypeOracle typeOracle = context.getTypeOracle(); if (type.isInterface() != null) { implType = null; JClassType[] types = type.getSubtypes(); log(logger, Type.DEBUG, "Get all sub types of %s : %s", type, Arrays.toString(types)); if (types != null && types.length > 0) { for (JClassType jClassType : types) { if (isInstantiable(jClassType, logger)) { implType = jClassType; implementation = new Source(implType.getPackage().getName(), implType.getName()); break; } } } if (implType == null) { log(logger, Type.ERROR, "The type %s has not valid subtypes " + "%s !", type, Arrays.toString(types)); return null; } } if (!implType.isDefaultInstantiable()) return null; String prefix = classAdapter.getSimpleName().replace("Adapter", ""); boolean isEntity = anno != null; String className = prefix + beanName; if (parseOnlyInterface && implType != type) className += "Light"; PrintWriter writer = context.tryCreate(logger, packageName, className); if (writer == null) { return new BeanMetadata(type, className, implementation, isEntity); } ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, className); logger.log(Type.DEBUG, "Create Entity " + factory.getCreatedClassName()); factory.setSuperclass(classAdapter.getSimpleName() + "<" + type.getName() + ">"); factory.addImport(RuntimeException.class.getName()); factory.addImport(classAdapter.getName()); factory.addImport(type.getQualifiedSourceName()); if (isEntity) { factory.addImport(ArrayList.class.getName()); factory.addImport(Collection.class.getName()); } factory.addImport(HashMap.class.getName()); factory.addImport(Property.class.getName()); factory.addImport(Property.class.getName() + ".Kind"); factory.addImport(Index.class.getName()); factory.addImport(implType.getQualifiedSourceName()); factory.addImport("javax.annotation.Generated"); factory.addAnnotationDeclaration("@Generated(" + "value=\"" + AdapterEntity.class.getName() + "\", " + "date=\"" + new Date() + "\", " + "comments=\"Generated by DAO-GWT project.\")"); SourceWriter sourceWriter = factory.createSourceWriter(context, writer); sourceWriter.println("//AUTO GENERATED FILE BY DAO-GWT " + getClass().getName() + ". DO NOT EDIT!\n"); sourceWriter.println("private static HashMap<String,Property<%s,?>> PROPERTIES = " + "new HashMap<String,Property<%s,?>>();", type.getName(), type.getName()); if (isEntity) { factory.addImport(ArrayList.class.getName()); factory.addImport(Index.class.getName()); sourceWriter.println("private static Collection<Index> INDEXES = " + "new ArrayList<Index>();"); } sourceWriter.println("static {"); sourceWriter.indent(); JClassType interfaz = type != implType ? type : null; JMethod[] methods = parseOnlyInterface ? type.getInheritableMethods() : implType.getInheritableMethods(); for (JMethod method : methods) { String name = method.getName(); //Check if the method has a IsIgnored annotation before to continue IsIgnored ignored = method.getAnnotation(IsIgnored.class); if (ignored != null) { log(logger, Type.DEBUG, EXPLICITELY_IGNORED, name, implType); continue; } boolean startsWithGet = name.startsWith("get"); boolean startsWithIs = name.startsWith("is"); if (!startsWithGet && !startsWithIs) { log(logger, Type.DEBUG, IGNORE_METHOD, name, implType); continue; } //check no parameters if (method.getParameterTypes().length != 0) { log(logger, Type.WARN, NO_PARAMETER_GETTER, name, implType); continue; } //check return type JType returnType = method.getReturnType(); if (returnType == null || returnType.getQualifiedSourceName().equals(Void.class.getName()) || returnType.getQualifiedSourceName().equals(void.class.getName())) { log(logger, Type.DEBUG, VOID_GETTER, name + "" + returnType, implType); continue; } //change the format of the name getXyy ==> xyy String getterSetter = name; if (startsWithGet) getterSetter = name.substring(3); else if (startsWithIs) getterSetter = name.substring(2); name = getterSetter.substring(0, 1).toLowerCase() + getterSetter.substring(1); // check if the getter has an annotation IsIndexable indexable = method.getAnnotation(IsIndexable.class); boolean isIndexable = indexable != null; if (isIndexable && !isEntity) log(logger, Type.WARN, ONLY_ENTITY_FOR_INDEX, name, implType, IsEntity.class); isIndexable = isIndexable && isEntity;//only entity can defined indexable element String indexName = isIndexable ? indexable.aliasName() : ""; String[] compositeIndexes = isIndexable ? indexable.compoundWith() : new String[0]; Kind kind = null; JType typeOfCollection = null; String typeOfCollectionString = "null"; if (!isPrimitive(returnType)) { //load complex properties except Key if (returnType.isEnum() != null) { kind = Kind.ENUM; } else { boolean isPrimitive = false; boolean isEnum = false; JParameterizedType pType = returnType.isParameterized(); JType collection = typeOracle.parse(Collection.class.getName()); if (pType != null && pType.getRawType().isAssignableTo(collection.isClassOrInterface())) { JClassType[] types = pType.getTypeArgs(); kind = Kind.COLLECTION_OF_PRIMITIVES; if (types.length > 1) { log(logger, Type.DEBUG, CANNOT_PROCESS_PARAMETERIZED_TYPE, returnType, implType); continue; } typeOfCollection = types[0]; typeOfCollectionString = typeOfCollection.getQualifiedSourceName() + ".class"; log(logger, Type.DEBUG, "The type of the collection is %s", typeOfCollectionString); isPrimitive = isPrimitive(typeOfCollection); isEnum = typeOfCollection.isEnum() != null; } if (!isPrimitive) { if (isEnum && kind != null) { kind = Kind.COLLECTION_OF_ENUMS; } else { JClassType classType = typeOfCollection != null ? typeOfCollection.isClassOrInterface() : returnType.isClassOrInterface(); boolean isBean = isBean(classType); if (isBean) { log(logger, Type.DEBUG, "The property %s is well a type %s", name, classType); if (kind == null) kind = Kind.BEAN; else kind = Kind.COLLECTION_OF_BEANS; } else { log(logger, Type.DEBUG, "The property %s has not a bean type %s", name, classType); continue; } } } } } assert kind != null; boolean isMemo = method.getAnnotation(IsMemo.class) != null; String oldName = "null"; OldName oldNameAnno = method.getAnnotation(OldName.class); if (oldNameAnno != null) oldName = "\"" + oldNameAnno.value() + "\""; //create a property if (kind == Kind.BEAN || kind == Kind.COLLECTION_OF_BEANS) factory.addImport(returnType.getQualifiedSourceName()); String valueType = ""; JClassType classType = returnType.isClassOrInterface(); JPrimitiveType primitiveType = returnType.isPrimitive(); if (classType != null) valueType = classType.getQualifiedSourceName(); else if (primitiveType != null) { valueType = primitiveType.getQualifiedBoxedSourceName(); } sourceWriter.println("{ //Property %s", name); sourceWriter.indent(); sourceWriter.print("Index index ="); if (isIndexable) { if (indexName.isEmpty()) indexName = name; sourceWriter.println("new Index(\"%s\",\"%s\",new String[]{%s});", indexName, name, String.join(",", compositeIndexes)); } else sourceWriter.println("null;"); boolean useKeyAsString = anno != null ? (name.equals(anno.keyName()) ? anno.useKeyAsString() : false) : false; KeyOf keyOf = method.getAnnotation(KeyOf.class); if (keyOf != null) { IsEntity isEntity2 = keyOf.entity().getAnnotation(IsEntity.class); if (isEntity2 == null) { log(logger, Type.ERROR, AdapterEntityManager.KEY_OF_NO_ENTITY, method, keyOf, keyOf.entity(), IsEntity.class); continue; } useKeyAsString = isEntity2.useKeyAsString(); } boolean isHidden = isHidden(method, interfaz); sourceWriter.println( "Property<%s,%s> property = new Property<%s,%s>(\"%s\",%s,%s.class,%s,%s,%s,%s,index,%s){", type.getName(), valueType, type.getName(), valueType, name, oldName, returnType.getQualifiedSourceName(), typeOfCollectionString, kind != null ? "Kind." + kind.name() : "null", useKeyAsString + "", isMemo + "", isHidden + ""); sourceWriter.indent(); sourceWriter.println("@Override"); sourceWriter.println("public %s get(%s instance){", valueType, type.getName()); sourceWriter.indent(); sourceWriter.println("return ((%s)instance).%s();", implType.getName(), startsWithGet ? "get" + getterSetter : "is" + getterSetter); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("@Override"); sourceWriter.println("public void set(%s instance, %s value){", type.getName(), valueType); sourceWriter.indent(); if (getSetter(implType, getterSetter, returnType) != null) sourceWriter.println("((%s)instance).%s(value);", implType.getName(), "set" + getterSetter); else { logger.log(Type.WARN, " Not found setter for " + getterSetter); sourceWriter.println("throw new RuntimeException(\"No such setter " + getterSetter + " \");"); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.outdent(); sourceWriter.println("};"); sourceWriter.println("PROPERTIES.put(\"%s\",property);", name); if (!oldName.equals("null")) { sourceWriter.println("PROPERTIES.put(%s,property);", oldName); } if (isIndexable) sourceWriter.println("INDEXES.add(index);"); sourceWriter.outdent(); sourceWriter.println("}"); log(logger, Type.DEBUG, SUCCESSFUL_ADD_PROPERTY, name + ":" + valueType, implType); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println(); sourceWriter.println("public %s(){", className); sourceWriter.indent(); /* * boolean asyncReady, boolean autoGeneratedFlag, String keyName, boolean useKeyAsString, Class<T> type,Class<? extends T> implType, Map<String, Property<T,?>> mapAllProperties, Collection<Index> indexes) { super(type,implType,mapAllProperties); */ if (isEntity) sourceWriter .println(String.format("super(\"%s\",%s,%s,\"%s\",%s,%s.class,%s.class,PROPERTIES,INDEXES);", anno.aliasName().isEmpty() ? type.getName() : anno.aliasName(), anno.asyncReady(), anno.autoGeneratedKey(), anno.keyName(), anno.useKeyAsString(), type.getName(), implType.getName())); else { sourceWriter.println( String.format("super(%s.class,%s.class,PROPERTIES);", type.getName(), implType.getName())); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println(); sourceWriter.println("@Override"); sourceWriter.println("public %s newInstance(){", type.getName()); sourceWriter.indent(); sourceWriter.println("return new %s();", implType.getName()); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.outdent(); sourceWriter.println("}"); context.commit(logger, writer); return new BeanMetadata(type, className, implementation, isEntity); }
From source file:com.github.ludorival.dao.gwt.rebind.EntityManagerGenerator.java
License:Apache License
private boolean isPrimitive(JType type) { if (type == null) return false; JPrimitiveType primitiveType = type.isPrimitive(); if (primitiveType != null) return true; String sourceName = type.getQualifiedSourceName(); return sourceName.equals(String.class.getName()) || sourceName.equals(Long.class.getName()) || sourceName.equals(Integer.class.getName()) || sourceName.equals(Double.class.getName()) || sourceName.equals(Float.class.getName()); }
From source file:com.github.nmorel.gwtjackson.rebind.CreatorUtils.java
License:Apache License
/** * Returns the default value of the given type. * <ul>//from w ww . j a v a 2 s .com * <li>{@link Object} : null</li> * <li>char : '\u0000'</li> * <li>boolean : false</li> * <li>other primitive : 0</li> * </ul> * * @param type type to find the default value * * @return the default value of the type. */ public static String getDefaultValueForType(JType type) { JPrimitiveType primitiveType = type.isPrimitive(); if (null != primitiveType) { return primitiveType.getUninitializedFieldExpression(); } return "null"; }
From source file:com.google.appinventor.rebind.ExtendedServiceProxyGenerator.java
License:Open Source License
/** * Generate the implementation of a single method. * * @param out where to print the method to * @param method the method// w w w . j ava2 s . co m * @param typeName type name of the containing proxy class */ private void printMethod(PrintWriter out, JMethod method, String typeName) { // Build parameter lists int i = 0; StringBuilder actualParamsBuilder = new StringBuilder(); StringBuilder formalParamsBuilder = new StringBuilder(); for (JParameter param : method.getParameters()) { if (i != 0) { actualParamsBuilder.append(", "); formalParamsBuilder.append(", "); } String paramType = param.getType().getParameterizedQualifiedSourceName(); String paramName = "p" + i++; actualParamsBuilder.append(paramName); formalParamsBuilder.append(paramType + " " + paramName); } String actualParams = actualParamsBuilder.toString(); String formalParams = formalParamsBuilder.toString(); // Information about the return type JType returnType = method.getReturnType(); boolean hasReturnValue = !returnType.getSimpleSourceName().equals("void"); JPrimitiveType primitiveReturnType = returnType.isPrimitive(); String resultType = primitiveReturnType != null ? primitiveReturnType.getQualifiedBoxedSourceName() : returnType.getParameterizedQualifiedSourceName(); String callbackType = AsyncCallback.class.getName() + "<" + resultType + ">"; // Print method out.println(" public void " + method.getName() + "(" + formalParams + (formalParams.isEmpty() ? "" : ", ") + "final " + callbackType + " callback" + ") {"); out.println(" fireStart(\"" + method.getName() + "\"" + (actualParams.isEmpty() ? "" : ", ") + actualParams + ");"); out.println(" proxy." + method.getName() + "(" + actualParams + (actualParams.isEmpty() ? "" : ", ") + "new " + callbackType + "() {"); out.println(" public void onSuccess(" + resultType + " result) {"); out.println(" " + outcome(method, "Success", "result")); out.println(" }"); out.println(" public void onFailure(Throwable caught) {"); out.println(" " + outcome(method, "Failure", "caught")); out.println(" }"); out.println(" });"); out.println(" }"); }
From source file:com.google.code.gwt.database.rebind.GeneratorUtils.java
License:Apache License
/** * Returns the name of the specified type, which can be safely emitted in the * generated sourcecode./*from w w w . ja va 2 s. co m*/ */ public String getClassName(JType type) { if (type.isPrimitive() != null) { return type.isPrimitive().getSimpleSourceName(); } StringBuilder sb = new StringBuilder(shortenName(type.getQualifiedSourceName())); if (type.isParameterized() != null && type.isParameterized().getTypeArgs().length > 0) { sb.append('<'); boolean needComma = false; for (JType typeArg : type.isParameterized().getTypeArgs()) { if (needComma) { sb.append(", "); } else { needComma = true; } sb.append(shortenName(typeArg.getParameterizedQualifiedSourceName())); } sb.append('>'); } return sb.toString(); }
From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java
License:Apache License
private void printMockMethodBody(SourceWriter sourceWriter, JMethod method, int methodNo, String newClassName) { JParameter[] args = method.getParameters(); String callVar = freeVariableName("call", args); sourceWriter.print("Call %s = new Call(this, %s.methods[%d]", callVar, newClassName, methodNo); int argsCount = method.isVarArgs() ? args.length - 1 : args.length; for (int i = 0; i < argsCount; i++) { sourceWriter.print(", %s", args[i].getName()); }/*from ww w . j a v a2 s.co m*/ sourceWriter.println(");"); if (method.isVarArgs()) { sourceWriter.println("%s.addVarArgument(%s);", callVar, args[args.length - 1].getName()); } sourceWriter.println("try {"); sourceWriter.indent(); if (!isVoid(method)) { sourceWriter.print("return ("); JType returnType = method.getReturnType(); JPrimitiveType primitiveType = returnType.isPrimitive(); if (primitiveType != null) { sourceWriter.print(primitiveType.getQualifiedBoxedSourceName()); } else if (returnType.isTypeParameter() != null) { sourceWriter.print(returnType.isTypeParameter().getName()); } else { sourceWriter.print(returnType.getQualifiedSourceName()); } sourceWriter.print(") "); } sourceWriter.println("this.mocksControl.invoke(%s).answer(%s.getArguments().toArray());", callVar, callVar); sourceWriter.outdent(); String exceptionVar = freeVariableName("exception", args); sourceWriter.println("} catch (Throwable %s) {", exceptionVar); sourceWriter.indent(); String assertionError = AssertionErrorWrapper.class.getCanonicalName(); sourceWriter.println( "if (%s instanceof %s) throw (AssertionError) " + "((%s) %s).getAssertionError().fillInStackTrace();", exceptionVar, assertionError, assertionError, exceptionVar); for (JClassType exception : method.getThrows()) { printRethrowException(sourceWriter, exceptionVar, exception.getQualifiedSourceName()); } printRethrowException(sourceWriter, exceptionVar, "RuntimeException"); printRethrowException(sourceWriter, exceptionVar, "Error"); sourceWriter.println("throw new UndeclaredThrowableException(%s);", exceptionVar); sourceWriter.outdent(); sourceWriter.println("}"); }
From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java
License:Apache License
/** * For interfaces that consist of nothing more than getters and setters, * create a map-based implementation that will allow the AutoBean's internal * state to be easily consumed.//from w w w . j av a2 s .c o m */ private void writeCreateSimpleBean(SourceWriter sw, AutoBeanType type) { sw.println("@Override protected %s createSimplePeer() {", type.getPeerType().getQualifiedSourceName()); sw.indent(); // return new FooIntf() { sw.println("return new %s() {", type.getPeerType().getQualifiedSourceName()); sw.indent(); sw.println("private final %s data = %s.this.data;", Splittable.class.getCanonicalName(), type.getQualifiedSourceName()); for (AutoBeanMethod method : type.getMethods()) { JMethod jmethod = method.getMethod(); JType returnType = jmethod.getReturnType(); sw.println("public %s {", getBaseMethodDeclaration(jmethod)); sw.indent(); switch (method.getAction()) { case GET: { String castType; if (returnType.isPrimitive() != null) { castType = returnType.isPrimitive().getQualifiedBoxedSourceName(); // Boolean toReturn = Other.this.getOrReify("foo"); sw.println("%s toReturn = %s.this.getOrReify(\"%s\");", castType, type.getSimpleSourceName(), method.getPropertyName()); // return toReturn == null ? false : toReturn; sw.println("return toReturn == null ? %s : toReturn;", returnType.isPrimitive().getUninitializedFieldExpression()); } else if (returnType .equals(context.getTypeOracle().findType(Splittable.class.getCanonicalName()))) { sw.println("return data.isNull(\"%1$s\") ? null : data.get(\"%1$s\");", method.getPropertyName()); } else { // return (ReturnType) Outer.this.getOrReify(\"foo\"); castType = ModelUtils.getQualifiedBaseSourceName(returnType); sw.println("return (%s) %s.this.getOrReify(\"%s\");", castType, type.getSimpleSourceName(), method.getPropertyName()); } } break; case SET: case SET_BUILDER: { JParameter param = jmethod.getParameters()[0]; // Other.this.setProperty("foo", parameter); sw.println("%s.this.setProperty(\"%s\", %s);", type.getSimpleSourceName(), method.getPropertyName(), param.getName()); if (JBeanMethod.SET_BUILDER.equals(method.getAction())) { sw.println("return this;"); } break; } case CALL: // return com.example.Owner.staticMethod(Outer.this, param, // param); JMethod staticImpl = method.getStaticImpl(); if (!returnType.equals(JPrimitiveType.VOID)) { sw.print("return "); } sw.print("%s.%s(%s.this", staticImpl.getEnclosingType().getQualifiedSourceName(), staticImpl.getName(), type.getSimpleSourceName()); for (JParameter param : jmethod.getParameters()) { sw.print(", %s", param.getName()); } sw.println(");"); break; default: throw new RuntimeException(); } sw.outdent(); sw.println("}"); } sw.outdent(); sw.println("};"); sw.outdent(); sw.println("}"); }
From source file:com.googlecode.gwtx.rebind.PropertyDescriptorsGenerator.java
License:Apache License
/** * @param sw/*from w w w .j a va 2 s. c o m*/ * @param type * @param propertyName * @param getter * @param setter */ private void writePropertyDescriptor(SourceWriter sw, JClassType type, String propertyName, String propertyType, JMethod getter, JMethod setter) { sw.print("new PropertyDescriptor( \"" + propertyName + "\", " + propertyType + ".class, "); if (getter != null) { sw.println("new Method() "); sw.println("{"); sw.indent(); sw.println("public Object invoke( Object bean, Object... args )"); sw.println("{"); sw.indent(); sw.println("return ( (" + type.getName() + ") bean)." + getter.getName() + "();"); sw.outdent(); sw.println("}"); sw.outdent(); sw.print("}, "); } else { sw.print("null, "); } if (setter != null) { sw.println("new Method() "); sw.println("{"); sw.indent(); sw.println("public Object invoke( Object bean, Object... args )"); sw.println("{"); sw.indent(); JType argType = setter.getParameters()[0].getType().getErasedType(); String argTypeName; if (argType.isPrimitive() != null) { argTypeName = argType.isPrimitive().getQualifiedBoxedSourceName(); } else { argTypeName = argType.getQualifiedSourceName(); } sw.println( "( (" + type.getName() + ") bean)." + setter.getName() + "( (" + argTypeName + ") args[0] );"); sw.println("return null;"); sw.outdent(); sw.println("}"); sw.outdent(); sw.print("} )"); } else { sw.print("null )"); } }
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 www . j a v a2s. c om*/ 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() + "});"); } } } } }