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.cgxlib.xq.rebind.LazyGenerator.java

License:Apache License

private void generateDoneMethod(SourceWriter sw, JClassType nonLazyType, TreeLogger treeLogger) {
    sw.indent();//from   w w  w  .  ja va  2  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("}");
}

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

License:Apache License

public void generateMethod(SourceWriter sw, JMethod method, TreeLogger logger)
        throws UnableToCompleteException {
    Selector selectorAnnotation = method.getAnnotation(Selector.class);
    if (selectorAnnotation == null) {
        return;/*from   w w w  .  j av  a 2s.c o m*/
    }

    JParameter[] params = method.getParameters();

    String retType = method.getReturnType().getParameterizedQualifiedSourceName();
    sw.print("public final " + retType + " " + method.getName());
    boolean hasContext = false;
    if (params.length == 0) {
        sw.print("()");
    } else if (params.length == 1) {
        JClassType type = params[0].getType().isClassOrInterface();
        if (type != null && type.isAssignableTo(nodeType)) {
            sw.print("(Node root)");
            hasContext = true;
        }
    }
    sw.println(" {");
    sw.indent();
    Selector sel = method.getAnnotation(Selector.class);

    if (sel != null && sel.value().matches("^#\\w+$")) {
        // short circuit #foo
        sw.println("return " + wrap(method,
                "JsNodeArray.create(((Document)root).getElementById(\"" + sel.value().substring(1) + "\"))")
                + ";");
    } else if (sel != null && sel.value().matches("^\\w+$")) {
        // short circuit FOO
        sw.println("return "
                + wrap(method,
                        "JsNodeArray.create(((Element)root).getElementsByTagName(\"" + sel.value() + "\"))")
                + ";");
    } else if (sel != null && sel.value().matches("^\\.\\w+$") && hasGetElementsByClassName()) {
        // short circuit .foo for browsers with native getElementsByClassName
        sw.println("return " + wrap(method,
                "JsNodeArray.create(getElementsByClassName(\"" + sel.value().substring(1) + "\", root))")
                + ";");
    } else {
        generateMethodBody(sw, method, logger, hasContext);
    }
    sw.outdent();
    sw.println("}");
}

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

License:Apache License

private void genGetAllMethod(SourceWriter sw, JMethod[] methods, TreeLogger treeLogger) {
    sw.println("public DeferredSelector[] getAllSelectors() {return ds;}");
    sw.println("private final DeferredSelector[] ds = new DeferredSelector[] {");
    sw.indent();//from w w  w. j a  v a  2s .c  o m
    for (JMethod m : methods) {
        Selector selectorAnnotation = m.getAnnotation(Selector.class);
        if (selectorAnnotation == null) {
            continue;
        }
        String selector = selectorAnnotation.value();

        sw.println("new DeferredSelector() {");
        sw.indent();
        sw.println("public String getSelector() { return \"" + selector + "\"; }");
        sw.println("public NodeList<Element> runSelector(Node ctx) { return "
                + (m.getName() + (m.getParameters().length == 0 ? "()" : "(ctx)"))
                + ("NodeList".equals(m.getReturnType().getSimpleSourceName()) ? "" : ".get()") + ";}");
        sw.outdent();
        sw.println("},");
    }
    sw.outdent();
    sw.println("};");
}

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

License:Apache License

