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

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

Introduction

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

Prototype

void println(String s);

Source Link

Usage

From source file:com.ait.toolkit.rebind.TemplateGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();
    this.templatesInterface = oracle.findType(Name.getSourceNameForClass(Template.class));

    JClassType interfaceType;// w  w  w .  j  a va2s. co m
    try {
        interfaceType = oracle.getType(typeName);
    } catch (NotFoundException e) {
        throw new RuntimeException(e);
    }

    if (interfaceType.isInterface() == null) {
        logger.log(TreeLogger.ERROR, typeName + " is not an interface type");
        throw new UnableToCompleteException();
    }
    if (!interfaceType.isAssignableTo(templatesInterface)) {
        logger.log(Type.ERROR, "This isn't a Template subtype...");
        throw new UnableToCompleteException();
    }

    String content = getTemplateContent(context, logger, interfaceType);
    String packageName = interfaceType.getPackage().getName();
    String className = "Tpl_For_" + interfaceType.getQualifiedSourceName().replace(".", "_") + "_Generated";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);
    composer.addImport(SafeHtml.class.getName());
    composer.addImport(SafeHtmlUtils.class.getName());
    composer.addImplementedInterface(Template.class.getName());

    PrintWriter pw = context.tryCreate(logger, packageName, className);

    if (pw != null) {
        SourceWriter sw = composer.createSourceWriter(context, pw);

        sw.println("  public SafeHtml getContent(){");
        sw.println("      return SafeHtmlUtils.fromSafeConstant(\"" + content + "\");");
        sw.println("  }");
        sw.println("");
        sw.println("");
        sw.println("  public SafeHtml getSafeContent(){");
        sw.println("      return SafeHtmlUtils.fromString(\"" + content + "\");");
        sw.println("  }");

        sw.commit(logger);
    }

    return composer.getCreatedClassName();

}

From source file:com.bramosystems.oss.player.core.rebind.PlayerManagerGenerator.java

License:Apache License

/**
 * @param logger Logger object/*from w  w w . j a va 2  s  .c o m*/
 * @param context Generator context
 */
