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.eleven.rebind.SkinBundleGenerator.java

License:Apache License

private void generateImageMethod(final SkinBundleBuilder compositeImage, final SourceWriter sw,
        final JMethod method, final String imgResName) {

    String decl = method.getReadableDeclaration(false, true, true, true, true);

    {//from   w w w  .j  a  v  a  2  s  .c  o m
        sw.indent();

        // Create a singleton that this method can return. There is no need
        // to
        // create a new instance every time this method is called, since
        // ClippedImagePrototype is immutable

        SkinBundleBuilder.ImageRect imageRect = compositeImage.getMapping(imgResName);
        String singletonName = method.getName() + "_SINGLETON";

        sw.print("private static final ClippedImagePrototype ");
        sw.print(singletonName);
        sw.print(" = new ClippedImagePrototype(IMAGE_BUNDLE_URL, ");
        sw.print(Integer.toString(imageRect.getLeft()));
        sw.print(", ");
        sw.print(Integer.toString(imageRect.getTop()));
        sw.print(", ");
        sw.print(Integer.toString(imageRect.getWidth()));
        sw.print(", ");
        sw.print(Integer.toString(imageRect.getHeight()));
        sw.println(");");

        sw.print(decl);
        sw.println(" {");
        sw.indent();
        sw.print("return ");
        sw.print(singletonName);
        sw.println(";");
        sw.outdent();

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

From source file:com.eleven.rebind.SkinBundleGenerator.java

License:Apache License

private void generateImageDef(final SkinBundleBuilder compositeImage, final SourceWriter sw,
        final List<String> imgResNames) {
    sw.indent();/*from   www .  j  av a2s  .co  m*/

    sw.println("private static final HashMap<String, ClippedImagePrototype> imageMap"
            + "= new HashMap<String, ClippedImagePrototype>() {");

    sw.indent();
    sw.println("{");

    sw.indent();

    for (String imgResName : imgResNames) {
        SkinBundleBuilder.ImageRect imageRect = compositeImage.getMapping(imgResName);

        sw.print("put (\"" + imgResName.replace(File.separatorChar, '/') + "\", ");
        sw.print("new ClippedImagePrototype(IMAGE_BUNDLE_URL, ");
        sw.print(Integer.toString(imageRect.getLeft()));
        sw.print(", ");
        sw.print(Integer.toString(imageRect.getTop()));
        sw.print(", ");
        sw.print(Integer.toString(imageRect.getWidth()));
        sw.print(", ");
        sw.print(Integer.toString(imageRect.getHeight()));
        sw.println("));");
    }

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

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

    sw.println("@Override");
    sw.println("public void prefetchAll() {");
    sw.indent();
    for (String imgResName : imgResNames)
        sw.println("Image.prefetch(\"" + imgResName.replace(File.separatorChar, '/') + "\");");

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

    sw.println("@Override");
    sw.println("public void prefetchBundle() {");
    sw.indent();
    sw.println("Image.prefetch(IMAGE_BUNDLE_URL);");
    sw.println("}");
    sw.outdent();
}

From source file:com.eleven.rebind.SkinBundleGenerator.java

License:Apache License

/**
 * Generates the image bundle implementation class, checking each method for
 * validity as it is encountered./*from  ww  w. jav  a2 s . com*/
 */
private String generateImplClass(final TreeLogger logger, final GeneratorContext context,
        final JClassType userType, final JMethod[] imageMethods) throws UnableToCompleteException {
    // Lookup the type info for AbstractImagePrototype so that we can check
    // for
    // the proper return type
    // on image bundle methods.
    final JClassType abstractImagePrototype;
    try {
        abstractImagePrototype = userType.getOracle().getType(ABSTRACTIMAGEPROTOTYPE_QNAME);
    } catch (NotFoundException e) {
        logger.log(TreeLogger.ERROR, "GWT " + ABSTRACTIMAGEPROTOTYPE_QNAME + " class is not available", e);
        throw new UnableToCompleteException();
    }

    // Compute the package and class names of the generated class.
    String pkgName = userType.getPackage().getName();
    String subName = computeSubclassName(userType);

    // 11pc
    String pkgPrefix = pkgName.replace('.', '/');

    if (pkgPrefix.length() > 0)
        pkgPrefix += "/";

    // Begin writing the generated source.
    ClassSourceFileComposerFactory f = new ClassSourceFileComposerFactory(pkgName, subName);
    f.addImport(ABSTRACTIMAGEPROTOTYPE_QNAME);
    f.addImport(CLIPPEDIMAGEPROTOTYPE_QNAME);
    f.addImport(GWT_QNAME);
    f.addImport(HASHMAP_QNAME);
    f.addImport(IMAGE_QNAME);
    f.addImplementedInterface(userType.getQualifiedSourceName());

    PrintWriter pw = context.tryCreate(logger, pkgName, subName);

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

        // Build a compound image from each individual image.
        SkinBundleBuilder bulder = new SkinBundleBuilder();

        // Store the computed image names so that we don't have to lookup
        // them up again.

        // 11pc
        List<String> imageResNames = getSkinImages(logger);

        for (String imageName : imageResNames)
            bulder.assimilate(logger, imageName);

        /*
        for (JMethod method : imageMethods) {
                    String branchMsg = "Analyzing method '" + method.getName()
                          + "' in type " + userType.getQualifiedSourceName();
                    TreeLogger branch = logger.branch(TreeLogger.DEBUG, branchMsg,
                          null);
                
                    // Verify that this method is valid on an image bundle.
                    if (method.getReturnType() != abstractImagePrototype) {
                       branch.log(TreeLogger.ERROR, "Return type must be "
                             + ABSTRACTIMAGEPROTOTYPE_QNAME, null);
                       throw new UnableToCompleteException();
                    }
                
                    if (method.getParameters().length > 0) {
                       branch.log(TreeLogger.ERROR,
                             "Method must have zero parameters", null);
                       throw new UnableToCompleteException();
                    }
                
                    // Find the associated imaged resource.
                    String imageResName = getImageResourceName(branch,
                          new JMethodOracleImpl(method));
                    assert (imageResName != null);
                    imageResNames.add(imageResName);
                    bulder.assimilate(logger, imageResName);
        }
        */
        // Write the compound image into the output directory.
        //         String bundledImageUrl = bulder.writeBundledImage(logger, context);
        String bundledImageUrl = "yeayeaa";

        // Emit a constant for the composite URL. Note that we prepend the
        // module's base URL so that the module can reference its own
        // resources
        // independently of the host HTML page.
        sw.print("private static final String IMAGE_BUNDLE_URL = GWT.getModuleBaseURL() + \"");
        sw.print(escape(bundledImageUrl));
        sw.println("\";");
        /*
                 // Generate an implementation of each method.
                 int imageResNameIndex = 0;
                 for (JMethod method : imageMethods) {
                    generateImageMethod(bulder, sw, method, imageResNames
          .get(imageResNameIndex++));
                 }
        */

        generateImageDef(bulder, sw, imageResNames);

        sw.println("@Override");
        sw.println("public AbstractImagePrototype get(String image) {");
        sw.indent();
        sw.println("return imageMap.get(image);");
        sw.outdent();
        sw.print("}");

        sw.println("@Override");
        sw.println("public HashMap<String, HashMap<String, String>>   getProperties() {");
        sw.indent();
        sw.println("return null;");
        sw.outdent();
        sw.print("}");

        // Finish.
        sw.commit(logger);
    }

    return f.getCreatedClassName();
}

From source file:com.emitrom.pilot.core.shared.rebind.BeanModelGenerator.java

License:Apache License

protected void createGetMethods(List<JMethod> getters, SourceWriter sw, String typeName) {
    sw.println("public <X> X getPropertyAsString(String s) {");

    sw.println("if (allowNestedValues && NestedModelUtil.isNestedProperty(s)) {");
    sw.indentln("return (X)NestedModelUtil.getNestedValue(this, s);");
    sw.println("}");

    for (JMethod method : getters) {
        JClassType returnType = method.getReturnType().isClassOrInterface();
        String s = method.getName();
        String p = lowerFirst(s.substring(s.startsWith("g") ? 3 : 2)); // get
                                                                       // or

        sw.println("if (s.equals(\"" + p + "\")) {");
        sw.println("Object value = ((" + typeName + ")bean)." + s + "();");

        try {/*  w  w  w  .  j a  v  a 2 s .com*/
            if (returnType != null && returnType.isAssignableTo(oracle.getType(List.class.getName()))
                    && returnType.isParameterized() != null) {
                JParameterizedType type = returnType.isParameterized();
                JClassType[] params = type.getTypeArgs();
                if (beans.contains(params[0])) {
                    sw.println("if (value != null) {");
                    sw.indent();
                    sw.println("java.util.List list = (java.util.List)value;");
                    sw.println("java.util.List list2 = " + BeanLookup.class.getCanonicalName()
                            + ".get().getFactory(" + params[0].getQualifiedSourceName()
                            + ".class).createModel((java.util.Collection) list);");
                    sw.outdent();
                    sw.println("return (X) list2;");
                    sw.println("}");
                }
            } else {
                // swap returnType as generic types were not matching
                // (beans.contains(returnType))
                if (returnType != null) {
                    String t = returnType.getQualifiedSourceName();
                    if (t.indexOf("extends") == -1) {
                        returnType = oracle.getType(t);
                    }
                }
                if (beans.contains(returnType)) {
                    sw.println("if (value != null) {");
                    sw.println("    Bean nestedModel = nestedModels.get(s);");
                    sw.println("    if (nestedModel != null) {");
                    sw.println("      Object bean = nestedModel.getBean();");
                    sw.println("      if (!bean.equals(value)){");
                    sw.println("        nestedModel = null;");
                    sw.println("      }");
                    sw.println("    }");
                    sw.println("    if (nestedModel == null) {");
                    sw.println("        nestedModel = " + BeanLookup.class.getCanonicalName()
                            + ".get().getFactory(" + returnType.getQualifiedSourceName()
                            + ".class).createModel(value);");
                    sw.println("        nestedModels.put(s, nestedModel);");
                    sw.println("    }");
                    sw.println("    return (X)processValue(nestedModel);");
                    sw.println("}");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        sw.println("return (X)processValue(value);");
        sw.println("}");
    }
    sw.println("return super.getFromCache(s);");
    sw.println("}");
}

From source file:com.emitrom.touch4j.rebind.BeanModelGenerator.java

License:Open Source License

protected void createGetMethods(List<JMethod> getters, SourceWriter sw, String typeName) {
    sw.println("public <X> X getPropertyAsString(String s) {");

    sw.println("if (allowNestedValues && NestedModelUtil.isNestedProperty(s)) {");
    sw.indentln("return (X)NestedModelUtil.getNestedValue(this, s);");
    sw.println("}");

    for (JMethod method : getters) {
        JClassType returnType = method.getReturnType().isClassOrInterface();
        String s = method.getName();
        String p = lowerFirst(s.substring(s.startsWith("g") ? 3 : 2)); // get
        // or/*from w w w. j a v  a2 s .  c o  m*/

        sw.println("if (s.equals(\"" + p + "\")) {");
        sw.println("Object value = ((" + typeName + ")bean)." + s + "();");

        try {
            if (returnType != null && returnType.isAssignableTo(oracle.getType(List.class.getName()))
                    && returnType.isParameterized() != null) {
                JParameterizedType type = returnType.isParameterized();
                JClassType[] params = type.getTypeArgs();
                if (beans.contains(params[0])) {
                    sw.println("if (value != null) {");
                    sw.indent();
                    sw.println("java.util.List list = (java.util.List)value;");
                    sw.println("java.util.List list2 = " + BeanModelLookup.class.getCanonicalName()
                            + ".get().getFactory(" + params[0].getQualifiedSourceName()
                            + ".class).createModel((java.util.Collection) list);");
                    sw.outdent();
                    sw.println("return (X) list2;");
                    sw.println("}");
                }
            } else {
                // swap returnType as generic types were not matching
                // (beans.contains(returnType))
                if (returnType != null) {
                    String t = returnType.getQualifiedSourceName();
                    if (t.indexOf("extends") == -1) {
                        returnType = oracle.getType(t);
                    }
                }
                if (beans.contains(returnType)) {
                    sw.println("if (value != null) {");
                    sw.println("    BeanModel nestedModel = nestedModels.get(s);");
                    sw.println("    if (nestedModel != null) {");
                    sw.println("      Object bean = nestedModel.getBean();");
                    sw.println("      if (!bean.equals(value)){");
                    sw.println("        nestedModel = null;");
                    sw.println("      }");
                    sw.println("    }");
                    sw.println("    if (nestedModel == null) {");
                    sw.println("        nestedModel = " + BeanModelLookup.class.getCanonicalName()
                            + ".get().getFactory(" + returnType.getQualifiedSourceName()
                            + ".class).createModel(value);");
                    sw.println("        nestedModels.put(s, nestedModel);");
                    sw.println("    }");
                    sw.println("    return (X)processValue(nestedModel);");
                    sw.println("}");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        sw.println("return (X)processValue(value);");
        sw.println("}");
    }
    sw.println("return super.getFromCache(s);");
    sw.println("}");
}

From source file:com.extjs.gxt.ui.rebind.core.BeanModelGenerator.java

License:sencha.com license

protected void createGetMethods(List<JMethod> getters, SourceWriter sw, String typeName) {
    sw.println("public <X> X get(String s) {");

    sw.println("if (allowNestedValues && NestedModelUtil.isNestedProperty(s)) {");
    sw.indentln("return (X)NestedModelUtil.getNestedValue(this, s);");
    sw.println("}");

    for (JMethod method : getters) {
        JClassType returnType = method.getReturnType().isClassOrInterface();
        String s = method.getName();
        String p = lowerFirst(s.substring(s.startsWith("g") ? 3 : 2)); // get or

        sw.println("if (s.equals(\"" + p + "\")) {");
        sw.println("Object value = ((" + typeName + ")bean)." + s + "();");

        try {/*ww w.j av a  2s .c om*/
            if (returnType != null && returnType.isAssignableTo(oracle.getType(List.class.getName()))
                    && returnType.isParameterized() != null) {
                JParameterizedType type = returnType.isParameterized();
                JClassType[] params = type.getTypeArgs();
                if (beans.contains(params[0])) {
                    sw.println("if (value != null) {");
                    sw.indent();
                    sw.println("java.util.List list = (java.util.List)value;");
                    sw.println("java.util.List list2 = " + BeanModelLookup.class.getCanonicalName()
                            + ".get().getFactory(" + params[0].getQualifiedSourceName()
                            + ".class).createModel((java.util.Collection) list);");
                    sw.outdent();
                    sw.println("return (X) list2;");
                    sw.println("}");
                }
            } else {
                // swap returnType as generic types were not matching
                // (beans.contains(returnType))
                if (returnType != null) {
                    String t = returnType.getQualifiedSourceName();
                    if (t.indexOf("extends") == -1) {
                        returnType = oracle.getType(t);
                    }
                }
                if (beans.contains(returnType)) {
                    sw.println("if (value != null) {");
                    sw.println("    BeanModel nestedModel = nestedModels.get(s);");
                    sw.println("    if (nestedModel != null) {");
                    sw.println("      Object bean = nestedModel.getBean();");
                    sw.println("      if (!bean.equals(value)){");
                    sw.println("        nestedModel = null;");
                    sw.println("      }");
                    sw.println("    }");
                    sw.println("    if (nestedModel == null) {");
                    sw.println("        nestedModel = " + BeanModelLookup.class.getCanonicalName()
                            + ".get().getFactory(" + returnType.getQualifiedSourceName()
                            + ".class).createModel(value);");
                    sw.println("        nestedModels.put(s, nestedModel);");
                    sw.println("    }");
                    sw.println("    return (X)processValue(nestedModel);");
                    sw.println("}");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        sw.println("return (X)processValue(value);");
        sw.println("}");
    }
    sw.println("return super.get(s);");
    sw.println("}");
}

From source file:com.extjs.gxt.ui.rebind.core.BeanModelGenerator.java

License:sencha.com license

protected void createSetMethods(List<JMethod> properties, SourceWriter sw, String typeName) {
    sw.println("public <X> X set(String s, X val) {");
    sw.indent();/*  ww  w.  j  av  a2 s . c  om*/
    sw.println("Object obj = val;");

    sw.println("if (obj instanceof BeanModel) {");
    sw.println("obj = ((BeanModel) 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 BeanModel) {");
    sw.println("list.add(((BeanModel) 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 BeanModel) {");
    sw.indent();
    sw.println("obj = ((BeanModel)val).getBean();");
    sw.println("if (nestedModels.containsKey(s)) {");
    sw.indent();
    sw.println("nestedModels.put(s, (BeanModel)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.github.gilbertotorrezan.gwtviews.rebind.NavigationManagerGenerator.java

License:Open Source License

@SuppressWarnings("rawtypes")
@Override/*ww  w.  j  av a  2s. c om*/
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {

    final TypeOracle typeOracle = context.getTypeOracle();
    JClassType mainType = typeOracle.findType(typeName);

    PrintWriter writer = context.tryCreate(logger, mainType.getPackage().getName(),
            mainType.getName() + "Impl");
    if (writer == null) {
        return mainType.getQualifiedSourceName() + "Impl";
    }

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(mainType.getPackage().getName(),
            mainType.getName() + "Impl");
    factory.addImplementedInterface(typeName);

    factory.addImport(Presenter.class.getPackage().getName() + ".*");
    factory.addImport("com.google.gwt.user.client.History");
    factory.addImport("com.google.gwt.user.client.ui.Widget");
    factory.addImport("com.google.gwt.user.client.ui.Panel");
    factory.addImport("com.google.gwt.http.client.URL");
    factory.addImport("com.google.gwt.user.client.rpc.AsyncCallback");
    factory.addImport("com.google.gwt.core.client.*");
    factory.addImport("com.google.gwt.event.logical.shared.*");
    factory.addImport("com.github.gilbertotorrezan.gwtviews.client.analytics.*");
    factory.addImport("javax.annotation.Generated");
    factory.addImport("java.util.*");

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

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

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

    sourceWriter.println("private Panel rootContainer;");
    sourceWriter.println("private UserPresenceManager userPresenceManager;");
    sourceWriter.println("private URLTokenFactory tokenFactory = new URLTokenFactory();");
    sourceWriter.println("private final Map<String, Presenter<?>> presentersMap = new HashMap<>();");
    sourceWriter.println("private URLToken currentToken = tokenFactory.createToken(\"\");");
    sourceWriter.println("private URLInterceptor currentInterceptor;\n");

    List<ViewPage> viewPages = new ArrayList<>();
    Map<String, HasViewPages> viewContainers = new HashMap<>();

    Set<ViewPage> viewsInNeedOfPresenters = new LinkedHashSet<>();
    Set<HasViewPages> containersInNeedOfPresenters = new LinkedHashSet<>();

    ViewPage defaultViewPage = null;
    ViewPage notFoundViewPage = null;
    HasViewPages defaultViewContainerPage = null;

    JClassType containerType = typeOracle.findType(HasViews.class.getName());

    JClassType[] types = typeOracle.getTypes();
    for (JClassType type : types) {
        if (type.isAnnotationPresent(View.class)) {
            View view = type.getAnnotation(View.class);
            if (shouldForceEmptyConstructor(view) && !type.isDefaultInstantiable()) {
                logger.log(Type.WARN, type.getName() + " must have an empty constructor to be a valid "
                        + View.class.getSimpleName() + ".");
                continue;
            }
            ViewPage page = new ViewPage(view, type);
            viewPages.add(page);
            if (view.defaultView()) {
                defaultViewPage = page;
            }
            if (view.notFoundView()) {
                notFoundViewPage = page;
            }
        } else if (type.isAnnotationPresent(ViewContainer.class)) {
            if (!type.isAssignableTo(containerType)) {
                logger.log(Type.WARN, type.getName() + " must implement " + containerType.getName()
                        + " to be a valid " + ViewContainer.class.getSimpleName() + ".");
                continue;
            }
            ViewContainer container = type.getAnnotation(ViewContainer.class);
            if (shouldForceEmptyConstructor(container) && !type.isDefaultInstantiable()) {
                logger.log(Type.WARN, type.getName() + " must have an empty constructor to be a valid "
                        + ViewContainer.class.getSimpleName() + ".");
                continue;
            }
            HasViewPages hasViews = new HasViewPages(container, type);
            viewContainers.put(type.getQualifiedSourceName(), hasViews);
            if (container.defaultContainer()) {
                defaultViewContainerPage = hasViews;
            }
        }
    }

    if (defaultViewPage == null) {
        logger.log(Type.ERROR, "No default view page defined!");
        throw new UnableToCompleteException();
    }

    if (defaultViewContainerPage == null && viewContainers.size() > 1) {
        logger.log(Type.ERROR, "There are more than one " + ViewContainer.class.getSimpleName()
                + " but no one is the default!");
        throw new UnableToCompleteException();
    }

    if (defaultViewContainerPage == null && !viewContainers.isEmpty()) {
        defaultViewContainerPage = viewContainers.values().iterator().next();
    }

    sourceWriter.println("public void onValueChange(ValueChangeEvent<String> event){");
    sourceWriter.indent();
    sourceWriter.println("final URLToken token = tokenFactory.createToken(event.getValue());");

    sourceWriter.println("if (currentInterceptor != null){");
    sourceWriter.indent();

    sourceWriter.println("History.newItem(currentToken.toString(), false);");
    sourceWriter.println("currentInterceptor.onUrlChanged(currentToken, token, new URLInterceptorCallback(){");
    sourceWriter.indent();
    sourceWriter.println("@Override\npublic void proceedTo(URLToken destination){");
    sourceWriter.indent();
    sourceWriter.println("History.newItem(destination.toString(), false);");
    sourceWriter.println("proceedToImpl(destination);");
    sourceWriter.outdent();
    sourceWriter.println("}");

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

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

    sourceWriter.println("this.proceedToImpl(token);");

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

    sourceWriter.println("private void proceedToImpl(final URLToken token){");
    sourceWriter.indent();

    sourceWriter.println("this.currentToken = token;");

    sourceWriter.println("switch (token.getId()){");
    sourceWriter.indent();

    int defaultViewIndex = -1;
    int notFoundViewIndex = -1;

    for (int i = 0; i < viewPages.size(); i++) {
        ViewPage viewPage = viewPages.get(i);
        final View view = viewPage.getView();
        logger.log(Type.DEBUG, "Processing view " + view.value() + "...");

        if (view.defaultView()) {
            defaultViewIndex = i;
            sourceWriter.println("case \"\":");
        }
        if (view.notFoundView()) {
            notFoundViewIndex = i;
        }

        sourceWriter.println("case \"" + view.value() + "\": {");
        sourceWriter.indent();

        if (!view.publicAccess()) {
            sourceWriter.println("if (userPresenceManager != null) {");
            sourceWriter.indent();

            if (view.rolesAllowed() != null && view.rolesAllowed().length > 0) {
                String[] roles = view.rolesAllowed();
                StringBuilder params = new StringBuilder("new String[]{ ");
                String sep = "";
                for (String role : roles) {
                    params.append(sep).append("\"").append(role).append("\"");
                    sep = ", ";
                }
                params.append(" }");
                sourceWriter.println("userPresenceManager.isUserInAnyRole(token, " + params.toString()
                        + ", new AsyncCallback<Boolean>(){");
            } else {
                sourceWriter.println(
                        "userPresenceManager.isUserInAnyRole(token, new String[0], new AsyncCallback<Boolean>(){");
            }
            sourceWriter.indent();
            sourceWriter.println("@Override");
            sourceWriter.println("public void onSuccess(Boolean allowed){");
            sourceWriter.indent();
            sourceWriter.println("if (allowed == null || !allowed){");
            sourceWriter.indent();
            sourceWriter.println("URLToken nextToken = tokenFactory.createToken(\""
                    + defaultViewPage.getView().value() + "\");");
            sourceWriter.println("nextToken.setParameter(\"next\", URL.encodeQueryString(token.toString()));");
            sourceWriter.println("nextToken.go();");
            sourceWriter.outdent();
            sourceWriter.println("}");
            sourceWriter.println("else {");
            sourceWriter.indent();
            sourceWriter.println("showPresenter" + i + "(token);");
            sourceWriter.outdent();
            sourceWriter.println("}");
            sourceWriter.outdent();
            sourceWriter.println("}");
            sourceWriter.println("@Override");
            sourceWriter.println("public void onFailure(Throwable error){");
            sourceWriter.indent();
            sourceWriter.println("GWT.log(\"Error loading view: \" + error, error);");
            sourceWriter.println("URLToken nextToken = tokenFactory.createToken(\""
                    + defaultViewPage.getView().value() + "\");");
            sourceWriter.println("nextToken.setParameter(\"next\", URL.encodeQueryString(token.toString()));");
            sourceWriter.println("nextToken.go();");
            sourceWriter.outdent();
            sourceWriter.println("}");
            sourceWriter.outdent();
            sourceWriter.println("});");

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

        sourceWriter.println("showPresenter" + i + "(token);");
        sourceWriter.outdent();
        sourceWriter.println("}\nbreak;");
    }

    sourceWriter.println("default: {");
    sourceWriter.indent();

    if (notFoundViewPage != null) {
        sourceWriter.println("//NotFound View");
        sourceWriter.println("showPresenter" + notFoundViewIndex + "(tokenFactory.createToken(\""
                + notFoundViewPage.getView().value() + "\"));");
    } else {
        sourceWriter.println("//Default View");
        sourceWriter.println("History.newItem(\"" + defaultViewPage.getView().value() + "\", false);");
        sourceWriter.println("showPresenter" + defaultViewIndex + "(tokenFactory.createToken(\""
                + defaultViewPage.getView().value() + "\"));");
    }
    sourceWriter.outdent();
    sourceWriter.println("}\nbreak;");
    sourceWriter.outdent();
    sourceWriter.println("}");

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

    for (int i = 0; i < viewPages.size(); i++) {
        ViewPage viewPage = viewPages.get(i);
        final View view = viewPage.getView();

        sourceWriter.println("/** Method to show the presenter of the " + view.value() + " view. */");
        sourceWriter.println("private void showPresenter" + i + "(final URLToken token) {");
        sourceWriter.indent();

        sourceWriter.println("GWT.runAsync(new RunAsyncCallback() {");
        sourceWriter.indent();

        sourceWriter.println("public void onSuccess() {");
        sourceWriter.indent();

        sourceWriter.println("UniversalAnalyticsTracker.sendPageView(token.toString());");
        sourceWriter.println("Presenter<?> presenter = presentersMap.get(\"" + view.value() + "\");");
        sourceWriter.println("if (presenter == null) {");
        sourceWriter.indent();

        Class<? extends Presenter> customPresenter = view.customPresenter();
        if (!Presenter.class.equals(customPresenter)) {
            sourceWriter.println("presenter = GWT.create(" + customPresenter.getName() + ".class);");
        } else {
            viewsInNeedOfPresenters.add(viewPage);
            sourceWriter.println("presenter = (Presenter<?>) GWT.create(" + viewPage.getType().getName()
                    + "Presenter.class);");
        }
        sourceWriter.println("presentersMap.put(\"" + view.value() + "\", presenter);");
        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.println("Widget widget = presenter.getView(token);");

        Class<? extends URLInterceptor> urlInterceptor = view.urlInterceptor();
        if (!URLInterceptor.class.equals(urlInterceptor)) {
            String interceptorName = urlInterceptor.getName();
            if (interceptorName.equals(viewPage.getType().getQualifiedSourceName())) {
                sourceWriter.println("currentInterceptor = (URLInterceptor) widget;");
            } else if (interceptorName.equals(customPresenter.getName())) {
                sourceWriter.println("currentInterceptor = (URLInterceptor) presenter;");
            } else {
                sourceWriter
                        .println("currentInterceptor = GWT.create(" + urlInterceptor.getName() + ".class);");
            }
        } else {
            sourceWriter.println("currentInterceptor = null;");
        }

        boolean usesViewContainer = view.usesViewContainer();
        if (usesViewContainer && !viewContainers.isEmpty()) {
            Class<?> viewContainer = view.viewContainer();
            HasViewPages hasViews;
            if (HasViews.class.equals(viewContainer)) {
                hasViews = defaultViewContainerPage;
            } else {
                hasViews = viewContainers.get(viewContainer.getName());
            }

            if (hasViews == null) {
                logger.log(Type.ERROR,
                        viewContainer.getName() + " is not a valid " + ViewContainer.class.getSimpleName()
                                + " for " + View.class.getSimpleName() + " "
                                + viewPage.getType().getQualifiedSourceName() + ".");
                throw new UnableToCompleteException();
            }
            sourceWriter.println("Presenter<?> containerPresenter = presentersMap.get(\""
                    + hasViews.getType().getQualifiedSourceName() + "\");");
            sourceWriter.println("if (containerPresenter == null) {");
            sourceWriter.indent();
            if (!Presenter.class.equals(hasViews.getContainer().customPresenter())) {
                sourceWriter.println("containerPresenter = GWT.create("
                        + hasViews.getContainer().customPresenter().getName() + ".class);");
            } else {
                containersInNeedOfPresenters.add(hasViews);
                sourceWriter.println("containerPresenter = (Presenter<?>) GWT.create("
                        + hasViews.getType().getName() + "Presenter.class);");
            }
            sourceWriter.println("presentersMap.put(\"" + hasViews.getType().getQualifiedSourceName()
                    + "\", containerPresenter);");
            sourceWriter.outdent();
            sourceWriter.println("}");
            sourceWriter.println("Widget container = containerPresenter.getView(token);");
            sourceWriter.println("((" + HasViews.class.getName() + ") container).showView(token, widget);");
            sourceWriter.println("if (container.getParent() == null){");
            sourceWriter.indent();
            sourceWriter.println("rootContainer.clear();");
            sourceWriter.println("rootContainer.add(container);");
            sourceWriter.outdent();
            sourceWriter.println("}");
        } else {
            sourceWriter.println("rootContainer.clear();");
            sourceWriter.println("rootContainer.add(widget);");
        }
        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.println(
                "public void onFailure(Throwable reason) { GWT.log(\"Error on loading presenter with token: \"+token, reason); }");
        sourceWriter.outdent();
        sourceWriter.println("});");

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

    sourceWriter.println("@Override\npublic void clearCache() {");
    sourceWriter.indent();
    sourceWriter.println("presentersMap.clear();");
    sourceWriter.outdent();
    sourceWriter.println("}\n");

    sourceWriter.println("@Override\npublic void clearCache(String tokenId) {");
    sourceWriter.indent();
    sourceWriter.println("presentersMap.remove(tokenId);");
    sourceWriter.outdent();
    sourceWriter.println("}\n");

    sourceWriter.println("@Override\npublic void setRootContainer(Panel container) {");
    sourceWriter.indent();
    sourceWriter.println("this.rootContainer = container;");
    sourceWriter.outdent();
    sourceWriter.println("}\n");

    sourceWriter.println("@Override\npublic void setUserPresenceManager(UserPresenceManager umanager) {");
    sourceWriter.indent();
    sourceWriter.println("this.userPresenceManager = umanager;");
    sourceWriter.outdent();
    sourceWriter.println("}\n");

    sourceWriter.println("@Override\npublic void setURLTokenFactory(URLTokenFactory tokenFactory) {");
    sourceWriter.indent();
    sourceWriter.println("this.tokenFactory = tokenFactory;");
    sourceWriter.outdent();
    sourceWriter.println("}\n");

    sourceWriter.println("@Override\npublic URLTokenFactory getURLTokenFactory() {");
    sourceWriter.indent();
    sourceWriter.println("return this.tokenFactory;");
    sourceWriter.outdent();
    sourceWriter.println("}\n");

    sourceWriter.println("//View presenters");
    for (ViewPage viewPage : viewsInNeedOfPresenters) {
        sourceWriter.println("public static interface " + viewPage.getType().getName()
                + "Presenter extends AutoPresenter<" + viewPage.getType().getQualifiedSourceName() + ">{}");
    }
    if (!containersInNeedOfPresenters.isEmpty()) {
        sourceWriter.println("\n//ViewContainer presenters");
        for (HasViewPages container : containersInNeedOfPresenters) {
            sourceWriter.println("public static interface " + container.getType().getName()
                    + "Presenter extends AutoPresenter<" + container.getType().getQualifiedSourceName()
                    + ">{}");
        }
    }

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

    context.commit(logger, writer);

    return factory.getCreatedClassName();
}

From source file:com.github.gilbertotorrezan.gwtviews.rebind.PresenterGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {

    final TypeOracle typeOracle = context.getTypeOracle();
    JClassType mainType = typeOracle.findType(typeName);

    JParameterizedType parameterized = mainType.getImplementedInterfaces()[0].isParameterized();
    JClassType viewType = parameterized.getTypeArgs()[0];
    final String className = viewType.getQualifiedSourceName();

    String name = mainType.getName().substring(mainType.getName().lastIndexOf('.') + 1);
    name = name.substring(0, name.length() - "Presenter".length());
    name = name + "_" + name + "PresenterImpl";

    PrintWriter writer = context.tryCreate(logger, viewType.getPackage().getName(), name);
    if (writer == null) {
        return viewType.getPackage().getName() + "." + name;
    }/*from w  ww.java2s .c o  m*/

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(viewType.getPackage().getName(),
            name);
    factory.addImplementedInterface(AutoPresenter.class.getName());

    factory.addImport(Presenter.class.getPackage().getName() + ".*");
    factory.addImport("com.google.gwt.user.client.History");
    factory.addImport("com.google.gwt.core.client.GWT");
    factory.addImport("com.google.gwt.user.client.ui.Widget");
    factory.addImport("javax.annotation.Generated");
    factory.addImport("java.util.*");

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

    View view = viewType.getAnnotation(View.class);
    ViewContainer viewContainer = viewType.getAnnotation(ViewContainer.class);

    CachePolicy cache;
    JClassType injectorType = null;
    String injectorMethod = null;
    if (view == null) {
        cache = CachePolicy.ALWAYS;
    } else {
        cache = view.cache();
    }

    if (cache == CachePolicy.SAME_URL) {
        factory.setSuperclass(CachedPresenter.class.getName());
    }

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

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

    if (cache == CachePolicy.ALWAYS) {
        sourceWriter.println("private Widget view; //the cached view");
    }

    Class<?> injector = view == null ? void.class : view.injector();
    if (injector.equals(void.class)) {
        injector = viewContainer == null ? void.class : viewContainer.injector();
    }

    if (!injector.equals(void.class)) {
        try {
            injectorType = typeOracle.findType(injector.getName());
            injectorMethod = view != null ? view.injectorMethod() : viewContainer.injectorMethod();
            injectorMethod = getInjectorMethod(logger, injectorType, injectorMethod, className);
        } catch (Exception e) {
            logger.log(Type.ERROR, "Error loading the injector class \"" + injector.getName() + "\": " + e, e);
            throw new UnableToCompleteException();
        }
    }

    if (cache == CachePolicy.SAME_URL) {
        sourceWriter.println("\n@Override\npublic Widget createNewView(URLToken url) {");
    } else {
        sourceWriter.println("\n@Override\npublic Widget getView(URLToken url) {");
    }
    sourceWriter.indent();

    switch (cache) {
    case NEVER: {
        sourceWriter.println("//code for the CachePolicy.NEVER:");
        printInjectorMethod(sourceWriter, className, injectorType, injectorMethod);
    }
        break;
    case ALWAYS: {
        sourceWriter.println("//code for the CachePolicy.ALWAYS:");
        sourceWriter.println("if (this.view == null) {");
        sourceWriter.indent();
        printInjectorMethod(sourceWriter, className, injectorType, injectorMethod);
        sourceWriter.println("this.view = view;");
        sourceWriter.outdent();
        sourceWriter.println("}");
    }
        break;
    case SAME_URL: {
        sourceWriter.println("//code for the CachePolicy.SAME_URL:");
        printInjectorMethod(sourceWriter, className, injectorType, injectorMethod);
    }
        break;
    }

    sourceWriter.println("return view;");
    sourceWriter.outdent();
    sourceWriter.println("}\n");

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

    context.commit(logger, writer);

    return factory.getCreatedClassName();
}

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;
    }/*from w  w  w. ja  va 2s .  com*/

    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();

}