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

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

Introduction

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

Prototype

<T extends Annotation> T getAnnotation(Class<T> annotationClass);

Source Link

Document

Returns an instance of the specified annotation type if it is present on this element or null if it is not.

Usage

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

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    filter = IntrospectorFilterHelper.getFilter(context);
    // System.out.println("ClientReflector generation...");
    long start = System.currentTimeMillis();
    Map<Class, String> ann2impl = new HashMap<Class, String>();
    Map<String, String> simpleNameCheck = new HashMap<String, String>();
    try {/* w  ww . jav  a 2s.c om*/
        ClassSourceFileComposerFactory crf = null;
        // scan for reflectable annotations etc
        String superClassName = null;
        JClassType intrType = context.getTypeOracle().getType(typeName);
        if (intrType.isInterface() != null) {
            intrType = context.getTypeOracle().getType(ClientReflector.class.getName());
        }
        ReflectionModule module = intrType.getAnnotation(ReflectionModule.class);
        String moduleName = module.value();
        filter.setModuleName(moduleName);
        String implementationName = String.format("ClientReflector_%s_Impl", moduleName);
        superClassName = intrType.getQualifiedSourceName();
        crf = new ClassSourceFileComposerFactory(this.packageName, implementationName);
        PrintWriter printWriter = context.tryCreate(logger, packageName, implementationName);
        if (printWriter == null) {
            return packageName + "." + implementationName;
        }
        crf.addImport(LinkedHashMap.class.getName());
        crf.addImport(Map.class.getName());
        crf.addImport(GWT.class.getName());
        crf.addImport(JavaScriptObject.class.getName());
        crf.addImport(Registry.class.getName());
        crf.addImport(Annotation.class.getName());
        crf.addImport(UnsafeNativeLong.class.getName());
        crf.setSuperclass(superClassName);
        crf.addImport(ClientBeanReflector.class.getName());
        crf.addImport(ClientPropertyReflector.class.getName());
        crf.addImport(ClientReflector.class.getName());
        crf.addImport(RegistryLocation.class.getName());
        ctLookup.clear();
        visibleAnnotationClasses = new ArrayList<Class<? extends Annotation>>();
        List<JAnnotationType> jAnns = this.getClientVisibleAnnotations(logger, context.getTypeOracle());
        for (JAnnotationType jAnnotationType : jAnns) {
            visibleAnnotationClasses
                    .add((Class<? extends Annotation>) Class.forName(jAnnotationType.getQualifiedBinaryName()));
        }
        visibleAnnotationClasses.add(Omit.class);
        filter.filterAnnotations(jAnns, visibleAnnotationClasses);
        writeAnnotations(logger, context, jAnns, crf, moduleName.equals(ReflectionModule.INITIAL));
        List<JClassType> beanInfoTypes = this.getBeanInfoTypes(logger, context.getTypeOracle(), crf);
        List<JClassType> instantiableTypes = this.getInstantiableTypes(logger, context.getTypeOracle(), crf);
        Map<JClassType, Set<RegistryLocation>> gwtRegisteringClasses = getRegistryAnnotations(
                context.getTypeOracle());
        filter.filterReflectionInfo(beanInfoTypes, instantiableTypes, gwtRegisteringClasses);
        SourceWriter srcW = createWriter(crf, printWriter);
        writeIt(beanInfoTypes, instantiableTypes, srcW, gwtRegisteringClasses, implementationName);
        commit(context, logger, printWriter);
        System.out.format(
                "Client reflection generation  [%s] - " + "%s annotations, %s beans, "
                        + "%s instantiable types - %s ms\n",
                filter.getModuleName(), jAnns.size(), beanInfoTypes.size(), instantiableTypes.size(),
                System.currentTimeMillis() - start);
        filter.generationComplete();
        return packageName + "." + implementationName;
    } catch (Exception e) {
        e.printStackTrace();
        throw new WrappedRuntimeException(e);
    }
}

From source file:com.ait.ext4j.rebind.BeanModelGenerator.java

License:Apache License

protected JClassType getMarkerBean(JClassType type) throws NotFoundException {
    BEAN pojo = type.getAnnotation(BEAN.class);
    return oracle.getType(pojo.value().getCanonicalName());
}

From source file:com.ait.ext4j.rebind.TemplateGenerator.java

License:Apache License

/**
 * Given a TemplateResource interface, return the path to its .html file,
 * suitable for any classloader to find it as a resource. If the .html does
 * not exist or is empty see if the template was declared inline. If no
 * content is found we throw an exception.
 *///  w w w.ja  va  2s .  c o m