private void generateClass(TreeLogger logger, GeneratorContext context)
        throws NotFoundException, BadPropertyValueException, UnableToCompleteException, IOException {
    // get print writer that receives the source code
    PrintWriter printWriter = context.tryCreate(logger, packageName, className);

    // print writer if null, source code has ALREADY been generated,  return
    if (printWriter == null) {
        return;
    }

    // build plugin mime types ...
    ConfigurationProperty mimeFile = context.getPropertyOracle()
            .getConfigurationProperty("bstplayer.media.mimeTypes");
    String val = mimeFile.getValues().get(0);
    if (val == null) {
        logger.log(TreeLogger.Type.INFO,
                "'" + mimeFile.getName() + "' configuration property not set! Using defaults");
        parseMimeFile(DEFAULT_MIME_TYPES_FILE);
    } else {
        logger.log(TreeLogger.Type.INFO, "'" + mimeFile.getName() + "' set! Using '" + val + "'");
        parseMimeFile(val);
    }

    collatePlayers(context.getTypeOracle());

    // init composer, set class properties, create source writer
    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);
    composer.setSuperclass("PlayerManager");
    composer.addImport("com.google.gwt.core.client.GWT");
    composer.addImport("com.bramosystems.oss.player.core.client.spi.PlayerProviderFactory");
    composer.addImport("com.bramosystems.oss.player.core.client.impl.CallbackUtility");
    composer.addImport("com.bramosystems.oss.player.core.client.spi.ConfigurationContext");
    composer.addImport("com.bramosystems.oss.player.core.client.*");
    composer.addImport("java.util.*");

    SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);

    sourceWriter.println(
            "private HashMap<String, HashMap<String, PlayerInfo>> pInfos = new HashMap<String, HashMap<String, PlayerInfo>>();");

    // collate widget factories & create static holders ...
    Iterator<String> fact = pMap.keySet().iterator();
    while (fact.hasNext()) {
        String provClass = fact.next();
        sourceWriter.println("private static PlayerProviderFactory pwf_"
                + escapeProviderName(pMap.get(provClass).name) + " = GWT.create(" + provClass + ".class);");
    }
    sourceWriter.println();

    Pattern ptrn = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)");

    // generate constructor source code
    sourceWriter.println("public " + className + "() { ");
    sourceWriter.indent();

    // init widget factories ...
    fact = pMap.keySet().iterator();
    while (fact.hasNext()) {
        String provClass = fact.next();
        String provName = escapeProviderName(pMap.get(provClass).name);
        sourceWriter.println(
                "pwf_" + provName + ".init(new ConfigurationContext(CallbackUtility.initCallbackHandlers(\""
                        + provName + "\"), \"bstplayer.handlers." + provName + "\"));");
    }

    sourceWriter.println();

    // init providers ...
    fact = pMap.keySet().iterator();
    while (fact.hasNext()) {
        _provider pvd = pMap.get(fact.next());
        sourceWriter.println("pInfos.put(\"" + pvd.name + "\", new HashMap<String, PlayerInfo>());");

        Iterator<_player> pns = pvd.players.iterator();
        while (pns.hasNext()) {
            _player ply = pns.next();
            boolean ps = false, ms = false;

            JClassType ints[] = ply.interfaces;
            for (int j = 0; j < ints.length; j++) {
                if (ints[j].getQualifiedSourceName().equals(MatrixSupport.class.getName())) {
                    ms = true;
                } else if (ints[j].getQualifiedSourceName().equals(PlaylistSupport.class.getName())) {
                    ps = true;
                }
            }
            Matcher m = ptrn.matcher(ply.minPluginVer);
            if (m.matches()) {
                sourceWriter.println("pInfos.get(\"" + pvd.name + "\").put(\"" + ply.name
                        + "\", new PlayerInfo(\"" + pvd.name + "\",\"" + ply.name + "\"," + "PluginVersion.get("
                        + Integer.parseInt(m.group(1)) + "," + Integer.parseInt(m.group(2)) + ","
                        + Integer.parseInt(m.group(3)) + ")," + ps + "," + ms + "));");
            } else {
                logger.log(TreeLogger.Type.WARN, "Min");
            }
        }
    }
    sourceWriter.outdent();
    sourceWriter.println("}"); // end constructor source generation

    sourceWriter.println();

    // implement get provider names ...
    sourceWriter.println("@Override");
    sourceWriter.println("public Set<String> getProviders(){");
    sourceWriter.indent();
    sourceWriter.println("return new TreeSet<String>(pInfos.keySet());");
    sourceWriter.outdent();
    sourceWriter.println("}");
    sourceWriter.println();

    // implement get player names by provider ...
    sourceWriter.println("@Override");
    sourceWriter.println("public Set<String> getPlayerNames(String providerName) {");
    sourceWriter.indent();
    sourceWriter.println("if(!pInfos.containsKey(providerName))");
    sourceWriter.println("throw new IllegalArgumentException(\"Unknown player provider - \" + providerName);");
    sourceWriter.println("return new TreeSet<String>(pInfos.get(providerName).keySet());");
    sourceWriter.outdent();
    sourceWriter.println("}");
    sourceWriter.println();

    // implement get player infos ...
    sourceWriter.println("@Override");
    sourceWriter.println("public PlayerInfo getPlayerInfo(String providerName, String playerName) {");
    sourceWriter.indent();
    sourceWriter.println("if(!pInfos.containsKey(providerName)) {");
    sourceWriter.println("throw new IllegalArgumentException(\"Unknown player provider - \" + providerName);}");
    sourceWriter.println("if(providerName.equals(\"api\")){");
    sourceWriter.println("return getApiPlayerInfoForPlugin(playerName);}");
    sourceWriter.println("else if(!pInfos.get(providerName).containsKey(playerName)){");
    sourceWriter.println("throw new IllegalArgumentException(\"Unknown player name - \" + playerName);}");
    sourceWriter.println("return pInfos.get(providerName).get(playerName);");
    sourceWriter.outdent();
    sourceWriter.println("}");
    sourceWriter.println();

    // implement get widget factory with defered binding on demand ....
    sourceWriter.println("@Override");
    sourceWriter.println("public PlayerProviderFactory getProviderFactory(String provider) {");
    sourceWriter.indent();
    sourceWriter.println("PlayerProviderFactory wf = null;");

    boolean firstRun = true;
    Iterator<_provider> provs = pMap.values().iterator();
    while (provs.hasNext()) {
        _provider prov = provs.next();
        if (firstRun) {
            sourceWriter.println("if(\"" + prov.name + "\".equals(provider)) {");
        } else {
            sourceWriter.println("else if(\"" + prov.name + "\".equals(provider)) {");
        }
        sourceWriter.indent();
        sourceWriter.println("wf = pwf_" + escapeProviderName(prov.name) + ";");
        sourceWriter.outdent();
        sourceWriter.println("}");
        firstRun = false;
    }
    sourceWriter.println("return wf;");
    sourceWriter.outdent();
    sourceWriter.println("}");
    sourceWriter.println();

    // implement mimeTypes ....
    sourceWriter.println("@Override");
    sourceWriter.println("protected void initMimeTypes(HashMap<String, String> mimeTypes) {");
    sourceWriter.indent();
    Iterator<String> mimeKeys = mimeMap.keySet().iterator();
    while (mimeKeys.hasNext()) {
        String mime = mimeKeys.next();
        sourceWriter.println("mimeTypes.put(\"" + mime + "\",\"" + mimeMap.get(mime) + "\");");
    }
    sourceWriter.outdent();
    sourceWriter.println("}");
    sourceWriter.println();

    // close generated class
    sourceWriter.outdent();
    sourceWriter.println("}");

    // commit generated class
    context.commit(logger, printWriter);
}