public void generateMethod(SourceWriter sw, JMethod method, TreeLogger logger)
        throws UnableToCompleteException {
    Name nameAnnotation = method.getAnnotation(Name.class);
    String name = nameAnnotation != null ? nameAnnotation.value()
            : method.getName().replaceFirst("^(get|set)", "");

    if (nameAnnotation == null) {
        name = name.substring(0, 1).toLowerCase() + name.substring(1);
    }/*w w  w  .j ava  2s . c o  m*/

    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();
        sw.println("() {");
        sw.indent();
        if (retType.matches("(java.lang.Boolean|boolean)")) {
            sw.println("return getBooleanBase(\"" + name + "\");");
        } else if (method.getReturnType().isPrimitive() != null) {
            sw.println("return (" + retType + ")getFloatBase(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), stringType)) {
            sw.println("return getStrBase(\"" + name + "\");");
        } else if (isTypeAssignableTo(method.getReturnType(), xmlBuilderType)) {
            String q = method.getReturnType().getQualifiedSourceName();
            sw.println("Element e = getElementBase(\"" + name + "\");");
            sw.println(
                    "return e == null ? null : (" + q + ")((" + q + ")GWT.create(" + q + ".class)).load(e);");
        } else if (retType.equals(Properties.class.getName())) {
            sw.println("return getPropertiesBase(\"" + name + "\");");
        } else if (arr != null) {
            String q = arr.getComponentType().getQualifiedSourceName();
            sw.println("ArrayList<" + q + "> l = new ArrayList<" + q + ">();");
            sw.println("for (Element e: getElementsBase(\"" + name + "\")) {");
            sw.println("  " + q + " c = GWT.create(" + q + ".class);");
            sw.println("  c.load(e);");
            sw.println("  l.add(c);");
            sw.println("}");
            sw.println("return l.toArray(new " + q + "[0]);");
        } else {
            sw.println("return null; // Unsupported return type: " + retType);
        }
        sw.outdent();
        sw.println("}");
    } else if (params.length == 1) {
        JType type = params[0].getType();
        JArrayType arr = type.isArray();
        String qname = type.getParameterizedQualifiedSourceName();
        sw.print("(" + qname + " a)");
        sw.println("{");
        sw.indent();
        if (arr != null) {
            sw.println("setArrayBase(\"" + name + "\", a);");
        } else {
            sw.println("setBase(\"" + 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.colinalworth.celltable.columns.rebind.ColumnsGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    //this.logger = logger;
    this.context = context;

    TypeOracle oracle = context.getTypeOracle();
    JClassType toGenerate = oracle.findType(typeName).isInterface();
    if (toGenerate == null) {
        logger.log(TreeLogger.ERROR, typeName + " is not an interface type");
        throw new UnableToCompleteException();
    }/*from w ww .  ja v a 2 s  . c  o m*/

    String packageName = toGenerate.getPackage().getName();
    String simpleSourceName = toGenerate.getName().replace('.', '_') + "_Impl";
    PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName);
    if (pw == null) {
        return packageName + "." + simpleSourceName;
    }

    ColumnSetModel columnSet = new ColumnSetModel(toGenerate, context, logger, names);

    //public class X implements X {
    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.addImplementedInterface(typeName);

    factory.addImport(Name.getSourceNameForClass(GWT.class));
    factory.addImport(Name.getSourceNameForClass(CellTable.class));
    factory.addImport(Name.getSourceNameForClass(HasDataFlushableEditor.class));
    factory.addImport(Name.getSourceNameForClass(Column.class));
    factory.addImport(Name.getSourceNameForClass(HasHorizontalAlignment.class));
    factory.addImport(Name.getSourceNameForClass(HasVerticalAlignment.class));
    factory.addImport(Name.getSourceNameForClass(FieldUpdater.class));
    factory.addImport(columnSet.getBeanName());

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

    //wire up the factory, if any
    if (columnSet.hasFactory()) {
        names.add("factory");
        sw.println("private %1$s factory;", columnSet.getFactoryClassName());
        sw.println("public void setFactory(%1$s factory) {", columnSet.getFactoryClassName());
        sw.indent();
        sw.println(
                "assert factory != null && this.factory == null : \"Factory cannot be reset, and factory cannot be set as null\";");
        sw.println("this.factory = factory;");
        sw.outdent();
        sw.println("}");
    }

    // generate column methods
    for (ColumnModel c : columnSet.getColumnModels()) {
        // make the field 
        // TODO: no sense in building multiple copies, right?
        sw.println("private %1$s %2$s;", c.getCellClassName(), c.getCellFieldName());

        sw.println("private Column<%1$s,%2$s> %3$s;", columnSet.getBeanName(), c.getCellDataTypeName(),
                c.getColumnFieldName());
        sw.println();

        // make the method: public MyCell myDataMember() {
        //sw.println("@Override");//jdk 5 doesnt like this
        sw.println("public %1$s %2$s() {", c.getCellClassName(), c.getMethodName());
        sw.indent();
        sw.println("if (%s == null) {", c.getCellFieldName());
        sw.indent();

        //create the cell
        sw.println("%1$s = %2$s;", c.getCellFieldName(), c.getCellCreateExpression());

        //create the column - probably should be done later in the case of using HasDataFlushableEditor
        sw.println("%1$s = new Column<%2$s,%3$s> (%4$s) {", c.getColumnFieldName(), columnSet.getBeanName(),
                c.getCellDataTypeName(), c.getCellFieldName());
        sw.indent();

        sw.println("@Override");
        sw.println("public %1$s getValue(%2$s bean) {", c.getCellDataTypeName(), columnSet.getBeanName());
        sw.indent();
        sw.println("return %1$s;", c.getGetterInModel("bean"));
        sw.outdent();
        sw.println("}");

        sw.outdent();// end anon Column class
        sw.println("};");

        // Refactor at least this part out, in anticipation of a proper link to the Editor framework
        // TODO this is done by replacement right now, fix that.
        if (c.isEditable()) {
            if (!c.hasCustomFieldUpdater()) {
                sw.println("%1$s.setFieldUpdater(new FieldUpdater<%2$s,%3$s>() {", c.getColumnFieldName(),
                        columnSet.getBeanName(), c.getCellDataTypeName());
                sw.indent();

                sw.println("public void update(int index, %1$s object, %2$s value) {", columnSet.getBeanName(),
                        c.getCellDataTypeName());
                sw.indent();
                sw.println("%1$s;", c.getSetterInModel("object", "value"));
                sw.outdent();
                sw.println("}");

                sw.outdent();// end anon FieldUpdater class
                sw.println("});");
            } else {
                sw.println("%1$s.setFieldUpdater(GWT.<%2$s>create(%2$s.class));", c.getColumnFieldName(),
                        c.getFieldUpdaterType().getQualifiedSourceName());
            }
        }
        sw.println("%1$s.setHorizontalAlignment(%2$s);", c.getColumnFieldName(), c.getHorizontalAlignment());
        sw.println("%1$s.setVerticalAlignment(%2$s);", c.getColumnFieldName(), c.getVerticalAlignment());

        if (supportsSortable()) {
            sw.println("%1$s.setSortable(%2$s);", c.getColumnFieldName(), c.isSortable());
        } else {
            if (c.isSortable()) {
                logger.log(Type.WARN,
                        "Your version of GWT does not appear to support Column.setSortable, compilation may fail.");
            }
        }
        //end column creation/setup

        sw.outdent();
        sw.println("}");// end column/cell creation
        sw.println("return %s;", c.getCellFieldName());
        sw.outdent();
        sw.println("}");
    }

    // generate configure methods

    // simple overload
    sw.println("public final void configure(CellTable<%1$s> table) {", columnSet.getBeanName());
    sw.indent();
    sw.println("configure(table, null);");
    sw.outdent();
    sw.println("}");

    // actual heavy-lifting one
    sw.println("public final void configure(CellTable<%1$s> table, HasDataFlushableEditor<%1$s> ed) {",
            columnSet.getBeanName());
    sw.indent();
    if (columnSet.hasFactory()) {
        sw.println(
                "assert factory != null : \"setFactory() must be called before configure() can be called.\";");
    }
    for (ColumnModel c : columnSet.getColumnModels()) {
        //wire up the cell and column
        sw.println("%1$s();", c.getMethodName());

        if (c.isEditable() && !c.hasCustomFieldUpdater()) {
            // if there is an editor, replace the FieldUpdater
            sw.println("if (ed != null) {");
            sw.indent();
            sw.println("final FieldUpdater<%1$s, %2$s> wrapped = %3$s.getFieldUpdater();",
                    columnSet.getBeanName(), c.getCellDataTypeName(), c.getColumnFieldName());
            sw.println("%1$s.setFieldUpdater(ed.new PendingFieldUpdateChange<%2$s>(){", c.getColumnFieldName(),
                    c.getCellDataTypeName());
            sw.indent();
            sw.println("public void commit(int index, %1$s object, %2$s value) {", columnSet.getBeanName(),
                    c.getCellDataTypeName());
            sw.indent();
            sw.println("wrapped.update(index, object, value);");
            sw.outdent();
            sw.println("}");
            sw.outdent();
            sw.println("});");
            sw.outdent();
            sw.println("}");
        }

        // attach the column
        sw.println("table.addColumn(%1$s, %2$s);", c.getColumnFieldName(), c.getHeaderValue());
    }
    sw.outdent();
    sw.println("}");

    sw.println("public String[] getPaths() {");
    sw.indent();
    sw.println("return %1$s;", columnSet.getPaths());
    sw.outdent();
    sw.println("}");

    sw.commit(logger);

    return factory.getCreatedClassName();
}

From source file:com.colinalworth.gwt.websockets.rebind.ServerBuilderGenerator.java

License:Apache License

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

    if (toGenerate == null) {
        logger.log(Type.ERROR, "Error generating " + typeName
                + ", either not an interface, or cannot be reached from client code.");
        throw new UnableToCompleteException();
    }/*from   w w  w. java 2  s  . c o  m*/
    JClassType serverBuilderType = oracle.findType(ServerBuilder.class.getName());
    JClassType serverImplType = ModelUtils.findParameterizationOf(serverBuilderType, toGenerate)[0];

    // Build an impl so we can call it ourselves
    ServerCreator creator = new ServerCreator(serverImplType);
    creator.create(logger, context);

    String packageName = toGenerate.getPackage().getName();
    String simpleName = toGenerate.getName().replace('.', '_') + "_Impl";

    PrintWriter pw = context.tryCreate(logger, packageName, simpleName);
    if (pw == null) {
        return packageName + "." + simpleName;
    }

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleName);
    factory.setSuperclass(Name.getSourceNameForClass(ServerBuilderImpl.class) + "<"
            + serverImplType.getQualifiedSourceName() + ">");
    factory.addImplementedInterface(typeName);

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

    RemoteServiceRelativePath path = serverImplType.getAnnotation(RemoteServiceRelativePath.class);
    if (path != null) {
        sw.println("public %1$s() {", simpleName);
        sw.indentln("setPath(\"%1$s\");", path.value());
        sw.println("}");
    }

    sw.println();
    // start method
    sw.println("public %1$s start() {", serverImplType.getQualifiedSourceName());
    sw.indent();
    sw.println("String url = getUrl();");
    sw.println("if (url == null) {");
    sw.indentln("return new %1$s(getErrorHandler());", creator.getQualifiedSourceName());
    sw.println("} else {");
    sw.indentln("return new %1$s(getErrorHandler(), url);", creator.getQualifiedSourceName());
    sw.println("}");

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

    sw.commit(logger);

    return factory.getCreatedClassName();

}

