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

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

Introduction

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

Prototype

void outdent();

Source Link

Usage

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

License:Open Source License

protected void createSetMethods(List<JMethod> properties, SourceWriter sw, String typeName) {
    sw.println("public <X> X setProperty(String s, X val) {");
    sw.indent();// w w  w.  j ava2s.c  o m
    sw.println("Object obj = val;");

    sw.println("if (obj instanceof Bean) {");
    sw.println("obj = ((Bean) obj).getBean();");
    sw.println("} else if (obj instanceof java.util.List) {");
    sw.println("java.util.List list = new java.util.ArrayList();");
    sw.println("for(Object o : (java.util.List) obj) {");
    sw.println("if(o instanceof Bean) {");
    sw.println("list.add(((Bean) o).getBean());");
    sw.println("} else {");
    sw.println("list.add(o);");
    sw.println("}");
    sw.println("}");
    sw.println("obj = list;");
    sw.println("}");

    sw.println("if (allowNestedValues && val instanceof Bean) {");
    sw.indent();
    sw.println("obj = ((Bean)val).getBean();");
    sw.println("if (nestedModels.containsKey(s)) {");
    sw.indent();
    sw.println("nestedModels.put(s, (Bean)val);");
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");

    sw.println("if (allowNestedValues && NestedModelUtil.isNestedProperty(s)) {");
    sw.indent();
    sw.println("X old = (X) NestedModelUtil.setNestedValue(this, s, val);");
    sw.println("notifyPropertyChanged(s, val, old);");
    sw.println("return old;");
    sw.outdent();
    sw.println("}");

    for (JMethod method : properties) {
        String s = method.getName();
        String p = lowerFirst(s.substring(3));
        String type = getMethodAttributeType(method);

        if (type.indexOf("extends") != -1) {
            type = "java.lang.Object";
        }

        if (type.equals("byte")) {
            type = "Byte";
        } else if (type.equals("char")) {
            type = "Character";
        } else if (type.equals("short")) {
            type = "Short";
        } else if (type.equals("int")) {
            type = "Integer";
        } else if (type.equals("long")) {
            type = "Long";
        } else if (type.equals("float")) {
            type = "Float";
        } else if (type.equals("double")) {
            type = "Double";
        } else if (type.equals("boolean")) {
            type = "Boolean";
        }

        sw.println("if (s.equals(\"" + p + "\")) {");
        sw.indent();
        sw.println("Object old = get(s);");

        sw.println("((" + typeName + ")bean)." + s + "((" + type + ")obj);");
        sw.println("notifyPropertyChanged(s, val, old);");
        sw.println("return (X)old;");
        sw.outdent();
        sw.println("}");
    }
    sw.println("return super.set(s, val);");
    sw.outdent();
    sw.println("}");
}

From source file:com.allen_sauer.gwt.log.rebind.LogMessageFormatterGenerator.java

