List of usage examples for com.google.gwt.user.rebind SourceWriter outdent
void outdent();
From source file:org.rstudio.core.rebind.command.MenuEmitter.java
License:Open Source License
public String generate() throws UnableToCompleteException { String className = bundleType_.getSimpleSourceName() + "__Menu_" + menuId_; PrintWriter printWriter = context_.tryCreate(logger_, packageName_, className); if (printWriter == null) return null; ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName_, className); factory.addImport("org.rstudio.core.client.Debug"); factory.addImport("org.rstudio.core.client.command.MenuCallback"); SourceWriter writer = factory.createSourceWriter(context_, printWriter); emitFields(writer);// w w w . j av a 2 s .c om emitConstructor(writer, className); emitMethod(writer); writer.outdent(); writer.println("}"); context_.commit(logger_, printWriter); return packageName_ + "." + className; }
From source file:org.rstudio.core.rebind.command.MenuEmitter.java
License:Open Source License
private void emitMethod(SourceWriter writer) throws UnableToCompleteException { writer.println("public void createMenu(MenuCallback callback) {"); writer.indent();/*from w ww .j ava 2s . c om*/ writer.println("callback.beginMainMenu();"); // Vertical defaults to true emitMenu(writer, menuEl_); writer.println("callback.endMainMenu();"); writer.outdent(); writer.println("}"); }
From source file:org.rstudio.core.rebind.command.ShortcutsEmitter.java
License:Open Source License
private void printShortcut(SourceWriter writer, String condition, String shortcutValue, String command, String shortcutGroup, String title, String disableModes) throws UnableToCompleteException { String[] chunks = shortcutValue.split("\\+"); int modifiers = KeyboardShortcut.NONE; boolean cmd = false; for (int i = 0; i < chunks.length - 1; i++) { String m = chunks[i];/* w w w . j ava2 s.c o m*/ if (m.equals("Ctrl")) modifiers += KeyboardShortcut.CTRL; else if (m.equals("Meta")) modifiers += KeyboardShortcut.META; else if (m.equals("Alt")) modifiers += KeyboardShortcut.ALT; else if (m.equals("Shift")) modifiers += KeyboardShortcut.SHIFT; else if (m.equals("Cmd")) cmd = true; else { logger_.log(Type.ERROR, "Invalid shortcut " + shortcutValue); throw new UnableToCompleteException(); } } String key = toKey(chunks[chunks.length - 1]); if (key == null) { logger_.log(Type.ERROR, "Invalid shortcut " + shortcutValue + ", only " + "modified alphanumeric characters, enter, " + "left, right, up, down, pageup, pagedown, " + "and tab are valid"); throw new UnableToCompleteException(); } if (!condition.isEmpty()) { writer.println("if (" + condition + ") {"); writer.indent(); } if (cmd) { writer.println("ShortcutManager.INSTANCE.register(" + (modifiers | KeyboardShortcut.CTRL) + ", " + key + ", " + command + ", " + "\"" + shortcutGroup + "\", " + "\"" + title + "\", " + "\"" + disableModes + "\");"); writer.println("ShortcutManager.INSTANCE.register(" + (modifiers | KeyboardShortcut.META) + ", " + key + ", " + command + ", " + "\"" + shortcutGroup + "\", " + "\"" + title + "\", " + "\"" + disableModes + "\");"); } else { writer.println("ShortcutManager.INSTANCE.register(" + modifiers + ", " + key + ", " + command + ", " + "\"" + shortcutGroup + "\", " + "\"" + title + "\", " + "\"" + disableModes + "\");"); } if (!condition.isEmpty()) { writer.outdent(); writer.println("}"); } }
From source file:org.rstudio.core.rebind.JavaScriptSerializerGenerator.java
License:Open Source License
private void printSerializers(List<JClassType> classes, SourceWriter w) { // print the method that dispatches to the appropriate serializer w.println("public <T> JavaScriptObject serialize(T source)"); w.println("{"); w.indent();/* w ww . j av a 2 s . c o m*/ for (JClassType classType : classes) { if (classType.isAbstract()) continue; w.println(); w.println("if (source.getClass().getName() == " + classType.getQualifiedSourceName() + ".class.getName())"); w.println("{"); w.indent(); w.println("return serializeJso((" + classType.getQualifiedSourceName() + ") source);"); w.outdent(); w.println("}"); w.println(); } w.println("return null;"); w.outdent(); w.println("}"); // print individual serializers for (JClassType classType : classes) { w.print("private final native JavaScriptObject serializeJso("); w.println(classType.getQualifiedSourceName() + " source) /*-{"); w.indent(); w.println("return {"); w.indent(); w.println("\"class_name\":\"" + classType.getQualifiedSourceName() + "\","); w.println("\"class_data\": {"); w.indent(); JField[] fields = classType.getFields(); for (int i = 0; i < fields.length; i++) { JField field = fields[i]; if (!field.isStatic()) { w.print("\"" + field.getName() + "\": "); if (isAnnotatedSerializable(field)) { w.print("this.@" + genPackageName + "." + genClassName + "::serializeJso(L"); w.print(field.getType().getQualifiedSourceName().replace(".", "/")); w.print(";)("); } w.println("source.@" + classType.getQualifiedSourceName() + "::" + field.getName()); if (isAnnotatedSerializable(field)) { w.print(")"); } if (i < (fields.length - 1)) w.print(", "); w.println(); } } w.outdent(); w.println("}"); w.outdent(); w.println("};"); w.outdent(); w.println("}-*/;"); w.println(); } }
From source file:org.rstudio.core.rebind.JavaScriptSerializerGenerator.java
License:Open Source License
private void printDeserializers(List<JClassType> classes, SourceWriter w) { w.println("private final native String classFromJso(" + "JavaScriptObject jso) /*-{"); w.indent();// w w w. ja va 2 s .co m w.println("return jso.class_name;"); w.outdent(); w.println("}-*/;"); w.println(); // print the method that dispatches to the appropriate deserializer w.println("public <T> T deserialize (JavaScriptObject jso)"); w.println("{"); w.indent(); for (JClassType classType : classes) { // ignore abstract classes if (classType.isAbstract()) continue; // determine class name from string w.println(); w.println("if (classFromJso(jso) == \"" + classType.getQualifiedSourceName() + "\")"); w.println("{"); w.indent(); w.println(classType.getQualifiedSourceName() + " ret = new " + classType.getQualifiedSourceName() + "();"); w.println("deserializeJso(ret, jso);"); w.println("return (T) ret;"); w.outdent(); w.println("}"); w.println(); } w.println("return null;"); w.outdent(); w.println("}"); // emit individual deserializer methods (overloads) for (JClassType classType : classes) { if (classType.isAbstract()) continue; w.println(); w.println("private final native void deserializeJso(" + classType.getQualifiedSourceName() + " dest, " + "JavaScriptObject source) /*-{"); w.indent(); for (JField field : classType.getFields()) { if (!field.isStatic()) { w.print("dest.@" + classType.getQualifiedSourceName() + "::"); w.print(field.getName() + " = "); if (isAnnotatedSerializable(field)) { w.print("this.@" + genPackageName + "." + genClassName + "::deserialize("); w.print("Lcom/google/gwt/core/client/JavaScriptObject;)("); } w.print("source.class_data[\"" + field.getName() + "\"]"); if (isAnnotatedSerializable(field)) w.print(")"); w.println(";"); } } w.outdent(); w.println("}-*/;"); } }
From source file:org.rstudio.core.rebind.StaticDataResourceGenerator.java
License:Open Source License
@Override public String createAssignment(TreeLogger logger, ResourceContext context, JMethod method) throws UnableToCompleteException { URL[] resources = ResourceGeneratorUtil.findResources(logger, context, method); if (resources.length != 1) { logger.log(TreeLogger.ERROR, "Exactly one resource must be specified", null); throw new UnableToCompleteException(); }/* www .ja v a2 s .c o m*/ URL resource = resources[0]; String outputUrlExpression = context.deploy(resource, null, true); SourceWriter sw = new StringSourceWriter(); // Write the expression to create the subtype. sw.println("new " + StaticDataResource.class.getName() + "() {"); sw.indent(); // Convenience when examining the generated code. sw.println("// " + resource.toExternalForm()); sw.println("public String getUrl() {"); sw.indent(); sw.println("return " + outputUrlExpression + ";"); sw.outdent(); sw.println("}"); sw.println("public com.google.gwt.safehtml.shared.SafeUri getSafeUri() {"); sw.indent(); sw.println("return new org.rstudio.core.client.SafeUriStringImpl(" + outputUrlExpression + ");"); sw.outdent(); sw.println("}"); sw.println("public String getName() {"); sw.indent(); sw.println("return \"" + method.getName() + "\";"); sw.outdent(); sw.println("}"); sw.outdent(); sw.println("}"); return sw.toString(); }
From source file:org.senchalabs.gwt.gwtdriver.SeExporterGenerator.java
License:Apache License
@Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { TypeOracle oracle = context.getTypeOracle(); JClassType jso = oracle.findType(Name.getSourceNameForClass(JavaScriptObject.class)); JClassType toGenerate = oracle.findType(typeName).isClass(); String packageName = toGenerate.getPackage().getName(); String simpleSourceName = toGenerate.getName().replace('.', '_') + "Impl"; PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName); if (pw == null) { return packageName + "." + simpleSourceName; }// www. ja v a2s.c o m ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName); factory.setSuperclass(typeName); SourceWriter sw = factory.createSourceWriter(context, pw); List<String> exportedTypes; try { exportedTypes = context.getPropertyOracle().getConfigurationProperty(SELENIUM_METHODS).getValues(); } catch (BadPropertyValueException e) { logger.log(TreeLogger.Type.ERROR, "Can't find any config property for " + SELENIUM_METHODS + " declared", e); throw new UnableToCompleteException(); } sw.println("protected void exportRegisteredTypes() {"); sw.indent(); //for each type set up in a config property, for (String exportedType : exportedTypes) { JClassType toExport = oracle.findType(exportedType); if (toExport == null) { logger.log(TreeLogger.Type.ERROR, "Cannot find " + exportedType + " be sure it is a valid GWT type"); throw new UnableToCompleteException(); } MethodsFor refersToType = toExport.getAnnotation(MethodsFor.class); if (refersToType == null) { logger.log(Type.ERROR, "Type " + exportedType + " is declared as having webdriver methods, but has no @MethodsFor annotation"); throw new UnableToCompleteException(); } //verify a default ctor - if not, methods must be static boolean requireStatic = toExport.getConstructors().length != 0 && toExport.findConstructor(new JType[] {}) == null; if (requireStatic) { logger.log(Type.INFO, "No default constructor found, all marked methods must be static"); } TreeLogger typeLogger = logger.branch(TreeLogger.Type.DEBUG, "Exporting methods in " + exportedType); //iterate through the methods for (JMethod m : toExport.getInheritableMethods()) { Method refersToMethod = m.getAnnotation(Method.class); if (refersToMethod == null) { continue; } TreeLogger methodLogger = typeLogger.branch(Type.DEBUG, "Examining " + m.getName()); if (requireStatic && !m.isStatic()) { typeLogger.log(Type.ERROR, "No default constructor found for " + exportedType + ", can't export instance method" + m.getName()); typeLogger.log(Type.ERROR, "Either mark the method as static, or ensure there is a default constructor."); throw new UnableToCompleteException(); } //verify that the method matches exactly one method in the webdriver side //TODO make this a little faster String matchingMethod = null; for (java.lang.reflect.Method exportableMethod : refersToType.value().getMethods()) { if (refersToMethod.value().equals(exportableMethod.getName())) { if (matchingMethod != null) { methodLogger.log(Type.ERROR, "Multiple methods found that match " + refersToMethod.value()); throw new UnableToCompleteException(); } matchingMethod = refersToMethod.value(); } } if (matchingMethod == null) { methodLogger.log(Type.ERROR, "Can't find a method that matches " + refersToMethod.value()); throw new UnableToCompleteException(); } //emit a registerFunction call wrapping it sw.println("registerFunction(\"%1$s\", \"%2$s\", new %3$s() {", escape(refersToType.value().getName()), escape(matchingMethod), Name.getSourceNameForClass(Function.class)); sw.indent(); sw.println("public Object apply(%1$s<?> args) {", Name.getSourceNameForClass(JsArray.class)); sw.indent(); JType retType = m.getReturnType(); if (retType.isPrimitive() != null) { switch (retType.isPrimitive()) { case VOID: //do nothing break; case INT: case DOUBLE: case BOOLEAN: sw.print("return \"\" + "); break; default: methodLogger.log(Type.ERROR, "Can't return primitive " + retType + " from exported method"); throw new UnableToCompleteException(); } } else if (retType.isClass() != null && retType.getQualifiedSourceName().equals("java.lang.String") || ((retType.isClass() != null) && retType.isClass().isAssignableTo(jso)) || ((retType.isInterface() != null) && oracle.getSingleJsoImplInterfaces().contains(retType))) { sw.print("return "); } else { methodLogger.log(Type.ERROR, "Can't return non-jso, non-supported primitive " + retType + " from exported method"); throw new UnableToCompleteException(); } if (m.isStatic()) { sw.print(exportedType); } else { sw.print("%1$s.<%2$s>create(%2$s.class)", GWT.class.getName(), exportedType); } sw.print(".%1$s(", matchingMethod); //iterate through the arguments //verify the arg type is legal JType[] erasedParameterTypes = m.getErasedParameterTypes(); for (int i = 0; i < erasedParameterTypes.length; i++) { JType type = erasedParameterTypes[i]; if (type.isPrimitive() != null || type.getQualifiedSourceName().equals("java.lang.String")) { //cast uglyness sw.print("args.<%2$s>cast().get(%1$d)", i, getJsArray(type)); } else if (type.isClass() != null && type.isClass().isAssignableTo(jso)) { //normal array plus cast() trickery sw.print("args.get(%1$d).<%2$s>cast()", i, type.getQualifiedSourceName()); } else if (type.isInterface() != null && oracle.getSingleJsoImplInterfaces().contains(type.isInterface())) { //single jso cast thing sw.print("args.get(%1$d).<%2$s>cast()", i, oracle.getSingleJsoImpl(type.isInterface()).getQualifiedSourceName()); } else {//TODO goktug's magic new jsinterface methodLogger.log(Type.ERROR, "Can't handle argument of type " + type); throw new UnableToCompleteException(); } if (i != erasedParameterTypes.length - 1) { sw.println(","); } } sw.println(");"); if (m.getReturnType() == JPrimitiveType.VOID) { sw.println("return null;"); } sw.outdent(); sw.println("}"); sw.outdent(); sw.println("});"); } } sw.outdent(); sw.println("}"); sw.commit(logger); return factory.getCreatedClassName(); }
From source file:org.switchyard.console.components.rebind.ComponentExtensionManagerGenerator.java
License:Apache License
private void generateClass(TreeLogger logger, GeneratorContext context, String packageName, String className, List<JClassType> componentExtensionClasses) { PrintWriter pw = context.tryCreate(logger, packageName, className); if (pw == null) { return;/*from ww w . j a va 2 s . c o m*/ } ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className); // imports composerFactory.addImport(HashMap.class.getCanonicalName()); composerFactory.addImport(Map.class.getCanonicalName()); composerFactory.addImport(ComponentProvider.class.getCanonicalName()); composerFactory.addImport(ComponentExtensionManager.class.getCanonicalName()); composerFactory.addImport(ComponentProviderProxyImpl.class.getCanonicalName()); composerFactory.addImport(GWT.class.getCanonicalName()); composerFactory.addImport(Inject.class.getCanonicalName()); // interface composerFactory.addImplementedInterface(ComponentExtensionManager.class.getCanonicalName()); SourceWriter sw = composerFactory.createSourceWriter(context, pw); // fields sw.println( "private Map<String, ComponentProviderProxy> _providers = new HashMap<String, ComponentProviderProxy>();"); sw.println("private Map<String, String> _typeToName = new HashMap<String, String>();"); // constructor sw.println("public " + className + "() {"); sw.indent(); for (JClassType extensionClass : componentExtensionClasses) { ComponentExtension extensionAnnotation = extensionClass.getAnnotation(ComponentExtension.class); sw.println("_providers.put(\"" + extensionAnnotation.componentName() + "\", new ComponentProviderProxyImpl(\"" + extensionAnnotation.displayName() + "\") {"); sw.indent(); sw.println("public ComponentProvider instantiate() {"); sw.indentln("return GWT.create(" + extensionClass.getQualifiedSourceName() + ".class);"); sw.println("}"); sw.outdent(); sw.println("});"); for (String type : extensionAnnotation.activationTypes()) { sw.println("_typeToName.put(\"" + type + "\", \"" + extensionAnnotation.componentName() + "\");"); } } sw.outdent(); sw.println("}"); // methods // getExtensionProviders sw.println("public Map<String, ComponentProviderProxy> getExtensionProviders() {"); sw.indentln("return _providers;"); sw.println("}"); // getExtensionProviderByComponentName sw.println("public ComponentProviderProxy getExtensionProviderByComponentName(String componentName) {"); sw.indent(); sw.println("if (_providers.containsKey(componentName)) {"); sw.indentln("return _providers.get(componentName);"); sw.println("}"); sw.println("return null;"); sw.outdent(); sw.println("}"); // getExtensionProviderByTypeName sw.println("public ComponentProviderProxy getExtensionProviderByTypeName(String typeName) {"); sw.indent(); sw.println("if (_typeToName.containsKey(typeName)) {"); sw.indentln("return getExtensionProviderByComponentName(_typeToName.get(typeName));"); sw.println("}"); sw.println("return null;"); sw.outdent(); sw.println("}"); // close it out sw.outdent(); sw.println("}"); context.commit(logger, pw); }
From source file:org.tiwonk.gwt.rest.generator.ClientResourceGenerator.java
License:Apache License
private void saveMethodReturnsLocation(GeneratorInfo info, SourceWriter writer, JMethod method) throws UnableToCompleteException { String callbackParam = info.asyncCallbackParam.getName(); String resourceParam = info.resourceParam.getName(); String methodName = info.httpMethod.toString(); // RequestBuilder request = new RequestBuilder(RequestBuilder.POST, getResourceURL()); writer.println();/*from ww w . j a v a 2 s.c o m*/ writer.indent(); writer.println("RequestBuilder request = new RequestBuilder(RequestBuilder." + methodName + ", getResourceURL());"); // request.setHeader("Content-Type", "application/vnd.example.v1.person"); String consumes = info.consumes(method); if (consumes != null) { writer.print("request.setHeader(\"Content-Type\", \""); writer.print(consumes); writer.println("\");"); } String produces = info.produces(method); if (produces != null) { writer.print("request.setHeader(\"Accept\", \""); writer.print(produces); writer.println("\");"); } // JSONObject json = new JSONObject(person); // String payload = json.toString(); writer.println(); writer.print("JSONObject json = new JSONObject("); writer.print(resourceParam); writer.println(");"); writer.println("String payload = json.toString();"); // try { // request.sendRequest(payload, new RequestCallback() { writer.println(); writer.println("try {"); writer.indent(); writer.println("request.sendRequest(payload, new RequestCallback() {"); writer.indent(); // @Override // public void onResponseReceived(Request request, Response response) { // // if ( // response.getStatusCode() != Response.SC_CREATED && // response.getStatusCode() != Response.SC_OK // ) { // onError(request, new ResourceAccessException(response)); // return; // } // // String location = response.getHeader("Location"); // callback.onSuccess(location); // // } writer.println(); writer.println("@Override"); writer.println("public void onResponseReceived(Request request, Response response) {"); writer.indent(); writer.println("if ("); writer.println(" response.getStatusCode() != Response.SC_CREATED &&"); writer.println(" response.getStatusCode() != Response.SC_OK"); writer.println(") {"); writer.println(" onError(request, new ResourceAccessException(response));"); writer.println(" return;"); writer.println("}"); writer.println(); writer.println("String location = response.getHeader(\"Location\");"); writer.print(callbackParam); writer.println(".onSuccess(location);"); writer.outdent(); writer.println("}"); // @Override // public void onError(Request request, Throwable e) { // callback.onFailure(e); // } // }); writer.println(); writer.println("@Override"); writer.println("public void onError(Request request, Throwable e) {"); writer.print(" "); writer.print(callbackParam); writer.println(".onFailure(e);"); writer.println("}"); writer.outdent(); writer.println("});"); writer.outdent(); // } catch (RequestException e) { // callback.onFailure(e); // } writer.println(); writer.println("} catch (RequestException e) {"); writer.print(" "); writer.print(callbackParam); writer.println(".onFailure(e);"); writer.println("}"); writer.outdent(); }
From source file:org.tiwonk.gwt.rest.generator.ClientResourceGenerator.java
License:Apache License
private void saveMethodReturnsEntity(GeneratorInfo info, SourceWriter writer, JMethod method) throws UnableToCompleteException { String callbackParam = info.asyncCallbackParam.getName(); String resourceParam = info.resourceParam.getName(); String callbackType = info.asyncType.getSimpleSourceName(); String methodName = info.httpMethod.toString(); // RequestBuilder request = new RequestBuilder(RequestBuilder.POST, getResourceURL()); writer.println();//www. ja v a 2s. co m writer.indent(); writer.println("RequestBuilder request = new RequestBuilder(RequestBuilder." + methodName + ", getResourceURL());"); // request.setHeader("Content-Type", "application/vnd.example.v1.person"); String consumes = info.consumes(method); if (consumes != null) { writer.print("request.setHeader(\"Content-Type\", \""); writer.print(consumes); writer.println("\");"); } String produces = info.produces(method); if (produces != null) { writer.print("request.setHeader(\"Accept\", \""); writer.print(produces); writer.println("\");"); } // JSONObject json = new JSONObject(person); // String payload = json.toString(); writer.println(); writer.print("JSONObject json = new JSONObject("); writer.print(resourceParam); writer.println(");"); writer.println("String payload = json.toString();"); // try { // request.sendRequest(payload, new RequestCallback() { writer.println(); writer.println("try {"); writer.indent(); writer.println("request.sendRequest(payload, new RequestCallback() {"); writer.indent(); // @Override // public void onResponseReceived(Request request, Response response) { // // if ( // response.getStatusCode() != Response.SC_CREATED && // response.getStatusCode() != Response.SC_OK // ) { // onError(request, new ResourceAccessException(response)); // return; // } // JSONValue value = JSONParser.parseStrict(response.getText()); // PersonRef entity = value.isObject().getJavaScriptObject().cast(); // callback.onSuccess(entity); // } writer.println(); writer.println("@Override"); writer.println("public void onResponseReceived(Request request, Response response) {"); writer.indent(); writer.println("if ("); writer.println(" response.getStatusCode() != Response.SC_CREATED &&"); writer.println(" response.getStatusCode() != Response.SC_OK"); writer.println(") {"); writer.println(" onError(request, new ResourceAccessException(response));"); writer.println(" return;"); writer.println("}"); writer.println(); writer.println("JSONValue value = JSONParser.parseStrict(response.getText());"); writer.print(callbackType); writer.println(" entity = value.isObject().getJavaScriptObject().cast();"); writer.print(callbackParam); writer.println(".onSuccess(entity);"); writer.outdent(); writer.println("}"); // @Override // public void onError(Request request, Throwable e) { // callback.onFailure(e); // } // }); writer.println(); writer.println("@Override"); writer.println("public void onError(Request request, Throwable e) {"); writer.print(" "); writer.print(callbackParam); writer.println(".onFailure(e);"); writer.println("}"); writer.outdent(); writer.println("});"); writer.outdent(); // } catch (RequestException e) { // callback.onFailure(e); // } writer.println(); writer.println("} catch (RequestException e) {"); writer.print(" "); writer.print(callbackParam); writer.println(".onFailure(e);"); writer.println("}"); writer.outdent(); }