List of usage examples for com.google.gwt.user.rebind SourceWriter commit
void commit(TreeLogger logger);
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 ww w. j a v a 2s . 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.gerrit.plugin.rebind.PluginGenerator.java
License:Apache License
@Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { // The TypeOracle knows about all types in the type system TypeOracle typeOracle = context.getTypeOracle(); // Get a reference to the type that the generator should implement JClassType sourceType = typeOracle.findType(typeName); // Ensure that the requested type exists if (sourceType == null) { logger.log(TreeLogger.ERROR, "Could not find requested typeName", null); throw new UnableToCompleteException(); }/*from w ww . jav a 2s. co m*/ // Make sure the Gadget type is correctly defined validateType(logger, sourceType); // Pick a name for the generated class to not conflict. String generatedSimpleSourceName = sourceType.getSimpleSourceName() + "PluginImpl"; // Begin writing the generated source. ClassSourceFileComposerFactory f = new ClassSourceFileComposerFactory(sourceType.getPackage().getName(), generatedSimpleSourceName); f.addImport(GWT.class.getName()); f.setSuperclass(typeName); // All source gets written through this Writer PrintWriter out = context.tryCreate(logger, sourceType.getPackage().getName(), generatedSimpleSourceName); // If an implementation already exists, we don't need to do any work if (out != null) { // We really use a SourceWriter since it's convenient SourceWriter sw = f.createSourceWriter(context, out); sw.commit(logger); } return f.getCreatedClassName(); }
From source file:com.google.gwt.testing.easygwtmock.rebind.MocksControlGenerator.java
License:Apache License
/** * Generates the concrete MocksControl implementation of the {@code typeName} interface and * delegates generation of mock classes to * {@link com.google.gwt.testing.easygwtmock.rebind.MocksGenerator} *//*from w w w .j a va 2 s . c o m*/ @Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { TypeOracle typeOracle = context.getTypeOracle(); JClassType mockControlInterface = typeOracle.findType(typeName); if (mockControlInterface == null) { logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null); throw new UnableToCompleteException(); } if (mockControlInterface.isInterface() == null) { logger.log(TreeLogger.ERROR, mockControlInterface.getQualifiedSourceName() + " is not an interface", null); throw new UnableToCompleteException(); } JPackage interfacePackage = mockControlInterface.getPackage(); String packageName = interfacePackage == null ? "" : interfacePackage.getName(); String newClassName = mockControlInterface.getName().replace(".", "_") + "Impl"; String fullNewClassName = packageName + "." + newClassName; PrintWriter printWriter = context.tryCreate(logger, packageName, newClassName); if (printWriter == null) { // We generated this before. return fullNewClassName; } ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, newClassName); composer.setSuperclass(MocksControlBase.class.getCanonicalName()); composer.addImplementedInterface(mockControlInterface.getQualifiedSourceName()); SourceWriter writer = composer.createSourceWriter(context, printWriter); writer.println(); MocksGenerator mocksGenerator = new MocksGenerator(context, logger); JClassType markerInterface = typeOracle.findType(MocksControl.class.getCanonicalName()); Set<String> reservedNames = getMethodNames(composer.getSuperclassName(), logger, typeOracle); // Report one error per method in the control interface. They are likely to be independent, // so it's a bit nicer for the user. boolean failed = false; for (JMethod method : mockControlInterface.getOverridableMethods()) { if (method.getEnclosingType().equals(markerInterface)) { // Method is implemented in MocksControlBase continue; } if (reservedNames.contains(method.getName())) { // Method name is already used in base class and method should not be overwritten! logger.log(TreeLogger.ERROR, method.getName() + " is a reserved name. Do not use it in the extended MocksControl interface", null); failed = true; continue; } JClassType typeToMock = method.getReturnType().isClassOrInterface(); if (typeToMock == null) { logger.log(TreeLogger.ERROR, method.getReturnType().getQualifiedSourceName() + " is not an interface or a class", null); failed = true; continue; } if (typeToMock.isInterface() != null) { if (method.getParameterTypes().length != 0) { String methodName = mockControlInterface.getSimpleSourceName() + "." + method.getName(); logger.log(TreeLogger.ERROR, "This method should not have parameters because it creates Ua mock of an interface: " + methodName, null); failed = true; continue; } } else { JConstructor constructorToCall = typeToMock.findConstructor(method.getParameterTypes()); if (constructorToCall == null) { String methodName = mockControlInterface.getSimpleSourceName() + "." + method.getName(); logger.log(TreeLogger.ERROR, "Cannot find matching constructor to call for " + methodName, null); failed = true; continue; } } String mockClassName = mocksGenerator.generateMock(typeToMock); printFactoryMethod(writer, method, mockControlInterface, mockClassName); } if (failed) { throw new UnableToCompleteException(); } writer.commit(logger); return fullNewClassName; }
From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java
License:Apache License
/** * Generates a mock class for {@code interfaceToMock}. *//*from w w w.ja v a2s.co m*/ String generateMock(JClassType typeToMock) throws UnableToCompleteException { JPackage interfacePackage = typeToMock.getPackage(); String packageName = interfacePackage == null ? "" : interfacePackage.getName(); String newClassName = typeToMock.getName().replace(".", "_") + "Mock"; // GenericType<Integer> has to generate a different mock implementation than // GenericType<String>, that's what we check and do here if (typeToMock.isParameterized() != null) { StringBuilder typeList = new StringBuilder(); for (JClassType genericArg : typeToMock.isParameterized().getTypeArgs()) { typeList.append(genericArg.getParameterizedQualifiedSourceName()); } newClassName += Integer.toHexString(typeList.toString().hashCode()); } String fullNewClassName = packageName + "." + newClassName; PrintWriter printWriter = this.context.tryCreate(this.logger, packageName, newClassName); if (printWriter == null) { // We generated this before. return fullNewClassName; } ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, newClassName); composer.addImport(MocksControlBase.class.getCanonicalName()); composer.addImport(Method.class.getCanonicalName()); composer.addImport(Call.class.getCanonicalName()); composer.addImport(UndeclaredThrowableException.class.getCanonicalName()); if (typeToMock.isInterface() != null) { composer.addImplementedInterface(typeToMock.getParameterizedQualifiedSourceName()); } else { composer.setSuperclass(typeToMock.getParameterizedQualifiedSourceName()); } SourceWriter sourceWriter = composer.createSourceWriter(this.context, printWriter); sourceWriter.println(); JMethod[] overridableMethods = typeToMock.getOverridableMethods(); List<JMethod> methodsToMock = new ArrayList<JMethod>(); Set<String> needsDefaultImplementation = new HashSet<String>(); for (JMethod method : overridableMethods) { if (isSpecialMethodOfObject(method)) { needsDefaultImplementation.add(method.getName()); } else if (method.getParameterTypes().length == 0 && method.getName().equals("getClass")) { // ignore, Bug 5026788 in GWT } else { methodsToMock.add(method); } } printFields(sourceWriter, methodsToMock); printConstructors(sourceWriter, newClassName, typeToMock.getConstructors()); printMockMethods(sourceWriter, methodsToMock, newClassName); printDefaultMethods(sourceWriter, typeToMock, needsDefaultImplementation); sourceWriter.commit(this.logger); return fullNewClassName; }
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 www . jav a 2 s . c o m*/ return f.getCreatedClassName(); }
From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java
License:Apache License
@Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { this.context = context; this.logger = logger; TypeOracle oracle = context.getTypeOracle(); JClassType toGenerate = oracle.findType(typeName).isInterface(); if (toGenerate == null) { logger.log(TreeLogger.ERROR, typeName + " is not an interface type"); throw new UnableToCompleteException(); }// w w w .j av a2 s . co m String packageName = toGenerate.getPackage().getName(); simpleSourceName = toGenerate.getName().replace('.', '_') + "Impl"; PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName); if (pw == null) { return packageName + "." + simpleSourceName; } model = new AutoBeanFactoryModel(logger, toGenerate); ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName); factory.setSuperclass(AbstractAutoBeanFactory.class.getCanonicalName()); factory.addImplementedInterface(typeName); SourceWriter sw = factory.createSourceWriter(context, pw); for (AutoBeanType type : model.getAllTypes()) { writeAutoBean(type); } writeDynamicMethods(sw); writeEnumSetup(sw); writeMethods(sw); sw.commit(logger); return factory.getCreatedClassName(); }
From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java
License:Apache License
private void writeAutoBean(AutoBeanType type) throws UnableToCompleteException { PrintWriter pw = context.tryCreate(logger, type.getPackageNome(), type.getSimpleSourceName()); if (pw == null) { // Previously-created return;/*from w w w.java 2 s .co m*/ } ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(type.getPackageNome(), type.getSimpleSourceName()); factory.setSuperclass(AbstractAutoBean.class.getCanonicalName() + "<" + type.getPeerType().getQualifiedSourceName() + ">"); SourceWriter sw = factory.createSourceWriter(context, pw); writeShim(sw, type); // Instance initializer code to set the shim's association sw.println("{ %s.set(shim, %s.class.getName(), this); }", WeakMapping.class.getCanonicalName(), AutoBean.class.getCanonicalName()); // Only simple wrappers have a default constructor if (type.isSimpleBean()) { // public FooIntfAutoBean(AutoBeanFactory factory) {} sw.println("public %s(%s factory) {super(factory);}", type.getSimpleSourceName(), AutoBeanFactory.class.getCanonicalName()); } // Wrapping constructor // public FooIntfAutoBean(AutoBeanFactory factory, FooIntfo wrapped) { sw.println("public %s(%s factory, %s wrapped) {", type.getSimpleSourceName(), AutoBeanFactory.class.getCanonicalName(), type.getPeerType().getQualifiedSourceName()); sw.indentln("super(wrapped, factory);"); sw.println("}"); // public FooIntf as() {return shim;} sw.println("public %s as() {return shim;}", type.getPeerType().getQualifiedSourceName()); // public Class<Intf> getType() {return Intf.class;} sw.println("public Class<%1$s> getType() {return %1$s.class;}", ModelUtils.ensureBaseType(type.getPeerType()).getQualifiedSourceName()); if (type.isSimpleBean()) { writeCreateSimpleBean(sw, type); } writeTraversal(sw, type); sw.commit(logger); }
From source file:com.google.web.bindery.event.gwt.rebind.binder.EventBinderGenerator.java
License:Apache License
@Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { try {//from w ww. ja v a2s .c o m JClassType eventBinderType = context.getTypeOracle().getType(typeName); JClassType targetType = getTargetType(eventBinderType, context.getTypeOracle()); SourceWriter writer = createSourceWriter(logger, context, eventBinderType, targetType); if (writer != null) { // Otherwise the class was already created new EventBinderWriter(logger, context.getTypeOracle().getType(GenericEvent.class.getCanonicalName())) .writeDoBindEventHandlers(targetType, writer, context.getTypeOracle()); writer.commit(logger); } return getFullyQualifiedGeneratedClassName(eventBinderType); } catch (NotFoundException e) { logger.log(Type.ERROR, "Error generating " + typeName, e); throw new UnableToCompleteException(); } }
From source file:com.google.web.bindery.requestfactory.gwt.rebind.RequestFactoryGenerator.java
License:Apache License
@Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { this.context = context; this.logger = logger; TypeOracle oracle = context.getTypeOracle(); JClassType toGenerate = oracle.findType(typeName).isInterface(); if (toGenerate == null) { logger.log(TreeLogger.ERROR, typeName + " is not an interface type"); throw new UnableToCompleteException(); }/*from w w w . j a v a 2s . co m*/ String packageName = toGenerate.getPackage().getName(); String simpleSourceName = toGenerate.getName().replace('.', '_') + "Impl"; PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName); if (pw == null) { return packageName + "." + simpleSourceName; } model = new RequestFactoryModel(logger, toGenerate); ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName); factory.setSuperclass(AbstractClientRequestFactory.class.getCanonicalName()); factory.addImplementedInterface(typeName); SourceWriter sw = factory.createSourceWriter(context, pw); writeAutoBeanFactory(sw, model.getAllProxyModels(), findExtraEnums(model)); writeContextMethods(sw); writeContextImplementations(); writeTypeMap(sw); sw.commit(logger); return factory.getCreatedClassName(); }
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; }/*w ww.java 2 s. com*/ 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); } }