From source file:com.colinalworth.gwt.websockets.rebind.ServerCreator.java

License:Apache License

public void create(TreeLogger logger, GeneratorContext context) throws UnableToCompleteException {
    String typeName = this.serverType.getQualifiedSourceName();

    String packageName = getPackageName();
    String simpleName = getSimpleName();

    TypeOracle oracle = context.getTypeOracle();

    PrintWriter pw = context.tryCreate(logger, packageName, simpleName);
    if (pw == null) {
        return;/*from  w  w w  .ja  v  a 2 s.  co  m*/
    }
    JClassType serverType = oracle.findType(Name.getSourceNameForClass(Server.class));
    JClassType clientType = ModelUtils.findParameterizationOf(serverType, this.serverType)[1];

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleName);
    factory.setSuperclass(Name.getSourceNameForClass(ServerImpl.class) + "<" + typeName + ","
            + clientType.getQualifiedSourceName() + ">");
    factory.addImplementedInterface(typeName);

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

    //TODO move this check before the printwriter creation can fail, and allow the warn to be optional
    sw.println("public %1$s(%2$s errorHandler) {", simpleName,
            Name.getSourceNameForClass(ServerBuilder.ConnectionErrorHandler.class));
    RemoteServiceRelativePath path = this.serverType.getAnnotation(RemoteServiceRelativePath.class);
    if (path == null) {
        //         logger.log(Type.WARN, "@RemoteServiceRelativePath required on " + typeName + " to make a connection to the server without a ServerBuilder");
        //         throw new UnableToCompleteException();
        sw.indentln("super(null);");
        sw.indentln(
                "throw new RuntimeException(\"@RemoteServiceRelativePath annotation required on %1$s to make a connection without a path defined in ServerBuilder\");");
    } else {
        sw.indentln("super(errorHandler, "
                + "com.google.gwt.user.client.Window.Location.getProtocol().toLowerCase().startsWith(\"https\") ? \"wss://\": \"ws://\", "
                + "com.google.gwt.user.client.Window.Location.getHost(), \"%1$s\");", path.value());
    }
    sw.println("}");

    sw.println("public %1$s(%2$s errorHandler, String url) {", simpleName,
            Name.getSourceNameForClass(ServerBuilder.ConnectionErrorHandler.class));
    sw.indentln("super(errorHandler, url);");
    sw.println("}");

    //Find all types that may go over the wire
    // Collect the types the server will send to the client using the Client interface
    SerializableTypeOracleBuilder serverSerializerBuilder = new SerializableTypeOracleBuilder(logger, context);
    appendMethodParameters(logger, clientType, Client.class, serverSerializerBuilder);
    // Also add the wrapper object ClientInvocation
    serverSerializerBuilder.addRootType(logger, oracle.findType(ClientInvocation.class.getName()));
    serverSerializerBuilder.addRootType(logger, oracle.findType(ClientCallbackInvocation.class.getName()));

    // Collect the types the client will send to the server using the Server interface
    SerializableTypeOracleBuilder clientSerializerBuilder = new SerializableTypeOracleBuilder(logger, context);
    appendMethodParameters(logger, this.serverType, Server.class, clientSerializerBuilder);
    // Also add the ServerInvocation wrapper
    clientSerializerBuilder.addRootType(logger, oracle.findType(ServerInvocation.class.getName()));
    clientSerializerBuilder.addRootType(logger, oracle.findType(ServerCallbackInvocation.class.getName()));

    String tsName = simpleName + "_TypeSerializer";
    TypeSerializerCreator serializerCreator = new TypeSerializerCreator(logger,
            clientSerializerBuilder.build(logger), serverSerializerBuilder.build(logger), context,
            packageName + "." + tsName, tsName);
    serializerCreator.realize(logger);

    // Make the newly created Serializer available at runtime
    sw.println("protected %1$s __getSerializer() {", Serializer.class.getName());
    sw.indentln("return %2$s.<%1$s>create(%1$s.class);", tsName, GWT.class.getName());
    sw.println("}");

    // Build methods that call from the client to the server
    for (JMethod m : this.serverType.getInheritableMethods()) {
        if (isRemoteMethod(m, Server.class)) {
            printServerMethodBody(logger, context, sw, m);
        }
    }

    // Read incoming calls and dispatch them to the correct client method
    sw.println("protected void __invoke(String method, Object[] params) {");
    for (JMethod m : clientType.getInheritableMethods()) {
        if (isRemoteMethod(m, Client.class)) {
            JParameter[] params = m.getParameters();
            sw.println("if (method.equals(\"%1$s\") && params.length == %2$d) {", m.getName(), params.length);
            sw.indent();
            sw.println("getClient().%1$s(", m.getName());
            sw.indent();
            for (int i = 0; i < params.length; i++) {
                if (i != 0) {
                    sw.print(",");
                }
                sw.println("(%1$s)params[%2$d]", params[i].getType().getQualifiedSourceName(), i);
            }
            sw.outdent();
            sw.println(");");
            sw.outdent();
            sw.println("}");
        }
    }
    sw.println("}");

    sw.println("protected void __onError(Exception error) {");
    sw.println("}");

    sw.commit(logger);
}

