Example usage for com.google.gwt.user.rebind ClassSourceFileComposerFactory addAnnotationDeclaration

List of usage examples for com.google.gwt.user.rebind ClassSourceFileComposerFactory addAnnotationDeclaration

Introduction

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

Prototype

public void addAnnotationDeclaration(String declaration) 

Source Link

Usage

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

License:Open Source License

@SuppressWarnings("rawtypes")
@Override/*from   w  w w .  ja va2  s  .c o  m*/
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   ww w  .  ja va2 s .c  om*/

    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;
    }/*www .j  a va  2s. co 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;/*from w w w  . j  a  va  2s .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.guit.rebind.gin.GinInjectorGenerator.java

License:Apache License

@Override
public RebindResult generateIncrementally(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    saveVariables(logger, context, typeName);
    if (typeOracle.findType(GinOracle.packageName, GinOracle.className) != null) {
        return new RebindResult(RebindMode.USE_EXISTING, GinOracle.packageName + "." + GinOracle.className);
    }// w  w w. j a  v  a2s .  co m

    // Clear
    injectedClasses.clear();
    providedClasses.clear();
    asyncProvidedClasses.clear();
    gmodules.clear();

    // Call gin contributors
    List<String> contributors = getConfigurationProperty("app.gin.contributor").getValues();
    for (String c : contributors) {
        GinContributor contributor = instantiateContributor(c);
        contributor.collaborate(this, logger, context);
    }

    // Generate the modules string
    StringBuilder sb = new StringBuilder();
    sb.append("({");
    for (Class<?> m : gmodules) {
        if (sb.length() > 2) {
            sb.append(", ");
        }
        sb.append(m.getCanonicalName() + ".class");
    }
    sb.append("})");

    GinOracle.setModules(gmodules);

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(GinOracle.packageName,
            GinOracle.className);
    composer.makeInterface();
    composer.addImplementedInterface(Ginjector.class.getCanonicalName());
    composer.addAnnotationDeclaration("@" + GinModules.class.getCanonicalName() + sb.toString());
    PrintWriter printWriter = context.tryCreate(logger, GinOracle.packageName, GinOracle.className);

    // Convert to linked to remove possible duplicated entries
    injectedClasses = findClassOrLinkedInjectionKey(injectedClasses);
    providedClasses = findClassOrLinkedInjectionKey(providedClasses);
    asyncProvidedClasses = findClassOrLinkedInjectionKey(asyncProvidedClasses);

    if (printWriter != null) {
        SourceWriter writer = composer.createSourceWriter(context, printWriter);

        writer.println(SINGLETON_DECLARATION);

        for (String classType : injectedClasses) {
            load(classType);
            writer.println(classType + " " + GinOracle.getGetterMethodName(classType) + "();");
        }

        for (String classType : providedClasses) {
            load(classType);
            writer.println(Provider.class.getCanonicalName() + "<" + classType + "> "
                    + GinOracle.getProviderGetterMethodName(classType) + "();");
        }

        for (String classType : asyncProvidedClasses) {
            load(classType);
            writer.println(AsyncProvider.class.getCanonicalName() + "<" + classType + "> "
                    + GinOracle.getAsyncProviderGetterMethodName(classType) + "();");
        }

        writer.commit(logger);
    }

    return new RebindResult(RebindMode.USE_PARTIAL_CACHED, GinOracle.packageName + "." + GinOracle.className);
}

From source file:com.gwtplatform.mvp.rebind.ProviderBundleGenerator.java

License:Apache License

private ClassSourceFileComposerFactory initComposer() throws UnableToCompleteException {
    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(getPackageName(),
            getClassName());//from w w  w.  java2  s.c  om
    composer.setSuperclass(ProviderBundle.class.getSimpleName());
    composer.addImport(ProviderBundle.class.getCanonicalName());
    composer.addImport(Provider.class.getCanonicalName());
    composer.addImport(Singleton.class.getCanonicalName());
    composer.addImport(Inject.class.getCanonicalName());

    composer.addAnnotationDeclaration("@" + Singleton.class.getSimpleName());

    return composer;
}

From source file:com.kk_electronic.gwt.rebind.JsonEncoderGenerator.java

License:Open Source License

/**
 * @param context//from  w w w .j  ava  2 s  .  c  o m
 */
private void generateHelperClass(GeneratorContext context) throws UnableToCompleteException, NotFoundException {
    PrintWriter printWriter = context.tryCreate(logger, packageName, className);

    if (printWriter == null) {
        return;
    }

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);

    composer.addImplementedInterface(JsonEncoderHelper.class.getCanonicalName());

    composer.addImport(Singleton.class.getCanonicalName());
    composer.addImport(Map.class.getCanonicalName());
    composer.addImport(HashMap.class.getCanonicalName());
    composer.addImport(JsonEncoderHelper.class.getCanonicalName());
    composer.addImport(JsonValue.class.getCanonicalName());
    composer.addAnnotationDeclaration("@Singleton");

    SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);

    writeHelperClass(sourceWriter);

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

    context.commit(logger, printWriter);
}

