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.seanchenxi.resteasy.autobean.generator.RESTServiceGenerator.java

License:Apache License

private void writeAsyncMethod(String asyncTypeName, JMethod asyncMethod, SourceWriter writer,
        TreeLogger logger) {// w w w.  java  2 s. c  om
    String methodName = asyncMethod.getName();
    String httpMethod = httpMethods.get(methodName);
    String restPath = restPaths.get(methodName);

    if (restPath == null || restPath.isEmpty()) {
        logger.log(Type.WARN, "Method " + methodName + " has no defined REST Path value, ingore");
        return; // method must have a rest path
    }

    StringBuilder methodParams = new StringBuilder();
    //      StringBuilder requestDatas = new StringBuilder(); //TODO treat request data
    String clazz = null;

    boolean isMethodParamsBegin = true;
    //      boolean isRequestDatasBegin = true;
    for (JParameter parameter : asyncMethod.getParameters()) {
        if (!isMethodParamsBegin)
            methodParams.append(", ");
        String name = parameter.getName();
        JType type = parameter.getType();
        JParameterizedType pType = parameter.getType().isParameterized();
        if (pType != null) {
            clazz = pType.getTypeArgs()[0].getQualifiedSourceName();
            methodParams.append(pType.getParameterizedQualifiedSourceName());
        } else {
            //            if(!isRequestDatasBegin) requestDatas.append(", ");
            //            requestDatas.append(name);
            //            isRequestDatasBegin = false;
            methodParams.append(type.getQualifiedSourceName());
        }
        methodParams.append(" ");
        methodParams.append(name);
        isMethodParamsBegin = false;
    }

    if (clazz == null || clazz.isEmpty()) {
        logger.log(Type.WARN, "Method " + methodName + " has no AsyncCallback<T> paramter, ingore");
        return; //should have AsyncCallback<T> parameter
    }
    String resourceName = asyncTypeName + "." + asyncMethod.getName();
    writer.println("@Override");
    writer.println("public void %s(%s){", methodName, methodParams);
    writer.println("   %1s request = new %1$s(%2$s, %3$s, \"%4$s\");", REST_REQUEST, httpMethod, restPath,
            resourceName);
    //      writer.println("   request.setRequestData(%s);", requestDatas); //TODO treat request data
    writer.println("   invoke(request, %s.class, callback);", clazz);
    writer.println("}");
    writer.println("");
}

From source file:com.seanchenxi.resteasy.autobean.generator.ThrowableFactoryGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();
    JClassType type = oracle.findType(typeName);
    type = type.isInterface();/*from   w  ww . jav a2s  .  c  om*/
    if (type == null) {
        logger.log(TreeLogger.ERROR, typeName + " is not found");
        throw new UnableToCompleteException();
    }

    String packageName = type.getPackage().getName();
    String simpleName = type.getSimpleSourceName() + "Impl";
    PrintWriter printWriter = context.tryCreate(logger, packageName, simpleName);
    if (printWriter == null) {
        return packageName + "." + simpleName;
    }

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleName);
    factory.addImplementedInterface(typeName);
    factory.addImport(Throwable.class.getName());

    SourceWriter writer = factory.createSourceWriter(context, printWriter);
    writer.indent();
    writer.println("@Override");
    writer.println("public Throwable create(String className, String message){");
    for (String qname : getAllThrowableTypes(oracle, logger)) {
        writer.println("   if(\"" + qname + "\".equals(className)) {");
        writer.println("      return new " + qname + " (message);");
        writer.println("   }");
    }
    writer.println("   return new Throwable(message);");
    writer.println("}");
    writer.outdent();
    writer.commit(logger);
    return factory.getCreatedClassName();
}

From source file:com.sencha.gxt.core.rebind.useragent.UserAgentPropertyGenerator.java

License:sencha.com license

