Example usage for com.google.gwt.user.rebind SourceWriter print

List of usage examples for com.google.gwt.user.rebind SourceWriter print

Introduction

In this page you can find the example usage for com.google.gwt.user.rebind SourceWriter print.

Prototype

void print(String s);

Source Link

Usage

From source file:com.gwtplatform.mvp.rebind.TabInfoMethod.java

License:Apache License

private void writeTabInfoFunctionCall(SourceWriter writer) throws UnableToCompleteException {
    writer.print(functionName + "(");
    for (int i = 0; i < parameters.length; i++) {
        if (i > 0) {
            writer.print(", ");
        }//  ww w  .j  a va2  s.c  o m
        writer.print("ginjector");

        JParameter parameter = parameters[i];
        final JClassType returnType = parameter.getType().isClassOrInterface();
        if (!returnType.equals(ginjectorInspector.getGinjectorClass())) {
            writer.print(".");
            writer.print(ginjectorInspector.findGetMethod(returnType));
            writer.print("()");
        }
    }
    writer.print(")");
}

From source file:com.intrinsarc.backbone.gwt.generators.StateDispatcherGenerator.java

License:Apache License

protected void writeToStringMethod(TreeLogger logger, String proxyClassName, JClassType T,
        SourceWriter writer) {
    writer.println(/*from w ww  . j  a va2 s .c o  m*/
            "private java.util.List<IEvent> dDispatch_IEventRequired = new java.util.ArrayList<IEvent>();");
    writer.println(
            "public void setDDispatch(IEvent event, int index) { PortHelper.fill(this.dDispatch_IEventRequired, event, index); }");
    writer.println(
            "public void addDDispatch(IEvent event) { PortHelper.fill(this.dDispatch_IEventRequired, event, -1); }");
    writer.println(
            "public void removeDDispatch(IEvent event) { PortHelper.remove(this.dDispatch_IEventRequired, event); }");
    writer.println("private ITerminal dStart_ITerminalRequired;");
    writer.println("public void setDStart(ITerminal start) { dStart_ITerminalRequired = start; }");
    writer.println(
            "private java.util.List<ITerminal> dEnd_ITerminalRequired = new java.util.ArrayList<ITerminal>();");
    writer.println(
            "public void setDEnd(ITerminal end, int index) { PortHelper.fill(this.dEnd_ITerminalRequired, end, index); }");
    writer.println("private boolean currentEntered;");
    writer.println("private IEvent current;");
    writer.println("private boolean primed;");

    writer.println("  private void findNextState()");
    writer.println("  {");
    writer.println("    // possibly still in start or end?");
    writer.println("    if (dStart_ITerminalRequired != null && !primed)");
    writer.println("    {");
    writer.println("      dStart_ITerminalRequired.moveToNextState(); primed = true;");
    writer.println("    }");
    writer.println("    if (dEnd_ITerminalRequired != null)");
    writer.println("      for (ITerminal end : dEnd_ITerminalRequired)");
    writer.println("        if (end.isCurrent())");
    writer.println("             end.moveToNextState();");
    writer.println("    // find the next state");
    writer.println("    current = null;");
    writer.println("    for (IEvent e : dDispatch_IEventRequired)");
    writer.println("      if (e.isCurrent())");
    writer.println("      {");
    writer.println("           current = e;");
    writer.println("           break;");
    writer.println("      }");
    writer.println("  }");
    writer.println();

    writer.println("public IEvent getDEvents_Provided(Class<?> required)");
    writer.println("{");
    writer.println("  return new " + T.getQualifiedSourceName() + "()");
    writer.println("  {");
    Set<JMethod> all = new LinkedHashSet<JMethod>();
    getAllMethods(all, T);
    for (JMethod method : all) {
        String ret = method.getReturnType().getQualifiedBinaryName();
        boolean isVoid = ret.equals("void");
        writer.print("    public " + ret + " " + method.getName() + "(");
        int lp = 0;
        String params = "";
        String cparams = "";
        for (JParameter p : method.getParameters()) {
            if (lp != 0) {
                params += ", ";
                cparams += ", ";
            }
            lp++;
            params += p.getType().getQualifiedBinaryName() + " param" + lp;
            cparams += " param" + lp;
        }
        writer.println(params + ")");
        writer.println("    {");
        writer.println("      findNextState();");
        writer.println("      if (current != null)");
        writer.println("      {");
        String cast = "(" + T.getQualifiedSourceName() + ")";
        if (!isVoid) {
            writer.println(
                    "        " + ret + " v = (" + cast + "current)." + method.getName() + "(" + cparams + ");");
            writer.println("        findNextState();");
            writer.println("        return v;");
            writer.println("      }");

            if (ret.equals("boolean"))
                writer.println("      return false;");
            else if (ret.equals("int") || ret.equals("short") || ret.equals("long") || ret.equals("float")
                    || ret.equals("double") || ret.equals("byte") || ret.equals("char"))
                writer.println("      return 0;");
            else if (ret.equals("long"))
                writer.println("      return 0;");
            else
                writer.println("      return null;");
        } else {
            writer.println("        (" + cast + "current)." + method.getName() + "(" + cparams + ");");
            writer.println("        findNextState();");
            writer.println("      }");
        }
        writer.println("    }");
    }
    writer.println("\n  public String toString() { return \"State dispatcher: current state =\" + current; }");
    writer.println("  };\n");
    writer.println("}\n");
}