From source file:com.cgxlib.xq.rebind.BrowserGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();
    PropertyOracle propOracle = context.getPropertyOracle();

    String ua = null;//from   w w  w . j  a  va  2  s .  c  om
    try {
        ua = propOracle.getSelectionProperty(logger, "user.agent").getCurrentValue();
    } catch (BadPropertyValueException e) {
        logger.log(TreeLogger.ERROR, "Can not resolve user.agent property", e);
        throw new UnableToCompleteException();
    }

    JClassType clz = oracle.findType(typeName);
    String pName = clz.getPackage().getName();
    String cName = clz.getName() + "_" + ua;

    PrintWriter pWriter = context.tryCreate(logger, pName, cName);

    if (pWriter != null) {
        ClassSourceFileComposerFactory cFact = new ClassSourceFileComposerFactory(pName, cName);
        cFact.setSuperclass(pName + "." + clz.getName());

        SourceWriter writer = cFact.createSourceWriter(context, pWriter);

        writer.println("protected boolean isWebkit() {return " + "safari".equals(ua) + ";}");
        writer.println("protected boolean isSafari() {return " + "safari".equals(ua) + ";}");
        writer.println("protected boolean isOpera() {return " + "opera".equals(ua) + ";}");
        writer.println("protected boolean isMozilla() {return " + ua.contains("gecko") + ";}");
        writer.println("protected boolean isMsie() {return " + ua.contains("ie") + ";}");
        writer.println("protected boolean isIe6() {return " + "ie6".equals(ua) + ";}");
        writer.println("protected boolean isIe8() {return " + "ie8".equals(ua) + ";}");
        writer.println("protected boolean isIe9() {return " + "ie9".equals(ua) + ";}");
        writer.println("protected boolean isIe10() {return " + "ie10".equals(ua) + ";}");
        writer.println("protected boolean isIe11() {return " + "gecko1_8".equals(ua) + ";}");
        writer.println("public String toString() {return \"Browser:\"" + " + \" webkit=\" + webkit"
                + " + \" mozilla=\" + mozilla" + " + \" opera=\" + opera" + " + \" msie=\" + msie"
                + " + \" ie6=\" + ie6" + " + \" ie8=\" + ie8" + " + \" ie9=\" + ie9" + ";}");
        writer.commit(logger);
    }

    return pName + "." + cName;
}

