List of usage examples for com.google.gwt.user.rebind SourceWriter outdent
void outdent();
From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java
License:Apache License
private void writeReturnWrapper(SourceWriter sw, AutoBeanType type, AutoBeanMethod method) throws UnableToCompleteException { if (!method.isValueType() && !method.isNoWrap()) { JMethod jmethod = method.getMethod(); JClassType returnClass = jmethod.getReturnType().isClassOrInterface(); AutoBeanType peer = model.getPeer(returnClass); sw.println("if (toReturn != null) {"); sw.indent();// ww w . ja va 2 s . co m sw.println("if (%s.this.isWrapped(toReturn)) {", type.getSimpleSourceName()); sw.indentln("toReturn = %s.this.getFromWrapper(toReturn);", type.getSimpleSourceName()); sw.println("} else {"); sw.indent(); if (peer != null) { // toReturn = new FooAutoBean(getFactory(), toReturn).as(); sw.println("toReturn = new %s(getFactory(), toReturn).as();", peer.getQualifiedSourceName()); } sw.outdent(); sw.println("}"); sw.outdent(); sw.println("}"); } // Allow return values to be intercepted JMethod interceptor = type.getInterceptor(); if (interceptor != null) { // toReturn = FooCategory.__intercept(FooAutoBean.this, toReturn); sw.println("toReturn = %s.%s(%s.this, toReturn);", interceptor.getEnclosingType().getQualifiedSourceName(), interceptor.getName(), type.getSimpleSourceName()); } }
From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java
License:Apache License
/** * Create the shim instance of the AutoBean's peer type that lets us hijack * the method calls. Using a shim type, as opposed to making the AutoBean * implement the peer type directly, means that there can't be any conflicts * between methods in the peer type and methods declared in the AutoBean * implementation./* ww w. j av a 2s . c o m*/ */ private void writeShim(SourceWriter sw, AutoBeanType type) throws UnableToCompleteException { // private final FooImpl shim = new FooImpl() { sw.println("private final %1$s shim = new %1$s() {", type.getPeerType().getQualifiedSourceName()); sw.indent(); for (AutoBeanMethod method : type.getMethods()) { JMethod jmethod = method.getMethod(); String methodName = jmethod.getName(); JParameter[] parameters = jmethod.getParameters(); if (isObjectMethodImplementedByShim(jmethod)) { // Skip any methods declared on Object, since we have special handling continue; } // foo, bar, baz StringBuilder arguments = new StringBuilder(); { for (JParameter param : parameters) { arguments.append(",").append(param.getName()); } if (arguments.length() > 0) { arguments = arguments.deleteCharAt(0); } } sw.println("public %s {", getBaseMethodDeclaration(jmethod)); sw.indent(); switch (method.getAction()) { case GET: /* * The getter call will ensure that any non-value return type is * definitely wrapped by an AutoBean instance. */ sw.println("%s toReturn = %s.this.getWrapped().%s();", ModelUtils.getQualifiedBaseSourceName(jmethod.getReturnType()), type.getSimpleSourceName(), methodName); // Non-value types might need to be wrapped writeReturnWrapper(sw, type, method); sw.println("return toReturn;"); break; case SET: case SET_BUILDER: // getWrapped().setFoo(foo); sw.println("%s.this.getWrapped().%s(%s);", type.getSimpleSourceName(), methodName, parameters[0].getName()); // FooAutoBean.this.set("setFoo", foo); sw.println("%s.this.set(\"%s\", %s);", type.getSimpleSourceName(), methodName, parameters[0].getName()); if (JBeanMethod.SET_BUILDER.equals(method.getAction())) { sw.println("return this;"); } break; case CALL: // XXX How should freezing and calls work together? // sw.println("checkFrozen();"); if (JPrimitiveType.VOID.equals(jmethod.getReturnType())) { // getWrapped().doFoo(params); sw.println("%s.this.getWrapped().%s(%s);", type.getSimpleSourceName(), methodName, arguments); // call("doFoo", null, params); sw.println("%s.this.call(\"%s\", null%s %s);", type.getSimpleSourceName(), methodName, arguments.length() > 0 ? "," : "", arguments); } else { // Type toReturn = getWrapped().doFoo(params); sw.println("%s toReturn = %s.this.getWrapped().%s(%s);", ModelUtils.ensureBaseType(jmethod.getReturnType()).getQualifiedSourceName(), type.getSimpleSourceName(), methodName, arguments); // Non-value types might need to be wrapped writeReturnWrapper(sw, type, method); // call("doFoo", toReturn, params); sw.println("%s.this.call(\"%s\", toReturn%s %s);", type.getSimpleSourceName(), methodName, arguments.length() > 0 ? "," : "", arguments); sw.println("return toReturn;"); } break; default: throw new RuntimeException(); } sw.outdent(); sw.println("}"); } // Delegate equals(), hashCode(), and toString() to wrapped object sw.println("@Override public boolean equals(Object o) {"); sw.indentln("return this == o || getWrapped().equals(o);"); sw.println("}"); sw.println("@Override public int hashCode() {"); sw.indentln("return getWrapped().hashCode();"); sw.println("}"); sw.println("@Override public String toString() {"); sw.indentln("return getWrapped().toString();"); sw.println("}"); // End of shim field declaration and assignment sw.outdent(); sw.println("};"); }
From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java
License:Apache License
/** * Generate traversal logic.//from ww w.java2s. 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("}-*/;"); } }
From source file:com.google.web.bindery.event.gwt.rebind.binder.EventBinderWriter.java
License:Apache License
private void writeBindMethodFooter(SourceWriter writer) { writer.println("return registrations;"); writer.outdent(); writer.println("}"); }
From source file:com.google.web.bindery.requestfactory.gwt.rebind.RequestFactoryGenerator.java
License:Apache License
private void writeAutoBeanFactory(SourceWriter sw, Collection<EntityProxyModel> models, Collection<JEnumType> extraEnums) { if (!extraEnums.isEmpty()) { StringBuilder extraClasses = new StringBuilder(); for (JEnumType enumType : extraEnums) { if (extraClasses.length() > 0) { extraClasses.append(","); }//w w w .j a v a2 s. c o m extraClasses.append(enumType.getQualifiedSourceName()).append(".class"); } sw.println("@%s({%s})", ExtraEnums.class.getCanonicalName(), extraClasses); } // Map in static implementations of EntityProxy methods sw.println("@%s({%s.class, %s.class, %s.class})", Category.class.getCanonicalName(), EntityProxyCategory.class.getCanonicalName(), ValueProxyCategory.class.getCanonicalName(), BaseProxyCategory.class.getCanonicalName()); // Don't wrap our id type, because it makes code grungy sw.println("@%s(%s.class)", NoWrap.class.getCanonicalName(), EntityProxyId.class.getCanonicalName()); sw.println("interface Factory extends %s {", AutoBeanFactory.class.getCanonicalName()); sw.indent(); for (EntityProxyModel proxy : models) { // AutoBean<FooProxy> com_google_FooProxy(); sw.println("%s<%s> %s();", AutoBean.class.getCanonicalName(), proxy.getQualifiedSourceName(), proxy.getQualifiedSourceName().replace('.', '_')); } sw.outdent(); sw.println("}"); // public static final Factory FACTORY = GWT.create(Factory.class); sw.println("public static Factory FACTORY;", GWT.class.getCanonicalName()); // Write public accessor sw.println("@Override public Factory getAutoBeanFactory() {"); sw.indent(); sw.println("if (FACTORY == null) {"); sw.indentln("FACTORY = %s.create(Factory.class);", GWT.class.getCanonicalName()); sw.println("}"); sw.println("return FACTORY;"); sw.outdent(); sw.println("}"); }
From source file:com.google.web.bindery.requestfactory.gwt.rebind.RequestFactoryGenerator.java
License:Apache License
private void writeContextImplementations() { for (ContextMethod method : model.getMethods()) { PrintWriter pw = context.tryCreate(logger, method.getPackageName(), method.getSimpleSourceName()); if (pw == null) { // Already generated continue; }/*from w w w.ja v a2 s . c om*/ ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(method.getPackageName(), method.getSimpleSourceName()); factory.setSuperclass(AbstractRequestContext.class.getCanonicalName()); factory.addImplementedInterface(method.getImplementedInterfaceQualifiedSourceName()); SourceWriter sw = factory.createSourceWriter(context, pw); // Constructor that accepts the parent RequestFactory sw.println("public %s(%s requestFactory) {super(requestFactory, %s.%s);}", method.getSimpleSourceName(), AbstractRequestFactory.class.getCanonicalName(), Dialect.class.getCanonicalName(), method.getDialect().name()); Set<EntityProxyModel> models = findReferencedEntities(method); Set<JEnumType> extraEnumTypes = findExtraEnums(method); writeAutoBeanFactory(sw, models, extraEnumTypes); // Write each Request method for (RequestMethod request : method.getRequestMethods()) { JMethod jmethod = request.getDeclarationMethod(); String operation = request.getOperation(); // foo, bar, baz StringBuilder parameterArray = new StringBuilder(); // final Foo foo, final Bar bar, final Baz baz StringBuilder parameterDeclaration = new StringBuilder(); // <P extends Blah> StringBuilder typeParameterDeclaration = new StringBuilder(); if (request.isInstance()) { // Leave a spot for the using() method to fill in later parameterArray.append(",null"); } for (JTypeParameter param : jmethod.getTypeParameters()) { typeParameterDeclaration.append(",").append(param.getQualifiedSourceName()); } for (JParameter param : jmethod.getParameters()) { parameterArray.append(",").append(param.getName()); parameterDeclaration.append(",final ") .append(param.getType().getParameterizedQualifiedSourceName()).append(" ") .append(param.getName()); } if (parameterArray.length() > 0) { parameterArray.deleteCharAt(0); } if (parameterDeclaration.length() > 0) { parameterDeclaration.deleteCharAt(0); } if (typeParameterDeclaration.length() > 0) { typeParameterDeclaration.deleteCharAt(0).insert(0, "<").append(">"); } // public Request<Foo> doFoo(final Foo foo) { sw.println("public %s %s %s(%s) {", typeParameterDeclaration, jmethod.getReturnType().getParameterizedQualifiedSourceName(), jmethod.getName(), parameterDeclaration); sw.indent(); // The implements clause covers InstanceRequest // class X extends AbstractRequest<Return> implements Request<Return> { sw.println("class X extends %s<%s> implements %s {", AbstractRequest.class.getCanonicalName(), request.getDataType().getParameterizedQualifiedSourceName(), jmethod.getReturnType().getParameterizedQualifiedSourceName()); sw.indent(); // public X() { super(FooRequestContext.this); } sw.println("public X() { super(%s.this);}", method.getSimpleSourceName()); // This could also be gotten rid of by having only Request / // InstanceRequest sw.println("@Override public X with(String... paths) {super.with(paths); return this;}"); // makeRequestData() sw.println("@Override protected %s makeRequestData() {", RequestData.class.getCanonicalName()); String elementType = request.isCollectionType() ? request.getCollectionElementType().getQualifiedSourceName() + ".class" : "null"; String returnTypeBaseQualifiedName = ModelUtils.ensureBaseType(request.getDataType()) .getQualifiedSourceName(); // return new RequestData("ABC123", {parameters}, propertyRefs, // List.class, FooProxy.class); sw.indentln("return new %s(\"%s\", new Object[] {%s}, propertyRefs, %s.class, %s);", RequestData.class.getCanonicalName(), operation, parameterArray, returnTypeBaseQualifiedName, elementType); sw.println("}"); /* * Only support extra properties in JSON-RPC payloads. Could add this to * standard requests to provide out-of-band data. */ if (method.getDialect().equals(Dialect.JSON_RPC)) { for (JMethod setter : request.getExtraSetters()) { PropertyName propertyNameAnnotation = setter.getAnnotation(PropertyName.class); String propertyName = propertyNameAnnotation == null ? JBeanMethod.SET.inferName(setter) : propertyNameAnnotation.value(); String maybeReturn = JBeanMethod.SET_BUILDER.matches(setter) ? "return this;" : ""; sw.println("%s { getRequestData().setNamedParameter(\"%s\", %s); %s}", setter.getReadableDeclaration(false, false, false, false, true), propertyName, setter.getParameters()[0].getName(), maybeReturn); } } // end class X{} sw.outdent(); sw.println("}"); // Instantiate, enqueue, and return sw.println("X x = new X();"); if (request.getApiVersion() != null) { sw.println("x.getRequestData().setApiVersion(\"%s\");", Generator.escape(request.getApiVersion())); } // JSON-RPC payloads send their parameters in a by-name fashion if (method.getDialect().equals(Dialect.JSON_RPC)) { for (JParameter param : jmethod.getParameters()) { PropertyName annotation = param.getAnnotation(PropertyName.class); String propertyName = annotation == null ? param.getName() : annotation.value(); boolean isContent = param.isAnnotationPresent(JsonRpcContent.class); if (isContent) { sw.println("x.getRequestData().setRequestContent(%s);", param.getName()); } else { sw.println("x.getRequestData().setNamedParameter(\"%s\", %s);", propertyName, param.getName()); } } } // See comment in AbstractRequest.using(EntityProxy) if (!request.isInstance()) { sw.println("addInvocation(x);"); } sw.println("return x;"); sw.outdent(); sw.println("}"); } sw.commit(logger); } }
From source file:com.google.web.bindery.requestfactory.gwt.rebind.RequestFactoryGenerator.java
License:Apache License
private void writeTypeMap(SourceWriter sw) { sw.println("private static final %1$s<String, Class<?>> tokensToTypes" + " = new %1$s<String, Class<?>>();", HashMap.class.getCanonicalName()); sw.println("private static final %1$s<Class<?>, String> typesToTokens" + " = new %1$s<Class<?>, String>();", HashMap.class.getCanonicalName()); sw.println("private static final %1$s<Class<?>> entityProxyTypes = new %1$s<Class<?>>();", HashSet.class.getCanonicalName()); sw.println("private static final %1$s<Class<?>> valueProxyTypes = new %1$s<Class<?>>();", HashSet.class.getCanonicalName()); sw.println("static {"); sw.indent();/*from ww w . j av a 2 s. c om*/ for (EntityProxyModel type : model.getAllProxyModels()) { // tokensToTypes.put("Foo", Foo.class); sw.println("tokensToTypes.put(\"%s\", %s.class);", OperationKey.hash(type.getQualifiedBinaryName()), type.getQualifiedSourceName()); // typesToTokens.put(Foo.class, Foo); sw.println("typesToTokens.put(%s.class, \"%s\");", type.getQualifiedSourceName(), OperationKey.hash(type.getQualifiedBinaryName())); // fooProxyTypes.add(MyFooProxy.class); sw.println("%s.add(%s.class);", type.getType().equals(Type.ENTITY) ? "entityProxyTypes" : "valueProxyTypes", type.getQualifiedSourceName()); } sw.outdent(); sw.println("}"); // Write instance methods sw.println("@Override public String getFactoryTypeToken() {"); sw.indentln("return \"%s\";", model.getFactoryType().getQualifiedBinaryName()); sw.println("}"); sw.println("@Override protected Class getTypeFromToken(String typeToken) {"); sw.indentln("return tokensToTypes.get(typeToken);"); sw.println("}"); sw.println("@Override protected String getTypeToken(Class type) {"); sw.indentln("return typesToTokens.get(type);"); sw.println("}"); sw.println("@Override public boolean isEntityType(Class<?> type) {"); sw.indentln("return entityProxyTypes.contains(type);"); sw.println("}"); sw.println("@Override public boolean isValueType(Class<?> type) {"); sw.indentln("return valueProxyTypes.contains(type);"); sw.println("}"); }
From source file:com.googlecode.gwtx.rebind.PropertyDescriptorsGenerator.java
License:Apache License
/** * @param logger/*from w w w . j a v a2s.co m*/ * @param w * @param typeOracle */ private void write(TreeLogger logger, SourceWriter w, JClassType type) { Collection<Property> properties = lookupJavaBeanPropertyAccessors(logger, type); w.println("// automatically register BeanInfos for bean properties"); w.println("static {"); w.indent(); w.println("GwtBeanInfo beanInfo = new GwtBeanInfo();"); for (Property property : properties) { w.println("try {"); w.indent(); w.print("beanInfo.addPropertyDescriptor( "); writePropertyDescriptor(w, type, property.name, property.propertyType, property.getter, property.setter); w.println(" );"); w.outdent(); w.println("} catch (Exception e) {}"); } w.println("GwtIntrospector.setBeanInfo( " + type.getName() + ".class, beanInfo );"); w.outdent(); w.println("}"); }
From source file:com.googlecode.gwtx.rebind.PropertyDescriptorsGenerator.java
License:Apache License
/** * @param sw/*from w w w . j av a2s. 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.googlecode.mgwt.ui.server.util.MGWTCssResourceGenerator.java
License:Apache License
@Override protected void writeEnsureInjected(SourceWriter sw) { if (!injectAtStart) { super.writeEnsureInjected(sw); } else {//from w ww . j ava 2 s . c om sw.println("private boolean injected;"); sw.println("public boolean ensureInjected() {"); sw.indent(); sw.println("if (!injected) {"); sw.indentln("injected = true;"); sw.indentln(StyleInjector.class.getName() + ".injectAtStart(getText());"); sw.indentln("return true;"); sw.println("}"); sw.println("return false;"); sw.outdent(); sw.println("}"); } }