License:Apache License

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

    JClassType userType;/*from   w w w . j a v  a 2s.c o m*/
    try {
        userType = typeOracle.getType(typeName);
    } catch (NotFoundException e) {
        logger.log(TreeLogger.ERROR, "OOPS", e);
        throw new UnableToCompleteException();
    }
    String packageName = userType.getPackage().getName();
    String className = userType.getName();

    JClassType remoteService = typeOracle.findType(typeName);
    if (remoteService == null) {
        logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null);
        throw new UnableToCompleteException();
    }

    if (remoteService.isInterface() == null) {
        logger.log(TreeLogger.ERROR, remoteService.getQualifiedSourceName() + " is not an interface", null);
        throw new UnableToCompleteException();
    }
    ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName,
            className + "Impl");
    composerFactory.addImplementedInterface(remoteService.getQualifiedSourceName());

    composerFactory.addImport(Date.class.getName());
    composerFactory.addImport(GWT.class.getName());
    composerFactory.addImport(LogUtil.class.getName());
    composerFactory.addImport(Duration.class.getName());

    PrintWriter pw = context.tryCreate(logger, packageName, className + "Impl");
    if (pw != null) {
        SourceWriter sw = composerFactory.createSourceWriter(context, pw);

        PropertyOracle propertyOracle = context.getPropertyOracle();
        String logPattern;
        try {
            ConfigurationProperty logPatternProperty = propertyOracle
                    .getConfigurationProperty(PROPERTY_LOG_PATTERN);
            List<String> values = logPatternProperty.getValues();
            logPattern = values.get(0);
        } catch (BadPropertyValueException e) {
            logger.log(TreeLogger.ERROR, "Unable to find value for '" + PROPERTY_LOG_PATTERN + "'", e);
            throw new UnableToCompleteException();
        }

        sw.println();
        sw.println("private double BIG_BANG = Duration.currentTimeMillis();");

        sw.println();
        sw.println(
                "public String format(String logLevelText, String category, String message, Throwable throwable) {");
        sw.indent();
        sw.println("if (category == null) {");
        sw.indent();
        sw.println("category = \"<null category>\";");
        sw.outdent();
        sw.println("}");
        sw.println("if (message == null) {");
        sw.indent();
        sw.println("message = \"<null message>\";");
        sw.outdent();
        sw.println("}");
        sw.println(logPatternToCode(logPattern));
        sw.outdent();
        sw.println("}");

        sw.commit(logger);
    }
    return composerFactory.getCreatedClassName();
}

From source file:com.allen_sauer.gwt.log.rebind.RemoteLoggerConfigGenerator.java

License:Apache License

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

    JClassType userType;/* www  .  ja  v  a2  s.  c o  m*/
    try {
        userType = typeOracle.getType(typeName);
    } catch (NotFoundException e) {
        logger.log(TreeLogger.ERROR, "OOPS", e);
        throw new UnableToCompleteException();
    }
    String packageName = userType.getPackage().getName();
    String className = userType.getName();

    JClassType remoteService = typeOracle.findType(typeName);
    if (remoteService == null) {
        logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null);
        throw new UnableToCompleteException();
    }

    if (remoteService.isInterface() == null) {
        logger.log(TreeLogger.ERROR, remoteService.getQualifiedSourceName() + " is not an interface", null);
        throw new UnableToCompleteException();
    }
    ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName,
            className + "Impl");
    composerFactory.addImplementedInterface(remoteService.getQualifiedSourceName());

    PrintWriter pw = context.tryCreate(logger, packageName, className + "Impl");
    if (pw != null) {
        SourceWriter sw = composerFactory.createSourceWriter(context, pw);

        PropertyOracle propertyOracle = context.getPropertyOracle();
        String logUrl;
        try {
            ConfigurationProperty logPatternProperty = propertyOracle
                    .getConfigurationProperty(PROPERTY_LOG_URL);
            List<String> values = logPatternProperty.getValues();
            logUrl = values.get(0);
        } catch (BadPropertyValueException e) {
            logger.log(TreeLogger.ERROR, "Unable to find value for '" + PROPERTY_LOG_URL + "'", e);
            throw new UnableToCompleteException();
        }

        sw.println();
        sw.println("public String serviceEntryPointUrl() {");
        sw.indent();

        if (logUrl == null) {
            sw.println("return null;");
        } else {
            sw.println("return \"" + logUrl.trim() + "\";");
        }

        sw.outdent();
        sw.println("}");

        sw.commit(logger);
    }
    return composerFactory.getCreatedClassName();
}

From source file:com.allen_sauer.gwt.voices.crowd.rebind.GwtUserAgentProviderGenerator.java

