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

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

Introduction

In this page you can find the example usage for com.google.gwt.core.ext.typeinfo JMethod 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:com.cgxlib.xq.rebind.JsniBundleGenerator.java

License:Apache License

public String generate(TreeLogger logger, GeneratorContext context, String requestedClass)
        throws UnableToCompleteException {

    TypeOracle oracle = context.getTypeOracle();
    JClassType clazz = oracle.findType(requestedClass);

    String packageName = clazz.getPackage().getName();
    String className = clazz.getName().replace('.', '_') + "_Impl";
    String fullName = packageName + "." + className;

    PrintWriter pw = context.tryCreate(logger, packageName, className);

    if (pw != null) {
        ClassSourceFileComposerFactory fact = new ClassSourceFileComposerFactory(packageName, className);
        if (clazz.isInterface() != null) {
            fact.addImplementedInterface(requestedClass);
        } else {/*ww  w. j ava  2  s.  c o m*/
            fact.setSuperclass(requestedClass);
        }

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

        if (sw != null) {
            for (JMethod method : clazz.getMethods()) {
                LibrarySource librarySource = method.getAnnotation(LibrarySource.class);
                String value, prepend, postpend;
                String replace[];
                if (librarySource != null) {
                    value = librarySource.value();
                    prepend = librarySource.prepend();
                    postpend = librarySource.postpend();
                    replace = librarySource.replace();
                } else {
                    MethodSource methodSource = method.getAnnotation(MethodSource.class);
                    if (methodSource != null) {
                        value = methodSource.value();
                        prepend = methodSource.prepend();
                        postpend = methodSource.postpend();
                        replace = methodSource.replace();
                    } else {
                        continue;
                    }
                }
                try {
                    // Read the javascript content
                    String content = getContent(logger, packageName.replace(".", "/"), value);

                    // Adjust javascript so as we can introduce it in a JSNI comment block without
                    // breaking java syntax.
                    String jsni = parseJavascriptSource(content);

                    for (int i = 0; i < replace.length - 1; i += 2) {
                        jsni = jsni.replaceAll(replace[i], replace[i + 1]);
                    }

                    pw.println(method.toString().replace("abstract", "native") + "/*-{");
                    pw.println(prepend);
                    pw.println(jsni);
                    pw.println(postpend);
                    pw.println("}-*/;");
                } catch (Exception e) {
                    logger.log(TreeLogger.ERROR,
                            "Error parsing javascript source: " + value + " " + e.getMessage());
                    throw new UnableToCompleteException();
                }
            }
        }
        sw.commit(logger);
    }

    return fullName;
}

From source file:com.cgxlib.xq.rebind.JsonBuilderGenerator.java

License:Apache License

public String generate(TreeLogger treeLogger, GeneratorContext generatorContext, String requestedClass)
        throws UnableToCompleteException {

    oracle = generatorContext.getTypeOracle();
    JClassType clazz = oracle.findType(requestedClass);

    jsonBuilderType = oracle.findType(JsonBuilder.class.getName());
    settingsType = oracle.findType(IsProperties.class.getName());
    stringType = oracle.findType(String.class.getName());
    jsType = oracle.findType(JavaScriptObject.class.getName());
    listType = oracle.findType(List.class.getName());
    functionType = oracle.findType(Function.class.getName());
    jsonFactoryType = oracle.findType(JsonFactory.class.getName());

    String t[] = generateClassName(clazz);

    boolean isFactory = clazz.isAssignableTo(jsonFactoryType);

    SourceWriter sw = getSourceWriter(treeLogger, generatorContext, t[0], t[1], isFactory, requestedClass);
    if (sw != null) {
        if (isFactory) {
            generateCreateMethod(sw, treeLogger);
        } else {//from   ww  w .  j  a va2 s  .c  o  m
            Set<String> attrs = new HashSet<String>();
            for (JMethod method : clazz.getInheritableMethods()) {
                String methName = method.getName();
                // skip method from JsonBuilder
                if (jsonBuilderType.findMethod(method.getName(), method.getParameterTypes()) != null
                        || settingsType.findMethod(method.getName(), method.getParameterTypes()) != null) {
                    continue;
                }

                Name nameAnnotation = method.getAnnotation(Name.class);
                String name = nameAnnotation != null ? nameAnnotation.value()
                        : methName.replaceFirst("^(get|set)", "");
                if (nameAnnotation == null) {
                    name = name.substring(0, 1).toLowerCase() + name.substring(1);
                }
                attrs.add(name);
                generateMethod(sw, method, name, treeLogger);
            }
            generateFieldNamesMethod(sw, attrs, treeLogger);
            generateToJsonMethod(sw, t[3], treeLogger);
        }
        sw.commit(treeLogger);
    }
    return t[2];
}