@Override
public String generate(TreeLogger logger, SortedSet<String> possibleValues, String fallback,
        SortedSet<ConfigurationProperty> configProperties) throws UnableToCompleteException {

    SourceWriter sw = new StringSourceWriter();
    sw.println("{");

    sw.println("var ua = navigator.userAgent.toLowerCase();");

    // Microsoft Edge
    uaContains(sw, "edge/", "edge");

    uaContains(sw, "chrome", "chrome");

    sw.println("if (ua.indexOf('trident') != -1 || ua.indexOf('msie') != -1) {");
    sw.indent();/*from ww  w  . ja  va2s.co m*/

    // TODO ChromeFrame?
    docModeGreaterThan(sw, 11, "ie11");
    docModeGreaterThan(sw, 10, "ie10");
    docModeGreaterThan(sw, 9, "ie9");
    docModeGreaterThan(sw, 8, "ie8");

    // last assume newest
    sw.println("return 'ie10';");
    sw.outdent();
    sw.println("}");

    sw.println("if (ua.indexOf('safari') != -1) {");
    sw.indent();
    uaContains(sw, "version/3", "safari3");
    uaContains(sw, "version/4", "safari4");
    // else assume newest
    // simpleStatement(sw, "version/5", "safari5");
    sw.println("return 'safari5';");
    sw.outdent();
    sw.println("}");

    sw.println("if (ua.indexOf('gecko') != -1) {");
    sw.indent();
    uaContains(sw, "rv:1.8", "gecko1_8");
    // Don't check for rev 1.9, check instead for the newest version, and treat
    // all
    // gecko browsers that don't match a rule as the newest version
    // simpleStatement(sw, "rv:1.9", "gecko1_9");
    sw.println("return 'gecko1_9';");
    sw.outdent();
    sw.println("}");

    uaContains(sw, "adobeair", "air");

    sw.println("return null;}");
    return sw.toString();
}

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

License:sencha.com license

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    // make sure it is an interface
    TypeOracle oracle = context.getTypeOracle();

    this.logger = logger;

    this.xTemplatesInterface = oracle.findType(Name.getSourceNameForClass(XTemplates.class));
    this.listInterface = oracle.findType(Name.getSourceNameForClass(List.class));
    JClassType toGenerate = oracle.findType(typeName).isInterface();
    if (toGenerate == null) {
        logger.log(TreeLogger.ERROR, typeName + " is not an interface type");
        throw new UnableToCompleteException();
    }/*from w w  w .  j a  v a  2  s .c om*/
    if (!toGenerate.isAssignableTo(xTemplatesInterface)) {
        logger.log(Type.ERROR, "This isn't a XTemplates subtype...");
        throw new UnableToCompleteException();
    }

    // Get the name of the new type
    String packageName = toGenerate.getPackage().getName();
    String simpleSourceName = toGenerate.getName().replace('.', '_') + "Impl";
    PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName);
    if (pw == null) {
        return packageName + "." + simpleSourceName;
    }

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.addImplementedInterface(typeName);
    // imports
    factory.addImport(Name.getSourceNameForClass(GWT.class));
    factory.addImport(Name.getSourceNameForClass(SafeHtml.class));
    factory.addImport(Name.getSourceNameForClass(SafeHtmlBuilder.class));

    // Loop through the formatters declared for this type and supertypes
    FormatCollector formatters = new FormatCollector(context, logger, toGenerate);
    MethodCollector invokables = new MethodCollector(context, logger, toGenerate);

    SourceWriter sw = factory.createSourceWriter(context, pw);

    for (JMethod method : toGenerate.getOverridableMethods()) {
        TreeLogger l = logger.branch(Type.DEBUG, "Creating XTemplate method " + method.getName());
        final String template;
        XTemplate marker = method.getAnnotation(XTemplate.class);
        if (marker == null) {
            l.log(Type.ERROR, "Unable to create template for method " + method.getReadableDeclaration()
                    + ", this may cause other failures.");
            continue;
        } else {
            if (marker.source().length() != 0) {
                if (marker.value().length() != 0) {
                    l.log(Type.WARN, "Found both source file and inline template, using source file");
                }

                InputStream stream = getTemplateResource(context, method.getEnclosingType(), l,
                        marker.source());
                if (stream == null) {
                    l.log(Type.ERROR, "No data could be loaded - no data at path " + marker.source());
                    throw new UnableToCompleteException();
                }
                template = Util.readStreamAsString(stream);
            } else if (marker.value().length() != 0) {
                template = marker.value();
            } else {
                l.log(Type.ERROR, "XTemplate annotation found with no contents, cannot generate method "
                        + method.getName() + ", this may cause other failures.");
                continue;
            }
        }

        XTemplateParser p = new XTemplateParser(
                l.branch(Type.DEBUG, "Parsing provided template for " + method.getReadableDeclaration()));
        TemplateModel m = p.parse(template);
        SafeHtmlTemplatesCreator safeHtml = new SafeHtmlTemplatesCreator(context,
                l.branch(Type.DEBUG, "Building SafeHtmlTemplates"), method);

        sw.println(method.getReadableDeclaration(false, true, true, false, true) + "{");
        sw.indent();

        Map<String, JType> params = new HashMap<String, JType>();
        for (JParameter param : method.getParameters()) {
            params.put(param.getName(), param.getType());
        }
        Context scopeContext = new Context(context, l, params, formatters);
        // if there is only one parameter, wrap the scope up so that properties
        // can be accessed directly
        if (method.getParameters().length == 1) {
            JParameter param = method.getParameters()[0];
            scopeContext = new Context(scopeContext, param.getName(), param.getType());

        }

        String outerSHVar = scopeContext.declareLocalVariable("outer");
        sw.println("SafeHtml %1$s;", outerSHVar);

        buildSafeHtmlTemplates(outerSHVar, sw, m, safeHtml, scopeContext, invokables);

        sw.println("return %1$s;", outerSHVar);

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

        safeHtml.create();
    }

    // Save the file and return its type name
    sw.commit(logger);
    return factory.getCreatedClassName();
}