From source file:com.colinalworth.gwt.websockets.rebind.ServerCreator.java

License:Apache License

/**
 * Writes out the method to use to invoke a server call. Mostly derived from RPC's way of building proxy methods
 *
 * @param logger//  w w  w  .  j  a  v a 2s.  c  o  m
 * @param context
 * @param sw
 * @param m
 */
private void printServerMethodBody(TreeLogger logger, GeneratorContext context, SourceWriter sw, JMethod m) {
    sw.println("%1$s {", m.getReadableDeclaration(false, true, true, true, true));
    sw.indent();

    sw.print("__sendMessage(\"%1$s\"", m.getName());
    StringBuilder sb = new StringBuilder();
    String callback = "null";
    JParameter[] parameters = m.getParameters();
    for (int i = 0; i < parameters.length; i++) {
        JParameter param = parameters[i];
        if (i + 1 == parameters.length && param.getType().isInterface() != null
                && param.getType().isInterface().getQualifiedSourceName().equals(Callback.class.getName())) {
            callback = param.getName();
        } else {
            sb.append(",\n").append(param.getName());
        }
    }
    sw.print(",");
    sw.println(callback);
    sw.print(sb.toString());
    sw.println(");");

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

From source file:com.dom_distiller.client.JsTestEntryGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typename)
        throws UnableToCompleteException {
    String packageName = "com.dom_distiller.client";
    String outputClassname = "JsTestBuilderImpl";

    List<TestCase> testCases = getTestCases(logger, context);

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, outputClassname);
    composer.addImplementedInterface("com.dom_distiller.client.JsTestSuiteBuilder");
    PrintWriter printWriter = context.tryCreate(logger, packageName, outputClassname);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("JsTestBuilderImpl () {");
        sourceWriter.println("}");
        sourceWriter.println("public JsTestSuiteBase build() {");
        sourceWriter.indent();//from   w  w w  .j av a  2  s  . c o m
        sourceWriter.println("JsTestSuiteBase testSuite = new JsTestSuiteBase();");
        for (TestCase ts : testCases) {
            String className = ts.classType.getName();
            String qualifiedClassName = ts.classType.getPackage().getName() + "." + className;
            sourceWriter.println("testSuite.addTestCase(");
            sourceWriter.println("        new JsTestSuiteBase.TestCaseFactory() {");
            sourceWriter.println("            @Override");
            sourceWriter.println("            public JsTestCase build() {");
            sourceWriter.println("                return new " + className + "();");
            sourceWriter.println("            }");
            sourceWriter.println("        }, \"" + qualifiedClassName + "\")");
            sourceWriter.indent();
            for (JMethod test : ts.tests) {
                String methodName = test.getName();
                sourceWriter.println(".addTest(");
                sourceWriter.println("        new JsTestSuiteBase.TestCaseRunner() {");
                sourceWriter.println("            @Override");
                sourceWriter.println("            public void run(JsTestCase testCase) throws Exception {");
                sourceWriter.println("                ((" + className + ")testCase)." + methodName + "();");
                sourceWriter.println("            }");
                sourceWriter.println("        }, \"" + methodName + "\")");
            }
            sourceWriter.println(";");
            sourceWriter.outdent();
        }
        sourceWriter.println("return testSuite;");
        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.commit(logger);
    }
    return composer.getCreatedClassName();
}