From source file:com.cgxlib.xq.rebind.SelectorGeneratorBase.java

License:Apache License

public void generateMethod(SourceWriter sw, JMethod method, TreeLogger logger)
        throws UnableToCompleteException {
    Selector selectorAnnotation = method.getAnnotation(Selector.class);
    if (selectorAnnotation == null) {
        return;//w ww  .j a va 2 s .  co  m
    }

    JParameter[] params = method.getParameters();

    String retType = method.getReturnType().getParameterizedQualifiedSourceName();
    sw.print("public final " + retType + " " + method.getName());
    boolean hasContext = false;
    if (params.length == 0) {
        sw.print("()");
    } else if (params.length == 1) {
        JClassType type = params[0].getType().isClassOrInterface();
        if (type != null && type.isAssignableTo(nodeType)) {
            sw.print("(Node root)");
            hasContext = true;
        }
    }
    sw.println(" {");
    sw.indent();
    Selector sel = method.getAnnotation(Selector.class);

    if (sel != null && sel.value().matches("^#\\w+$")) {
        // short circuit #foo
        sw.println("return " + wrap(method,
                "JsNodeArray.create(((Document)root).getElementById(\"" + sel.value().substring(1) + "\"))")
                + ";");
    } else if (sel != null && sel.value().matches("^\\w+$")) {
        // short circuit FOO
        sw.println("return "
                + wrap(method,
                        "JsNodeArray.create(((Element)root).getElementsByTagName(\"" + sel.value() + "\"))")
                + ";");
    } else if (sel != null && sel.value().matches("^\\.\\w+$") && hasGetElementsByClassName()) {
        // short circuit .foo for browsers with native getElementsByClassName
        sw.println("return " + wrap(method,
                "JsNodeArray.create(getElementsByClassName(\"" + sel.value().substring(1) + "\", root))")
                + ";");
    } else {
        generateMethodBody(sw, method, logger, hasContext);
    }
    sw.outdent();
    sw.println("}");
}

From source file:com.cgxlib.xq.rebind.SelectorGeneratorBase.java

License:Apache License

private void genGetAllMethod(SourceWriter sw, JMethod[] methods, TreeLogger treeLogger) {
    sw.println("public DeferredSelector[] getAllSelectors() {return ds;}");
    sw.println("private final DeferredSelector[] ds = new DeferredSelector[] {");
    sw.indent();//from   w  w  w .  j  a v a 2s.com
    for (JMethod m : methods) {
        Selector selectorAnnotation = m.getAnnotation(Selector.class);
        if (selectorAnnotation == null) {
            continue;
        }
        String selector = selectorAnnotation.value();

        sw.println("new DeferredSelector() {");
        sw.indent();
        sw.println("public String getSelector() { return \"" + selector + "\"; }");
        sw.println("public NodeList<Element> runSelector(Node ctx) { return "
                + (m.getName() + (m.getParameters().length == 0 ? "()" : "(ctx)"))
                + ("NodeList".equals(m.getReturnType().getSimpleSourceName()) ? "" : ".get()") + ";}");
        sw.outdent();
        sw.println("},");
    }
    sw.outdent();
    sw.println("};");
}

From source file:com.cgxlib.xq.rebind.SelectorGeneratorCssToXPath.java

License:Apache License

protected void generateMethodBody(SourceWriter sw, JMethod method, TreeLogger treeLogger, boolean hasContext)
        throws UnableToCompleteException {

    String selector = method.getAnnotation(Selector.class).value();
    String xselector = css2Xpath(selector);

    // Validate the generated xpath selector.
    try {//from  w  w w.j  a va2 s .  co m
        validateXpath(xselector);
    } catch (XPathExpressionException e1) {
        System.err.println("Invalid XPath generated selector, please revise it: " + xselector);
        if (!selector.equals(xselector)) {
            System.err.println(
                    "If your css2 selector syntax is correct, open an issue in the gwtquery project. cssselector:"
                            + selector + " xpath: " + xselector);
        }
        throw new UnableToCompleteException();
    }

    sw.println("return " + wrap(method, "xpathEvaluate(\"" + xselector + "\", root)") + ";");
}

From source file:com.cgxlib.xq.rebind.SelectorGeneratorJS.java

License:Apache License

protected void generateMethodBody(SourceWriter sw, JMethod method, TreeLogger treeLogger, boolean hasContext)
        throws UnableToCompleteException {
    String selector = method.getAnnotation(Selector.class).value();
    sw.println("return " + wrap(method, "impl.select(\"" + selector + "\", root)") + ";");
}