From source file:net.sf.mmm.util.nls.impl.rebind.NlsBundleGeneratorGwtI18n.java

License:Apache License

/**
 * This method generates the GWT-i18n-interface for the NLS-bundle.
 *
 * @param bundleClass is the {@link JClassType class} of the {@link net.sf.mmm.util.nls.api.NlsBundle} to
 *        generate./*from w w  w .j  a v a2s . c o  m*/
 * @param logger is the {@link TreeLogger}.
 * @param context is the {@link GeneratorContext}.
 * @return the name of the generated class.
 */
@SuppressWarnings({ "rawtypes" })
private String generateBundleInterface(JClassType bundleClass, TreeLogger logger, GeneratorContext context) {

    Class bundleJavaClass;
    String bundleName = bundleClass.getQualifiedSourceName();
    try {
        bundleJavaClass = Class.forName(bundleName);
    } catch (ClassNotFoundException e) {
        throw new TypeNotFoundException(bundleName);
    }
    @SuppressWarnings("unchecked")
    ClassName bundleClassName = NlsBundleHelper.getInstance().getQualifiedLocation(bundleJavaClass);
    String packageName = bundleClassName.getPackageName();
    String simpleName = bundleClassName.getSimpleName();
    if (bundleClassName.getName().equals(bundleName)) {
        logger.log(TreeLogger.ERROR, getClass().getSimpleName() + ": Illegal NlsBundle '" + bundleName
                + "' - has to end with suffix 'Root'. Localization will not work!");
        simpleName = simpleName + "_Interface";
    }
    logger.log(TreeLogger.INFO, getClass().getSimpleName() + ": Generating " + simpleName);
    ClassSourceFileComposerFactory sourceComposerFactory = new ClassSourceFileComposerFactory(packageName,
            simpleName);
    sourceComposerFactory.makeInterface();
    // import statements
    sourceComposerFactory.addImport(Constants.class.getName());
    sourceComposerFactory.addImport(Generate.class.getCanonicalName());

    sourceComposerFactory.addImplementedInterface(Constants.class.getSimpleName());

    // @Generate annotation
    StringBuilder annotationBuffer = new StringBuilder();
    annotationBuffer.append("@");
    annotationBuffer.append(Generate.class.getSimpleName());
    annotationBuffer.append("(format = \"");
    annotationBuffer.append(PropertiesFormat.class.getName());
    annotationBuffer.append("\")");

    sourceComposerFactory.addAnnotationDeclaration(annotationBuffer.toString());

    PrintWriter writer = context.tryCreate(logger, packageName, simpleName);
    if (writer != null) {
        SourceWriter sourceWriter = sourceComposerFactory.createSourceWriter(context, writer);

        // generate methods for fields of bundle
        for (JMethod method : bundleClass.getOverridableMethods()) {
            JType returnType = method.getReturnType();
            if (!isLookupMethod(method)) {
                if (!NlsMessage.class.getName().equals(returnType.getQualifiedSourceName())) {
                    throw new IllegalCaseException(returnType.getQualifiedSourceName());
                }
                NlsBundleMessage messageAnnotation = method.getAnnotation(NlsBundleMessage.class);
                if (messageAnnotation != null) {
                    String message = messageAnnotation.value();
                    // generate message annotation
                    sourceWriter.print("@DefaultStringValue(\"");
                    sourceWriter.print(escape(message));
                    sourceWriter.println("\")");
                }

                NlsBundleKey keyAnnotation = method.getAnnotation(NlsBundleKey.class);
                if (keyAnnotation != null) {
                    // generate key annotation
                    sourceWriter.print("@Key(\"");
                    sourceWriter.print(escape(keyAnnotation.value()));
                    sourceWriter.println("\")");
                }
                // generate method
                sourceWriter.print("String ");
                sourceWriter.print(method.getName());
                sourceWriter.println("();");

                sourceWriter.println();
            }

        }
        sourceWriter.commit(logger);
    }
    return sourceComposerFactory.getCreatedClassName();
}

From source file:org.fusesource.restygwt.rebind.DirectRestBaseSourceCreator.java

License:Apache License

protected ClassSourceFileComposerFactory createClassSourceComposerFactory(JavaSourceCategory createWhat,
        String[] annotationDeclarations, String[] extendedInterfaces) {
    String genericTypeParameters = createClassDeclarationGenericType();

    ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName,
            shortName + genericTypeParameters);

    if (createWhat == JavaSourceCategory.INTERFACE) {
        composerFactory.makeInterface();
    }/*  w w w  .  j  a v  a2 s  .co m*/

    if (annotationDeclarations != null) {
        for (String annotationDeclaration : annotationDeclarations) {
            composerFactory.addAnnotationDeclaration(annotationDeclaration);
        }
    }

    if (extendedInterfaces != null) {
        for (String anInterface : extendedInterfaces) {
            composerFactory.addImplementedInterface(anInterface);
        }
    }

    return composerFactory;
}