Example usage for com.google.gwt.core.ext.typeinfo TypeOracle getTypes

List of usage examples for com.google.gwt.core.ext.typeinfo TypeOracle getTypes

Introduction

In this page you can find the example usage for com.google.gwt.core.ext.typeinfo TypeOracle getTypes.

Prototype

public abstract JClassType[] getTypes();

Source Link

Document

Gets all types, both top-level and nested.

Usage

From source file:cc.alcina.framework.entity.gwtsynth.ClientReflectionGenerator.java

License:Apache License

private List<JClassType> getBeanInfoTypes(TreeLogger logger, TypeOracle typeOracle,
        ClassSourceFileComposerFactory crf) {
    List<JClassType> results = new ArrayList<JClassType>();
    JClassType[] types = typeOracle.getTypes();
    for (JClassType jClassType : types) {
        if (jClassType.isAnnotationPresent(cc.alcina.framework.common.client.logic.reflection.Bean.class)
                && !ignore(jClassType, ReflectionAction.BEAN_INFO_DESCRIPTOR)) {
            results.add(jClassType);/*from w w  w .  ja v a2  s  .com*/
            crf.addImport(jClassType.getQualifiedSourceName());
        }
    }
    return results;
}

From source file:cc.alcina.framework.entity.gwtsynth.ClientReflectionGenerator.java

License:Apache License

private List<JAnnotationType> getClientVisibleAnnotations(TreeLogger logger, TypeOracle oracle) {
    List<JAnnotationType> results = new ArrayList<JAnnotationType>();
    JClassType[] types = oracle.getTypes();
    for (JClassType jClassType : types) {
        if (jClassType.isAnnotationPresent(ClientVisible.class)) {
            JAnnotationType annotation = jClassType.isAnnotation();
            if (annotation != null) {
                results.add(annotation);
            }/*from   w w w  . ja v  a  2 s. c  o  m*/
        }
    }
    return results;
}

From source file:cc.alcina.framework.entity.gwtsynth.ClientReflectionGenerator.java

License:Apache License

private List<JClassType> getInstantiableTypes(TreeLogger logger, TypeOracle typeOracle,
        ClassSourceFileComposerFactory crf) {
    List<JClassType> results = new ArrayList<JClassType>();
    JClassType[] types = typeOracle.getTypes();
    for (JClassType jClassType : types) {
        if (jClassType.getQualifiedSourceName().equals("au.com.barnet.demeter.crm.client.Contact")) {
            int debug = 3;
        }//  ww  w.  j  a  va  2s  .  c o  m
        if ((hasAnnotationNamed(jClassType, ClientInstantiable.class) || jClassType
                .isAnnotationPresent(cc.alcina.framework.common.client.logic.reflection.Bean.class))
                && !ignore(jClassType, ReflectionAction.NEW_INSTANCE)) {
            results.add(jClassType);
            crf.addImport(jClassType.getQualifiedSourceName());
        }
    }
    return results;
}

From source file:cc.alcina.framework.entity.gwtsynth.ClientReflectionGenerator.java

License:Apache License

/**
 * Since overridden parent annotations are potentially useful, we don't use
 * standard overriding behaviour//from  w  ww.j av  a 2  s  .c  om
 *
 * @throws ClassNotFoundException
 */
private Map<JClassType, Set<RegistryLocation>> getRegistryAnnotations(TypeOracle typeOracle)
        throws ClassNotFoundException {
    HashMap<JClassType, Set<RegistryLocation>> results = new HashMap<JClassType, Set<RegistryLocation>>();
    JClassType[] types = typeOracle.getTypes();
    for (JClassType jct : types) {
        if (jct.getName().matches("(?i).*AlcinaBeanSerializerC.*")) {
            int debug = 3;
        }
        if ((jct.isAnnotationPresent(RegistryLocation.class)
                || jct.isAnnotationPresent(RegistryLocations.class)) && !jct.isAbstract()) {
            Set<RegistryLocation> rls = getClassAnnotations(jct, RegistryLocation.class, true);
            Set<RegistryLocations> rlsSet = getClassAnnotations(jct, RegistryLocations.class, true);
            for (RegistryLocations rlcs : rlsSet) {
                for (RegistryLocation rl : rlcs.value()) {
                    rls.add(rl);
                }
            }
            rls = new LinkedHashSet<RegistryLocation>(rls);
            CollectionFilters.filterInPlace(rls, CLIENT_VISIBLE_ANNOTATION_FILTER);
            rls = Registry.filterForRegistryPointUniqueness(rls);
            if (!rls.isEmpty() && !ignore(jct)) {
                results.put(jct, rls);
            }
        }
    }
    return results;
}

From source file:com.bramosystems.oss.player.core.rebind.PlayerManagerGenerator.java

License:Apache License