From source file:com.cgxlib.xq.rebind.JsonBuilderGenerator.java

License:Apache License

public void generateFieldNamesMethod(SourceWriter sw, Collection<String> attrs, TreeLogger logger) {
    String ret = "";
    for (Iterator<String> it = attrs.iterator(); it.hasNext();) {
        ret += (ret.isEmpty() ? "" : ",") + "\"" + it.next() + "\"";
    }/*  w w w  .j  a va  2  s  .com*/
    sw.println("{ fieldNames = new String[]{" + ret + "}; }");
}

From source file:com.cgxlib.xq.rebind.JsonBuilderGenerator.java

License:Apache License

public void generateMethod(SourceWriter sw, JMethod method, String name, TreeLogger logger)
        throws UnableToCompleteException {
    String ifaceName = method.getEnclosingType().getQualifiedSourceName();

    String retType = method.getReturnType().getParameterizedQualifiedSourceName();
    sw.print("public final " + retType + " " + method.getName());
    JParameter[] params = method.getParameters();
    if (params.length == 0) {
        JArrayType arr = method.getReturnType().isArray();
        JParameterizedType list = method.getReturnType().isParameterized();

        sw.println("() {");
        sw.indent();/*from   www  .j a v a  2 s.  co  m*/
        if (retType.matches("(java.lang.Boolean|boolean)")) {
            sw.println("return p.getBoolean(\"" + name + "\");");
        } else if (retType.matches("java.util.Date")) {
            sw.println("return new Date(java.lang.Long.parseLong(p.getStr(\"" + name + "\")));");
        } else if (method.getReturnType().isPrimitive() != null) {
            sw.println("return (" + retType + ")p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Character")) {
            sw.println("return (char) p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Byte")) {
            sw.println("return (byte) p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Integer")) {
            sw.println("return (int) p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Float")) {
            sw.println("return p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Double")) {
            sw.println("return (double) p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Long")) {
            sw.println("return (long) p.getFloat(\"" + name + "\");");
        } else if (retType.equals("java.lang.Byte")) {
            sw.println("return (byte) p.getFloat(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), stringType)) {
            sw.println("return p.getStr(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), jsonBuilderType)) {
            String q = method.getReturnType().getQualifiedSourceName();
            sw.println("return " + "((" + q + ")GWT.create(" + q + ".class))" + ".load(getPropertiesBase(\""
                    + name + "\"));");
        } else if (isTypeAssignableTo(method.getReturnType(), settingsType)) {
            String q = method.getReturnType().getQualifiedSourceName();
            sw.println("return " + "((" + q + ")getPropertiesBase(\"" + name + "\"));");
        } else if (retType.equals(Properties.class.getName())) {
            sw.println("return getPropertiesBase(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), jsType)) {
            sw.println("return p.getJavaScriptObject(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), functionType)) {
            sw.println("return p.getFunction(\"" + name + "\");");
        } else if (arr != null || list != null) {
            JType type = arr != null ? arr.getComponentType() : list.getTypeArgs()[0];
            boolean buildType = isTypeAssignableTo(type, jsonBuilderType);
            String t = type.getQualifiedSourceName();
            sw.println("JsArrayMixed a = p.getArray(\"" + name + "\");");
            sw.println("int l = a == null ? 0 : a.length();");
            String ret;
            if (buildType) {
                sw.println(t + "[] r = new " + t + "[l];");
                sw.println("JsObjectArray<?> a1 = p.getArray(\"" + name + "\").cast();");
                sw.println("int l1 = r.length;");
                sw.println("for (int i = 0 ; i < l1 ; i++) {");
                sw.println("  Object w = a1.get(i);");
                sw.println("  " + t + " instance = GWT.create(" + t + ".class);");
                sw.println("  r[i] = instance.load(w);");
                sw.println("}");
                ret = "r";
            } else {
                ret = "getArrayBase(\"" + name + "\", new " + t + "[l], " + t + ".class)";
            }
            if (arr != null) {
                sw.println("return " + ret + ";");
            } else {
                sw.println("return Arrays.asList(" + ret + ");");
            }
        } else if (method.getReturnType().isEnum() != null) {
            sw.println("return " + method.getReturnType().getQualifiedSourceName() + ".valueOf(p.getStr(\""
                    + name + "\"));");
        } else {
            sw.println("System.err.println(\"JsonBuilderGenerator WARN: unknown return type " + retType + " "
                    + ifaceName + "." + name + "()\"); ");
            // We return the object because probably the user knows how to handle it
            sw.println("return p.get(\"" + name + "\");");
        }
        sw.outdent();
        sw.println("}");
    } else if (params.length == 1) {
        JType type = params[0].getType();
        JArrayType arr = type.isArray();
        JParameterizedType list = type.isParameterized();

        sw.print("(" + type.getParameterizedQualifiedSourceName() + " a)");
        sw.println("{");
        sw.indent();
        if (arr != null || list != null) {
            String a = "a";
            if (list != null) {
                a = "a.toArray(new " + list.getTypeArgs()[0].getQualifiedSourceName() + "[0])";
            }
            sw.println("setArrayBase(\"" + name + "\", " + a + ");");
        } else if (type.getParameterizedQualifiedSourceName().matches("java.util.Date")) {
            sw.println("p.setNumber(\"" + name + "\", a.getTime());");
        } else if (type.getParameterizedQualifiedSourceName().matches(
                "(java.lang.(Character|Long|Double|Integer|Float|Byte)|(char|long|double|int|float|byte))")) {
            sw.println("p.setNumber(\"" + name + "\", a);");
        } else if (type.getParameterizedQualifiedSourceName().matches("(java.lang.Boolean|boolean)")) {
            sw.println("p.setBoolean(\"" + name + "\", a);");
        } else if (type.getParameterizedQualifiedSourceName().matches("com.cgxlib.xq.client.Function")) {
            sw.println("p.setFunction(\"" + name + "\", a);");
        } else if (type.isEnum() != null) {
            sw.println("p.set(\"" + name + "\", a.name());");
        } else {
            sw.println("set(\"" + name + "\", a);");
        }
        if (!"void".equals(retType)) {
            if (isTypeAssignableTo(method.getReturnType(), method.getEnclosingType())) {
                sw.println("return this;");
            } else {
                sw.println("return null;");
            }
        }
        sw.outdent();
        sw.println("}");
    }
}

From source file:com.cgxlib.xq.rebind.JsonBuilderGenerator.java

License:Apache License

public void generateToJsonMethod(SourceWriter sw, String name, TreeLogger logger) {
    sw.println("public final String getJsonName() {return \"" + name + "\";}");
}

From source file:com.cgxlib.xq.rebind.JsonBuilderGenerator.java

License:Apache License

private void generateCreateMethod(SourceWriter sw, TreeLogger logger) {
    sw.println("public <T extends " + JsonBuilder.class.getName() + "> T create(Class<T> clz) {");
    sw.indent();//ww w  .  j a  v a 2 s  .  c o m
    ArrayList<JClassType> types = new ArrayList<JClassType>();
    for (JClassType t : oracle.getTypes()) {
        if (t.isInterface() != null && t.isAssignableTo(jsonBuilderType)) {
            if (t.isPublic()) {
                sw.println("if (clz == " + t.getQualifiedSourceName() + ".class) return GWT.<T>create("
                        + t.getQualifiedSourceName() + ".class);");
            } else {
                logger.log(Type.WARN, t.getQualifiedSourceName() + " is not public");
            }
            types.add(t);
        }
    }
    sw.println("return null;");
    sw.outdent();
    sw.println("}");
    sw.println("public " + IsProperties.class.getName() + " create(String s) {");
    sw.indent();
    sw.println("return (" + IsProperties.class.getName() + ")" + JsUtils.class.getName() + ".parseJSON(s);");
    sw.outdent();
    sw.println("}");
    sw.println("public " + IsProperties.class.getName() + " create() {");
    sw.indent();
    sw.println("return " + Properties.class.getName() + ".create();");
    sw.outdent();
    sw.println("}");
}

From source file:com.cgxlib.xq.rebind.LazyGenerator.java

License:Apache License

private void generatePreamble(SourceWriter sw, String nonLazyClass, TreeLogger treeLogger) {
    sw.indent();/*from w w w. j a  v  a2s  .  co m*/
    sw.println("private JsArray<JsClosure> closures = JsArray.createArray().cast();");
    sw.println("private " + nonLazyClass + "  ctx;");
    sw.outdent();
}

From source file:com.cgxlib.xq.rebind.LazyGenerator.java

License:Apache License

public void generateMethod(SourceWriter sw, JMethod method, String nonLazyClass, String genClass,
        TreeLogger logger) throws UnableToCompleteException {

    JParameter[] params = method.getParameters();
    JTypeParameter gType = method.getReturnType().isTypeParameter();

    String retType = method.getReturnType().getParameterizedQualifiedSourceName();
    if (gType != null) {
        retType = "<" + gType.getParameterizedQualifiedSourceName() + " extends "
                + gType.getFirstBound().getQualifiedSourceName() + "> " + retType;
    }/*from   www. ja  v  a2s . c om*/
    sw.print("public final native " + retType + " " + method.getName());
    sw.print("(");
    int argNum = 0;
    for (JParameter param : params) {
        sw.print((argNum == 0 ? "" : ", ") + param.getType().getParameterizedQualifiedSourceName() + " arg"
                + argNum);
        argNum++;
    }
    sw.println(") /*-{");

    sw.indent();
    sw.println("var self=this;");
    sw.println("this.@" + genClass + "::closures.push(");
    sw.indent();
    sw.println("function() {");
    sw.indent();
    sw.print("self.@" + genClass + "::ctx=self.@" + genClass + "::ctx.@" + nonLazyClass + "::"
            + method.getName());
    sw.print(getJSNIParams(method));
    sw.print("(");
    for (int i = 0; i < argNum; i++) {
        sw.print("arg" + i + (i < argNum - 1 ? "," : ""));
    }

    sw.print(")");
    // special case, as() needs to invoke createLazy()
    if ("as".equals(method.getName())) {
        sw.print(".createLazy()");
    }
    sw.println(";");
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println(");");
    sw.println("return this;");
    sw.outdent();
    sw.println("}-*/;");
}

From source file:com.cgxlib.xq.rebind.LazyGenerator.java

License:Apache License

private void generateDoneMethod(SourceWriter sw, JClassType nonLazyType, TreeLogger treeLogger) {
    sw.indent();//from ww  w. j a v a2 s .  co  m
    sw.println("public Function done() {");
    sw.indent();
    sw.println("return new Function() {");
    sw.indent();

    sw.println("public void f() {");
    sw.indent();
    String classID = nonLazyType.getSimpleSourceName();
    if ("XQ".equals(classID)) {
        classID = "CGXQUERY";
    }

    sw.println("ctx = XQ.$(getElement()).as(" + nonLazyType.getQualifiedSourceName() + "." + classID + ");");
    sw.println("for (int i = 0; i < closures.length(); i++) {");
    sw.indent();
    sw.println("closures.get(i).invoke();");
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("};");
    sw.outdent();
    sw.println("}");
}