From source file:com.smartgwt.rebind.AnnotationMetaBeanFactoryGenerator.java

License:Open Source License

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

    final String genPackageName = "com.smartgwt.client.bean";
    final String genClassName = "AnnotationMetaFactoryImpl";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.addImplementedInterface(BeanFactory.AnnotationMetaFactory.class.getCanonicalName());

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter
                .println("// This class lovingly generated by " + this.getClass().getCanonicalName() + "\n");

        // Our constructor ... will be called by GWT.create()
        sourceWriter.println(genClassName + " () {");
        sourceWriter.indent();//from www .jav  a 2  s. c o m

        Set<JClassType> typesGenerated = new HashSet<JClassType>();

        // Collect the types ...
        for (JClassType classType : oracle.getTypes()) {
            BeanFactory.Generate annotation = classType.getAnnotation(BeanFactory.Generate.class);

            if (annotation != null) {
                TreeLogger annotationLogger = logger.branch(TreeLogger.DEBUG,
                        "Processing @BeanFactory.Generate annotation on " + classType.getQualifiedSourceName());

                Class[] value = annotation.value();
                if (value.length == 0) {
                    // No value supplied, so we use the class the annotation was applied to
                    if (!typesGenerated.contains(classType)) {
                        typesGenerated.add(classType);
                        generateFactory(classType, annotationLogger, context, sourceWriter);
                    }
                } else {
                    // Some values were supplied, so we use them, and not the class itself
                    for (Class klass : value) {
                        JClassType klassValue = oracle.findType(klass.getCanonicalName());
                        if (klassValue == null) {
                            annotationLogger.log(TreeLogger.ERROR,
                                    "Could not find " + klass.getName() + " in source classpath.");
                            throw new UnableToCompleteException();
                        } else {
                            if (!typesGenerated.contains(klassValue)) {
                                typesGenerated.add(klassValue);
                                generateFactory(klassValue, annotationLogger, context, sourceWriter);
                            }
                        }
                    }
                }
            }
        }

        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.commit(logger);
    }

    return composer.getCreatedClassName();
}

From source file:com.smartgwt.rebind.AnnotationMetaBeanFactoryGenerator.java