From source file:com.cgxlib.xq.rebind.SelectorGeneratorJSOptimal.java

License:Apache License

protected void generateMethodBody(SourceWriter sw, JMethod method, TreeLogger treeLogger, boolean hasContext)
        throws UnableToCompleteException {

    String selector = method.getAnnotation(Selector.class).value();

    sw.println("return " + wrap(method, "impl.select(\"" + selector + "\", root)") + ";");
    //    sw.println("JSArray n = JSArray.create();");
    //    if(!hasContext) {
    //      sw.println("Node root = Document.get();");
    //    }/*w  w w. java 2 s  .  c om*/
    //
    //    // add root node as context.
    //    // TODO: support any context
    //    sw.println("n.addNode(root);");
    //    String q = selector, lq = null;
    //    Matcher lmode = modeRe.matcher(q);
    //    Matcher mm = null;
    //    String mode = "";
    //    if (lmode.lookingAt() && notNull(lmode.group(1))) {
    //      mode = lmode.group(1).replaceAll(trimReStr, "").trim();
    //      q = q.replaceFirst("\\Q" + lmode.group(1) + "\\E", "");
    //    }
    //
    //    while (notNull(q) && !q.equals(lq)) {
    //      debug("Doing q=" + q);
    //
    //      lq = q;
    //      Matcher tm = tagTokenRe.matcher(q);
    //      if (tm.lookingAt()) {
    //        if ("#".equals(tm.group(1))) {
    //          sw.println("n = quickId(n, \"" + mode + "\", root, \"" + tm.group(2)
    //              + "\");");
    //        } else {
    //          String tagName = tm.group(2);
    //          tagName = "".equals(tagName) ? "*" : tagName;
    //     //     sw.println("if (n.size() == 0) { n=JSArray.create(); }");
    //          String func = "";
    //          if ("".equals(mode)) {
    //            func = "getDescendentNodes";
    //          } else if (">".equals(mode)) {
    //            func = "getChildNodes";
    //          } else if ("+".equals(mode)) {
    //            func = "getSiblingNodes";
    //          } else if ("~".equals(mode)) {
    //            func = "getGeneralSiblingNodes";
    //          } else {
    //            treeLogger.log(TreeLogger.ERROR, "Error parsing selector, combiner "
    //                + mode + " not recognized in " + selector, null);
    //            throw new UnableToCompleteException();
    //          }
    //          sw.println("n = " + func + "(n, \"" + tagName + "\");");
    //        }
    //        debug("replacing in q, the value " + tm.group(0));
    //        q = q.replaceFirst("\\Q" + tm.group(0) + "\\E", "");
    //      } else {
    //        String func = "";
    //        String tagName = "*";
    //        if ("".equals(mode)) {
    //          func = "getDescendentNodes";
    //        } else if (">".equals(mode)) {
    //          func = "getChildNodes";
    //        } else if ("+".equals(mode)) {
    //          func = "getSiblingNodes";
    //        } else if ("~".equals(mode)) {
    //          func = "getGeneralSiblingNodes";
    //        } else {
    //          treeLogger.log(TreeLogger.ERROR, "Error parsing selector, combiner "
    //              + mode + " not recognized in " + selector, null);
    //          throw new UnableToCompleteException();
    //        }
    //        sw.println("n = " + func + "(n, \"" + tagName + "\");");
    //      }
    //
    //      while (!(mm = modeRe.matcher(q)).lookingAt()) {
    //        debug("Looking at " + q);
    //        boolean matched = false;
    //        for (RuleMatcher rm : matchers) {
    //          Matcher rmm = rm.re.matcher(q);
    //          if (rmm.lookingAt()) {
    //            String res[] = new String[rmm.groupCount()];
    //            for (int i = 1; i <= rmm.groupCount(); i++) {
    //              res[i - 1] = rmm.group(i);
    //              debug("added param " + res[i - 1]);
    //            }
    //            Object[] r = res;
    //            // inline enum, perhaps type-tightening will allow inlined eval()
    //            // call
    //            if (rm.fnTemplate.indexOf("byPseudo") != -1) {
    //              sw.println("n = Pseudo."+res[0].toUpperCase().replace("-", "_") +
    //                  ".eval(n, \""+res[1]+"\");");
    //            } else {
    //              sw.println(MessageFormat.format(rm.fnTemplate, r));
    //            }
    //            q = q.replaceFirst("\\Q" + rmm.group(0) + "\\E", "");
    //            matched = true;
    //            break;
    //          }
    //        }
    //        if (!matched) {
    //          treeLogger
    //              .log(TreeLogger.ERROR, "Error parsing selector at " + q, null);
    //          throw new UnableToCompleteException();
    //        }
    //      }
    //
    //      if (notNull(mm.group(1))) {
    //        mode = mm.group(1).replaceAll(trimReStr, "");
    //        debug("replacing q=" + q + " this part: " + mm.group(1));
    //        q = q.replaceFirst("\\Q" + mm.group(1) + "\\E", "");
    //      }
    //    }
    //    sw.println("return "+wrap(method, "nodup(n)")+";");
}

