Example usage for com.google.gwt.core.ext.typeinfo JClassType isAnnotationPresent

List of usage examples for com.google.gwt.core.ext.typeinfo JClassType isAnnotationPresent

Introduction

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

Prototype

boolean isAnnotationPresent(Class<? extends Annotation> annotationClass);

Source Link

Document

Returns true if this item has an annotation of the specified type.

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);/* w ww  .  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 ww . j  a  va  2  s.  co  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;
        }//w  ww . java2 s.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 w w . j  ava2s. c  o m
 *
 * @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.github.gilbertotorrezan.gwtviews.rebind.NavigationManagerGenerator.java

License:Open Source License

@SuppressWarnings("rawtypes")
@Override/*from  w  w w .  j a v  a2  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;
    }/*from  w w w .  j a  v a  2 s  .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.nmorel.gwtjackson.rebind.CreatorUtils.java

License:Apache License

/**
 * Browse all the hierarchy of the type and return the first corresponding annotation it found
 *
 * @param type type/*  w  w w.  j  av  a 2  s . co m*/
 * @param annotation annotation to find
 * @param <T> type of the annotation
 * @param ignoreType type to ignore when browsing the hierarchy
 *
 * @return the annotation if found, null otherwise
 */
private static <T extends Annotation> Optional<T> findFirstEncounteredAnnotationsOnAllHierarchy(
        RebindConfiguration configuration, JClassType type, Class<T> annotation,
        Optional<JClassType> ignoreType) {
    JClassType currentType = type;
    while (null != currentType) {
        Optional<JClassType> mixin = configuration.getMixInAnnotations(currentType);
        if (mixin.isPresent() && mixin.get().isAnnotationPresent(annotation)) {
            return Optional.of(mixin.get().getAnnotation(annotation));
        }
        if (currentType.isAnnotationPresent(annotation)) {
            return Optional.of(currentType.getAnnotation(annotation));
        }
        for (JClassType interf : currentType.getImplementedInterfaces()) {
            if (!ignoreType.isPresent() || !ignoreType.get().equals(interf)) {
                Optional<T> annot = findFirstEncounteredAnnotationsOnAllHierarchy(configuration, interf,
                        annotation);
                if (annot.isPresent()) {
                    return annot;
                }
            }
        }
        currentType = currentType.getSuperclass();
        if (ignoreType.isPresent() && ignoreType.get().equals(currentType)) {
            currentType = null;
        }
    }
    return Optional.absent();
}

From source file:com.google.gwt.sample.showcase.generator.ShowcaseGenerator.java

License:Apache License

/**
 * Generate the raw files used by a {@link ContentWidget}.
 *
 * @param type the {@link ContentWidget} subclass
 *///from  ww  w .j  ava2 s.  c o m
private void generateRawFiles(JClassType type) throws UnableToCompleteException {
    // Look for annotation
    if (!type.isAnnotationPresent(ShowcaseRaw.class)) {
        return;
    }

    // Get the package info
    String pkgName = type.getPackage().getName();
    String pkgPath = pkgName.replace('.', '/') + "/";

    // Generate each raw source file
    String[] filenames = type.getAnnotation(ShowcaseRaw.class).value();
    for (String filename : filenames) {
        // Check if the file has already been generated.
        String path = pkgName + filename;
        if (rawFiles.contains(path)) {
            continue;
        }
        rawFiles.add(path);

        // Get the file contents
        String fileContents = getResourceContents(pkgPath + filename);

        // Make the source pretty
        fileContents = fileContents.replace("<", "&lt;");
        fileContents = fileContents.replace(">", "&gt;");
        fileContents = fileContents.replace("* \n   */\n", "*/\n");
        fileContents = "<pre>" + fileContents + "</pre>";

        // Save the raw source in the public directory
        String dstPath = ShowcaseConstants.DST_SOURCE_RAW + filename + ".html";
        createPublicResource(dstPath, fileContents);
    }
}

From source file:com.google.gwt.sample.showcase.generator.ShowcaseGenerator.java

License:Apache License

/**
 * Generate the styles used by a {@link ContentWidget}.
 *
 * @param type the {@link ContentWidget} subclass
 * @param styleDefs the concatenated style definitions
 * @param outDir the output directory/*w  w w .  j  ava 2  s.  c  o  m*/
 */
private void generateStyleFiles(JClassType type, String styleDefs, String outDir)
        throws UnableToCompleteException {
    // Look for annotation
    if (!type.isAnnotationPresent(ShowcaseStyle.class)) {
        return;
    }

    // Generate a style file for each theme/RTL mode pair
    String[] prefixes = type.getAnnotation(ShowcaseStyle.class).value();
    Map<String, String> matched = new LinkedHashMap<String, String>();
    for (String prefix : prefixes) {
        // Get the start location of the style code in the source file
        boolean foundStyle = false;
        int start = styleDefs.indexOf("\n" + prefix);
        while (start >= 0) {
            // Get the cssContents string name pattern
            int end = styleDefs.indexOf("{", start);
            String matchedName = styleDefs.substring(start, end).trim();

            // Get the style code
            end = styleDefs.indexOf("}", start) + 1;
            String styleDef = "<pre>" + styleDefs.substring(start, end) + "</pre>";
            matched.put(matchedName, styleDef);

            // Goto the next match
            foundStyle = true;
            start = styleDefs.indexOf("\n" + prefix, end);
        }

        // No style exists
        if (!foundStyle) {
            matched.put(prefix, "<pre>" + prefix + " {\n}</pre>");
        }
    }

    // Combine all of the styles into one formatted string
    String formattedStyle = "";
    for (String styleDef : matched.values()) {
        formattedStyle += styleDef;
    }

    // Save the raw source in the public directory
    String dstPath = outDir + type.getSimpleSourceName() + ".html";
    createPublicResource(dstPath, formattedStyle);
}

From source file:com.googlecode.gflot.examples.generator.SourceGenerator.java

License:Apache License

/**
 * Generate the raw files used by a {@link ExampleActivity}.
 *
 * @param type the {@link ExampleActivity} subclass
 *//*  w  w  w .  ja v  a 2  s.c o  m*/
private void generateRawFiles(JClassType type) throws UnableToCompleteException {
    // Look for annotation
    if (!type.isAnnotationPresent(GFlotExamplesRaw.class)) {
        return;
    }

    // Get the package info
    String pkgName = type.getPackage().getName();
    String pkgPath = pkgName.replace('.', '/') + "/";

    // Generate each raw source file
    String[] filenames = type.getAnnotation(GFlotExamplesRaw.class).value();
    for (String filename : filenames) {
        // Check if the file has already been generated.
        String path = pkgName + filename;
        if (rawFiles.contains(path)) {
            continue;
        }
        rawFiles.add(path);

        // Get the file contents
        String fileContents = getResourceContents(pkgPath + filename);

        // Make the source pretty
        fileContents = fileContents.replace("<", "&lt;");
        fileContents = fileContents.replace(">", "&gt;");
        fileContents = fileContents.replace("* \n   */\n", "*/\n");
        fileContents = "<pre>" + fileContents + "</pre>";

        // Save the raw source in the public directory
        String dstPath = SourceConstants.DST_SOURCE_RAW + filename + ".html";
        createPublicResource(dstPath, fileContents);
    }
}