From source file:com.kk_electronic.gwt.rebind.ClassMapGenerator.java

License:Open Source License

private void writeMethods(SourceWriter sw) {
    sw.print("private static HashMap<" + keyType.getName() + ", Class<? extends " + valueType.getName()
            + ">> map");
    sw.println("= new HashMap<" + keyType.getName() + ", Class<? extends " + valueType.getName() + ">>();");
    sw.print("private static HashMap<Class<? extends " + valueType.getName() + ">," + keyType.getName()
            + "> reversemap");
    sw.println("= new HashMap<Class<? extends " + valueType.getName() + ">," + keyType.getName() + ">();");
    sw.println();//from  w  ww  . jav  a2s  .c o m
    sw.println("@Override");
    sw.println("public Class<? extends " + valueType.getName() + "> getClassFromKey(" + keyType.getName()
            + " name) {");
    sw.println("   return map.get(name);");
    sw.println("}");
    sw.println();
    sw.println("@Override");
    sw.println("public " + keyType.getName() + " getKeyFromClass(Class<? extends " + valueType.getName()
            + "> clazz) {");
    sw.println("   return reversemap.get(clazz);");
    sw.println("}");
}

From source file:com.kk_electronic.gwt.rebind.FlexInjectorGenerator.java

License:Open Source License

private void writeStatic(SourceWriter sw) throws UnableToCompleteException {
    modules.toString();/*from   w w  w. ja  v a  2s.  c om*/
    sw.print("@GinModules(");
    for (Class<? extends GinModule> s : modules.value()) {
        sw.print(s.getCanonicalName());
        sw.print(".class");
    }
    sw.println(")");
    sw.println("static interface Injector extends Ginjector {");
    sw.indent();
    Set<JType> set = new HashSet<JType>();
    for (Vector<JClassType> group : getClasses().values()) {
        set.addAll(group);
    }
    for (JMethod method : classType.getMethods()) {
        set.add(method.getReturnType());
    }
    for (JType j : set) {
        sw.println(
                j.getQualifiedSourceName() + " create$" + j.getQualifiedSourceName().replace('.', '$') + "();");
    }
    //      for(Vector<JClassType> group : getClasses().values()){
    //         for(JClassType j : group){
    //            sw.println(j.getQualifiedSourceName() + " create$" + j.getQualifiedSourceName().replace('.', '$') + "();");
    //         }
    //      }
    sw.outdent();
    sw.println("}");
    sw.println();
    sw.println("private final Injector injector = GWT.create(Injector.class);");
    sw.println("private Map<Class<?>, FlexInjector> fragmentMap = new HashMap<Class<?>, FlexInjector>();");
    sw.println();
    sw.println("@Override");
    sw.println("public <T> void create(Class<? extends T> type, AsyncCallback<T> callback) {");
    sw.println("   FlexInjector x = fragmentMap.get(type);");
    sw.println("   if (x != null){");
    sw.println("      x.create(type, callback);");
    sw.println("   } else {");
    //      sw.println("      callback.onFailure(new ClassNotFoundException());");
    sw.println("      callback.onFailure(null);");
    sw.println("      GWT.log(\"Class Creation of \" + type + \" failed\");");
    sw.println("   }");
    sw.println("}");
}

