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.github.gilbertotorrezan.gwtviews.rebind.PresenterGenerator.java

License:Open Source License

private void printInjectorMethod(SourceWriter sourceWriter, String className, JClassType injectorType,
        String injectorMethod) {/* ww  w  .  ja  v  a2s.com*/
    if (injectorType != null && injectorMethod != null) {
        sourceWriter.println(
                injectorType.getQualifiedSourceName() + " injector = NavigationManager.getInjectorInstance("
                        + injectorType.getQualifiedSourceName() + ".class);");
        sourceWriter.println("if (injector == null) injector = GWT.create("
                + injectorType.getQualifiedSourceName() + ".class);");
        sourceWriter.println("Widget view = (" + className + ") injector." + injectorMethod + "();");
    } else {
        sourceWriter.println("Widget view = GWT.create( " + className + ".class);");
    }
}

From source file:com.github.ludorival.dao.gwt.rebind.EntityManagerGenerator.java

License:Apache License

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

    String packageName = mainType.getPackage().getName();
    String className = "Gwt" + mainType.getName();
    if (parseOnlyInterface)
        className += "Light";
    PrintWriter writer = context.tryCreate(logger, packageName, className);
    if (writer == null) {
        return packageName + "." + className;
    }/*  w  w w . j a va  2s  .  c  o m*/

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, className);
    logger.log(Type.DEBUG, "Create EntityManager " + factory.getCreatedClassName());
    factory.setSuperclass(AdapterEntityManager.class.getSimpleName());
    factory.addImport(AdapterEntityManager.class.getName());
    factory.addImport(Entity.class.getName());
    factory.addImport(Bean.class.getName());
    factory.addImport(HashMap.class.getName());
    factory.addImport("javax.annotation.Generated");

    JClassType[] types = typeOracle.getTypes();
    List<BeanMetadata> metadatas = new ArrayList<EntityManagerGenerator.BeanMetadata>();
    for (JClassType type : types) {
        BeanMetadata metaData = null;
        boolean candidate = false;
        if (type.isAnnotationPresent(IsEntity.class)) {
            candidate = true;
            try {
                metaData = createEntity(context, logger, packageName, type, type.getAnnotation(IsEntity.class));
            } catch (TypeOracleException e) {
                logger.log(Type.ERROR, e.getMessage(), e);
                continue;
            }

        } else if (type.isAnnotationPresent(IsBean.class)) {
            candidate = true;
            try {
                metaData = createBean(context, logger, packageName, type, type.getAnnotation(IsBean.class));
            } catch (TypeOracleException e) {
                logger.log(Type.ERROR, e.getMessage(), e);
                continue;
            }

        }
        if (!candidate)
            continue;
        if (metaData == null) {
            log(logger, Type.WARN, "The type %s is not instantiable", type);
            continue;
        }
        log(logger, Type.DEBUG, "The entity has been build : %s", metaData);
        factory.addImport(type.getQualifiedSourceName());

        if (metaData.implementation != null) {
            factory.addImport(metaData.implementation + "");
        }
        metadatas.add(metaData);
    }

    factory.addAnnotationDeclaration("@Generated(" + "value=\"" + AdapterEntityManager.class.getName() + "\", "
            + "date=\"" + new Date() + "\", " + "comments=\"Generated by DAO-GWT project.\")");

    SourceWriter sourceWriter = factory.createSourceWriter(context, writer);

    sourceWriter.println("//AUTO GENERATED FILE BY DAO-GWT " + getClass().getName() + ". DO NOT EDIT!\n");

    sourceWriter.println(
            "private static HashMap<Class<?>,Entity<?>> ENTITIES = new HashMap<Class<?>,Entity<?>>();");
    sourceWriter.println("private static HashMap<Class<?>,Bean<?>> BEANS = new HashMap<Class<?>,Bean<?>>();");

    sourceWriter.println("static {");
    sourceWriter.indent();
    for (BeanMetadata metaData : metadatas) {
        String variable = "entity";
        String plural = "ENTITIES";
        if (!metaData.entity) {
            variable = "bean";
            plural = "BEANS";
        }

        sourceWriter.println("{ //%s with its implementation", metaData.name);
        sourceWriter.indent();
        sourceWriter.println("%s %s = new %s();", metaData.name, variable, metaData.name);

        sourceWriter.println("%s.put(%s.class,%s);", plural, metaData.type.getName(), variable);
        if (metaData.implementation != null) {
            factory.addImport(metaData.implementation.packageName);
            sourceWriter.println("%s.put(%s.class,%s);", plural, metaData.implementation.className, variable);
        }
        sourceWriter.outdent();
        sourceWriter.println("}");

    }
    sourceWriter.outdent();
    sourceWriter.println("}");
    sourceWriter.println();
    sourceWriter.println("public %s(){", className);
    sourceWriter.indent();
    sourceWriter.println("super(ENTITIES,BEANS);");
    sourceWriter.outdent();
    sourceWriter.println("}");
    sourceWriter.outdent();
    sourceWriter.println("}");
    context.commit(logger, writer);

    return factory.getCreatedClassName();

}

