List of usage examples for com.google.gwt.user.rebind SourceWriter print
void print(String s);
From source file:org.jboss.errai.bus.rebind.BusClientConfigGenerator.java
License:Apache License
public void generate(GeneratorContext context, TreeLogger logger, SourceWriter writer, MetaDataScanner scanner, final TypeOracle oracle) { for (Class<?> entity : scanner.getTypesAnnotatedWith(ExposeEntity.class)) { generateMarshaller(loadType(oracle, entity), logger, writer); }/* w w w.jav a 2s . com*/ for (Class<?> remote : scanner.getTypesAnnotatedWith(Remote.class)) { JClassType type = loadType(oracle, remote); try { writer.print((String) execute(rpcProxyGenerator, Make.Map.<String, Object>$()._("implementationClassName", type.getName() + "Impl") ._("interfaceClass", Class.forName(type.getQualifiedSourceName()))._())); } catch (Throwable t) { throw new ErraiBootstrapFailure(t); } } Properties props = scanner.getProperties("ErraiApp.properties"); if (props != null) { logger.log(TreeLogger.Type.INFO, "Checking ErraiApp.properties for configured types ..."); for (Object o : props.keySet()) { String key = (String) o; /** * Types configuration */ if (ErraiServiceConfigurator.CONFIG_ERRAI_SERIALIZABLE_TYPE.equals(key)) { for (String s : props.getProperty(key).split(" ")) { try { generateMarshaller(oracle.getType(s.trim()), logger, writer); } catch (Exception e) { e.printStackTrace(); throw new ErraiBootstrapFailure(e); } } } /** * Entity configuration */ else if (ErraiServiceConfigurator.CONFIG_ERRAI_SERIALIZABLE_TYPE.equals(key)) { for (String s : props.getProperty(key).split(" ")) { try { generateMarshaller(oracle.getType(s.trim()), logger, writer); } catch (Exception e) { e.printStackTrace(); throw new ErraiBootstrapFailure(e); } } } } } else { // props not found log.warn("No modules found ot load. Unable to find ErraiApp.properties in the classpath"); } }
From source file:org.jboss.errai.bus.rebind.BusClientConfigGenerator.java
License:Apache License
private void generateMarshaller(JClassType visit, TreeLogger logger, SourceWriter writer) { Boolean enumType = visit.isEnum() != null; Map<String, Class> types = new HashMap<String, Class>(); Map<String, ValueExtractor> getters = new HashMap<String, ValueExtractor>(); Map<String, ValueBinder> setters = new HashMap<String, ValueBinder>(); Map<Class, Integer> arrayConverters = new HashMap<Class, Integer>(); try {//from w ww .j a v a 2s.c o m JClassType scan = visit; do { for (JField f : scan.getFields()) { if (f.isTransient() || f.isStatic() || f.isEnumConstant() != null) continue; JClassType type = f.getType().isClassOrInterface(); JMethod getterMeth; JMethod setterMeth; if (type == null) { JPrimitiveType pType = f.getType().isPrimitive(); Class c; if (pType == null) { JArrayType aType = f.getType().isArray(); if (aType == null) continue; String name = aType.getQualifiedBinaryName(); int depth = 0; for (int i = 0; i < name.length(); i++) { if (name.charAt(i) == '[') depth++; else break; } types.put(f.getName(), c = Class.forName(name.substring(0, depth) + getInternalRep(aType.getQualifiedBinaryName().substring(depth)))); arrayConverters.put(c, depth); } else { types.put(f.getName(), c = ParseTools .unboxPrimitive(Class.forName(pType.getQualifiedBoxedSourceName()))); } } else { types.put(f.getName(), Class.forName(type.getQualifiedBinaryName())); } getterMeth = getAccessorMethod(visit, f); setterMeth = getSetterMethod(visit, f); if (getterMeth == null) { if (f.isPublic()) { getters.put(f.getName(), new ValueExtractor(f)); } else if (visit == scan) { throw new GenerationException("could not find a read accessor in class: " + visit.getQualifiedSourceName() + "; for field: " + f.getName() + "; should declare an accessor: " + ReflectionUtil.getGetter(f.getName())); } } else { getters.put(f.getName(), new ValueExtractor(getterMeth)); } if (setterMeth == null) { if (f.isPublic()) { setters.put(f.getName(), new ValueBinder(f)); } else if (visit == scan) { throw new GenerationException("could not find a write accessor in class: " + visit.getQualifiedSourceName() + "; for field: " + f.getName() + "; should declare an accessor: " + ReflectionUtil.getSetter(f.getName())); } } else { setters.put(f.getName(), new ValueBinder(setterMeth)); } } } while ((scan = scan.getSuperclass()) != null && !scan.getQualifiedSourceName().equals("java.lang.Object")); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException(e); } try { if (!enumType) visit.getConstructor(new JClassType[0]); } catch (NotFoundException e) { String errorMsg = "Type marked for serialization does not expose a default constructor: " + visit.getQualifiedSourceName(); logger.log(TreeLogger.Type.ERROR, errorMsg, e); throw new GenerationException(errorMsg, e); } Map<String, Object> templateVars = Make.Map.<String, Object>$() ._("className", visit.getQualifiedSourceName()) ._("canonicalClassName", visit.getQualifiedBinaryName())._("fields", types.keySet()) ._("targetTypes", types)._("getters", getters)._("setters", setters) ._("arrayConverters", arrayConverters)._("enumType", enumType)._(); String genStr; writer.print(genStr = (String) execute(demarshallerGenerator, templateVars)); log.debug("generated demarshaller: \n" + genStr); logger.log(TreeLogger.Type.INFO, genStr); writer.print(genStr = (String) execute(marshallerGenerator, templateVars)); log.debug("generated marshaller: \n" + genStr); logger.log(TreeLogger.Type.INFO, genStr); logger.log(TreeLogger.Type.INFO, "Generated marshaller/demarshaller for: " + visit.getName()); }
From source file:org.jboss.errai.widgets.rebind.WidgetMappingsGenerator.java
License:Apache License
private void generateExtensions(GeneratorContext context, TreeLogger logger, SourceWriter sourceWriter) { // start constructor source generation sourceWriter.println("public " + className + "() { "); sourceWriter.println("}"); sourceWriter.println("public void mapAll(final " + strTargetType + " widget) { "); sourceWriter.outdent();// ww w .jav a2 s. c om try { JClassType widgetMapper = typeOracle.getType(CollectionWidgetMapper.class.getName()); for (JField currField : targetClass.getFields()) { if (currField.isAnnotationPresent(WidgetMapper.class) && widgetMapper.isAssignableFrom(currField.getType().isClassOrInterface())) { WidgetMapper mf = currField.getAnnotation(WidgetMapper.class); JField widgetField = targetClass.getField(mf.value()); String varName = widgetField.getName() + "Mapper"; JClassType binderField = currField.getType().isClassOrInterface(); JParameterizedType pType = binderField.isParameterized(); if (pType == null) { RuntimeException e = new RuntimeException( "Field '" + currField.getName() + "' must be parameterized"); logger.log(TreeLogger.Type.ERROR, e.getMessage(), e); throw e; } // The last type arg shall always be our domain object type per this spec. JClassType jEntityTarget = pType.getTypeArgs()[pType.getTypeArgs().length - 1]; String strTypeParms = generateTypeParmString(pType); List<JField> fieldsToMap = new LinkedList<JField>(); /** * If an EntityFields annotatio is present, then we discriminate on those fields. Otherwise * we capture all fields by default. */ if (currField.isAnnotationPresent(EntityFields.class)) { EntityFields ef = currField.getAnnotation(EntityFields.class); for (String fieldName : ef.value()) { JField fld = jEntityTarget.getField(fieldName); if (fld == null) { RuntimeException e = new RuntimeException("no such field in entity class '" + jEntityTarget.getName() + "': " + fieldName); logger.log(TreeLogger.Type.ERROR, e.getMessage(), e); throw e; } fieldsToMap.add(jEntityTarget.getField(fieldName)); } } else { for (JField fld : jEntityTarget.getFields()) { if (fld.getEnclosingType().equals(jEntityTarget)) { fieldsToMap.add(fld); } } } List<String> generatedInitializations = new LinkedList<String>(); List<String> generatedBindings = new LinkedList<String>(); FieldMapperGenerator g = getFieldMapper(widgetField.getType().getQualifiedSourceName()); generatedInitializations.add( g.init(typeOracle, widgetField, jEntityTarget, currField, null, varName, fieldsToMap)); if (g == null) { throw new RuntimeException( "Cannot generateGetField mapper for widget: " + jEntityTarget.getName()); } for (JField fld : fieldsToMap) { String fieldName = fld.getName(); JField targetField = jEntityTarget.getField(fieldName); if (targetField == null) { throw new RuntimeException( "The field '" + fieldName + "' does not correspond with a field in the class: " + jEntityTarget.getQualifiedSourceName()); } generatedBindings.add(g.generateFieldMapperGenerator(typeOracle, widgetField, jEntityTarget, null, targetField)); } Map<String, Object> vars = new HashMap<String, Object>(); vars.put("typeOracle", typeOracle); vars.put("variableName", varName); vars.put("strTypeParms", strTypeParms); vars.put("targetWidget", widgetField.getType().getQualifiedSourceName()); vars.put("targetType", jEntityTarget.getQualifiedSourceName()); vars.put("initializers", generatedInitializations); vars.put("bindings", generatedBindings); vars.put("targetFieldName", widgetField.getName()); String s = (String) TemplateRuntime.execute(mappingsGen, vars); sourceWriter.print(s); s = "widget." + currField.getName() + " = " + varName + ";"; sourceWriter.println(s); } else if (currField.isAnnotationPresent(EntityMapped.class)) { EntityMapped entityMappedA = currField.getAnnotation(EntityMapped.class); JClassType entityType = currField.getType().isClassOrInterface(); String varName = currField.getName() + "Mapper"; String entityFieldName = currField.getName(); String toEntityField; Map<String, List<JField>> toBeMapped = new HashMap<String, List<JField>>(); for (JField fld : targetClass.getFields()) { if (fld.isAnnotationPresent(MapField.class)) { MapField mapFieldA = fld.getAnnotation(MapField.class); toEntityField = "".equals(mapFieldA.value()) ? entityFieldName : mapFieldA.value(); if (!toBeMapped.containsKey(toEntityField)) { toBeMapped.put(toEntityField, new LinkedList<JField>()); } toBeMapped.get(toEntityField).add(fld); } } /** * Generate the field mappings. */ for (Map.Entry<String, List<JField>> entry : toBeMapped.entrySet()) { List<String> generatedInitializations = new LinkedList<String>(); List<String> generatedBindings = new LinkedList<String>(); ArrayList<String[]> fieldIndexPositions = new ArrayList<String[]>(); for (JField fld : entry.getValue()) { JClassType classType = fld.getType().isClassOrInterface(); String fieldName = fld.getAnnotation(MapField.class).value(); if ("".equals(fieldName)) { fieldName = fld.getName(); } JField targetField = entityType.getField(fieldName); if (targetField == null) { throw new RuntimeException("The field '" + fieldName + "' does not correspond with a field in the class: " + entityType.getQualifiedSourceName()); } JClassType targetFieldType = targetField.getType().isClassOrInterface(); FieldMapperGenerator g = getFieldMapper(classType.getQualifiedSourceName()); if (g == null) { throw new RuntimeException( "Cannot generateGetField mapper for widget: " + classType.getName()); } generatedInitializations .add(g.init(typeOracle, fld, entityType, targetField, currField, null, null)); generatedBindings.add(g.generateFieldMapperGenerator(typeOracle, fld, entityType, targetField, currField)); if (getType(typeOracle, Widget.class).isAssignableFrom(classType)) { fieldIndexPositions .add(new String[] { fieldName, g.generateValueExtractorStatement(typeOracle, fld, entityType, targetField, currField) }); } } Map<String, Object> vars = new HashMap<String, Object>(); vars.put("typeOracle", typeOracle); vars.put("variableName", varName); vars.put("initializers", generatedInitializations); vars.put("targetFieldName", entityFieldName); vars.put("bindings", generatedBindings); vars.put("fieldIndexPositions", fieldIndexPositions); vars.put("entityFieldName", entityFieldName); String s = (String) TemplateRuntime.execute(entityMappingGen, vars); sourceWriter.print(s); } } else if (currField.isAnnotationPresent(AddAllTo.class)) { String copyToField = currField.getAnnotation(AddAllTo.class).value(); String copyFromField = currField.getName(); Map<String, Object> vars = new HashMap<String, Object>(); vars.put("copyToField", copyToField); vars.put("copyFromField", copyFromField); String s = (String) TemplateRuntime.execute(addAllToGen, vars); sourceWriter.print(s); } } } catch (Exception e) { logger.log(TreeLogger.Type.ERROR, "failed to map field (does not exist)", e); e.printStackTrace(); } // end constructor source generation sourceWriter.outdent(); sourceWriter.println("}"); }
From source file:org.jboss.errai.workspaces.rebind.WorkspaceLoaderBootstrapGenerator.java
License:Apache License
private void generateBootstrapClass(final GeneratorContext context, final TreeLogger logger, final SourceWriter sourceWriter) { ResourceBundle bundle;//from ww w . java2 s. c om try { bundle = ResourceBundle.getBundle("org.jboss.errai.workspaces.rebind.WorkspaceModules"); } catch (Exception e) { logger.log(TreeLogger.Type.ERROR, "can't find WorkspaceModules.properties in classpath"); logger.log(TreeLogger.Type.ERROR, e.getMessage()); throw new RuntimeException(); } // start constructor source generation sourceWriter.println("public " + className + "() { "); sourceWriter.indent(); sourceWriter.println("super();"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println( "public void configure(org.jboss.errai.workspaces.client.framework.ToolContainer workspace) { "); sourceWriter.outdent(); // toolset profile (acts as whitelist). Used with BPM console atm final List<String> enabledTools = new ArrayList<String>(); InputStream in = getClass().getClassLoader().getResourceAsStream(TOOLSET_PROFILE); if (in != null) { try { BufferedReader input = new BufferedReader(new InputStreamReader(in)); try { String line = null; while ((line = input.readLine()) != null) { // ignore comments and empty lines if (line.equals("") || line.startsWith("#")) continue; enabledTools.add(line); } } finally { input.close(); } } catch (IOException ex) { throw new RuntimeException("Error reading '" + TOOLSET_PROFILE + "'"); } } for (Enumeration<String> keys = bundle.getKeys(); keys.hasMoreElements();) { String key = keys.nextElement(); sourceWriter.println("new " + bundle.getString(key) + "().initModule(errai);"); } final boolean applyFilter = in != null; MetaDataScanner scanner = ScannerSingleton.getOrCreateInstance(); /** * LoadToolSet */ Set<Class<?>> toolsets = scanner.getTypesAnnotatedWith(LoadToolSet.class); for (Class<?> toolSetClass : toolsets) { JClassType clazz = typeOracle.findType(toolSetClass.getName()); MetaClass metaClass = MetaClassFactory.get(clazz); if ((!applyFilter || enabledTools.contains(clazz.getQualifiedSourceName()))) { sourceWriter.println( "workspace.addToolSet(" + Stmt.newObject(metaClass).generate(Context.create()) + ");"); logger.log(TreeLogger.Type.INFO, "Adding Errai Toolset: " + clazz.getQualifiedSourceName()); } } /** * LoadTool */ Set<Class<?>> tools = scanner.getTypesAnnotatedWith(LoadTool.class); for (Class<?> toolClass : tools) { JClassType clazz = typeOracle.findType(toolClass.getName()); MetaClass metaClass = MetaClassFactory.get(clazz); if ((!applyFilter || enabledTools.contains(clazz.getQualifiedSourceName()))) { LoadTool loadTool = clazz.getAnnotation(LoadTool.class); logger.log(TreeLogger.Type.INFO, "Adding Errai Tool: " + clazz.getQualifiedSourceName()); if (clazz.isAnnotationPresent(RequireRoles.class)) { RequireRoles requireRoles = clazz.getAnnotation(RequireRoles.class); StringBuilder rolesBuilder = new StringBuilder("new String[] {"); String[] roles = requireRoles.value(); for (int i = 0; i < roles.length; i++) { rolesBuilder.append("\"").append(roles[i].trim()).append("\""); if ((i + 1) < roles.length) rolesBuilder.append(", "); } rolesBuilder.append("}"); generateWidgetProvisioning(context, clazz.getQualifiedSourceName(), loadTool, rolesBuilder, logger, sourceWriter); } else { generateWidgetProvisioning(context, clazz.getQualifiedSourceName(), loadTool, null, logger, sourceWriter); } } else if (clazz.isAnnotationPresent(LoginComponent.class)) { sourceWriter.println("workspace.setLoginComponent(new " + clazz.getQualifiedSourceName() + "());"); } } /** * Group order */ Set<Class<?>> groupOrderClasses = scanner.getTypesAnnotatedWith(GroupOrder.class); for (Class<?> clazz : groupOrderClasses) { GroupOrder groupOrder = clazz.getAnnotation(GroupOrder.class); if ("".equals(groupOrder.value().trim())) return; String[] order = groupOrder.value().split(","); sourceWriter.print("workspace.setPreferredGroupOrdering(new String[] {"); for (int i = 0; i < order.length; i++) { sourceWriter.print("\""); sourceWriter.print(order[i].trim()); sourceWriter.print("\""); if (i + 1 < order.length) { sourceWriter.print(","); } } sourceWriter.println("});"); } // wrap up sourceWriter.outdent(); sourceWriter.println("}"); }
From source file:org.jboss.errai.workspaces.rebind.WorkspaceLoaderBootstrapGenerator.java
License:Apache License
public void generateWidgetProvisioning(final GeneratorContext context, String className, final LoadTool loadTool, final StringBuilder rolesBuilder, final TreeLogger logger, final SourceWriter writer) { MetaClass type;/* ww w. jav a2 s . c o m*/ MetaClass widgetType; try { type = MetaClassFactory.get(typeOracle.getType(className)); widgetType = MetaClassFactory.get(typeOracle.getType(Widget.class.getName())); } catch (NotFoundException e) { throw new RuntimeException("error bootstrapping: " + className, e); } if (widgetType.isAssignableFrom(type)) { writer.println(WidgetProvider.class.getName() + " widgetProvider" + (++counter) + " = new " + WidgetProvider.class.getName() + "() {"); writer.outdent(); writer.println("public void provideWidget(" + ProvisioningCallback.class.getName() + " callback) {"); writer.outdent(); writer.println("callback.onSuccess(" + Stmt.newObject(type).generate(Context.create()) + ");"); writer.outdent(); writer.println("}"); writer.outdent(); writer.println("};"); } writer.print("workspace.addTool(\"" + loadTool.group() + "\"," + " \"" + loadTool.name() + "\", \"" + loadTool.icon() + "\", " + loadTool.multipleAllowed() + ", " + loadTool.priority() + ", " + Stmt.newObject(type).generate(Context.create())); if (rolesBuilder == null) { writer.println(");"); } else { writer.println(", " + rolesBuilder.toString() + ");"); } }
From source file:org.lirazs.gbackbone.gen.reflection.GeneratorHelper.java
License:Apache License
public static void addAnnotations_AnnotationImpl(TypeOracle typeOracle, String dest, SourceWriter source, Annotation[] annotations, TreeLogger logger) { if (annotations.length <= 0) return;//from ww w . j a va 2 s . c o m for (Annotation annotation : annotations) { JClassType classType = typeOracle .findType(ReflectionUtils.getQualifiedSourceName(annotation.annotationType())); if (classType != null) { source.print( dest + ".addAnnotation(" + createAnnotationValues(typeOracle, annotation, logger) + ");"); } else { logger.log(Type.ERROR, "Annotation (" + ReflectionUtils.getQualifiedSourceName(annotation.annotationType()) + ") not exists in compiled client source code, please ensure this class is exists and included in your module(.gwt.xml) file. GWTENT reflection process will ignore it and continue. "); } } }
From source file:org.lirazs.gbackbone.gen.reflection.ReflectAllInOneCreator.java
License:Apache License
@Override public void createSource(SourceWriter source, JClassType classType) { //ClassType -->> the interface name created automatically Map<JClassType, String> typeNameMap = new HashMap<JClassType, String>(); genAllClasses(source, typeNameMap);/*from www . j a v a2 s . c o m*/ // source.println("public " + getSimpleUnitName(classType) + "(){"); // source.indent(); // // for (String classname : allGeneratedClassNames){ // source.println("new " + classname + "();"); // } // source.outdent(); // source.println("}"); source.println("public org.lirazs.gbackbone.reflection.client.Type doGetType(String name) {"); source.indent(); //source.println("org.lirazs.gbackbone.reflection.client.Type resultType = super.doGetType(name);"); //source.println("if (resultType != null) {return resultType;}"); for (JClassType type : typeNameMap.keySet()) { source.println("if (name.equals( \"" + type.getQualifiedSourceName() + "\")){return GWT.create(" + typeNameMap.get(type) + ".class);}"); } source.println(); source.println("return null;"); source.outdent(); source.print("}"); }
From source file:org.nuxeo.ecm.platform.gwt.rebind.JSourceWriter.java
License:Open Source License
public void commit(TreeLogger logger) { for (String imp : imports) { composer.addImport(imp);//from w w w . jav a 2s . c o m } for (String intfName : interfaces) { composer.addImplementedInterface(intfName); } SourceWriter sw = composer.createSourceWriter(context, printWriter); // only to debug // System.out.println("----------------------------------------------"); // System.out.println(toString()); // System.out.println("----------------------------------------------"); sw.print(toString()); sw.commit(logger); }
From source file:org.parallax3d.parallax.platforms.gwt.generator.SourceTextResourceGenerator.java
License:Open Source License
private void writeLongString(SourceWriter sw, String toWrite) { sw.println("StringBuilder builder = new StringBuilder();"); int offset = 0; int subLength; for (int length = toWrite.length(); offset < length - 1; offset += subLength) { subLength = Math.min(16383, length - offset); sw.print("builder.append(\""); sw.print(Generator.escape(toWrite.substring(offset, offset + subLength))); sw.println("\");"); }//from w w w . ja va2 s .c om sw.println("return builder.toString();"); }
From source file:org.pentaho.ui.xul.gwt.generators.EventHandlerGenerator.java
License:Open Source License
private void generateMethods(SourceWriter sourceWriter) { sourceWriter.println("public void execute(String method, Object[] args) { "); sourceWriter.indent();/*from w ww. j a va 2 s .c o m*/ try { JClassType classType = typeOracle.getType(typeName); do { for (JMethod m : classType.getMethods()) { String methodName = m.getName(); if (!m.isPublic()) { continue; } sourceWriter.println("if(method.equals(\"" + methodName + "\")){"); sourceWriter.indent(); boolean firstParam = true; // method call sourceWriter.print("handler." + methodName + "("); int argPos = 0; for (JParameter param : m.getParameters()) { if (!firstParam) { sourceWriter.print(", "); } else { firstParam = false; } sourceWriter.print("(" + boxPrimative(param.getType()) + ") args[" + argPos + "]"); argPos++; } sourceWriter.print(");"); // end method call sourceWriter.println("return;"); sourceWriter.outdent(); sourceWriter.println("}"); } } while ((classType = classType.getSuperclass()).getSimpleSourceName().equals("Object") == false); } catch (Exception e) { // record to logger that Map generation threw an exception logger.log(TreeLogger.ERROR, "PropertyMap ERROR!!!", e); } sourceWriter.println( "System.err.println(\"ERROR: method '\" + method + \"' not annotated with EventMethod.\");"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println(handlerClassName + " handler;"); sourceWriter.println("public void setHandler(XulEventHandler handler) { "); sourceWriter.indent(); sourceWriter.println("this.handler = (" + handlerClassName + ") handler;"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("public XulEventHandler getHandler() { "); sourceWriter.indent(); sourceWriter.println("return this.handler;"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("public String getName() { "); sourceWriter.indent(); sourceWriter.println("return this.handler.getName();"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("public Object getData() { "); sourceWriter.indent(); sourceWriter.println("return null;"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("public void setData(Object o) { "); sourceWriter.println("}"); }