From source file:com.kk_electronic.gwt.rebind.RemoteServiceGenerator.java

License:Open Source License

private void writeMethod(SourceWriter sw, JClassType interfaze, JMethod method) {
    JParameter[] parameters = method.getParameters();
    sw.println();//from  ww w . j  av a  2  s.c o m
    sw.print("private Class<?>[] " + method.getName().toUpperCase() + "_RETVAL");
    sw.print(" = new Class<?>[]{");
    writeTypeInfo(sw, parameters[parameters.length - 1].getType().isParameterized().getTypeArgs()[0]);
    sw.println("};");
    sw.println("@Override");
    sw.print("public void " + method.getName() + "(");
    for (int i = 0, c = parameters.length; i < c; i++) {
        if (i > 0) {
            sw.print(",");
        }
        sw.print(parameters[i].getType().getParameterizedQualifiedSourceName());
        sw.print(" ");
        sw.print(parameters[i].getName());
    }
    sw.println(") {");
    String callbackname = parameters[parameters.length - 1].getName();
    sw.print("   dispatcher.execute(" + callbackname + "," + method.getName().toUpperCase() + "_RETVAL,"
            + interfaze.getQualifiedSourceName() + ".class,\"" + escape(method.getName()) + "\"");
    for (int i = 0, c = parameters.length - 1; i < c; i++) {
        sw.print(",");
        sw.print(parameters[i].getName());
    }
    sw.println(");");
    sw.println("}");
}

From source file:com.kk_electronic.gwt.rebind.RemoteServiceGenerator.java

License:Open Source License

private void writeTypeInfo(SourceWriter sw, JType type) {
    JWildcardType w = type.isWildcard();
    if (w != null) {
        type = w.getUpperBound();/*  w  w  w .  j  a v  a2s  .  com*/
    }
    sw.print(type.getQualifiedSourceName() + ".class");
    sw.print(",");
    JParameterizedType x = type.isParameterized();
    if (x != null) {
        for (JClassType nestedType : x.getTypeArgs()) {
            writeTypeInfo(sw, nestedType);
        }
    }
}

From source file:com.kk_electronic.gwt.rebind.VersionGenerator.java

License:Open Source License

private void writeGetSHA1(SourceWriter sourceWriter) {
    sourceWriter.println("public String getSHA1(){");
    sourceWriter.indent();//from www.j av a2 s.  c  o m
    sourceWriter.print("return \"");
    String result = executeCommand("git rev-parse HEAD");
    if (result != null) {
        sourceWriter.print(escape(result));
    }
    sourceWriter.println("\";");
    sourceWriter.outdent();
    sourceWriter.println("}");
}

From source file:com.kk_electronic.gwt.rebind.VersionGenerator.java

License:Open Source License

private void writeGetTag(SourceWriter sourceWriter) {
    sourceWriter.println("public String getTag(){");
    sourceWriter.indent();//from   w ww.j a  va2 s.  c om
    sourceWriter.print("return \"");
    String result = executeCommand("git describe --tags --always HEAD");
    if (result != null) {
        sourceWriter.print(escape(result));
    }
    sourceWriter.println("\";");
    sourceWriter.outdent();
    sourceWriter.println("}");
}

From source file:com.mvp4g.rebind.Mvp4gRunAsyncGenerator.java

License:Apache License

void writeClass(SourceWriter sourceWriter, String callBackType) {
    sourceWriter.print("public void load(");
    sourceWriter.print(callBackType);//from   ww  w. ja  va 2 s.c o m
    sourceWriter.println(" callback) {");
    sourceWriter.indent();
    sourceWriter.println("GWT.runAsync(callback);");
    sourceWriter.outdent();
    sourceWriter.println("}");
}

From source file:com.sencha.gxt.core.rebind.XTemplatesGenerator.java

License:sencha.com license

