List of usage examples for com.google.gwt.user.rebind SourceWriter print
void print(String s);
From source file:com.eleven.rebind.SkinBundleGenerator.java
License:Apache License
/** * Generates the image bundle implementation class, checking each method for * validity as it is encountered.// ww w.j a va 2 s .c o m */ private String generateImplClass(final TreeLogger logger, final GeneratorContext context, final JClassType userType, final JMethod[] imageMethods) throws UnableToCompleteException { // Lookup the type info for AbstractImagePrototype so that we can check // for // the proper return type // on image bundle methods. final JClassType abstractImagePrototype; try { abstractImagePrototype = userType.getOracle().getType(ABSTRACTIMAGEPROTOTYPE_QNAME); } catch (NotFoundException e) { logger.log(TreeLogger.ERROR, "GWT " + ABSTRACTIMAGEPROTOTYPE_QNAME + " class is not available", e); throw new UnableToCompleteException(); } // Compute the package and class names of the generated class. String pkgName = userType.getPackage().getName(); String subName = computeSubclassName(userType); // 11pc String pkgPrefix = pkgName.replace('.', '/'); if (pkgPrefix.length() > 0) pkgPrefix += "/"; // Begin writing the generated source. ClassSourceFileComposerFactory f = new ClassSourceFileComposerFactory(pkgName, subName); f.addImport(ABSTRACTIMAGEPROTOTYPE_QNAME); f.addImport(CLIPPEDIMAGEPROTOTYPE_QNAME); f.addImport(GWT_QNAME); f.addImport(HASHMAP_QNAME); f.addImport(IMAGE_QNAME); f.addImplementedInterface(userType.getQualifiedSourceName()); PrintWriter pw = context.tryCreate(logger, pkgName, subName); if (pw != null) { SourceWriter sw = f.createSourceWriter(context, pw); // Build a compound image from each individual image. SkinBundleBuilder bulder = new SkinBundleBuilder(); // Store the computed image names so that we don't have to lookup // them up again. // 11pc List<String> imageResNames = getSkinImages(logger); for (String imageName : imageResNames) bulder.assimilate(logger, imageName); /* for (JMethod method : imageMethods) { String branchMsg = "Analyzing method '" + method.getName() + "' in type " + userType.getQualifiedSourceName(); TreeLogger branch = logger.branch(TreeLogger.DEBUG, branchMsg, null); // Verify that this method is valid on an image bundle. if (method.getReturnType() != abstractImagePrototype) { branch.log(TreeLogger.ERROR, "Return type must be " + ABSTRACTIMAGEPROTOTYPE_QNAME, null); throw new UnableToCompleteException(); } if (method.getParameters().length > 0) { branch.log(TreeLogger.ERROR, "Method must have zero parameters", null); throw new UnableToCompleteException(); } // Find the associated imaged resource. String imageResName = getImageResourceName(branch, new JMethodOracleImpl(method)); assert (imageResName != null); imageResNames.add(imageResName); bulder.assimilate(logger, imageResName); } */ // Write the compound image into the output directory. // String bundledImageUrl = bulder.writeBundledImage(logger, context); String bundledImageUrl = "yeayeaa"; // Emit a constant for the composite URL. Note that we prepend the // module's base URL so that the module can reference its own // resources // independently of the host HTML page. sw.print("private static final String IMAGE_BUNDLE_URL = GWT.getModuleBaseURL() + \""); sw.print(escape(bundledImageUrl)); sw.println("\";"); /* // Generate an implementation of each method. int imageResNameIndex = 0; for (JMethod method : imageMethods) { generateImageMethod(bulder, sw, method, imageResNames .get(imageResNameIndex++)); } */ generateImageDef(bulder, sw, imageResNames); sw.println("@Override"); sw.println("public AbstractImagePrototype get(String image) {"); sw.indent(); sw.println("return imageMap.get(image);"); sw.outdent(); sw.print("}"); sw.println("@Override"); sw.println("public HashMap<String, HashMap<String, String>> getProperties() {"); sw.indent(); sw.println("return null;"); sw.outdent(); sw.print("}"); // Finish. sw.commit(logger); } return f.getCreatedClassName(); }
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;/*ww w . j av 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.google.code.gwt.rest.rebind.BeanConverterGenerator.java
License:Apache License
@Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { Map<String, Object> contextMap = createContextMap(); try {// w w w . j a v a 2 s . co m TypeOracle oracle = context.getTypeOracle(); JClassType type = oracle.findType(typeName); // Define creation class name String packageName = type.getPackage().getName(); String simpleSourceName = type.getName().replace('.', '_') + "Impl"; PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName); if (pw == null) { return packageName + "." + simpleSourceName; } // set SuperClass and Interface JClassType beanType = type.getImplementedInterfaces()[0].isParameterized().getTypeArgs()[0]; ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName); if (type.isInterface() != null) { factory.setSuperclass( AbstractBeanConverter.class.getName() + "<" + beanType.getQualifiedSourceName() + ">"); factory.addImplementedInterface(typeName); } else { factory.setSuperclass(typeName); } logger.log(logLevel, "create FormParamConverter " + beanType); SourceWriter sw = factory.createSourceWriter(context, pw); StringBuilder converterDeclarations = new StringBuilder(); StringBuilder convertLogic = new StringBuilder(); contextMap.put("typeName", beanType.getQualifiedSourceName()); // call super class FormParamConverter JClassType superClass = beanType.getSuperclass(); if (superClass != null) { if (!superClass.getQualifiedSourceName().equals(Object.class.getName())) { contextMap.put("actualType", superClass.getQualifiedSourceName()); contextMap.put("propertyName", "__super__"); converterDeclarations.append(ACTUAL_TYPE_CONVERTER.resolve(contextMap)); convertLogic.append(SUPERTYPE_CONERTER.resolve(contextMap)); } } for (JMethod method : beanType.getMethods()) { if (!isGetter(method)) { continue; } JClassType returnType = method.getReturnType().isClass(); if (returnType == null) { returnType = method.getReturnType().isInterface(); } contextMap.put("propertyName", toPropertyName(method)); contextMap.put("getterName", method.getName()); contextMap.put("propertyType", method.getReturnType().getQualifiedSourceName()); if (returnType != null && returnType.isAssignableTo(oracle.findType(Map.class.getName()))) { convertLogic.append(MAP_CONVERTER.resolve(contextMap)); continue; } if (returnType != null && returnType.isAssignableTo(oracle.findType(JsArray.class.getName()))) { JClassType actualType = returnType.isParameterized().getTypeArgs()[0]; contextMap.put("actualType", actualType.getQualifiedSourceName()); converterDeclarations.append(ACTUAL_TYPE_CONVERTER.resolve(contextMap)); convertLogic.append(LIST_CONVERTER.resolve(contextMap)); continue; } if (isReturnTypeJdkTypeOrPrimitiveType(method)) { convertLogic.append(PRIMITIVE_TYPE_CONVERTER.resolve(contextMap)); continue; } converterDeclarations.append(PROPERTY_COMVERTER.resolve(contextMap)); convertLogic.append(BEAN_CONVERTER.resolve(contextMap)); } contextMap.put("converterDeclarations", converterDeclarations); contextMap.put("convertLogic", convertLogic); String mainCode = MAIN_CLASS.resolve(contextMap); logger.log(logLevel, "create souce " + simpleSourceName + " \n" + mainCode); sw.print(mainCode); sw.commit(logger); return packageName + "." + simpleSourceName; } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:com.google.code.gwt.rest.rebind.RestRequestFactoryGenerator.java
License:Apache License
@Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { TypeOracle oracle = context.getTypeOracle(); JClassType type = oracle.findType(typeName); logger.log(logLevel, "create type " + type); String packageName = type.getPackage().getName(); String simpleSourceName = type.getName().replace('.', '_') + "Impl"; PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName); if (pw == null) { return packageName + "." + simpleSourceName; }//from w ww . jav a 2 s . c o m ClassSourceFileComposerFactory factory = createClassSourceFileComposerFactory(typeName, packageName, simpleSourceName); SourceWriter sw = factory.createSourceWriter(context, pw); Map<String, Object> contextMap = createContextMethod(); StringBuilder converters = new StringBuilder(); StringBuilder factoryMethods = new StringBuilder(); for (JMethod method : type.getMethods()) { if (method.getParameters().length != 0) { logger.log(Type.ERROR, " Factory Method must be zero paraemeter method. " + method); return null; } JClassType requestClass = method.getReturnType().isInterface(); String implClassName = requestClass.getSimpleSourceName() + "_Impl"; contextMap.put("returnType", requestClass.getQualifiedSourceName()); contextMap.put("methodName", method.getName()); contextMap.put("implClassName", implClassName); StringBuilder methods = new StringBuilder(); String baseUrl = resolveBaseUrl(requestClass); for (JMethod requestClassMethod : requestClass.getMethods()) { URLMapping mapping = requestClassMethod.getAnnotation(URLMapping.class); if (mapping == null) { logger.log(Type.ERROR, "method " + requestClassMethod + " don't have " + URLMapping.class.getSimpleName() + " annotation."); throw new IllegalArgumentException(); } SimpleTemplate requestClassMethodTemplate = selectRequestMethodTemplate( requestClassMethod.getReturnType().isInterface()); String url = baseUrl + mapping.value(); String restMethod = mapping.method().name().toLowerCase(); contextMap.put("url", url); contextMap.put("restMethod", restMethod); JParameterizedType jtype = requestClassMethod.getReturnType().isParameterized(); if (jtype != null) { contextMap.put("implReturnType", jtype.getQualifiedSourceName()); } else { contextMap.put("implReturnType", JavaScriptObject.class.getName()); } contextMap.put("beanType", requestClassMethod.getReturnType().isParameterized().getTypeArgs()[0] .getQualifiedSourceName()); contextMap.put("impleMethodName", requestClassMethod.getName()); String parameters = ""; String bindingLogic = ""; int i = 0; for (JParameter parameter : requestClassMethod.getParameters()) { if (i != 0) { parameters += ","; } parameters += parameter.getType().getQualifiedSourceName() + " arg" + i; if (parameter.isAnnotationPresent(URLParam.class)) { contextMap.put("key", parameter.getAnnotation(URLParam.class).value()); contextMap.put("parameter", "arg" + i); bindingLogic += CALL_PATH_BINDING.resolve(contextMap); } else if (parameter.isAnnotationPresent(QueryParam.class)) { contextMap.put("key", parameter.getAnnotation(QueryParam.class).value()); contextMap.put("parameter", "arg" + i); bindingLogic += CALL_QUERY_BINDING.resolve(contextMap); } else { contextMap.put("parameter", "arg" + i); contextMap.put("parameterType", parameter.getType().getQualifiedSourceName()); bindingLogic += CALL_CONVERTER.resolve(contextMap); converters.append(CONVERTER.resolve(contextMap)); } i++; } contextMap.put("parameters", parameters); contextMap.put("bindingLogic", bindingLogic); methods.append(requestClassMethodTemplate.resolve(contextMap)); } contextMap.put("methods", methods); String classImpl; if (method.getReturnType().getQualifiedSourceName().equals(RestRequestClient.class.getName())) { } classImpl = REQUEST_CLASS.resolve(contextMap); contextMap.put("classImpl", classImpl); factoryMethods.append(FACTORY_METHOD.resolve(contextMap)); } contextMap.put("factoryMethods", factoryMethods.toString()); contextMap.put("converters", converters.toString()); logger.log(logLevel, "create class \n" + MAIN_CLASS.resolve(contextMap)); sw.print(MAIN_CLASS.resolve(contextMap)); sw.commit(logger); return packageName + "." + simpleSourceName; }
From source file:com.google.gwt.testing.easygwtmock.rebind.MocksControlGenerator.java
License:Apache License
private void printMatchingParameters(SourceWriter out, JMethod methodToImplement) { JParameter[] params = methodToImplement.getParameters(); for (int i = 0; i < params.length; i++) { if (i > 0) { out.print(", "); }//w w w .j av a 2 s.c om out.print(params[i].getName()); } }
From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java
License:Apache License
private void printMatchingParameters(SourceWriter out, JConstructor constructorToCall) { JParameter[] params = constructorToCall.getParameters(); for (int i = 0; i < params.length; i++) { if (i > 0) { out.print(", "); }//from www . j av a 2 s . c o m JParameter param = params[i]; out.print(param.getType().getParameterizedQualifiedSourceName()); out.print(" "); out.print(param.getName()); } }
From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java
License:Apache License
private void printMatchingSuperCall(SourceWriter out, JConstructor constructorToCall) { if (constructorToCall.getParameters().length == 0) { return; // will be added automatically }/*from w ww . j a v a 2s . co m*/ out.print("super("); JParameter[] params = constructorToCall.getParameters(); for (int i = 0; i < params.length; i++) { if (i > 0) { out.print(", "); } out.print(params[i].getName()); } out.println(");"); }
From source file:com.google.speedtracer.generators.BuildInfoGenerator.java
License:Apache License
private String emitImplClass(TreeLogger logger, GeneratorContext context, JClassType typeClass, JMethod revisionMethod, JMethod timeMethod) { final int revision = getBuildRevision(); final String subclassName = typeClass.getSimpleSourceName() + "_r" + revision; final String packageName = typeClass.getPackage().getName(); final ClassSourceFileComposerFactory f = new ClassSourceFileComposerFactory(packageName, subclassName); f.addImplementedInterface(typeClass.getQualifiedSourceName()); final PrintWriter pw = context.tryCreate(logger, packageName, subclassName); if (pw != null) { final SourceWriter sw = f.createSourceWriter(context, pw); sw.print(revisionMethod.getReadableDeclaration(false, true, true, true, true)); sw.println("{ return " + revision + "; }"); sw.print(timeMethod.getReadableDeclaration(false, true, true, true, true)); sw.println("{ return new java.util.Date(" + System.currentTimeMillis() + "L); }"); sw.commit(logger);/*from ww w . java 2 s .c om*/ } return f.getCreatedClassName(); }
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 a va2 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.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java
License:Apache License
/** * Generate traversal logic./*w w w . j a v a2 s. c o m*/ */ private void writeTraversal(SourceWriter sw, AutoBeanType type) { List<AutoBeanMethod> referencedSetters = new ArrayList<AutoBeanMethod>(); sw.println("@Override protected void traverseProperties(%s visitor, %s ctx) {", AutoBeanVisitor.class.getCanonicalName(), OneShotContext.class.getCanonicalName()); sw.indent(); sw.println("%s bean;", AbstractAutoBean.class.getCanonicalName()); sw.println("Object value;"); sw.println("%s propertyContext;", ClientPropertyContext.class.getCanonicalName()); // Local variable ref cleans up emitted js sw.println("%1$s as = as();", type.getPeerType().getQualifiedSourceName()); for (AutoBeanMethod method : type.getMethods()) { if (!method.getAction().equals(JBeanMethod.GET)) { continue; } AutoBeanMethod setter = null; // If it's not a simple bean type, try to find a real setter method if (!type.isSimpleBean()) { for (AutoBeanMethod maybeSetter : type.getMethods()) { boolean isASetter = maybeSetter.getAction().equals(JBeanMethod.SET) || maybeSetter.getAction().equals(JBeanMethod.SET_BUILDER); if (isASetter && maybeSetter.getPropertyName().equals(method.getPropertyName())) { setter = maybeSetter; break; } } } // The type of property influences the visitation String valueExpression = String.format("bean = (%1$s) %2$s.getAutoBean(as.%3$s());", AbstractAutoBean.class.getCanonicalName(), AutoBeanUtils.class.getCanonicalName(), method.getMethod().getName()); String visitMethod; String visitVariable = "bean"; if (method.isCollection()) { visitMethod = "Collection"; } else if (method.isMap()) { visitMethod = "Map"; } else if (method.isValueType()) { valueExpression = String.format("value = as.%s();", method.getMethod().getName()); visitMethod = "Value"; visitVariable = "value"; } else { visitMethod = "Reference"; } sw.println(valueExpression); // Map<List<Foo>, Bar> --> Map, List, Foo, Bar List<JType> typeList = new ArrayList<JType>(); createTypeList(typeList, method.getMethod().getReturnType()); assert typeList.size() > 0; /* * Make the PropertyContext that lets us call the setter. We allow * multiple methods to be bound to the same property (e.g. to allow JSON * payloads to be interpreted as different types). The leading underscore * allows purely numeric property names, which are valid JSON map keys. */ // propertyContext = new CPContext(.....); sw.println("propertyContext = new %s(", ClientPropertyContext.class.getCanonicalName()); sw.indent(); // The instance on which the context is nominally operating sw.println("as,"); // Produce a JSNI reference to a setter function to call { if (setter != null) { // Call a method that returns a JSNI reference to the method to call // setFooMethodReference(), sw.println("%sMethodReference(as),", setter.getMethod().getName()); referencedSetters.add(setter); } else { // Create a function that will update the values map // CPContext.beanSetter(FooBeanImpl.this, "foo"); sw.println("%s.beanSetter(%s.this, \"%s\"),", ClientPropertyContext.Setter.class.getCanonicalName(), type.getSimpleSourceName(), method.getPropertyName()); } } if (typeList.size() == 1) { sw.println("%s.class", ModelUtils.ensureBaseType(typeList.get(0)).getQualifiedSourceName()); } else { // Produce the array of parameter types sw.print("new Class<?>[] {"); boolean first = true; for (JType lit : typeList) { if (first) { first = false; } else { sw.print(", "); } sw.print("%s.class", ModelUtils.ensureBaseType(lit).getQualifiedSourceName()); } sw.println("},"); // Produce the array of parameter counts sw.print("new int[] {"); first = true; for (JType lit : typeList) { if (first) { first = false; } else { sw.print(", "); } JParameterizedType hasParam = lit.isParameterized(); if (hasParam == null) { sw.print("0"); } else { sw.print(String.valueOf(hasParam.getTypeArgs().length)); } } sw.println("}"); } sw.outdent(); sw.println(");"); // if (visitor.visitReferenceProperty("foo", value, ctx)) sw.println("if (visitor.visit%sProperty(\"%s\", %s, propertyContext)) {", visitMethod, method.getPropertyName(), visitVariable); if (!method.isValueType()) { // Cycle-detection in AbstractAutoBean.traverse sw.indentln("if (bean != null) { bean.traverse(visitor, ctx); }"); } sw.println("}"); // visitor.endVisitorReferenceProperty("foo", value, ctx); sw.println("visitor.endVisit%sProperty(\"%s\", %s, propertyContext);", visitMethod, method.getPropertyName(), visitVariable); } sw.outdent(); sw.println("}"); for (AutoBeanMethod method : referencedSetters) { JMethod jmethod = method.getMethod(); assert jmethod.getParameters().length == 1; /*- * Setter setFooMethodReference(Object instance) { * return instance.@com.example.Blah::setFoo(Lcom/example/Foo;); * } */ sw.println("public static native %s %sMethodReference(Object instance) /*-{", ClientPropertyContext.Setter.class.getCanonicalName(), jmethod.getName()); sw.indentln("return instance.@%s::%s(%s);", jmethod.getEnclosingType().getQualifiedSourceName(), jmethod.getName(), jmethod.getParameters()[0].getType().getJNISignature()); sw.println("}-*/;"); } }