License:Apache License

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

    JClassType userType;//from w ww. ja va  2s.c  o  m
    try {
        userType = typeOracle.getType(typeName);
    } catch (NotFoundException e) {
        logger.log(TreeLogger.ERROR, "OOPS", e);
        throw new UnableToCompleteException();
    }
    String packageName = userType.getPackage().getName();
    String className = userType.getName();

    JClassType remoteService = typeOracle.findType(typeName);
    if (remoteService == null) {
        logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null);
        throw new UnableToCompleteException();
    }

    if (remoteService.isInterface() == null) {
        logger.log(TreeLogger.ERROR, remoteService.getQualifiedSourceName() + " is not an interface", null);
        throw new UnableToCompleteException();
    }
    ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName,
            className + "Impl");
    composerFactory.addImplementedInterface(remoteService.getQualifiedSourceName());

    PrintWriter pw = context.tryCreate(logger, packageName, className + "Impl");
    if (pw != null) {
        SourceWriter sw = composerFactory.createSourceWriter(context, pw);

        PropertyOracle propertyOracle = context.getPropertyOracle();
        String userAgent;
        try {
            SelectionProperty userAgentProperty = propertyOracle.getSelectionProperty(logger,
                    PROPERTY_USER_AGENT);

            // ALWAYS RETURNS 'gecko'
            userAgent = userAgentProperty.getCurrentValue();
        } catch (BadPropertyValueException e) {
            logger.log(TreeLogger.ERROR, "Unable to find value for '" + PROPERTY_USER_AGENT + "'", e);
            throw new UnableToCompleteException();
        }

        sw.println();
        sw.println("public String getGwtUserAgent() {");
        sw.indent();

        if (userAgent == null) {
            sw.println("return null;");
        } else {
            sw.println("return \"" + userAgent + "\";");
        }

        sw.outdent();
        sw.println("}\n");

        sw.commit(logger);
    }
    return composerFactory.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 v  a 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.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  w  ww  .j  ava2 s. com*/
        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

private void generateCreateMethod(SourceWriter sw, TreeLogger logger) {
    sw.println("public <T extends " + JsonBuilder.class.getName() + "> T create(Class<T> clz) {");
    sw.indent();//from   w w w .ja  v  a 2  s .c  om
    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

public String generate(TreeLogger treeLogger, GeneratorContext generatorContext, String requestedClass)
        throws UnableToCompleteException {
    TypeOracle oracle = generatorContext.getTypeOracle();
    lazyType = oracle.findType("com.cgxlib.xq.client.Lazy");
    lazyBaseType = oracle.findType("com.cgxlib.xq.client.LazyBase");

    assert lazyType != null : "Can't find Lazy interface type";
    assert lazyBaseType != null : "Can't find LazyBase interface type";

    JClassType requestedType = oracle.findType(requestedClass);
    JClassType targetType = null;/*from ww  w .  j a  v  a2s  . c om*/
    JClassType nonLazyType = null;

    for (JClassType inf : requestedType.getImplementedInterfaces()) {
        if (inf.isAssignableTo(lazyType)) {
            nonLazyType = inf.isParameterized().getTypeArgs()[0];
            targetType = inf.isParameterized().getTypeArgs()[1];
            break;
        }
    }

    if (targetType == null)
        return null;

    assert targetType != null : "Parameter of Lazy<T> not found";
    String genClass = targetType.getPackage().getName() + "." + targetType.getSimpleSourceName()
            + getImplSuffix();

    SourceWriter sw = getSourceWriter(treeLogger, generatorContext, requestedType.getPackage().getName(),
            targetType.getSimpleSourceName() + getImplSuffix(), targetType.getQualifiedSourceName());
    if (sw != null) {
        generatePreamble(sw, nonLazyType.getQualifiedSourceName(), treeLogger);
        sw.indent();
        for (JMethod method : targetType.getMethods()) {
            generateMethod(sw, method, nonLazyType.getQualifiedSourceName(), genClass, treeLogger);
        }
        sw.outdent();
        generateDoneMethod(sw, nonLazyType, treeLogger);
        sw.commit(treeLogger);
    }

    return genClass;
}

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

License:Apache License

private void generatePreamble(SourceWriter sw, String nonLazyClass, TreeLogger treeLogger) {
    sw.indent();/*w  w w  .ja  v a2s . c om*/
    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;
    }//  www .jav a  2 s .  co m
    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("}-*/;");
}