/**
 * Handles a given template chunk container by creating a method in the
 * safeHtmlTemplates impl//from  ww w  . ja  va 2  s . c  o  m
 * 
 * @param sw the current sourcewriter
 * @param wrapper the chunk container to act recursively on
 * @param safeHtml creator to add new SafeHtml calls to
 * @param scopeContext current scope to make method calls to
 * @param invokables
 * @throws UnableToCompleteException
 */
private void buildSafeHtmlTemplates(String safeHtmlVar, SourceWriter sw, ContainerTemplateChunk wrapper,
        SafeHtmlTemplatesCreator safeHtml, Context scopeContext, MethodCollector invokables)
        throws UnableToCompleteException {

    // debugging section to see what is about to be printed
    sw.beginJavaDocComment();
    sw.print(wrapper.toString());
    sw.endJavaDocComment();

    // make a new interface method for this content
    StringBuilder sb = new StringBuilder();
    List<String> paramTypes = new ArrayList<String>();
    List<String> params = new ArrayList<String>();

    // write out children to local vars or to the template
    int argCount = 0;
    for (TemplateChunk chunk : wrapper.children) {
        if (chunk instanceof ContentChunk) {
            ContentChunk contentChunk = (ContentChunk) chunk;
            // build up the template
            if (contentChunk.type == ContentType.LITERAL) {
                sb.append(contentChunk.content);
            } else if (contentChunk.type == ContentType.CODE) {
                sb.append("{").append(argCount++).append("}");
                paramTypes.add("java.lang.String");
                StringBuffer expr = new StringBuffer("\"\" + (");

                // parse out the quoted string literals first
                Matcher str = Pattern.compile("\"[^\"]+\"").matcher(contentChunk.content);
                TreeLogger code = logger.branch(Type.DEBUG,
                        "Parsing code segment: \"" + contentChunk.content + "\"");
                int lastMatchEnd = 0;
                while (str.find()) {
                    int begin = str.start(), end = str.end();
                    String escapedString = str.group();
                    String unmatched = contentChunk.content.substring(lastMatchEnd, begin);

                    appendCodeBlockOperatorOrIdentifier(scopeContext, expr, code, unmatched);

                    expr.append(escapedString);
                    lastMatchEnd = end;
                }

                //finish rest of non-string-lit expression
                appendCodeBlockOperatorOrIdentifier(scopeContext, expr, code,
                        contentChunk.content.substring(lastMatchEnd));

                params.add(expr.append(")").toString());
                code.log(Type.DEBUG, "Final compiled expression: " + expr);
            } else if (contentChunk.type == ContentType.REFERENCE) {
                sb.append("{").append(argCount++).append("}");

                JType argType = scopeContext.getType(contentChunk.content);
                if (argType == null) {
                    logger.log(Type.ERROR, "Reference could not be found: '" + contentChunk.content
                            + "'. Please fix the expression in your template.");
                    throw new UnableToCompleteException();
                }
                paramTypes.add(argType.getParameterizedQualifiedSourceName());
                params.add(scopeContext.deref(contentChunk.content));

            } else {
                assert false : "Content type not supported + " + contentChunk.type;
            }

        } else if (chunk instanceof ControlChunk) {
            ControlChunk controlChunk = (ControlChunk) chunk;
            // build logic, get scoped name
            boolean hasIf = controlChunk.controls.containsKey("if");
            boolean hasFor = controlChunk.controls.containsKey("for");

            if (!hasIf && !hasFor) {
                logger.log(Type.ERROR, "<tpl> tag did not define a 'for' or 'if' attribute!");
                throw new UnableToCompleteException();
            }

            // declare a sub-template, and stash content in there, interleaving it
            // into the current template
            String subTemplate = scopeContext.declareLocalVariable("subTemplate");
            String templateInBlock = scopeContext.declareLocalVariable("innerTemplate");
            sb.append("{").append(argCount++).append("}");
            paramTypes.add("com.google.gwt.safehtml.shared.SafeHtml");
            params.add(subTemplate);
            sw.println("SafeHtml %1$s;", subTemplate);
            sw.println("SafeHtmlBuilder %1$s_builder = new SafeHtmlBuilder();", subTemplate);

            // find the context that should be passed to the child template
            final Context childScope;

            // if we have both for and if, if needs to wrap the for
            if (hasIf) {
                ConditionParser p = new ConditionParser(logger);
                List<Token> tokens = p.parse(controlChunk.controls.get("if"));
                StringBuilder condition = new StringBuilder();
                for (Token t : tokens) {
                    switch (t.type) {
                    case ExpressionLiteral:
                        condition.append(t.contents);
                        break;
                    case MethodInvocation:
                        Matcher invoke = Pattern.compile("([a-zA-Z0-9\\._]+)\\:([a-zA-Z0-9_]+)\\(([^\\)]*)\\)")
                                .matcher(t.contents);
                        invoke.matches();
                        String deref = scopeContext.deref(invoke.group(1));
                        String methodName = invoke.group(2);
                        String args = "";
                        for (String a : invoke.group(3).split(",")) {
                            String possible = scopeContext.deref(a);
                            args += possible == null ? a : possible;
                        }

                        condition.append(invokables.getMethodInvocation(methodName, deref, args));
                        break;
                    case Reference:
                        condition.append("(").append(scopeContext.deref(t.contents)).append(")");
                        break;
                    default:
                        logger.log(Type.ERROR, "Unexpected token type: " + t.type);
                        throw new UnableToCompleteException();
                    }
                }
                sw.println("if (%1$s) {", condition.toString());
                sw.indent();
            }
            // if there is a for, print it out, and change scope
            if (hasFor) {
                String loopRef = controlChunk.controls.get("for");

                JType collectionType = scopeContext.getType(loopRef);
                if (collectionType == null) {
                    logger.log(Type.ERROR, "Reference in 'for' attribute could not be found: '" + loopRef
                            + "'. Please fix the expression in your template.");
                    throw new UnableToCompleteException();
                }
                final JType localType;// type accessed within the loop
                final String localAccessor;// expr to access looped instance, where
                                           // %1$s is the loop obj, and %2$s is the
                                           // int index
                if (collectionType.isArray() != null) {
                    localType = collectionType.isArray().getComponentType();
                    localAccessor = "%1$s[%2$s]";
                } else {// List subtype
                    localType = ModelUtils.findParameterizationOf(listInterface,
                            collectionType.isClassOrInterface())[0];
                    localAccessor = "%1$s.get(%2$s)";
                }

                String loopVar = scopeContext.declareLocalVariable("i");
                // make sure the collection isnt null
                sw.println("if (%1$s != null) {", scopeContext.deref(loopRef));
                sw.indent();
                sw.println("for (int %1$s = 0; %1$s < %2$s; %1$s++) {", loopVar,
                        scopeContext.derefCount(loopRef));
                String itemExpr = String.format(localAccessor, scopeContext.deref(loopRef), loopVar);
                childScope = new Context(scopeContext, itemExpr, localType);
                childScope.setCountVar(loopVar);
                sw.indent();
            } else {
                // if no for, use the same scope as the outer content
                childScope = scopeContext;
            }
            // generate a subtemplate, insert that
            sw.println("SafeHtml %1$s;", templateInBlock);
            buildSafeHtmlTemplates(templateInBlock, sw, controlChunk, safeHtml, childScope, invokables);
            sw.println("%1$s_builder.append(%2$s);", subTemplate, templateInBlock);

            // close up the blocks
            if (hasFor) {
                sw.outdent();
                sw.println("}");
                sw.outdent();
                sw.println("}");
            }
            if (hasIf) {
                sw.outdent();
                sw.println("}");
            }

            sw.println("%1$s = %1$s_builder.toSafeHtml();", subTemplate);

        } else {
            assert false : "Unsupported chunk type: " + chunk.getClass();
        }
    }

    String methodName = safeHtml.addTemplate(sb.toString(), paramTypes);
    sw.beginJavaDocComment();
    sw.println("safehtml content:");
    sw.indent();
    sw.println(sb.toString());
    sw.outdent();
    sw.println("params:");
    sw.indent();
    sw.print(args(params));
    sw.outdent();
    sw.endJavaDocComment();
    sw.println("%4$s = %1$s.%2$s(%3$s);", safeHtml.getInstanceExpression(), methodName, args(params),
            safeHtmlVar);
}