private void collatePlayers(TypeOracle typeOracle) {
    TreeLogger tl = logger.branch(TreeLogger.Type.INFO, "Searching for Player Providers");
    JClassType a[] = typeOracle.getTypes();
    for (int i = 0; i < a.length; i++) {
        if (a[i].isAnnotationPresent(PlayerProvider.class)) {
            String pName = a[i].getAnnotation(PlayerProvider.class).value();
            tl.log(TreeLogger.Type.INFO, "Processing Player Provider : " + pName);
            pMap.put(a[i].getQualifiedSourceName(), new _provider(pName));
        }/*ww  w.j  a  v a  2s  .  c om*/
    }

    tl = logger.branch(TreeLogger.Type.INFO, "Searching for Player widgets");
    for (int i = 0; i < a.length; i++) {
        if (a[i].isAnnotationPresent(Player.class)) {
            Player p = a[i].getAnnotation(Player.class);
            String pName = p.providerFactory().getName();
            if (pMap.containsKey(pName)) {
                tl.log(TreeLogger.Type.INFO, "Processing Player widget : " + a[i].getQualifiedSourceName());
                _player _py = new _player(p.name(), p.minPluginVersion(), a[i].getQualifiedSourceName());
                _py.interfaces = a[i].getImplementedInterfaces();
                pMap.get(pName).players.add(_py);
            } else {
                logger.log(TreeLogger.Type.ERROR,
                        "WidgetFactory '" + pName + "' should be annotated with @PlayerProvider");
            }
        }
    }
}

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

License:Open Source License

public static List<TestCase> getTestCases(TreeLogger logger, GeneratorContext context)
        throws UnableToCompleteException {
    if (DEBUG)// w ww  .  ja v  a  2 s .  c o m
        logger = logger.branch(TreeLogger.WARN, "Getting test cases", null, null);
    TypeOracle oracle = context.getTypeOracle();
    JClassType jsTestCaseClass = oracle.findType(JsTestCase.class.getName());

    List<TestCase> testCases = new ArrayList<TestCase>();

    for (JClassType classType : oracle.getTypes()) {
        if (classType.equals(jsTestCaseClass) || !classType.isAssignableTo(jsTestCaseClass)) {
            continue;
        }

        if (classType.getEnclosingType() != null) {
            if (DEBUG)
                logger.log(TreeLogger.WARN, "Skipping nested class: " + classType.getEnclosingType().getName()
                        + "." + classType.getName());
            continue;
        }

        if (DEBUG)
            logger.log(TreeLogger.WARN, "Found class: " + classType.getName());
        testCases.add(new TestCase(classType, findTests(logger, context, classType)));
    }
    return testCases;
}

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

License:Open Source License

@SuppressWarnings("rawtypes")
@Override//  w  w w .ja  va 2  s.  com
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.ludorival.dao.gwt.rebind.EntityManagerGenerator.java

License:Apache License

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return factory.getCreatedClassName();

}

From source file:com.gwtent.gen.aop.AspectCollectorImpl.java

License:Apache License

public AspectCollectorImpl(TypeOracle typeOracle) {
    this.typeOracle = typeOracle;

    for (JClassType classType : typeOracle.getTypes()) {
        Aspect aspect = classType.getAnnotation(org.aspectj.lang.annotation.Aspect.class);
        if (aspect != null) {
            aspectClasses.add(classType);
        }//from  ww w.  j a v  a 2s  . c  o m
    }

    for (JClassType classType : this.aspectClasses) {
        for (JMethod method : classType.getMethods()) {
            String expression = AOPUtils.getExpression(method);
            if ((expression != null) && (expression.length() > 0)) {
                this.pointcuts.put(method, new AspectJExpress(expression));
            }
        }
    }
}

From source file:com.josephalevin.gwtplug.rebind.PluginLookupGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    if (!PluginLookup.class.getName().equals(typeName)) {
        logger.log(TreeLogger.ERROR,//w w  w .  j  av a 2  s .c  o  m
                String.format("Do not extend or implement the %s.", PluginLookup.class.getName()));
        throw new UnableToCompleteException();
    }

    TypeOracle oracle = context.getTypeOracle();

    JClassType type = oracle.findType(typeName);

    String packageName = type.getPackage().getName();
    String implName = type.getName() + "Impl";

    PrintWriter writer = context.tryCreate(logger, packageName, implName);

    if (writer != null) {

        Map<JClassType, List<JClassType>> lookup = new HashMap<JClassType, List<JClassType>>();
        for (JClassType plugin : oracle.getTypes()) {
            List<JClassType> impls = implementations(logger, oracle, plugin);
            if (impls != null && !impls.isEmpty()) {
                lookup.put(plugin, impls);
            }
        }

        writer.format("package %s;", packageName);
        writer.println();

        writer.format("import %s;", Iterator.class.getName());
        writer.println();

        writer.format("public class %s implements %s {", implName, typeName);
        writer.println();

        writer.println("public <S> Iterator<S> lookup(Class<S> plugin){");

        //loop over each plugin type and map to the iterator
        for (Entry<JClassType, List<JClassType>> entry : lookup.entrySet()) {
            JClassType pluginType = entry.getKey();
            List<JClassType> impls = entry.getValue();

            writer.format("if (plugin.getName().equals(\"%s\")){", pluginType.getQualifiedBinaryName());
            writer.println();

            writer.format("return (Iterator<S>) new %s<%s>(%s){", PluginIterator.class.getName(),
                    pluginType.getQualifiedBinaryName(), impls.size());
            writer.println();

            writer.format("public %s get (int index){", pluginType.getQualifiedBinaryName());
            writer.println("switch(index){");
            for (int i = 0; i < impls.size(); i++) {
                writer.format("case %s: return new %s();", i, impls.get(i).getQualifiedBinaryName());
                writer.println();
            }
            writer.println("default:throw new ArrayIndexOutOfBoundsException(index);");
            writer.println("}");
            writer.println("}");

            writer.println("};");

            writer.println("}");
        }

        writer.println("return null;");

        writer.println("}");

        writer.println("}");

        //commit the generated source code
        context.commit(logger, writer);
    }
    return String.format("%s.%s", packageName, implName);

}