From source file:com.cgxlib.xq.rebind.SelectorGeneratorNative.java

License:Apache License

@Override
protected void generateMethodBody(SourceWriter sw, JMethod method, TreeLogger treeLogger, boolean hasContext)
        throws UnableToCompleteException {

    String selector = method.getAnnotation(Selector.class).value();
    if (selector.matches("#[\\w\\-]+")) {
        sw.println("return " + wrap(method, "veryQuickId(\"" + selector.substring(1) + "\", root)") + ";");
    } else if (selector.equals("*") || selector.matches("[\\w\\-]+")) {
        sw.println("return " + wrap(method, "elementsByTagName(\"" + selector + "\", root)") + ";");
    } else if (selector.matches("\\.[\\w\\-]+")) {
        sw.println(/*w  w w  . j a  va2  s.  com*/
                "return " + wrap(method, "elementsByClassName(\"" + selector.substring(1) + "\", root)") + ";");
    } else if (selector.contains("!=")) {
        sw.println(
                "return "
                        + wrap(method, "querySelectorAll(\""
                                + selector.replaceAll("(\\[\\w+)!(=[^\\]]+\\])", ":not($1$2)") + "\", root)")
                        + ";");
    } else if (selector.matches(SelectorEngineNative.NATIVE_EXCEPTIONS_REGEXP)) {
        super.generateMethodBody(sw, method, treeLogger, hasContext);
    } else {
        sw.println("return " + wrap(method, "querySelectorAll(\"" + selector + "\", root)") + ";");
    }
}

From source file:com.cgxlib.xq.rebind.SelectorGeneratorNativeIE8.java

License:Apache License

@Override
protected void generateMethodBody(SourceWriter sw, JMethod method, TreeLogger treeLogger, boolean hasContext)
        throws UnableToCompleteException {
    String selector = method.getAnnotation(Selector.class).value();
    if (selector.matches("#[\\w\\-]+")) {
        sw.println("return " + wrap(method, "veryQuickId(\"" + selector.substring(1) + "\", root)") + ";");
    } else if (selector.equals("*") || selector.matches("[\\w\\-]+")) {
        sw.println("return " + wrap(method, "elementsByTagName(\"" + selector + "\", root)") + ";");
    } else if (selector.matches("\\.[\\w\\-]+")) {
        sw.println(//from  www. j  a va  2 s .c o m
                "return " + wrap(method, "elementsByClassName(\"" + selector.substring(1) + "\", root)") + ";");
    } else if (selector.matches(SelectorEngineNativeIE8.NATIVE_EXCEPTIONS_REGEXP)) {
        super.generateMethodBody(sw, method, treeLogger, hasContext);
    } else {
        sw.println("return " + wrap(method, "querySelectorAll(\"" + selector + "\", root)") + ";");
    }
}

From source file:com.cgxlib.xq.rebind.SelectorGeneratorNativeIE9.java

License:Apache License

@Override
protected void generateMethodBody(SourceWriter sw, JMethod method, TreeLogger treeLogger, boolean hasContext)
        throws UnableToCompleteException {
    String selector = method.getAnnotation(Selector.class).value();
    if (selector.matches("#[\\w\\-]+")) {
        sw.println("return " + wrap(method, "veryQuickId(\"" + selector.substring(1) + "\", root)") + ";");
    } else if (selector.equals("*") || selector.matches("[\\w\\-]+")) {
        sw.println("return " + wrap(method, "elementsByTagName(\"" + selector + "\", root)") + ";");
    } else if (selector.matches("\\.[\\w\\-]+")) {
        sw.println(/*  w ww  .  ja v  a  2  s. c  om*/
                "return " + wrap(method, "elementsByClassName(\"" + selector.substring(1) + "\", root)") + ";");
    } else if (selector.matches(SelectorEngineNative.NATIVE_EXCEPTIONS_REGEXP)) {
        super.generateMethodBody(sw, method, treeLogger, hasContext);
    } else {
        sw.println("return " + wrap(method, "querySelectorAll(\"" + selector + "\", root)") + ";");
    }
}