License:Open Source License

public void generateFactory(JClassType classType, TreeLogger logger, GeneratorContext context,
        SourceWriter sourceWriter) throws UnableToCompleteException {
    BeanClass beanClass = new BeanClass(classType);
    beanClass.generateFactory(logger, context);

    // We have to instantiate the factory to register it in the BeanFactory static API
    sourceWriter.println(beanClass.getQualifiedFactoryName() + ".create(false);");
}

From source file:com.smartgwt.rebind.BeanMethod.java

License:Open Source License

public void writeJSNIFunction(SourceWriter source, boolean addComma) {
    if (isGetter()) {
        source.println("function (b) {return " + box(jsniGetter()) + "}" + (addComma ? "," : ""));
    } else {/*from w  w  w . j a va  2 s  .  c  om*/
        source.println("function (b,v) {b.@" + method.getEnclosingType().getQualifiedSourceName() + "::"
                + method.getName() + "(" + valueType.getJNISignature() + ")" + "(v" + deboxer + ")}"
                + (addComma ? "," : ""));
    }
}

From source file:com.smartgwt.rebind.BeanMethod.java

License:Open Source License

public void writeNew(SourceWriter source, String beanClassName, Integer getterMethodNumber,
        Integer setterMethodNumber, boolean addComma) {
    // This should look like this:
    // new BeanMethod<Canvas, Integer>(Integer.class, 27, 35),  
    StringBuilder s = new StringBuilder();

    s.append("new BeanMethod<");
    s.append(beanClassName);/*from w ww.j  ava 2s .  c  o  m*/
    s.append(", ");
    s.append(genericType.getQualifiedSourceName());
    s.append(">(");
    s.append(classLiteral);
    s.append(", ");
    s.append(getterMethodNumber == null ? "null" : ("methods.get(" + getterMethodNumber.toString() + ")"));
    s.append(", ");
    s.append(setterMethodNumber == null ? "null" : ("methods.get(" + setterMethodNumber.toString() + ")"));
    s.append(")");
    if (addComma)
        s.append(",");

    source.println(s.toString());
}

From source file:com.smartgwt.rebind.BeanProperty.java

License:Open Source License

public void writeConstructor(SourceWriter source, boolean addComma) {
    if (getters.size() == 0 && setters.size() == 0) {
        source.println("// Skipping because there are no getters and no setters: " + getName());
        return;/*from   w  w w  .  j a  v a 2s. com*/
    }

    if (getters.size() == 1 && setters.size() == 1
            && setters.get(0).getValueType() == getters.get(0).getValueType()) {
        writeSingleConstructor(source, "BeanProperty1Getter1Setter", getters.get(0), setters.get(0), addComma);
    } else if (getters.size() == 1 && setters.size() == 0) {
        writeSingleConstructor(source, "BeanProperty1Getter", getters.get(0), null, addComma);
    } else if (setters.size() == 1 && getters.size() == 0) {
        writeSingleConstructor(source, "BeanProperty1Setter", null, setters.get(0), addComma);
    } else {
        writeMultipleConstructor(source, addComma);
    }
}

From source file:com.smartgwt.rebind.BeanProperty.java

License:Open Source License

public void writeSingleConstructor(SourceWriter source, String propertyType, BeanMethod getter,
        BeanMethod setter, boolean addComma) {
    final String beanClassName = beanClass.getSimpleBeanClassName();

    source.println("new " + propertyType + "<" + beanClassName + "> (\"" + getName() + "\",");
    source.indent();//from  ww w  .j a  va  2  s  . c  om

    if (getter != null && setter != null) {
        getter.writeNew(source, beanClassName, getMethodIndex(getter), getMethodIndex(setter), false);
    } else if (getter != null) {
        getter.writeNew(source, beanClassName, getMethodIndex(getter), null, false);
    } else if (setter != null) {
        setter.writeNew(source, beanClassName, null, getMethodIndex(setter), false);
    }

    source.outdent();
    source.println(")" + (addComma ? "," : ""));
}