private String getTemplateContent(GeneratorContext context, TreeLogger logger, JClassType interfaceType)
        throws UnableToCompleteException {
    String templateHtmlFile = null;

    TemplateResource annotation = interfaceType.getAnnotation(TemplateResource.class);
    if (annotation == null) {
        // if the interface is defined as a nested class, use the name of
        // the
        // enclosing type
        if (interfaceType.getEnclosingType() != null) {
            interfaceType = interfaceType.getEnclosingType();
        }
        templateHtmlFile = slashify(interfaceType.getQualifiedBinaryName()) + TEMPLATE_SUFFIX;
        logger.log(TreeLogger.INFO, "Template : " + templateHtmlFile);

        InputStream stream = getTemplateResource(context, logger, templateHtmlFile);
        if (stream == null) {
            logger.log(Type.ERROR, "No data could be loaded - no data at path "
                    + interfaceType.getQualifiedBinaryName() + TEMPLATE_SUFFIX);
            throw new UnableToCompleteException();
        }
        return sanitize(Util.readStreamAsString(stream));

    } else {
        // first we look at the HTML File
        templateHtmlFile = annotation.source();

        if (templateHtmlFile.length() > 0) {

            if (!templateHtmlFile.endsWith(TEMPLATE_SUFFIX)) {
                logger.log(TreeLogger.ERROR, "Template file name must end with " + TEMPLATE_SUFFIX);
                throw new UnableToCompleteException();
            }

            if (annotation.value().length() != 0) {
                logger.log(Type.WARN, "Found both source file and inline template, using source file");
            }

            templateHtmlFile = slashify(interfaceType.getPackage().getName()) + "/" + templateHtmlFile;
            InputStream stream = getTemplateResource(context, logger, templateHtmlFile);
            return sanitize(Util.readStreamAsString(stream));

        } else if (annotation.value().length() > 0) {
            return annotation.value();
        } else {
            logger.log(Type.ERROR,
                    "Template annotation found with no contents, cannot generate method , this may cause other failures.");
        }

    }
    return null;
}

From source file:com.ait.toolkit.rebind.BeanModelGenerator.java

License:Open Source License

protected JClassType getMarkerBean(JClassType type) throws NotFoundException {
    BeanClass pojo = type.getAnnotation(BeanClass.class);
    return oracle.getType(pojo.value().getCanonicalName());
}

From source file:com.chrome.gwt.linker.ComponentGenerator.java

License:Apache License

private static String processBrowserAction(TreeLogger logger, GeneratorContext context, JClassType userType,
        String typeName) throws UnableToCompleteException {
    BrowserAction.ManifestInfo spec = userType.getAnnotation(BrowserAction.ManifestInfo.class);
    if (spec == null) {
        logger.log(TreeLogger.ERROR,/*from ww  w  . j  av a  2  s  .c o m*/
                "BrowserAction (" + typeName + ") must be annotated with a Specificaiton.");
        throw new UnableToCompleteException();
    }
    JMethod[] methods = userType.getMethods();
    List<String> iconFileNames = new ArrayList<String>();
    List<String> iconMethodNames = new ArrayList<String>();

    // TODO(jaimeyap): Do something smarter about verifying that the files
    // actually exist on disk, and then coming up with something sane for
    // the path information. May even consider strong names. See what
    // ClientBundle/ImageResource does.
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getReturnType().getQualifiedSourceName().equals(ICON_USER_TYPE)) {
            JMethod method = methods[i];
            String iconFileName;
            Icon.Source iconSource = method.getAnnotation(Icon.Source.class);
            if (iconSource == null) {
                iconFileName = method.getName() + ".png";
            } else {
                iconFileName = iconSource.value();
            }
            iconFileNames.add(iconFileName);
            iconMethodNames.add(method.getName());
        }
    }
    if (iconFileNames.size() == 0) {
        logger.log(TreeLogger.ERROR, "BrowserActions must have at least one Icon (" + typeName + ")");
        throw new UnableToCompleteException();
    }
    context.commitArtifact(logger, new BrowserActionArtifact(spec.name(), iconFileNames.toArray(new String[0]),
            spec.defaultIcon(), spec.popup()));
    return emitBrowserActionCode(logger, context, userType, spec.name(), iconMethodNames, iconFileNames);
}

From source file:com.chrome.gwt.linker.ComponentGenerator.java

License:Apache License

private static void processContentScript(TreeLogger logger, GeneratorContext context, JClassType userType,
        String typeName) throws UnableToCompleteException {
    ManifestInfo spec = userType.getAnnotation(ContentScript.ManifestInfo.class);
    if (spec == null) {
        logger.log(TreeLogger.ERROR,//from   w  ww  . ja va  2  s. c  o  m
                "ContentScript (" + typeName + ") must be annotated with a Specificaiton.");
        throw new UnableToCompleteException();
    }
    context.commitArtifact(logger, new ContentScriptArtifact(spec.path(), spec.whiteList(), spec.runAt()));
}

From source file:com.chrome.gwt.linker.ComponentGenerator.java

License:Apache License