From source file:com.github.ludorival.dao.gwt.rebind.EntityManagerGenerator.java

License:Apache License

private BeanMetadata create(GeneratorContext context, TreeLogger logger, String packageName, JClassType type,
        Class<?> classAdapter, IsEntity anno) throws TypeOracleException {
    String beanName = anno == null || anno.aliasName().isEmpty() ? type.getName() : anno.aliasName();
    Source implementation = null;
    JClassType implType = type;// ww w.j  a  va  2  s .c  o  m
    TypeOracle typeOracle = context.getTypeOracle();
    if (type.isInterface() != null) {
        implType = null;
        JClassType[] types = type.getSubtypes();
        log(logger, Type.DEBUG, "Get all sub types of %s : %s", type, Arrays.toString(types));
        if (types != null && types.length > 0) {
            for (JClassType jClassType : types) {
                if (isInstantiable(jClassType, logger)) {
                    implType = jClassType;
                    implementation = new Source(implType.getPackage().getName(), implType.getName());
                    break;
                }

            }

        }
        if (implType == null) {
            log(logger, Type.ERROR, "The type %s has not valid subtypes " + "%s !", type,
                    Arrays.toString(types));
            return null;
        }
    }
    if (!implType.isDefaultInstantiable())
        return null;
    String prefix = classAdapter.getSimpleName().replace("Adapter", "");
    boolean isEntity = anno != null;
    String className = prefix + beanName;
    if (parseOnlyInterface && implType != type)
        className += "Light";
    PrintWriter writer = context.tryCreate(logger, packageName, className);
    if (writer == null) {
        return new BeanMetadata(type, className, implementation, isEntity);
    }

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, className);
    logger.log(Type.DEBUG, "Create Entity " + factory.getCreatedClassName());

    factory.setSuperclass(classAdapter.getSimpleName() + "<" + type.getName() + ">");
    factory.addImport(RuntimeException.class.getName());
    factory.addImport(classAdapter.getName());
    factory.addImport(type.getQualifiedSourceName());
    if (isEntity) {
        factory.addImport(ArrayList.class.getName());
        factory.addImport(Collection.class.getName());
    }
    factory.addImport(HashMap.class.getName());
    factory.addImport(Property.class.getName());
    factory.addImport(Property.class.getName() + ".Kind");
    factory.addImport(Index.class.getName());
    factory.addImport(implType.getQualifiedSourceName());

    factory.addImport("javax.annotation.Generated");
    factory.addAnnotationDeclaration("@Generated(" + "value=\"" + AdapterEntity.class.getName() + "\", "
            + "date=\"" + new Date() + "\", " + "comments=\"Generated by DAO-GWT project.\")");

    SourceWriter sourceWriter = factory.createSourceWriter(context, writer);

    sourceWriter.println("//AUTO GENERATED FILE BY DAO-GWT " + getClass().getName() + ". DO NOT EDIT!\n");

    sourceWriter.println("private static HashMap<String,Property<%s,?>> PROPERTIES = "
            + "new HashMap<String,Property<%s,?>>();", type.getName(), type.getName());
    if (isEntity) {
        factory.addImport(ArrayList.class.getName());
        factory.addImport(Index.class.getName());
        sourceWriter.println("private static Collection<Index> INDEXES = " + "new ArrayList<Index>();");

    }
    sourceWriter.println("static {");
    sourceWriter.indent();
    JClassType interfaz = type != implType ? type : null;
    JMethod[] methods = parseOnlyInterface ? type.getInheritableMethods() : implType.getInheritableMethods();
    for (JMethod method : methods) {
        String name = method.getName();
        //Check if the method has a IsIgnored annotation before to continue
        IsIgnored ignored = method.getAnnotation(IsIgnored.class);
        if (ignored != null) {

            log(logger, Type.DEBUG, EXPLICITELY_IGNORED, name, implType);
            continue;
        }
        boolean startsWithGet = name.startsWith("get");
        boolean startsWithIs = name.startsWith("is");
        if (!startsWithGet && !startsWithIs) {
            log(logger, Type.DEBUG, IGNORE_METHOD, name, implType);
            continue;
        }

        //check no parameters
        if (method.getParameterTypes().length != 0) {
            log(logger, Type.WARN, NO_PARAMETER_GETTER, name, implType);
            continue;
        }
        //check return type
        JType returnType = method.getReturnType();
        if (returnType == null || returnType.getQualifiedSourceName().equals(Void.class.getName())
                || returnType.getQualifiedSourceName().equals(void.class.getName())) {
            log(logger, Type.DEBUG, VOID_GETTER, name + "" + returnType, implType);
            continue;
        }
        //change the format of the name getXyy ==> xyy
        String getterSetter = name;
        if (startsWithGet)
            getterSetter = name.substring(3);
        else if (startsWithIs)
            getterSetter = name.substring(2);
        name = getterSetter.substring(0, 1).toLowerCase() + getterSetter.substring(1);
        // check if the getter has an annotation
        IsIndexable indexable = method.getAnnotation(IsIndexable.class);
        boolean isIndexable = indexable != null;
        if (isIndexable && !isEntity)
            log(logger, Type.WARN, ONLY_ENTITY_FOR_INDEX, name, implType, IsEntity.class);

        isIndexable = isIndexable && isEntity;//only entity can defined indexable element

        String indexName = isIndexable ? indexable.aliasName() : "";
        String[] compositeIndexes = isIndexable ? indexable.compoundWith() : new String[0];
        Kind kind = null;
        JType typeOfCollection = null;
        String typeOfCollectionString = "null";

        if (!isPrimitive(returnType)) {

            //load complex properties except Key
            if (returnType.isEnum() != null) {
                kind = Kind.ENUM;
            } else {
                boolean isPrimitive = false;
                boolean isEnum = false;
                JParameterizedType pType = returnType.isParameterized();
                JType collection = typeOracle.parse(Collection.class.getName());

                if (pType != null && pType.getRawType().isAssignableTo(collection.isClassOrInterface())) {
                    JClassType[] types = pType.getTypeArgs();
                    kind = Kind.COLLECTION_OF_PRIMITIVES;
                    if (types.length > 1) {
                        log(logger, Type.DEBUG, CANNOT_PROCESS_PARAMETERIZED_TYPE, returnType, implType);
                        continue;
                    }
                    typeOfCollection = types[0];
                    typeOfCollectionString = typeOfCollection.getQualifiedSourceName() + ".class";
                    log(logger, Type.DEBUG, "The type of the collection is %s", typeOfCollectionString);
                    isPrimitive = isPrimitive(typeOfCollection);
                    isEnum = typeOfCollection.isEnum() != null;
                }
                if (!isPrimitive) {

                    if (isEnum && kind != null) {
                        kind = Kind.COLLECTION_OF_ENUMS;
                    } else {
                        JClassType classType = typeOfCollection != null ? typeOfCollection.isClassOrInterface()
                                : returnType.isClassOrInterface();
                        boolean isBean = isBean(classType);
                        if (isBean) {
                            log(logger, Type.DEBUG, "The property %s is well a type %s", name, classType);
                            if (kind == null)
                                kind = Kind.BEAN;
                            else
                                kind = Kind.COLLECTION_OF_BEANS;
                        } else {
                            log(logger, Type.DEBUG, "The property %s has not a bean type %s", name, classType);
                            continue;
                        }
                    }

                }
            }

        }
        assert kind != null;

        boolean isMemo = method.getAnnotation(IsMemo.class) != null;
        String oldName = "null";
        OldName oldNameAnno = method.getAnnotation(OldName.class);
        if (oldNameAnno != null)
            oldName = "\"" + oldNameAnno.value() + "\"";
        //create a property
        if (kind == Kind.BEAN || kind == Kind.COLLECTION_OF_BEANS)
            factory.addImport(returnType.getQualifiedSourceName());
        String valueType = "";
        JClassType classType = returnType.isClassOrInterface();
        JPrimitiveType primitiveType = returnType.isPrimitive();
        if (classType != null)
            valueType = classType.getQualifiedSourceName();
        else if (primitiveType != null) {
            valueType = primitiveType.getQualifiedBoxedSourceName();
        }

        sourceWriter.println("{ //Property %s", name);
        sourceWriter.indent();
        sourceWriter.print("Index index =");
        if (isIndexable) {
            if (indexName.isEmpty())
                indexName = name;
            sourceWriter.println("new Index(\"%s\",\"%s\",new String[]{%s});", indexName, name,
                    String.join(",", compositeIndexes));
        } else
            sourceWriter.println("null;");
        boolean useKeyAsString = anno != null ? (name.equals(anno.keyName()) ? anno.useKeyAsString() : false)
                : false;

        KeyOf keyOf = method.getAnnotation(KeyOf.class);
        if (keyOf != null) {
            IsEntity isEntity2 = keyOf.entity().getAnnotation(IsEntity.class);
            if (isEntity2 == null) {
                log(logger, Type.ERROR, AdapterEntityManager.KEY_OF_NO_ENTITY, method, keyOf, keyOf.entity(),
                        IsEntity.class);
                continue;
            }
            useKeyAsString = isEntity2.useKeyAsString();
        }
        boolean isHidden = isHidden(method, interfaz);
        sourceWriter.println(
                "Property<%s,%s> property = new Property<%s,%s>(\"%s\",%s,%s.class,%s,%s,%s,%s,index,%s){",
                type.getName(), valueType, type.getName(), valueType, name, oldName,
                returnType.getQualifiedSourceName(), typeOfCollectionString,
                kind != null ? "Kind." + kind.name() : "null", useKeyAsString + "", isMemo + "", isHidden + "");
        sourceWriter.indent();
        sourceWriter.println("@Override");
        sourceWriter.println("public %s get(%s instance){", valueType, type.getName());
        sourceWriter.indent();

        sourceWriter.println("return ((%s)instance).%s();", implType.getName(),
                startsWithGet ? "get" + getterSetter : "is" + getterSetter);
        sourceWriter.outdent();
        sourceWriter.println("}");

        sourceWriter.println("@Override");
        sourceWriter.println("public void set(%s instance, %s value){", type.getName(), valueType);
        sourceWriter.indent();

        if (getSetter(implType, getterSetter, returnType) != null)
            sourceWriter.println("((%s)instance).%s(value);", implType.getName(), "set" + getterSetter);
        else {
            logger.log(Type.WARN, " Not found setter for " + getterSetter);
            sourceWriter.println("throw new RuntimeException(\"No such setter " + getterSetter + " \");");
        }

        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.outdent();
        sourceWriter.println("};");
        sourceWriter.println("PROPERTIES.put(\"%s\",property);", name);
        if (!oldName.equals("null")) {
            sourceWriter.println("PROPERTIES.put(%s,property);", oldName);
        }
        if (isIndexable)
            sourceWriter.println("INDEXES.add(index);");
        sourceWriter.outdent();
        sourceWriter.println("}");

        log(logger, Type.DEBUG, SUCCESSFUL_ADD_PROPERTY, name + ":" + valueType, implType);

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

    sourceWriter.println();
    sourceWriter.println("public %s(){", className);
    sourceWriter.indent();

    /*
     * boolean asyncReady,
       boolean autoGeneratedFlag,
       String keyName,
       boolean useKeyAsString,
       Class<T> type,Class<? extends T> implType,
       Map<String, Property<T,?>> mapAllProperties, Collection<Index> indexes) {
    super(type,implType,mapAllProperties);
     */
    if (isEntity)
        sourceWriter
                .println(String.format("super(\"%s\",%s,%s,\"%s\",%s,%s.class,%s.class,PROPERTIES,INDEXES);",
                        anno.aliasName().isEmpty() ? type.getName() : anno.aliasName(), anno.asyncReady(),
                        anno.autoGeneratedKey(), anno.keyName(), anno.useKeyAsString(), type.getName(),
                        implType.getName()));
    else {
        sourceWriter.println(
                String.format("super(%s.class,%s.class,PROPERTIES);", type.getName(), implType.getName()));

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

    sourceWriter.println();
    sourceWriter.println("@Override");
    sourceWriter.println("public %s newInstance(){", type.getName());
    sourceWriter.indent();
    sourceWriter.println("return new %s();", implType.getName());
    sourceWriter.outdent();
    sourceWriter.println("}");

    sourceWriter.outdent();
    sourceWriter.println("}");
    context.commit(logger, writer);

    return new BeanMetadata(type, className, implementation, isEntity);
}

From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java

License:Apache License

/**
 * Print the default implementation for {@link java.lang.Object} methods.
 * If typeToMock is a class it will only print default implementations for
 * methods of Object listed in the methods parameter. If typeToMock is an interface
 * it will always print default implementations for all methods of Object.
 */// w  ww. j av  a2  s . co  m
private void printDefaultMethods(SourceWriter writer, JClassType typeToMock, Set<String> methods) {

    // always print default implementations for interfaces
    boolean isInterface = typeToMock.isInterface() != null;

    if (isInterface || methods.contains("equals")) {
        writer.println("public boolean equals(Object obj) {");
        writer.indent();
        writer.println("this.mocksControl.unmockableCallTo(\"equals()\");");
        writer.println("return obj == this;"); // object identity since Mocks don't hold any data
        writer.outdent();
        writer.println("}");
        writer.println();
    }

    if (isInterface || methods.contains("toString")) {
        writer.println("public String toString() {");
        writer.indent();
        writer.println("this.mocksControl.unmockableCallTo(\"toString()\");");
        writer.println("return \"Mock for %s\";", typeToMock.getName());
        writer.outdent();
        writer.println("}");
        writer.println();
    }

    if (isInterface || methods.contains("hashCode")) {
        writer.println("public int hashCode() {");
        writer.indent();
        writer.println("this.mocksControl.unmockableCallTo(\"hashCode()\");");
        writer.println("return System.identityHashCode(this);"); // hashCode of java.lang.Object
        writer.outdent();
        writer.println("}");
        writer.println();
    }

    if (isInterface || methods.contains("finalize")) {
        writer.println("protected void finalize() throws Throwable {");
        writer.indent();
        writer.println("this.mocksControl.unmockableCallTo(\"finalize()\");");
        writer.println("super.finalize();");
        writer.outdent();
        writer.println("}");
        writer.println();
    }
}

From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java

License:Apache License

/**
 * Prints required fields for mock class.
 *//*ww w .j av a2  s .c o m*/
private void printFields(SourceWriter sourceWriter, List<JMethod> methodsToMock) {

    StringBuilder throwableArray = new StringBuilder("private static final Class<?>[][] throwables = {");
    StringBuilder argumentTypesArray = new StringBuilder("private static final Class<?>[][] argumentTypes = {");
    StringBuilder methodArray = new StringBuilder("private static final Method[] methods = {");

    for (int i = 0; i < methodsToMock.size(); i++) {
        JMethod method = methodsToMock.get(i);

        throwableArray.append("{");
        for (JClassType throwable : method.getThrows()) {
            throwableArray.append(throwable.getQualifiedSourceName()).append(".class, ");
        }
        if (method.getThrows().length != 0) {
            throwableArray.setLength(throwableArray.length() - 2);
        }
        throwableArray.append("}, ");

        argumentTypesArray.append("{");
        for (JType argumentType : method.getParameterTypes()) {
            argumentTypesArray.append(argumentType.getErasedType().getQualifiedSourceName()).append(".class, ");
        }
        if (method.getParameterTypes().length != 0) {
            argumentTypesArray.setLength(argumentTypesArray.length() - 2);
        }
        argumentTypesArray.append("}, ");

        methodArray.append("new Method(\"").append(method.getName()).append("\", ")
                .append(method.getReturnType().getErasedType().getQualifiedSourceName())
                .append(".class, argumentTypes[").append(i).append("], ").append("throwables[").append(i)
                .append("]), ");
    }

    if (methodsToMock.size() != 0) {
        throwableArray.setLength(throwableArray.length() - 2);
        argumentTypesArray.setLength(argumentTypesArray.length() - 2);
        methodArray.setLength(methodArray.length() - 2);
    }
    throwableArray.append("};");
    argumentTypesArray.append("};");
    methodArray.append("};");

    sourceWriter.println(throwableArray.toString());
    sourceWriter.println(argumentTypesArray.toString());
    sourceWriter.println(methodArray.toString());
    sourceWriter.println("private MocksControlBase mocksControl;");
    sourceWriter.println();
}

From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java

License:Apache License

/**
 * Prints each constructor for the mock class, and a hidden init method.
 *//*from ww w. j  ava2  s  . c  o m*/
private void printConstructors(SourceWriter out, String newClassName, JConstructor[] constructors) {

    if (constructors.length == 0) {
        // probably an interface
        out.print("public  %s() {}", newClassName);
    }

    for (JConstructor constructor : constructors) {
        out.print("public  %s(", newClassName);
        printMatchingParameters(out, constructor);
        out.println(") {");

        out.indent();
        printMatchingSuperCall(out, constructor);
        out.outdent();

        out.println("}");
        out.println();
    }

    out.println("public %s __mockInit(MocksControlBase newValue) {", newClassName);
    out.indent();
    out.println("this.mocksControl = newValue;");
    out.println("return this;");
    out.outdent();
    out.println("}");
    out.println();
}

From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java

License:Apache License

private void printMatchingSuperCall(SourceWriter out, JConstructor constructorToCall) {
    if (constructorToCall.getParameters().length == 0) {
        return; // will be added automatically
    }// w  w  w.  ja  v a  2 s.  c  om

    out.print("super(");

    JParameter[] params = constructorToCall.getParameters();
    for (int i = 0; i < params.length; i++) {
        if (i > 0) {
            out.print(", ");
        }
        out.print(params[i].getName());
    }
    out.println(");");
}

From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java

License:Apache License

private void printMockMethodBody(SourceWriter sourceWriter, JMethod method, int methodNo, String newClassName) {

    JParameter[] args = method.getParameters();

    String callVar = freeVariableName("call", args);
    sourceWriter.print("Call %s = new Call(this, %s.methods[%d]", callVar, newClassName, methodNo);

    int argsCount = method.isVarArgs() ? args.length - 1 : args.length;

    for (int i = 0; i < argsCount; i++) {
        sourceWriter.print(", %s", args[i].getName());
    }/*from   ww w .j  av a2  s .  co  m*/
    sourceWriter.println(");");

    if (method.isVarArgs()) {
        sourceWriter.println("%s.addVarArgument(%s);", callVar, args[args.length - 1].getName());
    }

    sourceWriter.println("try {");
    sourceWriter.indent();

    if (!isVoid(method)) {
        sourceWriter.print("return (");

        JType returnType = method.getReturnType();
        JPrimitiveType primitiveType = returnType.isPrimitive();
        if (primitiveType != null) {
            sourceWriter.print(primitiveType.getQualifiedBoxedSourceName());
        } else if (returnType.isTypeParameter() != null) {
            sourceWriter.print(returnType.isTypeParameter().getName());
        } else {
            sourceWriter.print(returnType.getQualifiedSourceName());
        }

        sourceWriter.print(") ");
    }

    sourceWriter.println("this.mocksControl.invoke(%s).answer(%s.getArguments().toArray());", callVar, callVar);
    sourceWriter.outdent();

    String exceptionVar = freeVariableName("exception", args);
    sourceWriter.println("} catch (Throwable %s) {", exceptionVar);
    sourceWriter.indent();

    String assertionError = AssertionErrorWrapper.class.getCanonicalName();
    sourceWriter.println(
            "if (%s instanceof %s) throw (AssertionError) "
                    + "((%s) %s).getAssertionError().fillInStackTrace();",
            exceptionVar, assertionError, assertionError, exceptionVar);

    for (JClassType exception : method.getThrows()) {
        printRethrowException(sourceWriter, exceptionVar, exception.getQualifiedSourceName());
    }
    printRethrowException(sourceWriter, exceptionVar, "RuntimeException");
    printRethrowException(sourceWriter, exceptionVar, "Error");
    sourceWriter.println("throw new UndeclaredThrowableException(%s);", exceptionVar);
    sourceWriter.outdent();
    sourceWriter.println("}");
}

From source file:com.google.speedtracer.generators.BuildInfoGenerator.java

License:Apache License

private String emitImplClass(TreeLogger logger, GeneratorContext context, JClassType typeClass,
        JMethod revisionMethod, JMethod timeMethod) {
    final int revision = getBuildRevision();
    final String subclassName = typeClass.getSimpleSourceName() + "_r" + revision;
    final String packageName = typeClass.getPackage().getName();
    final ClassSourceFileComposerFactory f = new ClassSourceFileComposerFactory(packageName, subclassName);
    f.addImplementedInterface(typeClass.getQualifiedSourceName());
    final PrintWriter pw = context.tryCreate(logger, packageName, subclassName);
    if (pw != null) {
        final SourceWriter sw = f.createSourceWriter(context, pw);

        sw.print(revisionMethod.getReadableDeclaration(false, true, true, true, true));
        sw.println("{ return " + revision + "; }");

        sw.print(timeMethod.getReadableDeclaration(false, true, true, true, true));
        sw.println("{ return new java.util.Date(" + System.currentTimeMillis() + "L); }");
        sw.commit(logger);//from www.  j  a v a2  s .  com
    }
    return f.getCreatedClassName();
}

From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java

License:Apache License

private void writeEnumSetup(SourceWriter sw) {
    // Make the deobfuscation model
    Map<String, List<JEnumConstant>> map = new HashMap<String, List<JEnumConstant>>();
    for (Map.Entry<JEnumConstant, String> entry : model.getEnumTokenMap().entrySet()) {
        List<JEnumConstant> list = map.get(entry.getValue());
        if (list == null) {
            list = new ArrayList<JEnumConstant>();
            map.put(entry.getValue(), list);
        }/*w  ww.  ja v a 2 s  .  c om*/
        list.add(entry.getKey());
    }

    sw.println("@Override protected void initializeEnumMap() {");
    sw.indent();
    for (Map.Entry<JEnumConstant, String> entry : model.getEnumTokenMap().entrySet()) {
        // enumToStringMap.put(Enum.FOO, "FOO");
        sw.println("enumToStringMap.put(%s.%s, \"%s\");",
                entry.getKey().getEnclosingType().getQualifiedSourceName(), entry.getKey().getName(),
                entry.getValue());
    }
    for (Map.Entry<String, List<JEnumConstant>> entry : map.entrySet()) {
        String listExpr;
        if (entry.getValue().size() == 1) {
            JEnumConstant e = entry.getValue().get(0);
            // Collections.singletonList(Enum.FOO)
            listExpr = String.format("%s.<%s<?>> singletonList(%s.%s)", Collections.class.getCanonicalName(),
                    Enum.class.getCanonicalName(), e.getEnclosingType().getQualifiedSourceName(), e.getName());
        } else {
            // Arrays.asList(Enum.FOO, OtherEnum.FOO, ThirdEnum,FOO)
            StringBuilder sb = new StringBuilder();
            boolean needsComma = false;
            sb.append(String.format("%s.<%s<?>> asList(", Arrays.class.getCanonicalName(),
                    Enum.class.getCanonicalName()));
            for (JEnumConstant e : entry.getValue()) {
                if (needsComma) {
                    sb.append(",");
                }
                needsComma = true;
                sb.append(e.getEnclosingType().getQualifiedSourceName()).append(".").append(e.getName());
            }
            sb.append(")");
            listExpr = sb.toString();
        }
        sw.println("stringsToEnumsMap.put(\"%s\", %s);", entry.getKey(), listExpr);
    }
    sw.outdent();
    sw.println("}");
}