From source file:com.ekuefler.supereventbus.rebind.EventRegistrationWriter.java

License:Apache License

/**
 * Writes the source for getMethods() the given target class to the given writer.
 *///from   w  ww .j  a  v a 2  s  .c o  m
void writeGetMethods(JClassType target, SourceWriter writer) throws UnableToCompleteException {
    String targetType = target.getQualifiedSourceName();
    writer.println("public List<EventHandlerMethod<%s, ?>> getMethods() {", targetType);
    writer.indent();

    // Write a list that we will add all handlers to before returning
    writer.println("List<%1$s> methods = new LinkedList<%1$s>();",
            String.format("EventHandlerMethod<%s, ?>", targetType));

    // Iterate over each method in the target, looking for methods annotated with @Subscribe
    for (JMethod method : target.getInheritableMethods()) {
        if (method.getAnnotation(Subscribe.class) == null) {
            continue;
        }
        checkValidity(target, method);

        // Generate a list of types that should be handled by this method. Normally, this is a single
        // type equal to the method's first argument. If the argument in a MultiEvent, this list of
        // types comes from the @EventTypes annotation on the parameter.
        final List<String> paramTypes = new LinkedList<String>();
        final boolean isMultiEvent;
        if (getFirstParameterType(method).equals(MultiEvent.class.getCanonicalName())) {
            isMultiEvent = true;
            for (Class<?> type : method.getParameters()[0].getAnnotation(EventTypes.class).value()) {
                paramTypes.add(type.getCanonicalName());
            }
        } else {
            isMultiEvent = false;
            paramTypes.add(getFirstParameterType(method));
        }

        // Add an implementation of EventHandlerMethod to the list for each type this method handles
        for (String paramType : paramTypes) {
            writer.println("methods.add(new EventHandlerMethod<%s, %s>() {", targetType, paramType);
            writer.indent();
            {
                // Implement invoke() by calling the method, first checking filters if provided
                writer.println("public void invoke(%s instance, %s arg) {", targetType, paramType);
                String invocation = String.format(
                        isMultiEvent ? "instance.%s(new MultiEvent(arg));" : "instance.%s(arg);",
                        method.getName());
                if (method.getAnnotation(When.class) != null) {
                    writer.indentln("if (%s) { %s }", getFilter(method), invocation);
                } else {
                    writer.indentln(invocation);
                }
                writer.println("}");

                // Implement acceptsArgument using instanceof
                writer.println("public boolean acceptsArgument(Object arg) {");
                writer.indentln("return arg instanceof %s;", paramType);
                writer.println("}");

                // Implement getDispatchOrder as the inverse of the method's priority
                writer.println("public int getDispatchOrder() {");
                writer.indentln("return %d;",
                        method.getAnnotation(WithPriority.class) != null
                                ? -method.getAnnotation(WithPriority.class).value()
                                : 0);
                writer.println("}");
            }
            writer.outdent();
            writer.println("});");
        }
    }

    // Return the list of EventHandlerMethods
    writer.println("return methods;");
    writer.outdent();
    writer.println("}");
}