private static String processPageAction(TreeLogger logger, GeneratorContext context, JClassType userType,
        String typeName) throws UnableToCompleteException {
    PageAction.ManifestInfo spec = userType.getAnnotation(PageAction.ManifestInfo.class);
    Extension.ManifestInfo spec2 = userType.getAnnotation(Extension.ManifestInfo.class);
    if (spec == null) {
        logger.log(TreeLogger.ERROR, "PageAction (" + typeName + ") must be annotated with a Specificaiton.");
        throw new UnableToCompleteException();
    }//from ww  w.  ja  v a 2  s .  c  o  m
    JMethod[] methods = userType.getMethods();
    List<String> iconFileNames = new ArrayList<String>();
    List<String> iconMethodNames = new ArrayList<String>();

    // TODO(jaimeyap): Do something smarter about verifying that the files
    // actually exist on disk, and then coming up with something sane for
    // the path information. May even consider strong names. See what
    // ClientBundle/ImageResource does.
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getReturnType().getQualifiedSourceName().equals(ICON_USER_TYPE)) {
            JMethod method = methods[i];
            String iconFileName;
            Icon.Source iconSource = method.getAnnotation(Icon.Source.class);
            if (iconSource == null) {
                iconFileName = method.getName() + ".png";
            } else {
                iconFileName = iconSource.value();
            }
            iconFileNames.add(iconFileName);
            iconMethodNames.add(method.getName());
        }
    }
    if (iconFileNames.size() == 0) {
        logger.log(TreeLogger.ERROR, "PageActions must have at least one Icon (" + typeName + ")");
        throw new UnableToCompleteException();
    }
    context.commitArtifact(logger,
            new PageActionArtifact(spec.pageActionId(), spec.name(), iconFileNames.toArray(new String[0])));
    return emitPageActionCode(logger, context, userType, spec.pageActionId(), spec.name(), iconMethodNames,
            iconFileNames);
}

From source file:com.chrome.gwt.linker.ComponentGenerator.java

License:Apache License

private static void processPlugin(TreeLogger logger, GeneratorContext context, JClassType userType,
        String typeName) throws UnableToCompleteException {
    Plugin.ManifestInfo spec = userType.getAnnotation(Plugin.ManifestInfo.class);
    if (spec == null) {
        logger.log(TreeLogger.ERROR, "Plugin (" + typeName + ") must be annotated with a Specificaiton.");
        throw new UnableToCompleteException();
    }//ww  w .ja  v  a  2  s.  com
    context.commitArtifact(logger, new PluginArtifact(spec.path(), spec.isPublic()));
}

From source file:com.chrome.gwt.linker.ExtensionGenerator.java

License:Apache License

private static ExtensionArtifact getSpecification(TreeLogger logger, GeneratorContext context,
        JClassType userType) throws UnableToCompleteException {
    final ManifestInfo spec = userType.getAnnotation(Extension.ManifestInfo.class);
    if (spec != null) {
        return new ExtensionArtifact(spec.name(), spec.description(), spec.version(), spec.permissions(),
                spec.updateUrl(), createIconResources(logger, context, userType, spec.icons()),
                spec.optionsPage());/*  www .  j  a v  a  2 s.  c  o  m*/
    }

    logger.log(TreeLogger.ERROR, "You need a @Extension.Specification annotation on "
            + userType.getQualifiedSourceName() + " or else I'll have to make up a silly name for it.");
    throw new UnableToCompleteException();
}

From source file:com.colinalworth.gwt.websockets.rebind.ServerBuilderGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();
    JClassType toGenerate = oracle.findType(typeName).isInterface();

    if (toGenerate == null) {
        logger.log(Type.ERROR, "Error generating " + typeName
                + ", either not an interface, or cannot be reached from client code.");
        throw new UnableToCompleteException();
    }//ww w  .  j av  a 2 s.  co  m
    JClassType serverBuilderType = oracle.findType(ServerBuilder.class.getName());
    JClassType serverImplType = ModelUtils.findParameterizationOf(serverBuilderType, toGenerate)[0];

    // Build an impl so we can call it ourselves
    ServerCreator creator = new ServerCreator(serverImplType);
    creator.create(logger, context);

    String packageName = toGenerate.getPackage().getName();
    String simpleName = toGenerate.getName().replace('.', '_') + "_Impl";

    PrintWriter pw = context.tryCreate(logger, packageName, simpleName);
    if (pw == null) {
        return packageName + "." + simpleName;
    }

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleName);
    factory.setSuperclass(Name.getSourceNameForClass(ServerBuilderImpl.class) + "<"
            + serverImplType.getQualifiedSourceName() + ">");
    factory.addImplementedInterface(typeName);

    SourceWriter sw = factory.createSourceWriter(context, pw);

    RemoteServiceRelativePath path = serverImplType.getAnnotation(RemoteServiceRelativePath.class);
    if (path != null) {
        sw.println("public %1$s() {", simpleName);
        sw.indentln("setPath(\"%1$s\");", path.value());
        sw.println("}");
    }

    sw.println();
    // start method
    sw.println("public %1$s start() {", serverImplType.getQualifiedSourceName());
    sw.indent();
    sw.println("String url = getUrl();");
    sw.println("if (url == null) {");
    sw.indentln("return new %1$s(getErrorHandler());", creator.getQualifiedSourceName());
    sw.println("} else {");
    sw.indentln("return new %1$s(getErrorHandler(), url);", creator.getQualifiedSourceName());
    sw.println("}");

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

    sw.commit(logger);

    return factory.getCreatedClassName();

}